Spaces:
Runtime error
Runtime error
latterworks
commited on
Commit
•
d46ba59
1
Parent(s):
2dd1977
Update app.py
Browse files
app.py
CHANGED
@@ -1,64 +1,158 @@
|
|
|
|
1 |
import gradio as gr
|
2 |
from huggingface_hub import InferenceClient
|
|
|
|
|
|
|
3 |
|
4 |
-
|
5 |
-
For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
|
6 |
-
"""
|
7 |
client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
|
8 |
|
9 |
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
top_p,
|
17 |
-
):
|
18 |
-
messages = [{"role": "system", "content": system_message}]
|
19 |
-
|
20 |
-
for val in history:
|
21 |
-
if val[0]:
|
22 |
-
messages.append({"role": "user", "content": val[0]})
|
23 |
-
if val[1]:
|
24 |
-
messages.append({"role": "assistant", "content": val[1]})
|
25 |
-
|
26 |
-
messages.append({"role": "user", "content": message})
|
27 |
-
|
28 |
-
response = ""
|
29 |
-
|
30 |
-
for message in client.chat_completion(
|
31 |
-
messages,
|
32 |
-
max_tokens=max_tokens,
|
33 |
-
stream=True,
|
34 |
-
temperature=temperature,
|
35 |
-
top_p=top_p,
|
36 |
-
):
|
37 |
-
token = message.choices[0].delta.content
|
38 |
-
|
39 |
-
response += token
|
40 |
-
yield response
|
41 |
-
|
42 |
-
|
43 |
-
"""
|
44 |
-
For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
|
45 |
-
"""
|
46 |
-
demo = gr.ChatInterface(
|
47 |
-
respond,
|
48 |
-
additional_inputs=[
|
49 |
-
gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
|
50 |
-
gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
|
51 |
-
gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
|
52 |
-
gr.Slider(
|
53 |
-
minimum=0.1,
|
54 |
-
maximum=1.0,
|
55 |
-
value=0.95,
|
56 |
-
step=0.05,
|
57 |
-
label="Top-p (nucleus sampling)",
|
58 |
-
),
|
59 |
-
],
|
60 |
-
)
|
61 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
62 |
|
63 |
if __name__ == "__main__":
|
64 |
demo.launch()
|
|
|
1 |
+
import os
|
2 |
import gradio as gr
|
3 |
from huggingface_hub import InferenceClient
|
4 |
+
from noaa_incidents import NOAAIncidentDB, NOAAIncidentScraper
|
5 |
+
import json
|
6 |
+
from datetime import datetime
|
7 |
|
8 |
+
# Initialize Hugging Face client
|
|
|
|
|
9 |
client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
|
10 |
|
11 |
|
12 |
+
class NOAAIncidentApp:
|
13 |
+
def __init__(self):
|
14 |
+
"""Initialize the NOAA Incident App with database and chatbot components."""
|
15 |
+
self.db = NOAAIncidentDB(persist_directory="noaa_db")
|
16 |
+
self.last_update = None
|
17 |
+
self._load_last_update_time()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
18 |
|
19 |
+
def _load_last_update_time(self):
|
20 |
+
"""Load the last update time from metadata file."""
|
21 |
+
try:
|
22 |
+
if os.path.exists("metadata.json"):
|
23 |
+
with open("metadata.json", "r") as f:
|
24 |
+
metadata = json.load(f)
|
25 |
+
self.last_update = metadata.get("last_update")
|
26 |
+
except Exception as e:
|
27 |
+
print(f"Error loading metadata: {e}")
|
28 |
+
|
29 |
+
def _save_last_update_time(self):
|
30 |
+
"""Save the last update time to metadata file."""
|
31 |
+
try:
|
32 |
+
with open("metadata.json", "w") as f:
|
33 |
+
json.dump({"last_update": self.last_update}, f)
|
34 |
+
except Exception as e:
|
35 |
+
print(f"Error saving metadata: {e}")
|
36 |
+
|
37 |
+
def search_incidents(self, query, min_date=None, max_date=None, location_filter=None, num_results=5):
|
38 |
+
"""Search incidents with optional filters and return results."""
|
39 |
+
results = self.db.search(query, n_results=num_results)
|
40 |
+
filtered_results = []
|
41 |
+
|
42 |
+
for result in results:
|
43 |
+
if min_date and result['date'] < min_date:
|
44 |
+
continue
|
45 |
+
if max_date and result['date'] > max_date:
|
46 |
+
continue
|
47 |
+
if location_filter and location_filter.lower() not in result['location'].lower():
|
48 |
+
continue
|
49 |
+
filtered_results.append(result)
|
50 |
+
|
51 |
+
if not filtered_results:
|
52 |
+
return "No matching incidents found."
|
53 |
+
|
54 |
+
output = []
|
55 |
+
for i, result in enumerate(filtered_results, 1):
|
56 |
+
output.append(f"## Result {i}: {result['title']}")
|
57 |
+
output.append(f"**Date:** {result['date']}")
|
58 |
+
output.append(f"**Location:** {result['location']}")
|
59 |
+
output.append(f"**Details:** {result['details']}")
|
60 |
+
output.append("---\n")
|
61 |
+
return "\n".join(output)
|
62 |
+
|
63 |
+
def respond(self, message, history, system_message, max_tokens, temperature, top_p):
|
64 |
+
"""Generate chatbot responses or query the NOAA database based on user input."""
|
65 |
+
# Check if the message is a NOAA query
|
66 |
+
if "search noaa" in message.lower():
|
67 |
+
# Extract filters (basic implementation, can be expanded)
|
68 |
+
query = message.replace("search noaa", "").strip()
|
69 |
+
response = self.search_incidents(query=query, num_results=5)
|
70 |
+
return response
|
71 |
+
|
72 |
+
# Generate chatbot response
|
73 |
+
messages = [{"role": "system", "content": system_message}]
|
74 |
+
for val in history:
|
75 |
+
if val[0]:
|
76 |
+
messages.append({"role": "user", "content": val[0]})
|
77 |
+
if val[1]:
|
78 |
+
messages.append({"role": "assistant", "content": val[1]})
|
79 |
+
messages.append({"role": "user", "content": message})
|
80 |
+
|
81 |
+
response = ""
|
82 |
+
for message in client.chat_completion(
|
83 |
+
messages,
|
84 |
+
max_tokens=max_tokens,
|
85 |
+
stream=True,
|
86 |
+
temperature=temperature,
|
87 |
+
top_p=top_p,
|
88 |
+
):
|
89 |
+
token = message.choices[0].delta.content
|
90 |
+
response += token
|
91 |
+
yield response
|
92 |
+
|
93 |
+
def refresh_database(self, progress=gr.Progress()):
|
94 |
+
"""Refresh the database with new incidents."""
|
95 |
+
try:
|
96 |
+
progress(0, desc="Initializing scraper...")
|
97 |
+
scraper = NOAAIncidentScraper(max_workers=5)
|
98 |
+
progress(0.2, desc="Scraping new incidents...")
|
99 |
+
csv_file, _ = scraper.run(validate_first=True)
|
100 |
+
if not csv_file:
|
101 |
+
return "Error: Failed to scrape new incidents."
|
102 |
+
progress(0.6, desc="Loading new data into database...")
|
103 |
+
num_loaded = self.db.load_incidents(csv_file)
|
104 |
+
self.last_update = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
105 |
+
self._save_last_update_time()
|
106 |
+
progress(1.0, desc="Complete!")
|
107 |
+
return f"Successfully refreshed database with {num_loaded} incidents."
|
108 |
+
except Exception as e:
|
109 |
+
return f"Error refreshing database: {str(e)}"
|
110 |
+
|
111 |
+
def create_interface(self):
|
112 |
+
"""Create the Gradio interface."""
|
113 |
+
with gr.Blocks(title="NOAA Incident & Chatbot App") as interface:
|
114 |
+
gr.Markdown("# NOAA Incident & Chatbot Application")
|
115 |
+
with gr.Row():
|
116 |
+
with gr.Column(scale=2):
|
117 |
+
gr.Markdown("### Chatbot Interaction")
|
118 |
+
system_message = gr.Textbox(
|
119 |
+
label="System Message", value="You are a friendly assistant."
|
120 |
+
)
|
121 |
+
chat_history = gr.State([])
|
122 |
+
message = gr.Textbox(label="Message")
|
123 |
+
max_tokens = gr.Slider(1, 2048, 512, step=1, label="Max Tokens")
|
124 |
+
temperature = gr.Slider(0.1, 4.0, 0.7, step=0.1, label="Temperature")
|
125 |
+
top_p = gr.Slider(0.1, 1.0, 0.95, step=0.05, label="Top-p")
|
126 |
+
chat_btn = gr.Button("Send")
|
127 |
+
chat_md = gr.Markdown()
|
128 |
+
|
129 |
+
with gr.Column(scale=1):
|
130 |
+
refresh_btn = gr.Button("Refresh Database")
|
131 |
+
last_update_md = gr.Markdown(
|
132 |
+
f"*Last database update: {self.last_update or 'Never'}*"
|
133 |
+
)
|
134 |
+
|
135 |
+
chat_btn.click(
|
136 |
+
self.respond,
|
137 |
+
inputs=[
|
138 |
+
message,
|
139 |
+
chat_history,
|
140 |
+
system_message,
|
141 |
+
max_tokens,
|
142 |
+
temperature,
|
143 |
+
top_p,
|
144 |
+
],
|
145 |
+
outputs=chat_md,
|
146 |
+
)
|
147 |
+
|
148 |
+
refresh_btn.click(self.refresh_database, inputs=[], outputs=last_update_md)
|
149 |
+
|
150 |
+
return interface
|
151 |
+
|
152 |
+
|
153 |
+
# Run the app
|
154 |
+
app = NOAAIncidentApp()
|
155 |
+
demo = app.create_interface()
|
156 |
|
157 |
if __name__ == "__main__":
|
158 |
demo.launch()
|