Kashif17 commited on
Commit
884da84
·
verified ·
1 Parent(s): 02494f8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +68 -48
app.py CHANGED
@@ -1,63 +1,83 @@
1
  import gradio as gr
2
  from huggingface_hub import InferenceClient
 
 
 
 
3
 
4
- """
5
- 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
6
- """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
8
 
 
 
9
 
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
19
-
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
25
-
26
- messages.append({"role": "user", "content": message})
27
 
 
 
 
28
  response = ""
29
-
30
  for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
  stream=True,
34
- temperature=temperature,
35
- top_p=top_p,
36
  ):
37
  token = message.choices[0].delta.content
38
-
39
  response += token
40
- yield response
41
-
42
- """
43
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
44
- """
45
- demo = gr.ChatInterface(
46
- respond,
47
- additional_inputs=[
48
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
49
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
50
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
51
- gr.Slider(
52
- minimum=0.1,
53
- maximum=1.0,
54
- value=0.95,
55
- step=0.05,
56
- label="Top-p (nucleus sampling)",
57
- ),
58
- ],
59
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60
 
 
61
 
62
  if __name__ == "__main__":
63
- demo.launch()
 
 
1
  import gradio as gr
2
  from huggingface_hub import InferenceClient
3
+ import pandas as pd
4
+ import matplotlib.pyplot as plt
5
+ import io
6
+ import sqlite3
7
 
8
+ # Initialize the InferenceClient with the specified model
9
+ client = InferenceClient(model="HuggingFaceH4/zephyr-7b-beta")
 
 
10
 
11
+ # Specify the path to your CSV file here
12
+ csv_file_path = 'Movies.csv'
13
 
14
+ # Load dataset into a dataframe
15
+ df = pd.read_csv(csv_file_path)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
 
17
+ # Function to generate SQL queries
18
+ def generate_sql_query(prompt, table_metadata):
19
+ input_text = f"Generate an SQL query for the table with the following structure: {table_metadata}. Prompt: {prompt}"
20
  response = ""
 
21
  for message in client.chat_completion(
22
+ messages=[{"role": "system", "content": input_text}],
23
+ max_tokens=512,
24
  stream=True,
25
+ temperature=0.7,
26
+ top_p=0.95,
27
  ):
28
  token = message.choices[0].delta.content
 
29
  response += token
30
+ return response
31
+
32
+ # Function to execute SQL query on the dataframe
33
+ def execute_query(df, query):
34
+ try:
35
+ with sqlite3.connect(':memory:') as conn:
36
+ df.to_sql('data', conn, index=False, if_exists='replace')
37
+ result_df = pd.read_sql_query(query, conn)
38
+ return result_df
39
+ except Exception as e:
40
+ return str(e)
41
+
42
+ # Function to create a plot from the result dataframe
43
+ def create_plot(df):
44
+ fig, ax = plt.subplots()
45
+ df.plot(ax=ax)
46
+ buf = io.BytesIO()
47
+ plt.savefig(buf, format='png')
48
+ buf.seek(0)
49
+ return buf
50
+
51
+ # Gradio function to handle user input and interaction
52
+ def respond(user_prompt, system_message, max_tokens, temperature, top_p):
53
+ table_metadata = str(df.dtypes.to_dict())
54
+ sql_query = generate_sql_query(user_prompt, table_metadata)
55
+ result_df = execute_query(df, sql_query)
56
+
57
+ if isinstance(result_df, str):
58
+ return sql_query, result_df, None # Return the error message
59
+
60
+ plot = create_plot(result_df)
61
+ return sql_query, result_df.head().to_html(), plot
62
+
63
+ # Gradio UI components
64
+ def create_demo():
65
+ with gr.Blocks() as demo:
66
+ user_prompt = gr.Textbox(lines=2, placeholder="Enter your prompt here...", label="User Prompt")
67
+ system_message = gr.Textbox(value="You are an AI assistant that generates SQL queries based on user prompts.", label="System message")
68
+ max_tokens = gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens")
69
+ temperature = gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature")
70
+ top_p = gr.Slider(minimum=0.1, maximum=1.0, value=0.95, step=0.05, label="Top-p (nucleus sampling)")
71
+
72
+ output_sql_query = gr.Textbox(label="Generated SQL Query")
73
+ output_result_df = gr.HTML(label="Query Result")
74
+ output_plot = gr.Image(label="Result Plot")
75
+
76
+ submit_btn = gr.Button("Submit")
77
+ submit_btn.click(respond, inputs=[user_prompt, system_message, max_tokens, temperature, top_p], outputs=[output_sql_query, output_result_df, output_plot])
78
 
79
+ return demo
80
 
81
  if __name__ == "__main__":
82
+ demo = create_demo()
83
+ demo.launch()