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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
)
|