Shreyass334 commited on
Commit
3e26011
Β·
verified Β·
1 Parent(s): c13186a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +113 -62
app.py CHANGED
@@ -1,70 +1,121 @@
 
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
 
 
 
3
 
 
 
 
4
 
5
- def respond(
6
- message,
7
- history: list[dict[str, str]],
8
- system_message,
9
- max_tokens,
10
- temperature,
11
- top_p,
12
- hf_token: gr.OAuthToken,
13
- ):
14
- """
15
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
16
- """
17
- client = InferenceClient(token=hf_token.token, model="openai/gpt-oss-20b")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
 
19
- messages = [{"role": "system", "content": system_message}]
20
-
21
- messages.extend(history)
22
-
23
- messages.append({"role": "user", "content": message})
24
-
25
- response = ""
26
-
27
- for message in client.chat_completion(
28
- messages,
29
- max_tokens=max_tokens,
30
- stream=True,
31
- temperature=temperature,
32
- top_p=top_p,
33
- ):
34
- choices = message.choices
35
- token = ""
36
- if len(choices) and choices[0].delta.content:
37
- token = choices[0].delta.content
38
-
39
- response += token
40
- yield response
41
-
42
-
43
- """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- chatbot = gr.ChatInterface(
47
- respond,
48
- type="messages",
49
- additional_inputs=[
50
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
51
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
52
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
53
- gr.Slider(
54
- minimum=0.1,
55
- maximum=1.0,
56
- value=0.95,
57
- step=0.05,
58
- label="Top-p (nucleus sampling)",
59
- ),
60
- ],
61
  )
62
 
63
- with gr.Blocks() as demo:
64
- with gr.Sidebar():
65
- gr.LoginButton()
66
- chatbot.render()
67
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68
 
 
69
  if __name__ == "__main__":
70
- demo.launch()
 
1
+ # app.py
2
  import gradio as gr
3
+ import requests
4
+ import pandas as pd
5
+ import base64
6
+ from io import BytesIO
7
 
8
+ # πŸ”§ CONFIGURE: Replace with your EC2 public IP
9
+ API_URL = "http://<your-ec2-public-ip>:5000/ask"
10
+ # Example: "http://3.8.123.45:5000/ask"
11
 
12
+ def query_database(question):
13
+ if not question.strip():
14
+ return "", None, None, "Please enter a question."
15
+
16
+ try:
17
+ response = requests.post(API_URL, json={"question": question}, timeout=30)
18
+ result = response.json()
19
+
20
+ if "error" in result:
21
+ return "", None, None, f"❌ {result['error']}"
22
+
23
+ sql = result.get("sql", "N/A")
24
+ rows = result.get("result", [])
25
+ chart_data = result.get("chart") # base64 PNG
26
+
27
+ df = pd.DataFrame(rows) if rows else pd.DataFrame()
28
+
29
+ # Decode chart
30
+ chart_image = None
31
+ if chart_data:
32
+ image_bytes = base64.b64decode(chart_data)
33
+ chart_image = BytesIO(image_bytes)
34
+
35
+ return sql, df, chart_image, ""
36
+
37
+ except requests.exceptions.ConnectionError:
38
+ return "", None, None, "❌ Connection failed. Is your API running?"
39
+ except requests.exceptions.Timeout:
40
+ return "", None, None, "⏱️ Request timed out. Try a simpler question."
41
+ except Exception as e:
42
+ return "", None, None, f"🚨 Unexpected error: {str(e)}"
43
 
44
+ # 🎨 Theme: Enterprise Dark Blue
45
+ theme = gr.themes.Default(
46
+ primary_hue="blue",
47
+ secondary_hue="gray",
48
+ neutral_hue="slate",
49
+ font=["Inter", "sans-serif"]
50
+ ).set(
51
+ body_background_fill="*neutral_950",
52
+ background_fill_secondary="*neutral_900"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53
  )
54
 
55
+ # πŸš€ UI Layout
56
+ with gr.Blocks(theme=theme, title="Enterprise SQL Assistant") as demo:
57
+ gr.HTML("""
58
+ <div style="text-align: center; padding: 20px;">
59
+ <h1 style="color: #3B82F6;">πŸ“Š Enterprise SQL Assistant</h1>
60
+ <p style="color: #9CA3AF; font-size: 1.1em;">
61
+ Ask questions about your data. Get SQL, results, and insights.
62
+ </p>
63
+ </div>
64
+ """)
65
+
66
+ with gr.Row():
67
+ with gr.Column(scale=1):
68
+ gr.Markdown("### πŸ” Ask a Question")
69
+ question_input = gr.Textbox(
70
+ placeholder="E.g., How many members are there?",
71
+ label="Natural Language Query",
72
+ lines=3
73
+ )
74
+ submit_btn = gr.Button("πŸš€ Generate SQL & Results", variant="primary")
75
+
76
+ gr.Markdown("### πŸ’‘ Example Queries")
77
+ gr.Examples(
78
+ examples=[
79
+ ["How many members are there?"],
80
+ ["What is the total transaction amount?"],
81
+ ["Show members with their account balances"],
82
+ ["Which member has the highest balance?"],
83
+ ["Show transaction trends over time"]
84
+ ],
85
+ inputs=question_input,
86
+ label=""
87
+ )
88
+
89
+ with gr.Column(scale=2):
90
+ gr.Markdown("### πŸ“„ Results")
91
+ status = gr.Textbox(label="Status", interactive=False)
92
+
93
+ with gr.Tabs():
94
+ with gr.Tab("SQL Query"):
95
+ sql_output = gr.Code(label="", language="sql")
96
+
97
+ with gr.Tab("Data Results"):
98
+ results_output = gr.Dataframe(
99
+ label="Query Results",
100
+ interactive=False,
101
+ wrap=True
102
+ )
103
+
104
+ with gr.Tab("Visual Insights"):
105
+ chart_output = gr.Image(
106
+ label="Chart",
107
+ type="pil",
108
+ height=400,
109
+ elem_classes="chart-container"
110
+ )
111
+
112
+ # Events
113
+ submit_btn.click(
114
+ fn=query_database,
115
+ inputs=question_input,
116
+ outputs=[sql_output, results_output, chart_output, status]
117
+ )
118
 
119
+ # Launch
120
  if __name__ == "__main__":
121
+ demo.launch()