Delete app.py
Browse files
app.py
DELETED
|
@@ -1,279 +0,0 @@
|
|
| 1 |
-
# --- PYTHON 3.13 COMPATIBILITY MONKEY-PATCH ---
|
| 2 |
-
import sys
|
| 3 |
-
import types
|
| 4 |
-
|
| 5 |
-
if 'audioop' not in sys.modules:
|
| 6 |
-
mock_audioop = types.ModuleType('audioop')
|
| 7 |
-
mock_audioop.error = Exception
|
| 8 |
-
mock_audioop.getsample = lambda data, width, index: 0
|
| 9 |
-
sys.modules['audioop'] = mock_audioop
|
| 10 |
-
# ----------------------------------------------
|
| 11 |
-
|
| 12 |
-
import os
|
| 13 |
-
import sqlite3
|
| 14 |
-
import pandas as pd
|
| 15 |
-
import json
|
| 16 |
-
import gradio as gr
|
| 17 |
-
from groq import Groq
|
| 18 |
-
import requests
|
| 19 |
-
|
| 20 |
-
# --- Database Initialization ---
|
| 21 |
-
DB_NAME = "strides_production.db"
|
| 22 |
-
|
| 23 |
-
def init_db():
|
| 24 |
-
conn = sqlite3.connect(DB_NAME)
|
| 25 |
-
cursor = conn.cursor()
|
| 26 |
-
cursor.execute('''
|
| 27 |
-
CREATE TABLE IF NOT EXISTS project_tasks (
|
| 28 |
-
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 29 |
-
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
|
| 30 |
-
phase TEXT,
|
| 31 |
-
task_name TEXT,
|
| 32 |
-
owner TEXT,
|
| 33 |
-
timeline TEXT,
|
| 34 |
-
priority TEXT
|
| 35 |
-
)
|
| 36 |
-
''')
|
| 37 |
-
|
| 38 |
-
cursor.execute("SELECT COUNT(*) FROM project_tasks")
|
| 39 |
-
if cursor.fetchone()[0] == 0:
|
| 40 |
-
dummy_data = [
|
| 41 |
-
('Discovery', 'Identify Deviation Root Cause', 'A. Sharma', 'Week 1', 'High'),
|
| 42 |
-
('Data Prep', 'Clean LIMS Batch Records', 'R. Verma', 'Week 2-3', 'Medium'),
|
| 43 |
-
('Modeling', 'Train Predictive Quality AI', 'S. Iyer', 'Week 4-5', 'High'),
|
| 44 |
-
('Validation', 'Draft GxP Validation Protocol', 'M. Reddy', 'Week 6', 'High'),
|
| 45 |
-
('Discovery', 'Audit Existing Logbook Manuals', 'P. Gupta', 'Week 1', 'Low'),
|
| 46 |
-
('Data Prep', 'Standardize Sensor Timestamp Data', 'R. Verma', 'Week 2-3', 'Medium'),
|
| 47 |
-
('Validation', 'Perform IQ/OQ/PQ for AI Model', 'M. Reddy', 'Week 6', 'High')
|
| 48 |
-
]
|
| 49 |
-
cursor.executemany(
|
| 50 |
-
'INSERT INTO project_tasks (phase, task_name, owner, timeline, priority) VALUES (?,?,?,?,?)',
|
| 51 |
-
dummy_data
|
| 52 |
-
)
|
| 53 |
-
conn.commit()
|
| 54 |
-
conn.close()
|
| 55 |
-
|
| 56 |
-
init_db()
|
| 57 |
-
|
| 58 |
-
# --- Dynamic Model Dropdown Refresher Logic ---
|
| 59 |
-
GROQ_MODELS = [
|
| 60 |
-
"llama-3.1-8b-instant",
|
| 61 |
-
"llama-3.1-70b-versatile",
|
| 62 |
-
"openai/gpt-oss-20b",
|
| 63 |
-
"whisper-large-v3-turbo"
|
| 64 |
-
]
|
| 65 |
-
|
| 66 |
-
OPENROUTER_MODELS = [
|
| 67 |
-
"nvidia/nemotron-3.5-content-safety:free",
|
| 68 |
-
"qwen/qwen3.7-plus",
|
| 69 |
-
"microsoft/mai-transcribe-1.5",
|
| 70 |
-
"google/gemini-embedding-2"
|
| 71 |
-
]
|
| 72 |
-
|
| 73 |
-
def update_model_dropdown(provider):
|
| 74 |
-
if provider == "Groq":
|
| 75 |
-
return gr.Dropdown(choices=GROQ_MODELS, value=GROQ_MODELS[0], label="Target Engine Architecture")
|
| 76 |
-
elif provider == "OpenRouter":
|
| 77 |
-
return gr.Dropdown(choices=OPENROUTER_MODELS, value=OPENROUTER_MODELS[0], label="Target Engine Architecture")
|
| 78 |
-
|
| 79 |
-
# --- Common LLM API Request Orchestrator ---
|
| 80 |
-
def call_llm(provider, api_key, model_choice, system_prompt, user_message, chat_history_format=None):
|
| 81 |
-
messages = [{"role": "system", "content": system_prompt}]
|
| 82 |
-
|
| 83 |
-
if chat_history_format:
|
| 84 |
-
messages.extend(chat_history_format)
|
| 85 |
-
else:
|
| 86 |
-
messages.append({"role": "user", "content": user_message})
|
| 87 |
-
|
| 88 |
-
if provider == "Groq":
|
| 89 |
-
client = Groq(api_key=api_key)
|
| 90 |
-
groq_model_map = {
|
| 91 |
-
"llama-3.1-8b-instant": "llama-3.1-8b-instant",
|
| 92 |
-
"llama-3.1-70b-versatile": "llama-3.1-70b-versatile",
|
| 93 |
-
"openai/gpt-oss-20b": "llama-3.1-8b-instant",
|
| 94 |
-
"whisper-large-v3-turbo": "whisper-large-v3-turbo"
|
| 95 |
-
}
|
| 96 |
-
target_model = groq_model_map.get(model_choice, "llama-3.1-8b-instant")
|
| 97 |
-
response = client.chat.completions.create(
|
| 98 |
-
model=target_model, messages=messages, temperature=0.0
|
| 99 |
-
)
|
| 100 |
-
return response.choices[0].message.content.strip()
|
| 101 |
-
|
| 102 |
-
elif provider == "OpenRouter":
|
| 103 |
-
headers = {"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"}
|
| 104 |
-
|
| 105 |
-
# Maps user-facing selection directly to their OpenRouter global endpoints
|
| 106 |
-
openrouter_model_map = {
|
| 107 |
-
"nvidia/nemotron-3.5-content-safety:free": "nvidia/nemotron-3.5-content-safety:free",
|
| 108 |
-
"qwen/qwen3.7-plus": "qwen/qwen3.7-plus",
|
| 109 |
-
"microsoft/mai-transcribe-1.5": "microsoft/mai-transcribe-1.5",
|
| 110 |
-
"google/gemini-embedding-2": "google/gemini-embedding-2"
|
| 111 |
-
}
|
| 112 |
-
target_model = openrouter_model_map.get(model_choice, "nvidia/nemotron-3.5-content-safety:free")
|
| 113 |
-
|
| 114 |
-
payload = {
|
| 115 |
-
"model": target_model,
|
| 116 |
-
"messages": messages,
|
| 117 |
-
"temperature": 0.0
|
| 118 |
-
}
|
| 119 |
-
response = requests.post("https://openrouter.ai/api/v1/chat/completions", headers=headers, json=payload)
|
| 120 |
-
if response.status_code == 200:
|
| 121 |
-
return response.json()['choices'][0]['message']['content'].strip()
|
| 122 |
-
else:
|
| 123 |
-
raise Exception(f"OpenRouter Gateway Alert ({response.status_code}): {response.text}")
|
| 124 |
-
|
| 125 |
-
# --- Tab 1: Text-to-SQL Reader Desk Core Logic ---
|
| 126 |
-
def execute_ai_query(provider, api_key, model_choice, user_question):
|
| 127 |
-
if not api_key.strip():
|
| 128 |
-
return None, "⚠️ Please enter a valid API Key to proceed."
|
| 129 |
-
if not user_question.strip():
|
| 130 |
-
return None, "⚠️ Please type a question or scenario."
|
| 131 |
-
|
| 132 |
-
system_prompt = (
|
| 133 |
-
"You are an expert SQL assistant. The database table is called 'project_tasks' with columns: "
|
| 134 |
-
"[id, timestamp, phase, task_name, owner, timeline, priority]. "
|
| 135 |
-
"Return ONLY a valid, executable raw SQLite query based on the user's question. "
|
| 136 |
-
"Do not include any explanation, introductory markdown, markdown code block wrappers, or trailing text. "
|
| 137 |
-
"Output raw text only."
|
| 138 |
-
)
|
| 139 |
-
|
| 140 |
-
try:
|
| 141 |
-
sql_query = call_llm(provider, api_key, model_choice, system_prompt, user_question)
|
| 142 |
-
sql_query = sql_query.replace("```sql", "").replace("```", "").replace("`", "").strip()
|
| 143 |
-
|
| 144 |
-
conn = sqlite3.connect(DB_NAME)
|
| 145 |
-
df = pd.read_sql_query(sql_query, conn)
|
| 146 |
-
conn.close()
|
| 147 |
-
return df, f"⚡ **Generated SQL Query:** `{sql_query}`"
|
| 148 |
-
except Exception as e:
|
| 149 |
-
return None, f"❌ Execution Failed: {str(e)}"
|
| 150 |
-
|
| 151 |
-
# --- Tab 2: Conversation & Data Append Agent Core Logic ---
|
| 152 |
-
def conversation_and_commit_agent(chat_history, provider, api_key, model_choice, user_msg):
|
| 153 |
-
if not api_key.strip():
|
| 154 |
-
chat_history.append({"role": "assistant", "content": "⚠️ Authentication missing. Please input your API Key on the left menu pane."})
|
| 155 |
-
return chat_history, ""
|
| 156 |
-
if not user_msg.strip():
|
| 157 |
-
return chat_history, ""
|
| 158 |
-
|
| 159 |
-
system_prompt = (
|
| 160 |
-
"You are a helpful conversational assistant and workflow coordinator for the Strides Pharma AI operational framework.\n"
|
| 161 |
-
"Your goal is twofold:\n"
|
| 162 |
-
"1. Respond to general conversational statements normally and professionally.\n"
|
| 163 |
-
"2. If the user expresses intent to log, add, or append a task milestone to the schedule, guide them or process it. "
|
| 164 |
-
"The required metrics are: Phase, Task_Name, Owner, Timeline, and Priority.\n\n"
|
| 165 |
-
"CRITICAL MECHANISM FOR DATA INSERTION:\n"
|
| 166 |
-
"If you have gathered or been explicitly provided structural task properties to log, you MUST append a raw JSON block at the very end of your final response text. "
|
| 167 |
-
"The format must exactly be: ||JSON_DATA: {\"phase\": \"...\", \"task_name\": \"...\", \"owner\": \"...\", \"timeline\": \"...\", \"priority\": \"...\"}||\n"
|
| 168 |
-
"If some schema details are completely absent, converse politely with the client to verify those remaining parameters before adding the string tag marker."
|
| 169 |
-
)
|
| 170 |
-
|
| 171 |
-
formatted_history = []
|
| 172 |
-
for turn in chat_history:
|
| 173 |
-
formatted_history.append({"role": turn["role"], "content": turn["content"]})
|
| 174 |
-
formatted_history.append({"role": "user", "content": user_msg})
|
| 175 |
-
|
| 176 |
-
try:
|
| 177 |
-
raw_response = call_llm(provider, api_key, model_choice, system_prompt, "", chat_history_format=formatted_history)
|
| 178 |
-
|
| 179 |
-
cleaned_response = raw_response
|
| 180 |
-
database_committed_alert = ""
|
| 181 |
-
|
| 182 |
-
if "||JSON_DATA:" in raw_response:
|
| 183 |
-
try:
|
| 184 |
-
parts = raw_response.split("||JSON_DATA:")
|
| 185 |
-
cleaned_response = parts[0].strip()
|
| 186 |
-
json_string = parts[1].replace("||", "").strip()
|
| 187 |
-
|
| 188 |
-
data_payload = json.loads(json_string)
|
| 189 |
-
|
| 190 |
-
conn = sqlite3.connect(DB_NAME)
|
| 191 |
-
cursor = conn.cursor()
|
| 192 |
-
cursor.execute(
|
| 193 |
-
"INSERT INTO project_tasks (phase, task_name, owner, timeline, priority) VALUES (?, ?, ?, ?, ?)",
|
| 194 |
-
(data_payload.get('phase'), data_payload.get('task_name'), data_payload.get('owner'), data_payload.get('timeline'), data_payload.get('priority'))
|
| 195 |
-
)
|
| 196 |
-
conn.commit()
|
| 197 |
-
conn.close()
|
| 198 |
-
|
| 199 |
-
database_committed_alert = f"\n\n⚙️ **[SYSTEM UPDATE]:** Successfully appended task '{data_payload.get('task_name')}' to the internal server database master record structure."
|
| 200 |
-
except Exception as inner_err:
|
| 201 |
-
database_committed_alert = f"\n\n⚠️ **[SYSTEM NOTICE]:** Captured structure request token, but insertion execution aborted due to tracking parsing discrepancies: {str(inner_err)}"
|
| 202 |
-
|
| 203 |
-
final_display_text = cleaned_response + database_committed_alert
|
| 204 |
-
|
| 205 |
-
chat_history.append({"role": "user", "content": user_msg})
|
| 206 |
-
chat_history.append({"role": "assistant", "content": final_display_text})
|
| 207 |
-
return chat_history, ""
|
| 208 |
-
|
| 209 |
-
except Exception as e:
|
| 210 |
-
chat_history.append({"role": "user", "content": user_msg})
|
| 211 |
-
chat_history.append({"role": "assistant", "content": f"❌ API Connection Failure: {str(e)}"})
|
| 212 |
-
return chat_history, ""
|
| 213 |
-
|
| 214 |
-
# --- Interface Layout Configuration ---
|
| 215 |
-
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 216 |
-
gr.Markdown("# 💊 Strides Pharma AI Production & Data Portal")
|
| 217 |
-
gr.Markdown("Orchestrate production tasks, converse with core system workflows, and modify infrastructure records securely.")
|
| 218 |
-
|
| 219 |
-
with gr.Row():
|
| 220 |
-
with gr.Column(scale=1):
|
| 221 |
-
gr.Markdown("### 🔑 Global Control Tower")
|
| 222 |
-
provider_select = gr.Dropdown(choices=["Groq", "OpenRouter"], value="Groq", label="API Gateway Provider")
|
| 223 |
-
token_input = gr.Textbox(label="User API Secret Key", type="password", placeholder="gsk_... or sk-or-...")
|
| 224 |
-
|
| 225 |
-
# This component gets updated dynamically by the event handler below
|
| 226 |
-
model_select = gr.Dropdown(
|
| 227 |
-
choices=GROQ_MODELS,
|
| 228 |
-
value=GROQ_MODELS[0],
|
| 229 |
-
label="Target Engine Architecture"
|
| 230 |
-
)
|
| 231 |
-
|
| 232 |
-
gr.Markdown("✨ **Global Platform Database State Schema:**\n- `phase` (Discovery, Data Prep, Modeling, Validation)\n- `task_name` (Structural workflow description string)\n- `owner` (Assigned personnel scientist name)\n- `timeline` (Expected operational delivery time frames)\n- `priority` (High, Medium, Low)")
|
| 233 |
-
|
| 234 |
-
with gr.Column(scale=2):
|
| 235 |
-
with gr.Tabs():
|
| 236 |
-
|
| 237 |
-
with gr.TabItem("🤖 Interactive Data Contributor Chatbot"):
|
| 238 |
-
gr.Markdown("### Conversational Contributor Agent")
|
| 239 |
-
gr.Markdown("Chat with this engine normally, or tell it to log a brand-new task assignment milestone directly into the active SQLite infrastructure.")
|
| 240 |
-
|
| 241 |
-
chatbot_viewport = gr.Chatbot(type="messages", label="Operational History Workspace")
|
| 242 |
-
chat_input = gr.Textbox(placeholder="Say hello, or submit task details to log...", label="Your Message")
|
| 243 |
-
send_btn = gr.Button("Submit Message", variant="primary")
|
| 244 |
-
|
| 245 |
-
send_btn.click(
|
| 246 |
-
fn=conversation_and_commit_agent,
|
| 247 |
-
inputs=[chatbot_viewport, provider_select, token_input, model_select, chat_input],
|
| 248 |
-
outputs=[chatbot_viewport, chat_input]
|
| 249 |
-
)
|
| 250 |
-
chat_input.submit(
|
| 251 |
-
fn=conversation_and_commit_agent,
|
| 252 |
-
inputs=[chatbot_viewport, provider_select, token_input, model_select, chat_input],
|
| 253 |
-
outputs=[chatbot_viewport, chat_input]
|
| 254 |
-
)
|
| 255 |
-
|
| 256 |
-
with gr.TabItem("🔎 SQL Inquisitor Desk"):
|
| 257 |
-
gr.Markdown("### Natural Language SQL Query Engine")
|
| 258 |
-
query_input = gr.Textbox(label="Query the current database contents using conversational English:", placeholder="e.g., Show me all records sorted by priority status")
|
| 259 |
-
query_btn = gr.Button("Evaluate Infrastructure", variant="secondary")
|
| 260 |
-
|
| 261 |
-
sql_status_display = gr.Markdown()
|
| 262 |
-
output_data_table = gr.DataFrame(label="Queried Records Dataframe Live Output")
|
| 263 |
-
|
| 264 |
-
query_btn.click(
|
| 265 |
-
fn=execute_ai_query,
|
| 266 |
-
inputs=[provider_select, token_input, model_select, query_input],
|
| 267 |
-
outputs=[output_data_table, sql_status_display]
|
| 268 |
-
)
|
| 269 |
-
|
| 270 |
-
# --- REACTIVE EVENT LISTENER ---
|
| 271 |
-
# Whenever the provider dropdown changes, change the choices of the model select dropdown
|
| 272 |
-
provider_select.change(
|
| 273 |
-
fn=update_model_dropdown,
|
| 274 |
-
inputs=[provider_select],
|
| 275 |
-
outputs=[model_select]
|
| 276 |
-
)
|
| 277 |
-
|
| 278 |
-
if __name__ == "__main__":
|
| 279 |
-
demo.launch()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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