Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,22 +1,91 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
from huggingface_hub import InferenceClient
|
|
|
|
|
|
|
|
|
|
| 3 |
|
| 4 |
-
#
|
| 5 |
client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
|
| 6 |
|
| 7 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
def respond(message, history: list[tuple[str, str]], system_message, max_tokens, temperature, top_p):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
messages = [{"role": "system", "content": system_message}]
|
| 10 |
-
|
| 11 |
for val in history:
|
| 12 |
if val[0]:
|
| 13 |
messages.append({"role": "user", "content": val[0]})
|
| 14 |
if val[1]:
|
| 15 |
messages.append({"role": "assistant", "content": val[1]})
|
| 16 |
-
|
| 17 |
messages.append({"role": "user", "content": message})
|
| 18 |
-
response = ""
|
| 19 |
|
|
|
|
| 20 |
for message in client.chat_completion(
|
| 21 |
messages,
|
| 22 |
max_tokens=max_tokens,
|
|
@@ -28,21 +97,20 @@ def respond(message, history: list[tuple[str, str]], system_message, max_tokens,
|
|
| 28 |
response += token
|
| 29 |
yield response
|
| 30 |
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
# Build the UI using Gradio Blocks
|
| 34 |
with gr.Blocks() as demo:
|
| 35 |
gr.Markdown("## 🤖 Wiser AI Assistant")
|
| 36 |
gr.Markdown(
|
| 37 |
"""
|
| 38 |
Welcome to **Wiser's AI Assistant**, your smart companion for all things manufacturing.
|
| 39 |
-
Ask questions about:
|
| 40 |
-
- Smart factory operations 🏭
|
| 41 |
-
- Workflow automation ⚙️
|
| 42 |
-
- Efficiency tips 📈
|
| 43 |
-
- Wiser’s AI-powered solutions 🧠
|
| 44 |
|
| 45 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 46 |
"""
|
| 47 |
)
|
| 48 |
|
|
@@ -50,7 +118,7 @@ with gr.Blocks() as demo:
|
|
| 50 |
respond,
|
| 51 |
additional_inputs=[
|
| 52 |
gr.Textbox(
|
| 53 |
-
value="You are Wiser, an expert AI assistant in smart manufacturing. Help users
|
| 54 |
label="System message"
|
| 55 |
),
|
| 56 |
gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
|
|
@@ -59,7 +127,6 @@ with gr.Blocks() as demo:
|
|
| 59 |
],
|
| 60 |
)
|
| 61 |
|
| 62 |
-
# Run
|
| 63 |
if __name__ == "__main__":
|
| 64 |
demo.launch()
|
| 65 |
-
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
from huggingface_hub import InferenceClient
|
| 3 |
+
import psycopg2
|
| 4 |
+
import os
|
| 5 |
+
import re
|
| 6 |
|
| 7 |
+
# Hugging Face Zephyr model
|
| 8 |
client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
|
| 9 |
|
| 10 |
+
# TimescaleDB config (via Hugging Face Space secrets)
|
| 11 |
+
DB_CONFIG = {
|
| 12 |
+
"host": os.getenv("DB_HOST"),
|
| 13 |
+
"port": os.getenv("DB_PORT", 5432),
|
| 14 |
+
"database": os.getenv("DB_NAME"),
|
| 15 |
+
"user": os.getenv("DB_USER"),
|
| 16 |
+
"password": os.getenv("DB_PASSWORD"),
|
| 17 |
+
}
|
| 18 |
+
|
| 19 |
+
# Query TimescaleDB
|
| 20 |
+
def query_timescaledb(sql_query):
|
| 21 |
+
try:
|
| 22 |
+
with psycopg2.connect(**DB_CONFIG) as conn:
|
| 23 |
+
with conn.cursor() as cur:
|
| 24 |
+
cur.execute(sql_query)
|
| 25 |
+
return cur.fetchall()
|
| 26 |
+
except Exception as e:
|
| 27 |
+
return f"DB Error: {e}"
|
| 28 |
+
|
| 29 |
+
# Basic pattern matching to route question types
|
| 30 |
+
def get_sql_for_question(message):
|
| 31 |
+
message = message.lower()
|
| 32 |
+
|
| 33 |
+
if "average current" in message:
|
| 34 |
+
return """
|
| 35 |
+
SELECT AVG(CT_Avg) as avg_current FROM machine_current_log
|
| 36 |
+
WHERE created_at >= NOW() - INTERVAL '1 day';
|
| 37 |
+
""", "Here's the average current over the past 24 hours:"
|
| 38 |
+
|
| 39 |
+
elif "total current" in message:
|
| 40 |
+
return """
|
| 41 |
+
SELECT created_at, total_current FROM machine_current_log
|
| 42 |
+
WHERE created_at >= NOW() - INTERVAL '1 day'
|
| 43 |
+
ORDER BY created_at DESC LIMIT 10;
|
| 44 |
+
""", "Here are the latest 10 total current readings:"
|
| 45 |
+
|
| 46 |
+
elif "state duration" in message or "longest running state" in message:
|
| 47 |
+
return """
|
| 48 |
+
SELECT state, MAX(state_duration) FROM machine_current_log
|
| 49 |
+
WHERE created_at >= NOW() - INTERVAL '1 week'
|
| 50 |
+
GROUP BY state
|
| 51 |
+
ORDER BY MAX(state_duration) DESC LIMIT 1;
|
| 52 |
+
""", "Here's the longest running machine state this week:"
|
| 53 |
+
|
| 54 |
+
elif "fault" in message:
|
| 55 |
+
return """
|
| 56 |
+
SELECT fault_status, COUNT(*) FROM machine_current_log
|
| 57 |
+
WHERE fault_status IS NOT NULL
|
| 58 |
+
GROUP BY fault_status
|
| 59 |
+
ORDER BY COUNT(*) DESC;
|
| 60 |
+
""", "Here is the frequency of different fault statuses:"
|
| 61 |
+
|
| 62 |
+
return None, None
|
| 63 |
+
|
| 64 |
+
# Respond using LLM + data if relevant
|
| 65 |
def respond(message, history: list[tuple[str, str]], system_message, max_tokens, temperature, top_p):
|
| 66 |
+
sql_query, context_prefix = get_sql_for_question(message)
|
| 67 |
+
|
| 68 |
+
if sql_query:
|
| 69 |
+
result = query_timescaledb(sql_query)
|
| 70 |
+
if isinstance(result, str): # error case
|
| 71 |
+
db_info = result
|
| 72 |
+
elif not result:
|
| 73 |
+
db_info = "No data found."
|
| 74 |
+
else:
|
| 75 |
+
# Clean and format result
|
| 76 |
+
db_info = "\n".join(str(row) for row in result)
|
| 77 |
+
|
| 78 |
+
message = f"{context_prefix}\n{db_info}\n\nAnswer the user's query based on this information."
|
| 79 |
+
|
| 80 |
messages = [{"role": "system", "content": system_message}]
|
|
|
|
| 81 |
for val in history:
|
| 82 |
if val[0]:
|
| 83 |
messages.append({"role": "user", "content": val[0]})
|
| 84 |
if val[1]:
|
| 85 |
messages.append({"role": "assistant", "content": val[1]})
|
|
|
|
| 86 |
messages.append({"role": "user", "content": message})
|
|
|
|
| 87 |
|
| 88 |
+
response = ""
|
| 89 |
for message in client.chat_completion(
|
| 90 |
messages,
|
| 91 |
max_tokens=max_tokens,
|
|
|
|
| 97 |
response += token
|
| 98 |
yield response
|
| 99 |
|
| 100 |
+
# Gradio UI
|
|
|
|
|
|
|
| 101 |
with gr.Blocks() as demo:
|
| 102 |
gr.Markdown("## 🤖 Wiser AI Assistant")
|
| 103 |
gr.Markdown(
|
| 104 |
"""
|
| 105 |
Welcome to **Wiser's AI Assistant**, your smart companion for all things manufacturing.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 106 |
|
| 107 |
+
Ask anything like:
|
| 108 |
+
- "What's the average current today?"
|
| 109 |
+
- "What faults happened this week?"
|
| 110 |
+
- "Tell me the latest machine states"
|
| 111 |
+
- "Any machines running too long?"
|
| 112 |
+
|
| 113 |
+
I'm connected to live TimescaleDB data 👨🏭📊
|
| 114 |
"""
|
| 115 |
)
|
| 116 |
|
|
|
|
| 118 |
respond,
|
| 119 |
additional_inputs=[
|
| 120 |
gr.Textbox(
|
| 121 |
+
value="You are Wiser, an expert AI assistant in smart manufacturing. Help users understand machine metrics using the latest database values.",
|
| 122 |
label="System message"
|
| 123 |
),
|
| 124 |
gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
|
|
|
|
| 127 |
],
|
| 128 |
)
|
| 129 |
|
| 130 |
+
# Run
|
| 131 |
if __name__ == "__main__":
|
| 132 |
demo.launch()
|
|
|