Spaces:
Sleeping
Sleeping
Download app.py from Aseel17/Data_Analysis: direct link, hf CLI and curl.
- Browser
- Download file 8.17 kB
-
https://huggingface.co/spaces/Aseel17/Data_Analysis/resolve/main/app.py
- Command line
-
hf download hf://spaces/Aseel17/Data_Analysis/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Aseel17/Data_Analysis/resolve/main/app.py
8.17 kB
| import os | |
| import gradio as gr | |
| import sqlite3 | |
| from huggingface_hub import InferenceClient # <-- Import the new client | |
| import json | |
| import re | |
| import pandas as pd | |
| # --- API CLIENT INITIALIZATION --- | |
| # It's best practice to get your token from a secret, not hardcode it. | |
| # In Hugging Face Spaces, you can set a Secret named HF_TOKEN. | |
| # In Google Colab, you can add it to the secrets manager on the left panel. | |
| # Define the model ID and initialize the client | |
| MODEL_ID = "google/gemma-2-2b-it" | |
| HF_TOKEN = os.getenv("HF_TOKEN") | |
| if not HF_TOKEN: | |
| raise ValueError("Hugging Face API token not found. Please set the HF_TOKEN secret.") | |
| client = InferenceClient(model=MODEL_ID, token=HF_TOKEN) | |
| # --- DATABASE CONNECTION --- | |
| DB_PATH = "data.db" # <-- Important: Use the relative path for HF Spaces | |
| # --- SYSTEM PROMPT --- | |
| system_prompt = '''You are an AI assistant for database interaction. Your primary job is to generate JSON responses based on user requests. | |
| There are two types of tasks: | |
| 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". | |
| - Example User Input: "show me the names and departments for all granted patents" | |
| - Your Output: { "intent": "fetch_data", "message": "SELECT faculty_name, department FROM patents WHERE granted = 'Granted'" } | |
| 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 *`). | |
| - Example User Input: "How many patents were granted per department?" | |
| - Your Output: { "intent": "analyse_data", "message": "SELECT * FROM patents" } | |
| **IMPORTANT**: For analysis, in the second call, you must provide a concise, natural language answer. Do not output JSON in the second step. | |
| Database Schema: | |
| - `patents` table columns: `department`, `patent_title`, `application_number`, `faculty_name`, `granted`, `status`, `date` | |
| - `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` | |
| Strictly adhere to the JSON format: `{"intent": "intent_name", "message": "SQL_query"}`. | |
| ''' | |
| # --- CORE FUNCTIONS --- | |
| def get_llm_response(prompt): | |
| """ | |
| Generates a response from the Hugging Face Inference API. | |
| """ | |
| messages = [{"role": "user", "content": prompt}] | |
| try: | |
| response = client.chat_completion( | |
| messages=messages, max_tokens=350, temperature=0.7, stream=False | |
| ) | |
| reply = response.choices[0].message.content | |
| print(f"API Clean Reply: {repr(reply)}") | |
| return reply | |
| except Exception as e: | |
| print(f"Error calling Inference API: {e}") | |
| return f"Sorry, there was an error with the inference provider: {e}" | |
| def clean_and_parse_json(model_reply): | |
| """ | |
| Cleans markdown code blocks and parses the JSON string. | |
| """ | |
| match = re.search(r'\{.*\}', model_reply, re.DOTALL) | |
| if not match: | |
| print("Error: No JSON object found in the model's reply.") | |
| return None | |
| json_string = match.group(0) | |
| try: | |
| return json.loads(json_string) | |
| except json.JSONDecodeError as e: | |
| print(f"Error: Failed to decode JSON. String was: '{json_string}'. Error: {e}") | |
| return None | |
| def execute_sql(sql_command): | |
| """ | |
| Executes a SQL query and returns a pandas DataFrame. | |
| """ | |
| try: | |
| with sqlite3.connect(DB_PATH) as conn: | |
| df = pd.read_sql_query(sql_command, conn) | |
| return df | |
| except (sqlite3.OperationalError, pd.io.sql.DatabaseError) as e: | |
| print(f"SQL Execution Error: {e}") | |
| return f"Error executing SQL: {e}" | |
| # --- GRADIO INTERFACE AND LOGIC --- | |
| # (This part of the code remains exactly the same) | |
| with gr.Blocks(theme=gr.themes.Soft(), title="Database Chatbot") as demo: | |
| gr.Markdown("## 💬 Chatbot for Database Query and Analysis") | |
| gr.Markdown("Ask questions about patents or publications. You can ask for specific data or for high-level analysis.") | |
| chatbot = gr.Chatbot(label="Chat History", height=500, type='messages') | |
| user_msg = gr.Textbox( | |
| label="Enter your query here", | |
| placeholder="e.g., 'Analyze the publications data' or 'Fetch all patents from the CS department'", | |
| ) | |
| send_btn = gr.Button("▶️ Send") | |
| with gr.Accordion("Query Output and Download", open=True): | |
| output_df = gr.Dataframe(label="Query Result Table", wrap=True) | |
| download_btn = gr.File(label="Download Data as CSV", file_count="single") | |
| gr.Examples( | |
| examples=[ | |
| "Fetch all data from the patents table", | |
| "What is the status of patents from the 'Electronics' department?", | |
| "Analyze the patents data", | |
| "Summarize the publications based on journal type" | |
| ], | |
| inputs=user_msg | |
| ) | |
| def respond(message, chat_history): | |
| chat_history.append({"role": "user", "content": message}) | |
| # The prompt now includes the full system message each time for stateless API calls | |
| 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" | |
| initial_reply = get_llm_response(full_prompt) | |
| parsed_json = clean_and_parse_json(initial_reply) | |
| if not parsed_json: | |
| error_message = initial_reply # Show the raw error from the API | |
| chat_history.append({"role": "assistant", "content": error_message}) | |
| return chat_history, pd.DataFrame(), None | |
| intent = parsed_json.get("intent") | |
| sql_command = parsed_json.get("message") | |
| if intent == "fetch_data": | |
| df = execute_sql(sql_command) | |
| if isinstance(df, str): | |
| chat_history.append({"role": "assistant", "content": df}) | |
| return chat_history, pd.DataFrame(), None | |
| bot_message = "Here is the data you requested. It is displayed in the table below." | |
| chat_history.append({"role": "assistant", "content": bot_message}) | |
| csv_path = "output.csv" | |
| df.to_csv(csv_path, index=False) | |
| return chat_history, df, gr.File(value=csv_path, visible=True) | |
| elif intent == "analyse_data": | |
| bot_message = "Starting analysis... First, I need to fetch the relevant data." | |
| chat_history.append({"role": "assistant", "content": bot_message}) | |
| df = execute_sql(sql_command) | |
| if isinstance(df, str): | |
| chat_history[-1] = {"role": "assistant", "content": df} | |
| return chat_history, pd.DataFrame(), None | |
| data_json = df.to_json(orient='records') | |
| analysis_prompt = f"""<start_of_turn>system | |
| You are a data analyst. Your task is to answer the user's question based on the JSON data provided. | |
| Provide a concise, easy-to-read, natural language summary. Do not output JSON. Use markdown for formatting if needed. | |
| <end_of_turn> | |
| <start_of_turn>user | |
| Original Question: "{message}" | |
| Data: | |
| {data_json} | |
| <end_of_turn> | |
| <start_of_turn>assistant | |
| """ | |
| final_analysis = get_llm_response(analysis_prompt) | |
| chat_history[-1] = {"role": "assistant", "content": final_analysis} | |
| csv_path = "analysis_data.csv" | |
| df.to_csv(csv_path, index=False) | |
| return chat_history, df, gr.File(value=csv_path, visible=True) | |
| else: | |
| error_message = f"Received an unknown intent: '{intent}'. Please try again." | |
| chat_history.append({"role": "assistant", "content": error_message}) | |
| return chat_history, pd.DataFrame(), None | |
| send_btn.click(fn=respond, inputs=[user_msg, chatbot], outputs=[chatbot, output_df, download_btn]) | |
| user_msg.submit(fn=respond, inputs=[user_msg, chatbot], outputs=[chatbot, output_df, download_btn]) | |
| if __name__ == "__main__": | |
| demo.launch(debug=True) |