Kai Izumoto commited on
Commit
989deb5
·
verified ·
1 Parent(s): 6378730

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +12 -255
app.py CHANGED
@@ -1,261 +1,18 @@
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, Optional
8
- import os
9
 
10
- # ============================================================================
11
- # Configuration - YOUR TUNNEL URL
12
- # ============================================================================
13
- API_URL = os.getenv("API_URL", "https://inge-chalcographic-helene.ngrok-free.dev")
14
 
15
- # Remove trailing slash if present
16
- API_URL = API_URL.rstrip('/')
 
 
17
 
18
- # ============================================================================
19
- # API Client Functions
20
- # ============================================================================
21
- def call_api(message: str, temperature: float = 0.1, max_tokens: int = 512) -> str:
22
- """Call the remote API with error handling"""
23
- if not message or not message.strip():
24
- return "⚠️ Please enter a message"
25
-
26
- try:
27
- response = requests.post(
28
- f"{API_URL}/api/chat",
29
- json={
30
- "messages": [{"role": "user", "content": message}],
31
- "temperature": temperature,
32
- "max_tokens": max_tokens
33
- },
34
- timeout=90,
35
- headers={
36
- "Content-Type": "application/json",
37
- "ngrok-skip-browser-warning": "true" # Skip ngrok warning page
38
- }
39
- )
40
-
41
- if response.status_code == 200:
42
- result = response.json()
43
- return result.get("response", "No response from API")
44
- elif response.status_code == 503:
45
- return "🔧 Backend service unavailable. Please ensure your local server is running."
46
- else:
47
- return f"❌ API Error ({response.status_code}): {response.text[:200]}"
48
-
49
- except requests.exceptions.Timeout:
50
- return "⏱️ Request timed out. The model might be processing a complex request or the server is down."
51
- except requests.exceptions.ConnectionError:
52
- 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"
53
- except Exception as e:
54
- return f"⚠️ Unexpected error: {str(e)}"
55
 
