khanhamzawiser commited on
Commit
8b52d2b
·
verified ·
1 Parent(s): a2788aa

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +45 -38
app.py CHANGED
@@ -3,6 +3,7 @@ from huggingface_hub import InferenceClient
3
  import psycopg2
4
  import os
5
  import logging
 
6
 
7
  # Set up logging
8
  logging.basicConfig(level=logging.DEBUG)
@@ -11,17 +12,15 @@ logger = logging.getLogger(__name__)
11
  # Hugging Face Zephyr model
12
  client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
13
 
14
- # TimescaleDB config (via Hugging Face Space secrets)
15
  DB_CONFIG = {
16
- "host": os.getenv("DB_HOST", "127.0.0.1"), # Use the actual DB host
17
- "port": os.getenv("DB_PORT", 5434),
18
- "database": os.getenv("DB_NAME", "postgres"),
19
- "user": os.getenv("DB_USER", "postgres"),
20
- "password": os.getenv("DB_PASSWORD", "password"),
21
  }
22
 
23
-
24
-
25
  # Query TimescaleDB with improved error handling
26
  def query_timescaledb(sql_query):
27
  try:
@@ -37,47 +36,51 @@ def query_timescaledb(sql_query):
37
  logger.error(f"DB Error: {e}")
38
  return f"DB Error: {e}"
39
 
40
- # Basic pattern matching to route question types
41
  def get_sql_for_question(message):
42
  message = message.lower()
43
 
44
  if "average current" in message:
45
  return """
46
- SELECT AVG(CT_Avg) as avg_current FROM machine_current_log
 
47
  WHERE created_at >= NOW() - INTERVAL '1 day';
48
  """, "Here's the average current over the past 24 hours:"
49
 
50
- elif "total machines not faulty" in message:
51
  return """
52
- SELECT COUNT(DISTINCT machine_id)
53
  FROM machine_current_log
54
- WHERE fault_status = 'NOT_FAULTY'
55
- AND created_at >= NOW() - INTERVAL '1 day';
56
- """, "Here is the total number of machines that are not faulty today:"
57
-
58
- elif "total current" in message:
 
 
 
59
  return """
60
- SELECT created_at, total_current FROM machine_current_log
61
- WHERE created_at >= NOW() - INTERVAL '1 day'
62
- ORDER BY created_at DESC LIMIT 10;
63
- """, "Here are the latest 10 total current readings:"
 
64
 
65
- elif "state duration" in message or "longest running state" in message:
66
  return """
67
- SELECT state, MAX(state_duration) FROM machine_current_log
68
- WHERE created_at >= NOW() - INTERVAL '1 week'
69
- GROUP BY state
70
- ORDER BY MAX(state_duration) DESC LIMIT 1;
71
- """, "Here's the longest running machine state this week:"
72
 
73
- elif "fault" in message:
74
  return """
75
- SELECT fault_status, COUNT(*) FROM machine_current_log
76
- WHERE fault_status IS NOT NULL
77
- GROUP BY fault_status
78
- ORDER BY COUNT(*) DESC;
79
- """, "Here is the frequency of different fault statuses:"
80
-
81
  return None, None
82
 
83
  # Respond using LLM + data if relevant
@@ -118,10 +121,14 @@ def respond(message, history: list[tuple[str, str]], system_message, max_tokens,
118
 
119
  # Gradio UI
120
  with gr.Blocks() as demo:
121
- gr.Markdown("## 🤖 Wiser AI Assistant")
122
  gr.Markdown(
123
  """
124
- Welcome to **Wiser's AI Assistant**, your smart companion for all things manufacturing.
 
 
 
 
125
  """
126
  )
127
 
@@ -129,7 +136,7 @@ with gr.Blocks() as demo:
129
  respond,
130
  additional_inputs=[
131
  gr.Textbox(
132
- value="You are Wiser, an expert AI assistant in smart manufacturing. Help users understand machine metrics using the latest database values.",
133
  label="System message"
134
  ),
135
  gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
@@ -140,4 +147,4 @@ with gr.Blocks() as demo:
140
 
141
  # Run
142
  if __name__ == "__main__":
143
- demo.launch()
 
3
  import psycopg2
4
  import os
5
  import logging
6
+ from datetime import datetime, timezone
7
 
8
  # Set up logging
9
  logging.basicConfig(level=logging.DEBUG)
 
12
  # Hugging Face Zephyr model
13
  client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
14
 
15
+ # Use your existing database connection settings
16
  DB_CONFIG = {
17
+ "host": "127.0.0.1",
18
+ "port": 5434,
19
+ "database": "postgres",
20
+ "user": "postgres",
21
+ "password": "password"
22
  }
23
 
 
 
24
  # Query TimescaleDB with improved error handling
25
  def query_timescaledb(sql_query):
26
  try:
 
36
  logger.error(f"DB Error: {e}")
37
  return f"DB Error: {e}"
38
 
39
+ # Modified to match your table structure
40
  def get_sql_for_question(message):
41
  message = message.lower()
42
 
43
  if "average current" in message:
44
  return """
45
+ SELECT AVG("CT_Avg") as avg_current
46
+ FROM machine_current_log
47
  WHERE created_at >= NOW() - INTERVAL '1 day';
48
  """, "Here's the average current over the past 24 hours:"
49
 
50
+ elif "machine status" in message:
51
  return """
52
+ SELECT mac, state, state_duration, fault_status
53
  FROM machine_current_log
54
+ WHERE created_at = (
55
+ SELECT MAX(created_at)
56
+ FROM machine_current_log
57
+ )
58
+ LIMIT 5;
59
+ """, "Here are the latest machine statuses:"
60
+
61
+ elif "current readings" in message:
62
  return """
63
+ SELECT mac, created_at, "CT1", "CT2", "CT3", "CT_Avg"
64
+ FROM machine_current_log
65
+ ORDER BY created_at DESC
66
+ LIMIT 5;
67
+ """, "Here are the latest current readings:"
68
 
69
+ elif "fault status" in message:
70
  return """
71
+ SELECT fault_status, COUNT(*)
72
+ FROM machine_current_log
73
+ WHERE created_at >= NOW() - INTERVAL '1 day'
74
+ GROUP BY fault_status;
75
+ """, "Here's the distribution of fault statuses in the last 24 hours:"
76
 
77
+ elif "firmware versions" in message:
78
  return """
79
+ SELECT DISTINCT fw_version, COUNT(*)
80
+ FROM machine_current_log
81
+ GROUP BY fw_version;
82
+ """, "Here are the firmware versions in use:"
83
+
 
84
  return None, None
85
 
86
  # Respond using LLM + data if relevant
 
121
 
122
  # Gradio UI
123
  with gr.Blocks() as demo:
124
+ gr.Markdown("## 🤖 Machine Monitoring Assistant")
125
  gr.Markdown(
126
  """
127
+ Welcome to the **Machine Monitoring Assistant**. You can ask questions about:
128
+ - Current readings (CT1, CT2, CT3, CT_Avg)
129
+ - Machine status and state duration
130
+ - Fault status
131
+ - Firmware versions
132
  """
133
  )
134
 
 
136
  respond,
137
  additional_inputs=[
138
  gr.Textbox(
139
+ value="You are an expert AI assistant for machine monitoring. Help users understand machine metrics and status using the latest database values.",
140
  label="System message"
141
  ),
142
  gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
 
147
 
148
  # Run
149
  if __name__ == "__main__":
150
+ demo.launch()