Spaces:
Running
on
CPU Upgrade
Running
on
CPU Upgrade
changes for UI
Browse files
app.py
CHANGED
@@ -1,10 +1,11 @@
|
|
1 |
import gradio as gr
|
2 |
import time
|
3 |
import pandas as pd
|
|
|
4 |
from uuid import uuid4
|
5 |
from gradio_client import Client, handle_file
|
6 |
|
7 |
-
# Sample questions for examples
|
8 |
SAMPLE_QUESTIONS = {
|
9 |
"Deforestation Analysis": [
|
10 |
"What are the main deforestation hotspots in Ecuador?",
|
@@ -23,107 +24,130 @@ SAMPLE_QUESTIONS = {
|
|
23 |
]
|
24 |
}
|
25 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
26 |
def handle_geojson_upload(file):
|
27 |
"""Handle GeoJSON file upload and call WHISP API"""
|
28 |
if file is not None:
|
29 |
try:
|
30 |
# Initialize WHISP API client
|
31 |
client = Client("https://giz-chatfed-whisp.hf.space/")
|
32 |
-
|
33 |
# Call the API with the uploaded file
|
34 |
result = client.predict(
|
35 |
file=handle_file(file.name),
|
36 |
api_name="/get_statistics"
|
37 |
)
|
38 |
-
|
39 |
# Convert result to DataFrame
|
40 |
df = pd.DataFrame(result['data'], columns=result['headers'])
|
41 |
-
|
|
|
|
|
|
|
42 |
return (
|
43 |
"✅ GeoJSON file processed successfully! Analysis results are displayed below.",
|
44 |
gr.update(visible=True), # upload_status
|
45 |
-
gr.update(value=df, visible=True) # results_table
|
|
|
46 |
)
|
47 |
-
|
48 |
except Exception as e:
|
49 |
error_msg = f"❌ Error processing GeoJSON file: {str(e)}"
|
50 |
-
return (
|
51 |
-
error_msg,
|
52 |
-
gr.update(visible=True), # upload_status
|
53 |
-
gr.update(visible=False) # results_table
|
54 |
-
)
|
55 |
else:
|
56 |
-
return (
|
57 |
-
"",
|
58 |
-
gr.update(visible=False), # upload_status
|
59 |
-
gr.update(visible=False) # results_table
|
60 |
-
)
|
61 |
|
|
|
|
|
|
|
62 |
def start_chat(query, history):
|
63 |
-
"""Start a new chat interaction"""
|
64 |
history = history + [(query, None)]
|
65 |
return gr.update(interactive=False), gr.update(selected=1), history
|
66 |
|
67 |
def finish_chat():
|
68 |
-
"""Finish chat and reset input"""
|
69 |
return gr.update(interactive=True, value="")
|
70 |
|
71 |
-
async def chat_response(query, history, method, country, uploaded_file):
|
72 |
-
"""Generate chat response based on method and inputs"""
|
73 |
-
|
74 |
-
# Validate inputs based on method
|
75 |
if method == "Upload GeoJSON":
|
76 |
if uploaded_file is None:
|
77 |
warning_message = "⚠️ **No GeoJSON file uploaded.** Please upload a GeoJSON file first."
|
78 |
history[-1] = (query, warning_message)
|
79 |
yield history, ""
|
80 |
return
|
81 |
-
|
|
|
|
|
|
|
|
|
|
|
82 |
if not country:
|
83 |
warning_message = "⚠️ **No country selected.** Please select a country to analyze reports."
|
84 |
history[-1] = (query, warning_message)
|
85 |
yield history, ""
|
86 |
return
|
87 |
-
|
88 |
-
|
|
|
89 |
response = ""
|
90 |
-
if method == "Upload GeoJSON":
|
91 |
-
full_response = f"Based on your uploaded GeoJSON file, I can help you analyze the deforestation patterns and EUDR compliance aspects in your area of interest. Your question: '{query}' is being processed against the geographic data you provided."
|
92 |
-
else:
|
93 |
-
full_response = f"Based on EUDR reports for {country}, I can help you understand deforestation patterns and compliance requirements. Your question: '{query}' is being analyzed against our {country} database."
|
94 |
-
|
95 |
-
# Simulate streaming response
|
96 |
words = full_response.split()
|
97 |
for word in words:
|
98 |
response += word + " "
|
99 |
history[-1] = (query, response)
|
100 |
yield history, "**Sources:** Sample source documents would appear here..."
|
101 |
-
await asyncio.sleep(0.
|
102 |
|
103 |
def toggle_search_method(method):
|
104 |
-
"""Toggle between GeoJSON upload and country selection"""
|
105 |
if method == "Upload GeoJSON":
|
106 |
-
return (
|
107 |
-
|
108 |
-
|
109 |
-
gr.update(value=None), # dropdown_country
|
110 |
-
)
|
111 |
-
else: # "Talk to Reports"
|
112 |
-
return (
|
113 |
-
gr.update(visible=False), # geojson_section
|
114 |
-
gr.update(visible=True), # reports_section
|
115 |
-
gr.update(), # dropdown_country
|
116 |
-
)
|
117 |
|
118 |
def change_sample_questions(key):
|
119 |
-
"""Update visible examples based on selected category"""
|
120 |
keys = list(SAMPLE_QUESTIONS.keys())
|
121 |
index = keys.index(key)
|
122 |
visible_bools = [False] * len(keys)
|
123 |
visible_bools[index] = True
|
124 |
return [gr.update(visible=visible_bools[i]) for i in range(len(keys))]
|
125 |
|
126 |
-
#
|
|
|
|
|
127 |
theme = gr.themes.Base(
|
128 |
primary_hue="green",
|
129 |
secondary_hue="blue",
|
@@ -131,54 +155,14 @@ theme = gr.themes.Base(
|
|
131 |
text_size=gr.themes.utils.sizes.text_sm,
|
132 |
)
|
133 |
|
134 |
-
# Custom CSS for DataFrame styling
|
135 |
-
custom_css = """
|
136 |
-
/* DataFrame text sizing - Modify these values to change text size */
|
137 |
-
.dataframe table {
|
138 |
-
font-size: 12px !important; /* Change this value (e.g., 10px, 14px, 16px) */
|
139 |
-
}
|
140 |
-
|
141 |
-
.dataframe th {
|
142 |
-
font-size: 13px !important; /* Header text size */
|
143 |
-
font-weight: 600 !important;
|
144 |
-
}
|
145 |
-
|
146 |
-
.dataframe td {
|
147 |
-
font-size: 12px !important; /* Cell text size */
|
148 |
-
padding: 8px !important; /* Cell padding */
|
149 |
-
}
|
150 |
-
|
151 |
-
/* Alternative size classes - change elem_classes="dataframe-small" in DataFrame component */
|
152 |
-
.dataframe-small table { font-size: 10px !important; }
|
153 |
-
.dataframe-small th { font-size: 11px !important; }
|
154 |
-
.dataframe-small td { font-size: 10px !important; }
|
155 |
-
|
156 |
-
.dataframe-medium table { font-size: 14px !important; }
|
157 |
-
.dataframe-medium th { font-size: 15px !important; }
|
158 |
-
.dataframe-medium td { font-size: 14px !important; }
|
159 |
-
|
160 |
-
.dataframe-large table { font-size: 16px !important; }
|
161 |
-
.dataframe-large th { font-size: 17px !important; }
|
162 |
-
.dataframe-large td { font-size: 16px !important; }
|
163 |
-
"""
|
164 |
-
|
165 |
init_prompt = """
|
166 |
-
Hello, I am EUDR Q&A, an AI-powered conversational assistant designed to help you understand EU Deforestation Regulation compliance and analysis.
|
167 |
-
|
168 |
-
💡 **How to use (tabs on right)**
|
169 |
-
- **Data Sources**: Choose to either upload a GeoJSON file for analysis or talk to EUDR reports filtered by country.
|
170 |
-
- **Examples**: Select from curated example questions across different categories.
|
171 |
-
- **Sources**: View the content sources used to generate answers for fact-checking.
|
172 |
-
|
173 |
-
⚠️ For limitations and data collection information, please check the **Disclaimer** tab.
|
174 |
"""
|
175 |
|
176 |
-
with gr.Blocks(title="EUDR Q&A", theme=theme
|
177 |
-
|
178 |
-
# Main Chat Interface
|
179 |
with gr.Tab("EUDR Q&A"):
|
180 |
with gr.Row():
|
181 |
-
# Left column - Chat interface (2/3 width)
|
182 |
with gr.Column(scale=2):
|
183 |
chatbot = gr.Chatbot(
|
184 |
value=[(None, init_prompt)],
|
@@ -188,194 +172,53 @@ with gr.Blocks(title="EUDR Q&A", theme=theme, css=custom_css) as demo:
|
|
188 |
avatar_images=(None, "🌳"),
|
189 |
height=500
|
190 |
)
|
191 |
-
|
192 |
-
|
193 |
-
|
194 |
-
|
195 |
-
|
196 |
-
|
197 |
-
|
198 |
-
|
199 |
-
feedback_thanks = gr.Markdown("Thanks for the feedback!", visible=False)
|
200 |
-
|
201 |
-
# Input textbox
|
202 |
-
with gr.Row():
|
203 |
-
textbox = gr.Textbox(
|
204 |
-
placeholder="Ask me anything about EUDR compliance or upload your GeoJSON for analysis!",
|
205 |
-
show_label=False,
|
206 |
-
scale=7,
|
207 |
-
lines=1,
|
208 |
-
interactive=True
|
209 |
-
)
|
210 |
-
|
211 |
-
# Right column - Controls and tabs (1/3 width)
|
212 |
with gr.Column(scale=1, variant="panel"):
|
213 |
with gr.Tabs() as tabs:
|
214 |
-
|
215 |
-
# Data Sources Tab
|
216 |
with gr.Tab("Data Sources", id=2):
|
217 |
search_method = gr.Radio(
|
218 |
choices=["Upload GeoJSON", "Talk to Reports"],
|
219 |
label="Choose data source",
|
220 |
-
|
221 |
-
value="Upload GeoJSON",
|
222 |
)
|
223 |
-
|
224 |
-
# GeoJSON Upload Section
|
225 |
with gr.Group(visible=True) as geojson_section:
|
226 |
-
uploaded_file = gr.File(
|
227 |
-
label="Upload GeoJSON File",
|
228 |
-
file_types=[".geojson", ".json"],
|
229 |
-
file_count="single"
|
230 |
-
)
|
231 |
upload_status = gr.Markdown("", visible=False)
|
232 |
-
|
233 |
-
# Results table for WHISP API response
|
234 |
-
results_table = gr.DataFrame(
|
235 |
-
label="Analysis Results",
|
236 |
-
visible=False,
|
237 |
-
interactive=False,
|
238 |
-
wrap=True,
|
239 |
-
elem_classes="dataframe"
|
240 |
-
)
|
241 |
-
|
242 |
-
# Talk to Reports Section
|
243 |
with gr.Group(visible=False) as reports_section:
|
244 |
-
dropdown_country = gr.Dropdown(
|
245 |
-
["Ecuador", "Guatemala"],
|
246 |
-
label="Select Country",
|
247 |
-
value=None,
|
248 |
-
interactive=True,
|
249 |
-
)
|
250 |
-
|
251 |
-
# Examples Tab
|
252 |
with gr.Tab("Examples", id=0):
|
253 |
examples_hidden = gr.Textbox(visible=False)
|
254 |
-
|
255 |
first_key = list(SAMPLE_QUESTIONS.keys())[0]
|
256 |
-
dropdown_samples = gr.Dropdown(
|
257 |
-
SAMPLE_QUESTIONS.keys(),
|
258 |
-
value=first_key,
|
259 |
-
interactive=True,
|
260 |
-
show_label=True,
|
261 |
-
label="Select a category of sample questions"
|
262 |
-
)
|
263 |
-
|
264 |
-
# Create example sections
|
265 |
sample_groups = []
|
266 |
for i, (key, questions) in enumerate(SAMPLE_QUESTIONS.items()):
|
267 |
examples_visible = True if i == 0 else False
|
268 |
with gr.Row(visible=examples_visible) as group_examples:
|
269 |
-
gr.Examples(
|
270 |
-
questions,
|
271 |
-
[examples_hidden],
|
272 |
-
examples_per_page=8,
|
273 |
-
run_on_click=False,
|
274 |
-
)
|
275 |
sample_groups.append(group_examples)
|
276 |
-
|
277 |
-
# Sources Tab
|
278 |
with gr.Tab("Sources", id=1):
|
279 |
-
sources_textbox = gr.HTML(
|
280 |
-
|
281 |
-
|
282 |
-
|
283 |
-
|
284 |
-
#
|
285 |
-
|
286 |
-
|
287 |
-
#### Welcome to EUDR Q&A!
|
288 |
-
|
289 |
-
This AI-powered assistant helps you understand EU Deforestation Regulation compliance and analyze geographic data.
|
290 |
-
|
291 |
-
## 💬 How to Ask Effective Questions
|
292 |
-
|
293 |
-
| ❌ Less Effective | ✅ More Effective |
|
294 |
-
|------------------|-------------------|
|
295 |
-
| "What is deforestation?" | "What are the main deforestation hotspots in Ecuador?" |
|
296 |
-
| "Tell me about compliance" | "What EUDR requirements apply to coffee imports from Guatemala?" |
|
297 |
-
| "Show me data" | "What is the deforestation rate in the uploaded region?" |
|
298 |
-
|
299 |
-
## 🔍 Using Data Sources
|
300 |
-
|
301 |
-
**Upload GeoJSON:** Upload your geographic data files for automatic analysis via WHISP API
|
302 |
-
**Talk to Reports:** Select Ecuador or Guatemala for country-specific EUDR analysis
|
303 |
-
|
304 |
-
## ⭐ Best Practices
|
305 |
-
|
306 |
-
- Be specific about regions, commodities, or time periods
|
307 |
-
- Ask one question at a time for clearer answers
|
308 |
-
- Use follow-up questions to explore topics deeper
|
309 |
-
- Provide context when possible
|
310 |
-
""")
|
311 |
-
|
312 |
-
# About Tab
|
313 |
-
with gr.Tab("About"):
|
314 |
-
gr.Markdown("""
|
315 |
-
## About EUDR Q&A
|
316 |
-
|
317 |
-
The **EU Deforestation Regulation (EUDR)** requires companies to ensure that specific commodities
|
318 |
-
placed on the EU market are deforestation-free and legally produced.
|
319 |
-
|
320 |
-
This AI-powered tool helps stakeholders:
|
321 |
-
- Understand EUDR compliance requirements
|
322 |
-
- Analyze geographic deforestation data using WHISP API
|
323 |
-
- Assess supply chain risks
|
324 |
-
- Navigate complex regulatory landscapes
|
325 |
-
|
326 |
-
**Developed by GIZ** to enhance accessibility and understanding of EUDR requirements
|
327 |
-
through advanced AI and geographic data processing capabilities.
|
328 |
-
|
329 |
-
### Key Features:
|
330 |
-
- Automatic analysis of uploaded GeoJSON files via WHISP API
|
331 |
-
- Country-specific EUDR compliance guidance
|
332 |
-
- Real-time question answering with source citations
|
333 |
-
- User-friendly interface for complex regulatory information
|
334 |
-
""")
|
335 |
-
|
336 |
-
# Disclaimer Tab
|
337 |
-
with gr.Tab("Disclaimer"):
|
338 |
-
gr.Markdown("""
|
339 |
-
## Important Disclaimers
|
340 |
-
|
341 |
-
⚠️ **Scope & Limitations:**
|
342 |
-
- This tool is designed for EUDR compliance assistance and geographic data analysis
|
343 |
-
- Responses should not be considered official legal or compliance advice
|
344 |
-
- Always consult qualified professionals for official compliance decisions
|
345 |
-
|
346 |
-
⚠️ **Data & Privacy:**
|
347 |
-
- Uploaded GeoJSON files are processed via external WHISP API for analysis
|
348 |
-
- We collect usage statistics to improve the tool
|
349 |
-
- Files are processed temporarily and not permanently stored
|
350 |
-
|
351 |
-
⚠️ **AI Limitations:**
|
352 |
-
- Responses are AI-generated and may contain inaccuracies
|
353 |
-
- The tool is a prototype under continuous development
|
354 |
-
- Always verify important information with authoritative sources
|
355 |
-
|
356 |
-
**Data Collection:** We collect questions, answers, feedback, and anonymized usage statistics
|
357 |
-
to improve tool performance based on legitimate interest in service enhancement.
|
358 |
-
|
359 |
-
By using this tool, you acknowledge these limitations and agree to use responses responsibly.
|
360 |
-
""")
|
361 |
-
|
362 |
-
# Event Handlers
|
363 |
-
|
364 |
-
# Toggle search method
|
365 |
-
search_method.change(
|
366 |
-
fn=toggle_search_method,
|
367 |
-
inputs=[search_method],
|
368 |
-
outputs=[geojson_section, reports_section, dropdown_country]
|
369 |
-
)
|
370 |
-
|
371 |
-
# File upload - automatically process when file is uploaded
|
372 |
uploaded_file.change(
|
373 |
fn=handle_geojson_upload,
|
374 |
inputs=[uploaded_file],
|
375 |
-
outputs=[upload_status, upload_status, results_table]
|
376 |
)
|
377 |
-
|
378 |
-
# Chat functionality
|
379 |
textbox.submit(
|
380 |
start_chat,
|
381 |
[textbox, chatbot],
|
@@ -383,17 +226,12 @@ with gr.Blocks(title="EUDR Q&A", theme=theme, css=custom_css) as demo:
|
|
383 |
queue=False
|
384 |
).then(
|
385 |
chat_response,
|
386 |
-
[textbox, chatbot, search_method, dropdown_country, uploaded_file],
|
387 |
[chatbot, sources_textbox]
|
388 |
).then(
|
389 |
-
|
390 |
-
outputs=[feedback_row]
|
391 |
-
).then(
|
392 |
-
finish_chat,
|
393 |
-
outputs=[textbox]
|
394 |
)
|
395 |
-
|
396 |
-
# Examples functionality
|
397 |
examples_hidden.change(
|
398 |
start_chat,
|
399 |
[examples_hidden, chatbot],
|
@@ -401,34 +239,13 @@ with gr.Blocks(title="EUDR Q&A", theme=theme, css=custom_css) as demo:
|
|
401 |
queue=False
|
402 |
).then(
|
403 |
chat_response,
|
404 |
-
[examples_hidden, chatbot, search_method, dropdown_country, uploaded_file],
|
405 |
[chatbot, sources_textbox]
|
406 |
).then(
|
407 |
-
|
408 |
-
outputs=[feedback_row]
|
409 |
-
).then(
|
410 |
-
finish_chat,
|
411 |
-
outputs=[textbox]
|
412 |
-
)
|
413 |
-
|
414 |
-
# Sample questions dropdown
|
415 |
-
dropdown_samples.change(
|
416 |
-
change_sample_questions,
|
417 |
-
[dropdown_samples],
|
418 |
-
sample_groups
|
419 |
-
)
|
420 |
-
|
421 |
-
# Feedback buttons
|
422 |
-
okay_btn.click(
|
423 |
-
lambda: (gr.update(visible=False), gr.update(visible=True)),
|
424 |
-
outputs=[feedback_row, feedback_thanks]
|
425 |
-
)
|
426 |
-
|
427 |
-
not_okay_btn.click(
|
428 |
-
lambda: (gr.update(visible=False), gr.update(visible=True)),
|
429 |
-
outputs=[feedback_row, feedback_thanks]
|
430 |
)
|
431 |
|
432 |
-
|
|
|
433 |
if __name__ == "__main__":
|
434 |
-
demo.launch()
|
|
|
1 |
import gradio as gr
|
2 |
import time
|
3 |
import pandas as pd
|
4 |
+
import asyncio
|
5 |
from uuid import uuid4
|
6 |
from gradio_client import Client, handle_file
|
7 |
|
8 |
+
# Sample questions for examples
|
9 |
SAMPLE_QUESTIONS = {
|
10 |
"Deforestation Analysis": [
|
11 |
"What are the main deforestation hotspots in Ecuador?",
|
|
|
24 |
]
|
25 |
}
|
26 |
|
27 |
+
# ------------------------
|
28 |
+
# NEW: Generate readable summary from WHISP API DataFrame
|
29 |
+
# ------------------------
|
30 |
+
def generate_summary(df: pd.DataFrame) -> str:
|
31 |
+
"""Generate human-readable summary from WHISP API output"""
|
32 |
+
try:
|
33 |
+
# Convert DataFrame to dict for easier access
|
34 |
+
data = {row[0]: row[1] for row in df.values}
|
35 |
+
|
36 |
+
country = data.get("Country", "Unknown")
|
37 |
+
admin = data.get("Admin_Level_1", "Unknown region")
|
38 |
+
area = data.get("Area", "Unknown")
|
39 |
+
risk_level = data.get("Risk level", "Unknown")
|
40 |
+
risk_pcrop = data.get("risk_pcrop", "Unknown")
|
41 |
+
risk_acrop = data.get("risk_acrop", "Unknown")
|
42 |
+
risk_timber = data.get("risk_timber", "Unknown")
|
43 |
+
def_after_2020 = data.get("TMF_def_after_2020", "0")
|
44 |
+
|
45 |
+
summary = f"""
|
46 |
+
**Analysis Summary**
|
47 |
+
|
48 |
+
The uploaded GeoJSON corresponds to a region in **{admin}, {country}**, covering about **{area} hectares**.
|
49 |
+
|
50 |
+
- **Overall Deforestation Risk**: The area is classified as **{risk_level} risk**, meaning there is a likelihood that agricultural or timber activities are linked to deforestation.
|
51 |
+
- **Perennial Crops Risk**: The risk from crops such as cocoa, coffee, and oil palm is **{risk_pcrop}**.
|
52 |
+
- **Annual Crops Risk**: The risk from crops like maize or soy is **{risk_acrop}**.
|
53 |
+
- **Timber Risk**: The risk linked to timber extraction is **{risk_timber}**.
|
54 |
+
- **Recent Deforestation**: Since 2020, about **{def_after_2020} hectares** of natural forest have been cleared in this area.
|
55 |
+
|
56 |
+
This indicates that while some crops may not be a major concern, perennial crops and timber extraction could present notable risks to deforestation-free compliance.
|
57 |
+
"""
|
58 |
+
return summary
|
59 |
+
except Exception as e:
|
60 |
+
return f"⚠️ Could not generate summary: {str(e)}"
|
61 |
+
|
62 |
+
# ------------------------
|
63 |
+
# GeoJSON upload handler
|
64 |
+
# ------------------------
|
65 |
def handle_geojson_upload(file):
|
66 |
"""Handle GeoJSON file upload and call WHISP API"""
|
67 |
if file is not None:
|
68 |
try:
|
69 |
# Initialize WHISP API client
|
70 |
client = Client("https://giz-chatfed-whisp.hf.space/")
|
71 |
+
|
72 |
# Call the API with the uploaded file
|
73 |
result = client.predict(
|
74 |
file=handle_file(file.name),
|
75 |
api_name="/get_statistics"
|
76 |
)
|
77 |
+
|
78 |
# Convert result to DataFrame
|
79 |
df = pd.DataFrame(result['data'], columns=result['headers'])
|
80 |
+
|
81 |
+
# Generate human-readable summary
|
82 |
+
summary = generate_summary(df)
|
83 |
+
|
84 |
return (
|
85 |
"✅ GeoJSON file processed successfully! Analysis results are displayed below.",
|
86 |
gr.update(visible=True), # upload_status
|
87 |
+
gr.update(value=df, visible=True), # results_table
|
88 |
+
summary # NEW: summary to send into chatbot
|
89 |
)
|
|
|
90 |
except Exception as e:
|
91 |
error_msg = f"❌ Error processing GeoJSON file: {str(e)}"
|
92 |
+
return (error_msg, gr.update(visible=True), gr.update(visible=False), None)
|
|
|
|
|
|
|
|
|
93 |
else:
|
94 |
+
return ("", gr.update(visible=False), gr.update(visible=False), None)
|
|
|
|
|
|
|
|
|
95 |
|
96 |
+
# ------------------------
|
97 |
+
# Chat functions
|
98 |
+
# ------------------------
|
99 |
def start_chat(query, history):
|
|
|
100 |
history = history + [(query, None)]
|
101 |
return gr.update(interactive=False), gr.update(selected=1), history
|
102 |
|
103 |
def finish_chat():
|
|
|
104 |
return gr.update(interactive=True, value="")
|
105 |
|
106 |
+
async def chat_response(query, history, method, country, uploaded_file, geojson_summary):
|
|
|
|
|
|
|
107 |
if method == "Upload GeoJSON":
|
108 |
if uploaded_file is None:
|
109 |
warning_message = "⚠️ **No GeoJSON file uploaded.** Please upload a GeoJSON file first."
|
110 |
history[-1] = (query, warning_message)
|
111 |
yield history, ""
|
112 |
return
|
113 |
+
else:
|
114 |
+
if geojson_summary:
|
115 |
+
full_response = geojson_summary
|
116 |
+
else:
|
117 |
+
full_response = f"Based on your uploaded GeoJSON file, I can help you analyze the deforestation patterns and EUDR compliance aspects in your area of interest."
|
118 |
+
else:
|
119 |
if not country:
|
120 |
warning_message = "⚠️ **No country selected.** Please select a country to analyze reports."
|
121 |
history[-1] = (query, warning_message)
|
122 |
yield history, ""
|
123 |
return
|
124 |
+
else:
|
125 |
+
full_response = f"Based on EUDR reports for {country}, I can help you understand deforestation patterns and compliance requirements."
|
126 |
+
|
127 |
response = ""
|
|
|
|
|
|
|
|
|
|
|
|
|
128 |
words = full_response.split()
|
129 |
for word in words:
|
130 |
response += word + " "
|
131 |
history[-1] = (query, response)
|
132 |
yield history, "**Sources:** Sample source documents would appear here..."
|
133 |
+
await asyncio.sleep(0.02)
|
134 |
|
135 |
def toggle_search_method(method):
|
|
|
136 |
if method == "Upload GeoJSON":
|
137 |
+
return (gr.update(visible=True), gr.update(visible=False), gr.update(value=None))
|
138 |
+
else:
|
139 |
+
return (gr.update(visible=False), gr.update(visible=True), gr.update())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
140 |
|
141 |
def change_sample_questions(key):
|
|
|
142 |
keys = list(SAMPLE_QUESTIONS.keys())
|
143 |
index = keys.index(key)
|
144 |
visible_bools = [False] * len(keys)
|
145 |
visible_bools[index] = True
|
146 |
return [gr.update(visible=visible_bools[i]) for i in range(len(keys))]
|
147 |
|
148 |
+
# ------------------------
|
149 |
+
# UI Setup
|
150 |
+
# ------------------------
|
151 |
theme = gr.themes.Base(
|
152 |
primary_hue="green",
|
153 |
secondary_hue="blue",
|
|
|
155 |
text_size=gr.themes.utils.sizes.text_sm,
|
156 |
)
|
157 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
158 |
init_prompt = """
|
159 |
+
Hello, I am EUDR Q&A, an AI-powered conversational assistant designed to help you understand EU Deforestation Regulation compliance and analysis.
|
160 |
+
I will answer your questions by using **EUDR reports and uploaded GeoJSON files**.
|
|
|
|
|
|
|
|
|
|
|
|
|
161 |
"""
|
162 |
|
163 |
+
with gr.Blocks(title="EUDR Q&A", theme=theme) as demo:
|
|
|
|
|
164 |
with gr.Tab("EUDR Q&A"):
|
165 |
with gr.Row():
|
|
|
166 |
with gr.Column(scale=2):
|
167 |
chatbot = gr.Chatbot(
|
168 |
value=[(None, init_prompt)],
|
|
|
172 |
avatar_images=(None, "🌳"),
|
173 |
height=500
|
174 |
)
|
175 |
+
textbox = gr.Textbox(
|
176 |
+
placeholder="Ask me anything about EUDR compliance or upload your GeoJSON for analysis!",
|
177 |
+
show_label=False,
|
178 |
+
scale=7,
|
179 |
+
lines=1,
|
180 |
+
interactive=True
|
181 |
+
)
|
182 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
183 |
with gr.Column(scale=1, variant="panel"):
|
184 |
with gr.Tabs() as tabs:
|
|
|
|
|
185 |
with gr.Tab("Data Sources", id=2):
|
186 |
search_method = gr.Radio(
|
187 |
choices=["Upload GeoJSON", "Talk to Reports"],
|
188 |
label="Choose data source",
|
189 |
+
value="Upload GeoJSON"
|
|
|
190 |
)
|
|
|
|
|
191 |
with gr.Group(visible=True) as geojson_section:
|
192 |
+
uploaded_file = gr.File(label="Upload GeoJSON File", file_types=[".geojson", ".json"], file_count="single")
|
|
|
|
|
|
|
|
|
193 |
upload_status = gr.Markdown("", visible=False)
|
194 |
+
results_table = gr.DataFrame(label="Analysis Results", visible=False, interactive=False, wrap=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
195 |
with gr.Group(visible=False) as reports_section:
|
196 |
+
dropdown_country = gr.Dropdown(["Ecuador", "Guatemala"], label="Select Country", value=None, interactive=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
197 |
with gr.Tab("Examples", id=0):
|
198 |
examples_hidden = gr.Textbox(visible=False)
|
|
|
199 |
first_key = list(SAMPLE_QUESTIONS.keys())[0]
|
200 |
+
dropdown_samples = gr.Dropdown(SAMPLE_QUESTIONS.keys(), value=first_key, interactive=True, show_label=True, label="Select a category of sample questions")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
201 |
sample_groups = []
|
202 |
for i, (key, questions) in enumerate(SAMPLE_QUESTIONS.items()):
|
203 |
examples_visible = True if i == 0 else False
|
204 |
with gr.Row(visible=examples_visible) as group_examples:
|
205 |
+
gr.Examples(questions, [examples_hidden], examples_per_page=8, run_on_click=False)
|
|
|
|
|
|
|
|
|
|
|
206 |
sample_groups.append(group_examples)
|
|
|
|
|
207 |
with gr.Tab("Sources", id=1):
|
208 |
+
sources_textbox = gr.HTML(show_label=False, value="Source documents will appear here after you ask a question...")
|
209 |
+
|
210 |
+
# Hidden state to store summary from WHISP API
|
211 |
+
geojson_summary = gr.State()
|
212 |
+
|
213 |
+
# Event handlers
|
214 |
+
search_method.change(fn=toggle_search_method, inputs=[search_method], outputs=[geojson_section, reports_section, dropdown_country])
|
215 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
216 |
uploaded_file.change(
|
217 |
fn=handle_geojson_upload,
|
218 |
inputs=[uploaded_file],
|
219 |
+
outputs=[upload_status, upload_status, results_table, geojson_summary]
|
220 |
)
|
221 |
+
|
|
|
222 |
textbox.submit(
|
223 |
start_chat,
|
224 |
[textbox, chatbot],
|
|
|
226 |
queue=False
|
227 |
).then(
|
228 |
chat_response,
|
229 |
+
[textbox, chatbot, search_method, dropdown_country, uploaded_file, geojson_summary],
|
230 |
[chatbot, sources_textbox]
|
231 |
).then(
|
232 |
+
finish_chat, outputs=[textbox]
|
|
|
|
|
|
|
|
|
233 |
)
|
234 |
+
|
|
|
235 |
examples_hidden.change(
|
236 |
start_chat,
|
237 |
[examples_hidden, chatbot],
|
|
|
239 |
queue=False
|
240 |
).then(
|
241 |
chat_response,
|
242 |
+
[examples_hidden, chatbot, search_method, dropdown_country, uploaded_file, geojson_summary],
|
243 |
[chatbot, sources_textbox]
|
244 |
).then(
|
245 |
+
finish_chat, outputs=[textbox]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
246 |
)
|
247 |
|
248 |
+
dropdown_samples.change(change_sample_questions, [dropdown_samples], sample_groups)
|
249 |
+
|
250 |
if __name__ == "__main__":
|
251 |
+
demo.launch()
|