Kai Izumoto commited on
Commit
872296d
Β·
verified Β·
1 Parent(s): 989deb5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +200 -12
app.py CHANGED
@@ -1,18 +1,206 @@
 
 
 
 
1
  import gradio as gr
2
  import requests
 
 
3
 
4
- API_URL = "https://inge-chalcographic-helene.ngrok-free.dev"
 
 
 
 
 
5
 
6
- def call_api(message):
7
- response = requests.post(f"{API_URL}/api/chat",
8
- json={"messages": [{"role": "user", "content": message}]})
9
- return response.json().get("response", "Error")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
 
11
- with gr.Blocks() as demo:
12
- gr.Markdown("# AI Assistant")
13
- chatbot = gr.Chatbot()
14
- msg_input = gr.Textbox(placeholder="Ask me about code...")
15
- msg_input.submit(lambda m, h: (h + [(m, call_api(m))], ""),
16
- [msg_input, chatbot], [chatbot, msg_input])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
 
18
- demo.launch(server_name="0.0.0.0", server_port=7860, share=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ SuperCoder - Hugging Face Spaces Frontend (FIXED)
3
+ Connects to your local API server via tunnel
4
+ """
5
  import gradio as gr
6
  import requests
7
+ from typing import List, Tuple
8
+ import os
9
 
10
+ # ============================================================================
11
+ # Configuration - YOUR TUNNEL URL
12
+ # ============================================================================
13
+ # The API_URL is pulled from a Space Secret for better security
14
+ API_URL = os.getenv("API_URL", "https://your-tunnel-url.ngrok-free.dev")
15
+ API_URL = API_URL.rstrip('/')
16
 
17
+ # ============================================================================
18
+ # API Client Functions
19
+ # ============================================================================
20
+ def call_api(message: str, temperature: float = 0.1, max_tokens: int = 512) -> str:
21
+ """Call the remote API with error handling"""
22
+ if not message or not message.strip():
23
+ return "⚠️ Please enter a message"
24
+
25
+ try:
26
+ response = requests.post(
27
+ f"{API_URL}/api/chat",
28
+ json={
29
+ "messages": [{"role": "user", "content": message}],
30
+ "temperature": temperature,
31
+ "max_tokens": max_tokens
32
+ },
33
+ timeout=90,
34
+ headers={
35
+ "Content-Type": "application/json",
36
+ "ngrok-skip-browser-warning": "true"
37
+ }
38
+ )
39
+
40
+ if response.status_code == 200:
41
+ result = response.json()
42
+ return result.get("response", "No response from API")
43
+ elif response.status_code == 503:
44
+ return "πŸ”§ Backend service unavailable. Please ensure your local server is running."
45
+ else:
46
+ return f"❌ API Error ({response.status_code}): {response.text[:200]}"
47
+
48
+ except requests.exceptions.Timeout:
49
+ return "⏱️ Request timed out. The model might be processing a complex request or the server is down."
50
+ except requests.exceptions.ConnectionError:
51
+ return f"πŸ”Œ Cannot connect to API at {API_URL}. Please verify:\n1. Local server is running\n2. Tunnel (ngrok/cloudflare) is active\n3. API_URL is correct"
52
+ except Exception as e:
53
+ return f"⚠️ Unexpected error: {str(e)}"
54
 
55
+ def check_api_status() -> str:
56
+ """Check if the API is reachable and healthy"""
57
+ try:
58
+ response = requests.get(
59
+ f"{API_URL}/health",
60
+ timeout=10, # Increased timeout slightly for cold starts
61
+ headers={"ngrok-skip-browser-warning": "true"}
62
+ )
63
+
64
+ if response.status_code == 200:
65
+ data = response.json()
66
+ status = data.get("status", "unknown")
67
+ if status == "ok":
68
+ return "βœ… Connected - Backend Ready"
69
+ else:
70
+ return f"⚠️ Connected but status: {status}"
71
+ else:
72
+ return f"❌ API returned status {response.status_code}"
73
+
74
+ except requests.exceptions.ConnectionError:
75
+ return f"πŸ”΄ Cannot reach {API_URL} - Check tunnel status"
76
+ except requests.exceptions.Timeout:
77
+ return "⏱️ Health check timed out"
78
+ except Exception as e:
79
+ return f"❌ Error: {str(e)}"
80
 
81
+ # ============================================================================
82
+ # Gradio Interface
83
+ # ============================================================================
84
+ def respond(message: str, history: List[Tuple[str, str]], temperature: float, max_tokens: int):
85
+ """Handle chat responses"""
86
+ history.append((message, None))
87
+ yield history # Show user message immediately
88
+
89
+ bot_response = call_api(message, temperature, max_tokens)
90
+ history[-1] = (message, bot_response)
91
+ yield history
92
+
93
+ def apply_template(template: str, history: List[Tuple[str, str]]) -> tuple:
94
+ """Apply a code template"""
95
+ templates = {
96
+ "Explain Code": "Please explain the following code in detail:\n```python\n# Paste your code here\n```",
97
+ "Debug Code": "I have a bug in my code. Can you help me debug it?\n```python\n# Paste your buggy code here\n```",
98
+ "Write Function": "Please write a Python function that: [describe what you need]",
99
+ "Optimize Code": "Can you optimize this code for better performance?\n```python\n# Paste your code here\n```",
100
+ "Add Comments": "Please add clear comments to this code:\n```python\n# Paste your code here\n```"
101
+ }
102
+ return templates.get(template, ""), history
103
+
104
+ # Create the Gradio interface
105
+ with gr.Blocks(
106
+ title="SuperCoder Pro",
107
+ theme=gr.themes.Soft(primary_hue="indigo"),
108
+ css=".gradio-container {max-width: 1200px !important}"
109
+ ) as demo:
110
+
111
+ gr.Markdown(
112
+ """
113
+ # πŸ€– SuperCoder Pro
114
+ ### AI-Powered Coding Assistant
115
+ > **Note:** This interface connects to a local backend via a secure tunnel.
116
+ > Ensure your local server and tunnel are running.
117
+ """
118
+ )
119
+
120
+ # Status bar
121
+ with gr.Row():
122
+ with gr.Column(scale=4):
123
+ # --- FIX ---: Set a static default value here
124
+ status_display = gr.Textbox(
125
+ value="⏳ Initializing...",
126
+ label="πŸ”Œ Backend Status",
127
+ interactive=False,
128
+ show_copy_button=True
129
+ )
130
+ with gr.Column(scale=1):
131
+ refresh_btn = gr.Button("πŸ”„ Refresh Status", size="sm")
132
+
133
+ # Main chat interface
134
+ with gr.Row():
135
+ with gr.Column(scale=3):
136
+ chatbot = gr.Chatbot(
137
+ label="πŸ’¬ Conversation",
138
+ height=500,
139
+ show_copy_button=True,
140
+ avatar_images=(None, "πŸ€–"),
141
+ bubble_full_width=False
142
+ )
143
+
144
+ with gr.Row():
145
+ msg_input = gr.Textbox(
146
+ placeholder="Ask me to write, explain, debug, or review code...",
147
+ scale=5,
148
+ lines=2,
149
+ show_label=False,
150
+ autofocus=True,
151
+ container=False
152
+ )
153
+ send_btn = gr.Button("Send πŸš€", scale=1, variant="primary")
154
+
155
+ # Settings sidebar
156
+ with gr.Column(scale=1):
157
+ gr.Markdown("### βš™οΈ Model Settings")
158
+ temperature = gr.Slider(0.0, 1.0, value=0.1, step=0.05, label="🌑️ Temperature")
159
+ max_tokens = gr.Slider(128, 4096, value=1024, step=128, label="πŸ“ Max Tokens")
160
+
161
+ gr.Markdown("---")
162
+ gr.Markdown("### 🎯 Quick Templates")
163
+ template_dropdown = gr.Dropdown(
164
+ choices=["Explain Code", "Debug Code", "Write Function", "Optimize Code", "Add Comments"],
165
+ label="Select Template",
166
+ value="Explain Code"
167
+ )
168
+ use_template_btn = gr.Button("πŸ“ Use Template", size="sm")
169
+ clear_btn = gr.Button("πŸ—‘οΈ Clear Chat", variant="stop", size="sm")
170
+
171
+ gr.Markdown("---")
172
+ gr.Markdown(f"""### πŸ“‘ Connection Info\n**API Endpoint:**\n`{API_URL}`""")
173
+
174
+ # Event handlers
175
+
176
+ # --- FIX ---: Use the demo.load() event to check status after UI is ready
177
+ demo.load(check_api_status, outputs=[status_display])
178
+
179
+ refresh_btn.click(check_api_status, outputs=[status_display])
180
+
181
+ msg_submit_event = msg_input.submit(
182
+ respond,
183
+ inputs=[msg_input, chatbot, temperature, max_tokens],
184
+ outputs=[chatbot]
185
+ )
186
+ msg_submit_event.then(lambda: gr.update(value=""), outputs=[msg_input])
187
+
188
+ send_btn.click(
189
+ respond,
190
+ inputs=[msg_input, chatbot, temperature, max_tokens],
191
+ outputs=[chatbot]
192
+ ).then(lambda: gr.update(value=""), outputs=[msg_input])
193
+
194
+ use_template_btn.click(apply_template, inputs=[template_dropdown, chatbot], outputs=[msg_input, chatbot])
195
+
196
+ clear_btn.click(lambda: [], outputs=[chatbot])
197
+
198
+ # ============================================================================
199
+ # Launch Configuration for HF Spaces
200
+ # ============================================================================
201
+ if __name__ == "__main__":
202
+ demo.launch(
203
+ server_name="0.0.0.0",
204
+ server_port=7860,
205
+ show_error=True
206
+ )