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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import gradio as gr
|
| 3 |
+
import sqlite3
|
| 4 |
+
from huggingface_hub import InferenceClient # <-- Import the new client
|
| 5 |
+
import json
|
| 6 |
+
import re
|
| 7 |
+
import pandas as pd
|
| 8 |
+
|
| 9 |
+
# --- API CLIENT INITIALIZATION ---
|
| 10 |
+
# It's best practice to get your token from a secret, not hardcode it.
|
| 11 |
+
# In Hugging Face Spaces, you can set a Secret named HF_TOKEN.
|
| 12 |
+
# In Google Colab, you can add it to the secrets manager on the left panel.
|
| 13 |
+
|
| 14 |
+
# Define the model ID and initialize the client
|
| 15 |
+
MODEL_ID = "google/gemma-2-2b-it"
|
| 16 |
+
HF_TOKEN = os.getenv("HF_TOKEN")
|
| 17 |
+
if not HF_TOKEN:
|
| 18 |
+
raise ValueError("Hugging Face API token not found. Please set the HF_TOKEN secret.")
|
| 19 |
+
client = InferenceClient(model=MODEL_ID, token=HF_TOKEN)
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
# --- DATABASE CONNECTION ---
|
| 23 |
+
DB_PATH = "data.db" # <-- Important: Use the relative path for HF Spaces
|
| 24 |
+
|
| 25 |
+
# --- SYSTEM PROMPT ---
|
| 26 |
+
system_prompt = '''You are an AI assistant for database interaction. Your primary job is to generate JSON responses based on user requests.
|
| 27 |
+
There are two types of tasks:
|
| 28 |
+
1. **Data Fetching**: If the user asks to "get", "fetch", "show", or "extract" specific data, generate a JSON object with the intent "fetch_data" and a precise SQL query in the "message".
|
| 29 |
+
- Example User Input: "show me the names and departments for all granted patents"
|
| 30 |
+
- Your Output: { "intent": "fetch_data", "message": "SELECT faculty_name, department FROM patents WHERE granted = 'Granted'" }
|
| 31 |
+
2. **Data Analysis**: If the user asks to "analyze", "summarize", "count", or asks a general question, your FIRST response must be a JSON object with intent "analyse_data" and a SQL query to select all relevant columns (`SELECT *`).
|
| 32 |
+
- Example User Input: "How many patents were granted per department?"
|
| 33 |
+
- Your Output: { "intent": "analyse_data", "message": "SELECT * FROM patents" }
|
| 34 |
+
**IMPORTANT**: For analysis, in the second call, you must provide a concise, natural language answer. Do not output JSON in the second step.
|
| 35 |
+
Database Schema:
|
| 36 |
+
- `patents` table columns: `department`, `patent_title`, `application_number`, `faculty_name`, `granted`, `status`, `date`
|
| 37 |
+
- `publications` table columns: `faculty_name`, `manuscript_title`, `journal_type`, `journal_title`, `volume`, `issue_no`, `page_no`, `publication_date`, `index_info`, `h_index`, `impact_factor`, `quartile`
|
| 38 |
+
Strictly adhere to the JSON format: `{"intent": "intent_name", "message": "SQL_query"}`.
|
| 39 |
+
'''
|
| 40 |
+
|
| 41 |
+
# --- CORE FUNCTIONS ---
|
| 42 |
+
def get_llm_response(prompt):
|
| 43 |
+
"""
|
| 44 |
+
Generates a response from the Hugging Face Inference API.
|
| 45 |
+
"""
|
| 46 |
+
messages = [{"role": "user", "content": prompt}]
|
| 47 |
+
try:
|
| 48 |
+
response = client.chat_completion(
|
| 49 |
+
messages=messages, max_tokens=350, temperature=0.7, stream=False
|
| 50 |
+
)
|
| 51 |
+
reply = response.choices[0].message.content
|
| 52 |
+
print(f"API Clean Reply: {repr(reply)}")
|
| 53 |
+
return reply
|
| 54 |
+
except Exception as e:
|
| 55 |
+
print(f"Error calling Inference API: {e}")
|
| 56 |
+
return f"Sorry, there was an error with the inference provider: {e}"
|
| 57 |
+
|
| 58 |
+
def clean_and_parse_json(model_reply):
|
| 59 |
+
"""
|
| 60 |
+
Cleans markdown code blocks and parses the JSON string.
|
| 61 |
+
"""
|
| 62 |
+
match = re.search(r'\{.*\}', model_reply, re.DOTALL)
|
| 63 |
+
if not match:
|
| 64 |
+
print("Error: No JSON object found in the model's reply.")
|
| 65 |
+
return None
|
| 66 |
+
json_string = match.group(0)
|
| 67 |
+
try:
|
| 68 |
+
return json.loads(json_string)
|
| 69 |
+
except json.JSONDecodeError as e:
|
| 70 |
+
print(f"Error: Failed to decode JSON. String was: '{json_string}'. Error: {e}")
|
| 71 |
+
return None
|
| 72 |
+
|
| 73 |
+
def execute_sql(sql_command):
|
| 74 |
+
"""
|
| 75 |
+
Executes a SQL query and returns a pandas DataFrame.
|
| 76 |
+
"""
|
| 77 |
+
try:
|
| 78 |
+
with sqlite3.connect(DB_PATH) as conn:
|
| 79 |
+
df = pd.read_sql_query(sql_command, conn)
|
| 80 |
+
return df
|
| 81 |
+
except (sqlite3.OperationalError, pd.io.sql.DatabaseError) as e:
|
| 82 |
+
print(f"SQL Execution Error: {e}")
|
| 83 |
+
return f"Error executing SQL: {e}"
|
| 84 |
+
|
| 85 |
+
# --- GRADIO INTERFACE AND LOGIC ---
|
| 86 |
+
# (This part of the code remains exactly the same)
|
| 87 |
+
with gr.Blocks(theme=gr.themes.Soft(), title="Database Chatbot") as demo:
|
| 88 |
+
gr.Markdown("## 💬 Chatbot for Database Query and Analysis")
|
| 89 |
+
gr.Markdown("Ask questions about patents or publications. You can ask for specific data or for high-level analysis.")
|
| 90 |
+
|
| 91 |
+
chatbot = gr.Chatbot(label="Chat History", height=500, type='messages')
|
| 92 |
+
user_msg = gr.Textbox(
|
| 93 |
+
label="Enter your query here",
|
| 94 |
+
placeholder="e.g., 'Analyze the publications data' or 'Fetch all patents from the CS department'",
|
| 95 |
+
)
|
| 96 |
+
send_btn = gr.Button("▶️ Send")
|
| 97 |
+
|
| 98 |
+
with gr.Accordion("Query Output and Download", open=True):
|
| 99 |
+
output_df = gr.Dataframe(label="Query Result Table", wrap=True)
|
| 100 |
+
download_btn = gr.File(label="Download Data as CSV", file_count="single")
|
| 101 |
+
|
| 102 |
+
gr.Examples(
|
| 103 |
+
examples=[
|
| 104 |
+
"Fetch all data from the patents table",
|
| 105 |
+
"What is the status of patents from the 'Electronics' department?",
|
| 106 |
+
"Analyze the patents data",
|
| 107 |
+
"Summarize the publications based on journal type"
|
| 108 |
+
],
|
| 109 |
+
inputs=user_msg
|
| 110 |
+
)
|
| 111 |
+
|
| 112 |
+
def respond(message, chat_history):
|
| 113 |
+
chat_history.append({"role": "user", "content": message})
|
| 114 |
+
|
| 115 |
+
# The prompt now includes the full system message each time for stateless API calls
|
| 116 |
+
full_prompt = f"<start_of_turn>system\n{system_prompt}<end_of_turn>\n<start_of_turn>user\n{message}<end_of_turn>\n<start_of_turn>assistant\n"
|
| 117 |
+
|
| 118 |
+
initial_reply = get_llm_response(full_prompt)
|
| 119 |
+
parsed_json = clean_and_parse_json(initial_reply)
|
| 120 |
+
|
| 121 |
+
if not parsed_json:
|
| 122 |
+
error_message = initial_reply # Show the raw error from the API
|
| 123 |
+
chat_history.append({"role": "assistant", "content": error_message})
|
| 124 |
+
return chat_history, pd.DataFrame(), None
|
| 125 |
+
|
| 126 |
+
intent = parsed_json.get("intent")
|
| 127 |
+
sql_command = parsed_json.get("message")
|
| 128 |
+
|
| 129 |
+
if intent == "fetch_data":
|
| 130 |
+
df = execute_sql(sql_command)
|
| 131 |
+
if isinstance(df, str):
|
| 132 |
+
chat_history.append({"role": "assistant", "content": df})
|
| 133 |
+
return chat_history, pd.DataFrame(), None
|
| 134 |
+
|
| 135 |
+
bot_message = "Here is the data you requested. It is displayed in the table below."
|
| 136 |
+
chat_history.append({"role": "assistant", "content": bot_message})
|
| 137 |
+
csv_path = "output.csv"
|
| 138 |
+
df.to_csv(csv_path, index=False)
|
| 139 |
+
return chat_history, df, gr.File(value=csv_path, visible=True)
|
| 140 |
+
|
| 141 |
+
elif intent == "analyse_data":
|
| 142 |
+
bot_message = "Starting analysis... First, I need to fetch the relevant data."
|
| 143 |
+
chat_history.append({"role": "assistant", "content": bot_message})
|
| 144 |
+
|
| 145 |
+
df = execute_sql(sql_command)
|
| 146 |
+
if isinstance(df, str):
|
| 147 |
+
chat_history[-1] = {"role": "assistant", "content": df}
|
| 148 |
+
return chat_history, pd.DataFrame(), None
|
| 149 |
+
|
| 150 |
+
data_json = df.to_json(orient='records')
|
| 151 |
+
analysis_prompt = f"""<start_of_turn>system
|
| 152 |
+
You are a data analyst. Your task is to answer the user's question based on the JSON data provided.
|
| 153 |
+
Provide a concise, easy-to-read, natural language summary. Do not output JSON. Use markdown for formatting if needed.
|
| 154 |
+
<end_of_turn>
|
| 155 |
+
<start_of_turn>user
|
| 156 |
+
Original Question: "{message}"
|
| 157 |
+
|
| 158 |
+
Data:
|
| 159 |
+
{data_json}
|
| 160 |
+
<end_of_turn>
|
| 161 |
+
<start_of_turn>assistant
|
| 162 |
+
"""
|
| 163 |
+
final_analysis = get_llm_response(analysis_prompt)
|
| 164 |
+
chat_history[-1] = {"role": "assistant", "content": final_analysis}
|
| 165 |
+
|
| 166 |
+
csv_path = "analysis_data.csv"
|
| 167 |
+
df.to_csv(csv_path, index=False)
|
| 168 |
+
return chat_history, df, gr.File(value=csv_path, visible=True)
|
| 169 |
+
|
| 170 |
+
else:
|
| 171 |
+
error_message = f"Received an unknown intent: '{intent}'. Please try again."
|
| 172 |
+
chat_history.append({"role": "assistant", "content": error_message})
|
| 173 |
+
return chat_history, pd.DataFrame(), None
|
| 174 |
+
|
| 175 |
+
send_btn.click(fn=respond, inputs=[user_msg, chatbot], outputs=[chatbot, output_df, download_btn])
|
| 176 |
+
user_msg.submit(fn=respond, inputs=[user_msg, chatbot], outputs=[chatbot, output_df, download_btn])
|
| 177 |
+
|
| 178 |
+
if __name__ == "__main__":
|
| 179 |
+
demo.launch(debug=True)
|
data.db
ADDED
|
Binary file (20.5 kB). View file
|
|
|
requirements.txt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gradio
|
| 2 |
+
pandas
|
| 3 |
+
huggingface_hub
|