CoolFace
Apppublic

Shrook21/Code-Assistant

sourceHugging Faceupdated 1y agoView on Hugging Face
0likes
app.py180 linesDownload Raw Back to root
1import gradio as gr
2from langchain_core.messages import HumanMessage
3from graph.conditional_graph import get_app
4
5# Initialize the app once
6app = get_app()
7
8def process_question(username, question):
9    """Process the user's question and return classification and answer"""
10    if not question.strip():
11        return "", "Please enter a question!"
12    
13    try:
14        # Invoke the langchain app
15        result = app.invoke({"message": [HumanMessage(content=question)]})
16        
17        # Extract classification and answer
18        classification = result.get('classification', 'unknown').upper()
19        answer = result['message'][-1].content
20        
21        return classification, answer
22        
23    except Exception as e:
24        return "ERROR", f"⚠️ Error: {str(e)}"
25
26def create_interface():
27    """Create the Gradio interface"""
28    
29    with gr.Blocks(title="Smart Code Assistant", theme=gr.themes.Soft()) as demo:
30        # Store username in state
31        username_state = gr.State("")
32        
33        # Welcome section
34        with gr.Row():
35            gr.Markdown("# 🤖 Smart Code Assistant")
36        
37        # Username input (initially visible)
38        with gr.Row() as username_row:
39            with gr.Column():
40                gr.Markdown("### Welcome! Please enter your name to get started:")
41                username_input = gr.Textbox(
42                    placeholder="Enter your name...",
43                    label="Your Name",
44                    interactive=True
45                )
46                start_btn = gr.Button("Start Assistant", variant="primary")
47        
48        # Main interface (initially hidden)
49        with gr.Row(visible=False) as main_interface:
50            with gr.Column():
51                # Personalized greeting
52                greeting = gr.Markdown("")
53                
54                # Question input
55                question_input = gr.Textbox(
56                    placeholder="Ask me anything about code...",
57                    label="Your Question",
58                    lines=3
59                )
60                
61                with gr.Row():
62                    submit_btn = gr.Button("Ask Question", variant="primary")
63                    clear_btn = gr.Button("Clear", variant="secondary")
64                
65                # Results section
66                with gr.Row():
67                    with gr.Column(scale=1):
68                        classification_output = gr.Textbox(
69                            label="🔍 Task Classification",
70                            interactive=False,
71                            lines=1
72                        )
73                    
74                with gr.Row():
75                    answer_output = gr.Textbox(
76                        label="🧠 Answer",
77                        interactive=False,
78                        lines=10
79                    )
80                
81                # Reset button
82                with gr.Row():
83                    reset_btn = gr.Button("Start Over", variant="secondary", size="sm")
84        
85        def start_session(name):
86            """Initialize the session with username"""
87            if not name.strip():
88                gr.Warning("Please enter your name!")
89                return gr.update(), gr.update(), gr.update(), ""
90            
91            greeting_text = f"## Hi, {name}! 👋 How can I help you today?"
92            
93            return (
94                gr.update(visible=False),  # Hide username section
95                gr.update(visible=True),   # Show main interface
96                gr.update(value=greeting_text),  # Update greeting
97                name  # Store username in state
98            )
99        
100        def ask_question(username, question):
101            """Handle question submission"""
102            if not question.strip():
103                gr.Warning("Please enter a question!")
104                return "", ""
105            
106            classification, answer = process_question(username, question)
107            return classification, answer
108        
109        def clear_inputs():
110            """Clear the input fields"""
111            return "", "", ""
112        
113        def reset_session():
114            """Reset to username input"""
115            return (
116                gr.update(visible=True),   # Show username section
117                gr.update(visible=False),  # Hide main interface
118                gr.update(value=""),       # Clear greeting
119                "",  # Clear username state
120                "",  # Clear username input
121                "",  # Clear question input
122                "",  # Clear classification
123                ""   # Clear answer
124            )
125        
126        # Event handlers
127        start_btn.click(
128            start_session,
129            inputs=[username_input],
130            outputs=[username_row, main_interface, greeting, username_state]
131        )
132        
133        submit_btn.click(
134            ask_question,
135            inputs=[username_state, question_input],
136            outputs=[classification_output, answer_output]
137        )
138        
139        clear_btn.click(
140            clear_inputs,
141            outputs=[question_input, classification_output, answer_output]
142        )
143        
144        reset_btn.click(
145            reset_session,
146            outputs=[username_row, main_interface, greeting, username_state, 
147                    username_input, question_input, classification_output, answer_output]
148        )
149        
150        # Allow Enter key to submit
151        username_input.submit(
152            start_session,
153            inputs=[username_input],
154            outputs=[username_row, main_interface, greeting, username_state]
155        )
156        
157        question_input.submit(
158            ask_question,
159            inputs=[username_state, question_input],
160            outputs=[classification_output, answer_output]
161        )
162    
163    return demo
164
165def main():
166    """Launch the Gradio app"""
167    print("=== LAUNCHING SMART CODE ASSISTANT WEB APP ===")
168    
169    demo = create_interface()
170    
171    # Launch the app
172    demo.launch(
173        server_name="0.0.0.0",  # Allow external access
174        server_port=7860,       # Default Gradio port
175        share=False,            # Set to True for public sharing
176        debug=True              # Enable debug mode
177    )
178
179if __name__ == "__main__":
180    main()