56
- def check_api_status() -> str:
57
- """Check if the API is reachable and healthy"""
58
- try:
59
- response = requests.get(
60
- f"{API_URL}/health",
61
- timeout=5,
62
- headers={"ngrok-skip-browser-warning": "true"}
63
- )
64
-
65
- if response.status_code == 200:
66
- data = response.json()
67
- status = data.get("status", "unknown")
68
- if status == "ok":
69
- return "✅ Connected - Backend Ready"
70
- else:
71
- return f"⚠️ Connected but status: {status}"
72
- else:
73
- return f"❌ API returned status {response.status_code}"
74
-
75
- except requests.exceptions.ConnectionError:
76
- return f"🔴 Cannot reach {API_URL} - Check tunnel status"
77
- except requests.exceptions.Timeout:
78
- return "⏱️ Health check timed out"
79
- except Exception as e:
80
- return f"❌ Error: {str(e)}"
81
-
82
- # ============================================================================
83
- # Gradio Interface
84
- # ============================================================================
85
- def respond(message: str, history: List[Tuple[str, str]], temperature: float, max_tokens: int):
86
- """Handle chat responses"""
87
- if not message.strip():
88
- return history
89
-
90
- # Add user message
91
- history.append((message, None))
92
-
93
- # Get bot response
94
- bot_response = call_api(message, temperature, max_tokens)
95
-
96
- # Update with bot response
97
- history[-1] = (message, bot_response)
98
-
99
- return history
100
-
101
- def apply_template(template: str, history: List[Tuple[str, str]]) -> tuple:
102
- """Apply a code template"""
103
- templates = {
104
- "Explain Code": "Please explain the following code in detail:\n```\n# Paste your code here\n```",
105
- "Debug Code": "I have a bug in my code. Can you help me debug it?\n```\n# Paste your buggy code here\n```",
106
- "Write Function": "Please write a function that: [describe what you need]",
107
- "Optimize Code": "Can you optimize this code for better performance?\n```\n# Paste your code here\n```",
108
- "Add Comments": "Please add clear comments to this code:\n```\n# Paste your code here\n```"
109
- }
110
- return templates.get(template, ""), history
111
-
112
- # Create the Gradio interface
113
- with gr.Blocks(
114
- title="SuperCoder Pro",
115
- theme=gr.themes.Soft(primary_hue="indigo"),
116
- css=".gradio-container {max-width: 1200px !important}"
117
- ) as demo:
118
-
119
- gr.Markdown(
120
- """
121
- # 🤖 SuperCoder Pro
122
- ### AI-Powered Coding Assistant
123
-
124
- > **Note:** This interface connects to a local backend via tunnel.
125
- > Make sure your local server is running with `python supercoder.py --mode api --tunnel ngrok`
126
- """
127
- )
128
-
129
- # Status bar
130
- with gr.Row():
131
- with gr.Column(scale=4):
132
- status_display = gr.Textbox(
133
- value=check_api_status(),
134
- label="🔌 Backend Status",
135
- interactive=False,
136
- show_copy_button=True
137
- )
138
- with gr.Column(scale=1):
139
- refresh_btn = gr.Button("🔄 Refresh", size="sm", variant="secondary")
140
-
141
- # Main chat interface
142
- with gr.Row():
143
- with gr.Column(scale=3):
144
- chatbot = gr.Chatbot(
145
- label="💬 Conversation",
146
- height=500,
147
- show_copy_button=True,
148
- avatar_images=(None, "🤖")
149
- )
150
-
151
- with gr.Row():
152
- msg_input = gr.Textbox(
153
- placeholder="Ask me to write, explain, debug, or review code...",
154
- scale=5,
155
- lines=2,
156
- show_label=False,
157
- autofocus=True
158
- )
159
- send_btn = gr.Button("Send 🚀", scale=1, variant="primary")
160
-
161
- # Settings sidebar
162
- with gr.Column(scale=1):
163
- gr.Markdown("### ⚙️ Model Settings")
164
-
165
- temperature = gr.Slider(
166
- minimum=0.0,
167
- maximum=1.0,
168
- value=0.1,
169
- step=0.05,
170
- label="🌡️ Temperature",
171
- info="Lower = more focused, Higher = more creative"
172
- )
173
-
174
- max_tokens = gr.Slider(
175
- minimum=128,
176
- maximum=2048,
177
- value=512,
178
- step=128,
179
- label="📏 Max Tokens",
180
- info="Maximum response length"
181
- )
182
-
183
- gr.Markdown("---")
184
- gr.Markdown("### 🎯 Quick Templates")
185
-
186
- template_dropdown = gr.Dropdown(
187
- choices=[
188
- "Explain Code",
189
- "Debug Code",
190
- "Write Function",
191
- "Optimize Code",
192
- "Add Comments"
193
- ],
194
- label="Select Template",
195
- value="Explain Code"
196
- )
197
-
198
- use_template_btn = gr.Button("📝 Use Template", size="sm", variant="secondary")
199
-
200
- gr.Markdown("---")
201
-
202
- clear_btn = gr.Button("🗑️ Clear Chat", variant="stop", size="sm")
203
-
204
- gr.Markdown("---")
205
- gr.Markdown(
206
- f"""
207
- ### 📡 Connection Info
208
- **API Endpoint:**
209
- `{API_URL}`
210
-
211
- **Tunnel Status:**
212
- Check status above ⬆️
213
- """
214
- )
215
-
216
- # Event handlers
217
- msg_input.submit(
218
- respond,
219
- inputs=[msg_input, chatbot, temperature, max_tokens],
220
- outputs=[chatbot]
221
- ).then(
222
- lambda: "",
223
- outputs=[msg_input]
224
- )
225
-
226
- send_btn.click(
227
- respond,
228
- inputs=[msg_input, chatbot, temperature, max_tokens],
229
- outputs=[chatbot]
230
- ).then(
231
- lambda: "",
232
- outputs=[msg_input]
233
- )
234
-
235
- refresh_btn.click(
236
- check_api_status,
237
- outputs=[status_display]
238
- )
239
-
240
- use_template_btn.click(
241
- apply_template,
242
- inputs=[template_dropdown, chatbot],
243
- outputs=[msg_input, chatbot]
244
- )
245
-
246
- clear_btn.click(
247
- lambda: [],
248
- outputs=[chatbot]
249
- )
250
-
251
- # ============================================================================
252
- # Launch Configuration for HF Spaces
253
- # ============================================================================
254
- if __name__ == "__main__":
255
- demo.launch(
256
- server_name="0.0.0.0", # Required for HF Spaces
257
- server_port=7860, # Required for HF Spaces
258
- show_error=True,
259
- show_api=False,
260
- share=False # Don't create gradio.live share link
261
- )
 
 
 
 
 
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)