Spaces:
Running
Running
Consoli Sergio
commited on
Commit
·
1e4a193
1
Parent(s):
83834cd
new dashboard version
Browse files- app_pyvis.py +230 -212
- app_pyvis_old.py +329 -0
app_pyvis.py
CHANGED
@@ -4,9 +4,58 @@ from datetime import date
|
|
4 |
import gradio as gr
|
5 |
from pyvis.network import Network
|
6 |
import ast
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
7 |
|
8 |
-
# Load the CSV file
|
9 |
-
df = pd.read_csv("https://jeodpp.jrc.ec.europa.eu/ftp/jrc-opendata/ETOHA/storylines/emdat2.csv", sep=',', header=0, dtype=str, encoding='utf-8')
|
10 |
|
11 |
def try_parse_date(y, m, d):
|
12 |
try:
|
@@ -16,6 +65,7 @@ def try_parse_date(y, m, d):
|
|
16 |
except (ValueError, TypeError):
|
17 |
return None
|
18 |
|
|
|
19 |
def plot_cgraph_pyvis(grp):
|
20 |
if not grp:
|
21 |
return "<div>No data available to plot.</div>"
|
@@ -44,268 +94,236 @@ def plot_cgraph_pyvis(grp):
|
|
44 |
html = net.generate_html()
|
45 |
html = html.replace("'", "\"")
|
46 |
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
|
|
|
|
|
|
|
|
|
|
53 |
return html_s
|
54 |
|
55 |
-
def display_info(selected_row_str, country, year, month, day, graph_type):
|
56 |
-
additional_fields = [
|
57 |
-
"Country", "ISO", "Subregion", "Region", "Location", "Origin",
|
58 |
-
"Disaster Group", "Disaster Subgroup", "Disaster Type", "Disaster Subtype", "External IDs",
|
59 |
-
"Event Name", "Associated Types", "OFDA/BHA Response", "Appeal", "Declaration",
|
60 |
-
"AID Contribution ('000 US$)", "Magnitude", "Magnitude Scale", "Latitude",
|
61 |
-
"Longitude", "River Basin", "Total Deaths", "No. Injured",
|
62 |
-
"No. Affected", "No. Homeless", "Total Affected",
|
63 |
-
"Reconstruction Costs ('000 US$)", "Reconstruction Costs, Adjusted ('000 US$)",
|
64 |
-
"Insured Damage ('000 US$)", "Insured Damage, Adjusted ('000 US$)",
|
65 |
-
"Total Damage ('000 US$)", "Total Damage, Adjusted ('000 US$)", "CPI",
|
66 |
-
"Admin Units",
|
67 |
-
]
|
68 |
-
|
69 |
-
if selected_row_str is None or selected_row_str == '':
|
70 |
-
print("No row selected.")
|
71 |
-
return ('', '', '', '', '', '', '', None, '', '') + tuple([''] * len(additional_fields))
|
72 |
-
|
73 |
-
print(f"Selected Country: {country}, Selected Row: {selected_row_str}, Date: {year}-{month}-{day}")
|
74 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
75 |
filtered_df = df
|
|
|
|
|
|
|
|
|
|
|
|
|
76 |
if country:
|
77 |
filtered_df = filtered_df[filtered_df['Country'] == country]
|
78 |
|
79 |
-
#
|
|
|
|
|
|
|
|
|
80 |
|
81 |
-
|
82 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
83 |
|
84 |
if not row_data.empty:
|
85 |
print(f"Row data: {row_data}")
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
-
causal_graph_caption = ''
|
101 |
grp = ast.literal_eval(causal_graph_caption) if causal_graph_caption else []
|
102 |
causal_graph_html = plot_cgraph_pyvis(grp)
|
103 |
|
104 |
# Parse and format the start date
|
105 |
-
|
106 |
-
start_date_str = start_date.strftime('%Y-%m-%d') if start_date else str(row_data['Start Year'])+"-"+str(row_data['Start Month'])+"-"+str(row_data['Start Day'])
|
107 |
|
108 |
# Parse and format the end date
|
109 |
-
|
110 |
-
end_date_str = end_date.strftime('%Y-%m-%d') if end_date else str(row_data['End Year'])+"-"+str(row_data['End Month'])+"-"+str(row_data['End Day'])
|
111 |
-
|
112 |
-
additional_data = [row_data.get(field, '') for field in additional_fields]
|
113 |
|
114 |
return (
|
115 |
-
|
116 |
-
severity,
|
117 |
-
key_drivers,
|
118 |
-
impacts_exposure_vulnerability,
|
119 |
-
likelihood_multi_hazard,
|
120 |
-
best_practices,
|
121 |
-
recommendations,
|
122 |
causal_graph_html,
|
123 |
start_date_str,
|
124 |
end_date_str
|
125 |
-
)
|
126 |
else:
|
127 |
print("No valid data found for the selection.")
|
128 |
-
return ('
|
129 |
-
|
130 |
-
def update_row_dropdown(country, year, month, day):
|
131 |
-
filtered_df = df
|
132 |
-
if country:
|
133 |
-
filtered_df = filtered_df[filtered_df['Country'] == country]
|
134 |
-
|
135 |
-
selected_date = try_parse_date(year, month, day)
|
136 |
-
|
137 |
-
if selected_date:
|
138 |
-
# filtered_rows = []
|
139 |
-
# for idx, row in filtered_df.iterrows():
|
140 |
-
# if (try_parse_date(row['Start Year'], row['Start Month'], row['Start Day']) is not None) and \
|
141 |
-
# (try_parse_date(row['End Year'], row['End Month'], row['End Day']) is not None) and \
|
142 |
-
# (try_parse_date(row['Start Year'], row['Start Month'], row['Start Day']) <= selected_date <= \
|
143 |
-
# try_parse_date(row['End Year'], row['End Month'], row['End Day'])):
|
144 |
-
# filtered_rows.append(row)
|
145 |
-
#
|
146 |
-
# filtered_df = pd.DataFrame(filtered_rows)
|
147 |
-
filtered_df = filtered_df[filtered_df.apply(
|
148 |
-
lambda row: (
|
149 |
-
(try_parse_date(row['Start Year'], "01" if row['Start Month'] == "" else row['Start Month'], "01" if row['Start Day'] == "" else row['Start Day']) is not None) and
|
150 |
-
(try_parse_date(row['End Year'], "01" if row['End Month'] == "" else row['End Month'], "01" if row['End Day'] == "" else row['End Day']) is not None) and
|
151 |
-
(try_parse_date(row['Start Year'], "01" if row['Start Month'] == "" else row['Start Month'], "01" if row['Start Day'] == "" else row['Start Day']) <= selected_date <=
|
152 |
-
try_parse_date(row['End Year'], "01" if row['End Month'] == "" else row['End Month'], "01" if row['End Day'] == "" else row['End Day']))
|
153 |
-
), axis=1)]
|
154 |
-
else:
|
155 |
-
|
156 |
-
if year:
|
157 |
-
sstart = None
|
158 |
-
eend = None
|
159 |
-
if month:
|
160 |
-
try:
|
161 |
-
sstart = try_parse_date(year, month, "01")
|
162 |
-
eend = try_parse_date(year, int(float(month)) + 1, "01")
|
163 |
-
except Exception as err:
|
164 |
-
print("Invalid selected date.")
|
165 |
-
sstart = None
|
166 |
-
eend = None
|
167 |
-
|
168 |
-
if sstart and eend:
|
169 |
-
filtered_df = filtered_df[filtered_df.apply(
|
170 |
-
lambda row: (
|
171 |
-
(try_parse_date(row['Start Year'], "01" if row['Start Month'] == "" else row['Start Month'], "01" if row['Start Day'] == "" else row['Start Day']) is not None) and
|
172 |
-
(sstart <= try_parse_date(row['Start Year'], "01" if row['Start Month'] == "" else row['Start Month'], "01" if row['Start Day'] == "" else row['Start Day']) < eend)
|
173 |
-
), axis=1)]
|
174 |
-
else:
|
175 |
-
try:
|
176 |
-
sstart = try_parse_date(year, "01", "01")
|
177 |
-
eend = try_parse_date(year, "12", "31")
|
178 |
-
except Exception as err:
|
179 |
-
print("Invalid selected date.")
|
180 |
-
sstart = None
|
181 |
-
eend = None
|
182 |
-
|
183 |
-
if sstart and eend:
|
184 |
-
filtered_df = filtered_df[filtered_df.apply(
|
185 |
-
lambda row: (
|
186 |
-
(try_parse_date(row['Start Year'], "01" if row['Start Month'] == "" else row['Start Month'], "01" if row['Start Day'] == "" else row['Start Day']) is not None) and
|
187 |
-
(sstart <= try_parse_date(row['Start Year'], "01" if row['Start Month'] == "" else row['Start Month'], "01" if row['Start Day'] == "" else row['Start Day']) <= eend)
|
188 |
-
), axis=1)]
|
189 |
-
|
190 |
-
else:
|
191 |
-
print("Invalid selected date.")
|
192 |
-
|
193 |
-
|
194 |
-
|
195 |
-
# Use the "DisNo." column for choices
|
196 |
-
choices = filtered_df['DisNo.'].tolist() if not filtered_df.empty else []
|
197 |
-
print(f"Available rows for {country} on {year}-{month}-{day}: {choices}")
|
198 |
-
return gr.update(choices=choices, value=choices[0] if choices else None)
|
199 |
|
200 |
|
201 |
def build_interface():
|
202 |
-
with gr.Blocks() as interface:
|
203 |
-
gr.Markdown("## From Data to Narratives: AI-Enhanced Disaster and Health Threats Storylines")
|
204 |
gr.Markdown(
|
205 |
-
"
|
206 |
-
|
207 |
-
|
208 |
-
|
209 |
-
|
210 |
-
|
211 |
-
|
212 |
-
|
213 |
-
|
214 |
-
|
215 |
-
|
216 |
-
|
217 |
-
|
218 |
-
|
219 |
-
|
220 |
-
|
221 |
-
|
222 |
-
|
223 |
-
|
224 |
-
|
225 |
-
|
226 |
-
|
227 |
-
|
228 |
-
|
229 |
)
|
230 |
|
231 |
-
|
232 |
-
|
233 |
-
|
234 |
-
"
|
235 |
-
|
236 |
-
|
237 |
-
|
238 |
-
"
|
239 |
-
|
240 |
-
|
241 |
-
|
242 |
-
|
|
|
|
|
243 |
|
244 |
with gr.Column():
|
245 |
-
|
246 |
-
#with gr.Column():
|
247 |
country_dropdown
|
248 |
-
year_dropdown
|
249 |
-
month_dropdown
|
250 |
-
day_dropdown
|
251 |
row_dropdown
|
252 |
-
graph_type_dropdown
|
253 |
|
254 |
-
gr.Markdown("### AI-Generated Storyline:")
|
255 |
outputs = [
|
256 |
-
gr.Textbox(label="
|
257 |
-
gr.Textbox(label="Severity", interactive=False),
|
258 |
-
gr.Textbox(label="Key Drivers", interactive=False),
|
259 |
-
gr.Textbox(label="Main Impacts, Exposure, and Vulnerability", interactive=False),
|
260 |
-
gr.Textbox(label="Likelihood of Multi-Hazard Risks", interactive=False),
|
261 |
-
gr.Textbox(label="Best Practices for Managing This Risk", interactive=False),
|
262 |
-
gr.Textbox(label="Recommendations and Supportive Measures for Recovery", interactive=False),
|
263 |
-
#gr.Markdown("### Causal Graph:"), # Title
|
264 |
gr.HTML(label="Causal Graph") # Change from gr.Plot to gr.HTML
|
265 |
]
|
266 |
|
267 |
-
#
|
268 |
-
gr.
|
269 |
-
|
270 |
-
gr.
|
271 |
-
gr.
|
272 |
-
|
273 |
-
|
274 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
275 |
|
|
|
276 |
country_dropdown.change(
|
277 |
fn=update_row_dropdown,
|
278 |
-
inputs=[
|
279 |
-
outputs=row_dropdown
|
280 |
-
)
|
281 |
-
year_dropdown.change(
|
282 |
-
fn=update_row_dropdown,
|
283 |
-
inputs=[country_dropdown, year_dropdown, month_dropdown, day_dropdown],
|
284 |
-
outputs=row_dropdown
|
285 |
-
)
|
286 |
-
month_dropdown.change(
|
287 |
-
fn=update_row_dropdown,
|
288 |
-
inputs=[country_dropdown, year_dropdown, month_dropdown, day_dropdown],
|
289 |
-
outputs=row_dropdown
|
290 |
-
)
|
291 |
-
day_dropdown.change(
|
292 |
-
fn=update_row_dropdown,
|
293 |
-
inputs=[country_dropdown, year_dropdown, month_dropdown, day_dropdown],
|
294 |
outputs=row_dropdown
|
295 |
)
|
296 |
|
|
|
297 |
row_dropdown.change(
|
298 |
fn=display_info,
|
299 |
-
inputs=[row_dropdown, country_dropdown
|
300 |
outputs=outputs
|
301 |
)
|
302 |
-
|
303 |
-
|
304 |
-
|
305 |
-
|
|
|
|
|
306 |
)
|
307 |
|
308 |
return interface
|
309 |
|
|
|
310 |
app = build_interface()
|
311 |
app.launch()
|
|
|
4 |
import gradio as gr
|
5 |
from pyvis.network import Network
|
6 |
import ast
|
7 |
+
from openai import OpenAI
|
8 |
+
import json
|
9 |
+
import string
|
10 |
+
from datetime import datetime
|
11 |
+
import random
|
12 |
+
|
13 |
+
EMM_RETRIEVERS_OPENAI_API_BASE_URL = "https://api-gpt.jrc.ec.europa.eu/v1"
|
14 |
+
with open('./data/gpt_token.json', 'r') as file:
|
15 |
+
config = json.load(file)
|
16 |
+
EMM_RETRIEVERS_OPENAI_API_KEY = config['EMM_RETRIEVERS_OPENAI_API_KEY']
|
17 |
+
|
18 |
+
client1 = OpenAI(
|
19 |
+
api_key=EMM_RETRIEVERS_OPENAI_API_KEY,
|
20 |
+
base_url="https://api-gpt.jrc.ec.europa.eu/v1",
|
21 |
+
)
|
22 |
+
|
23 |
+
df = pd.read_csv("https://jeodpp.jrc.ec.europa.eu/ftp/jrc-opendata/ETOHA/storylines/emdat2.csv", sep=',', header=0,
|
24 |
+
dtype=str, encoding='utf-8')
|
25 |
+
|
26 |
+
|
27 |
+
def gpt_story(storyline):
|
28 |
+
prompt = (
|
29 |
+
"Use the information provided to create a short, clear, and useful narrative about a disaster event. "
|
30 |
+
"The goal is to help decision-makers (e.g. policy makers, disaster managers, civil protection) understand what happened, why, and what it caused. "
|
31 |
+
"Keep it short and focused.\n\n"
|
32 |
+
"Include all key information, but keep the text concise and easy to read. Avoid technical jargon.\n\n"
|
33 |
+
"Steps to Follow:\n"
|
34 |
+
"1. Start with what happened: Briefly describe the disaster event (what, where, when, who was affected).\n"
|
35 |
+
"2. Explain why it happened: Use the evidence provided to describe possible causes or triggers (e.g. heavy rainfall, poor infrastructure, heatwave).\n"
|
36 |
+
"3. Show the impacts: Highlight key impacts such as fatalities, displacement, health effects, or damage.\n"
|
37 |
+
"4. Connect the dots: Show how different factors are linked. Use simple cause-effect language (e.g. drought led to crop failure, which caused food insecurity).\n"
|
38 |
+
"5. Mention complexity if needed: If there were multiple contributing factors or reinforcing effects (e.g. climate + conflict), briefly explain them.\n"
|
39 |
+
"6. Keep it useful: Write with a decision-maker in mind. Focus on what matters: drivers, impacts, and lessons for preparedness or response.\n\n"
|
40 |
+
f"Information: {storyline}"
|
41 |
+
)
|
42 |
+
|
43 |
+
completion = client1.chat.completions.create(
|
44 |
+
model='gpt-4o',
|
45 |
+
messages=[
|
46 |
+
{"role": "system", "content": "You are a disaster manager expert in risk dynamics."},
|
47 |
+
{"role": "user", "content": prompt}
|
48 |
+
]
|
49 |
+
)
|
50 |
+
|
51 |
+
# Extract the content from the response
|
52 |
+
message_content = completion.choices[0].message.content
|
53 |
+
return message_content
|
54 |
+
|
55 |
+
|
56 |
+
# DataFrame to store evaluation data
|
57 |
+
evaluation_df = pd.DataFrame(columns=["DisNo.", "TPN", "TPL", "FPN", "FPL", "FNN", "FNL", "User ID"])
|
58 |
|
|
|
|
|
59 |
|
60 |
def try_parse_date(y, m, d):
|
61 |
try:
|
|
|
65 |
except (ValueError, TypeError):
|
66 |
return None
|
67 |
|
68 |
+
|
69 |
def plot_cgraph_pyvis(grp):
|
70 |
if not grp:
|
71 |
return "<div>No data available to plot.</div>"
|
|
|
94 |
html = net.generate_html()
|
95 |
html = html.replace("'", "\"")
|
96 |
|
97 |
+
# Adjust the iframe style to center the graph and fit the container
|
98 |
+
html_s = f"""
|
99 |
+
<div style="display: flex; justify-content: center; align-items: center;">
|
100 |
+
<iframe style="width: 90%; height: 800px; margin: 0 auto;" name="result" allow="midi; geolocation; microphone; camera;
|
101 |
+
display-capture; encrypted-media;" sandbox="allow-modals allow-forms
|
102 |
+
allow-scripts allow-same-origin allow-popups
|
103 |
+
allow-top-navigation-by-user-activation allow-downloads" allowfullscreen=""
|
104 |
+
allowpaymentrequest="" frameborder="0" srcdoc='{html}'></iframe>
|
105 |
+
</div>
|
106 |
+
"""
|
107 |
+
|
108 |
return html_s
|
109 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
110 |
|
111 |
+
def generate_unique_user_id():
|
112 |
+
# Generate a timestamp string
|
113 |
+
timestamp_str = datetime.now().strftime("%Y%m%d%H%M%S")
|
114 |
+
# Generate a random string of 5 letters
|
115 |
+
random_str = ''.join(random.choices(string.ascii_letters, k=5))
|
116 |
+
# Combine both to form a unique User ID
|
117 |
+
return f"{timestamp_str}_{random_str}"
|
118 |
+
|
119 |
+
|
120 |
+
def save_data_to_csv():
|
121 |
+
# Save the evaluation DataFrame to a CSV file
|
122 |
+
evaluation_df.to_csv("evaluation_data.csv", index=False)
|
123 |
+
print("Data saved to CSV successfully.")
|
124 |
+
|
125 |
+
|
126 |
+
def save_data(dis_no, tpn, tpl, fp_node, fp_link, fn_node, fn_link):
|
127 |
+
global evaluation_df
|
128 |
+
|
129 |
+
# Debug: Print input values to ensure they're being received correctly
|
130 |
+
print(
|
131 |
+
f"Inputs received - DisNo: {dis_no}, TPN: {tpn}, TPL: {tpl}, FPN: {fp_node}, FPL: {fp_link}, FNN: {fn_node}, FNL: {fn_link}")
|
132 |
+
|
133 |
+
# Check if a valid disaster number has been selected
|
134 |
+
if not dis_no or dis_no == "Select a Disaster Event":
|
135 |
+
print("Invalid input. Ensure a disaster event is selected.")
|
136 |
+
return # Ensure no output is returned
|
137 |
+
|
138 |
+
# Generate a unique User ID
|
139 |
+
user_id = generate_unique_user_id()
|
140 |
+
|
141 |
+
# Append the new data to the DataFrame
|
142 |
+
new_data = pd.DataFrame([[dis_no, tpn, tpl, fp_node, fp_link, fn_node, fn_link, user_id]],
|
143 |
+
columns=["DisNo.", "TPN", "TPL", "FPN", "FPL", "FNN", "FNL", "User ID"])
|
144 |
+
evaluation_df = pd.concat([evaluation_df, new_data], ignore_index=True)
|
145 |
+
|
146 |
+
# Debug: Print the updated DataFrame to verify the new row addition
|
147 |
+
print("Updated DataFrame:")
|
148 |
+
print(evaluation_df)
|
149 |
+
|
150 |
+
# Save the DataFrame to a CSV file
|
151 |
+
save_data_to_csv()
|
152 |
+
|
153 |
+
print(
|
154 |
+
f"Data saved: DisNo: {dis_no}, TPN: {tpn}, TPL: {tpl}, FPN: {fp_node}, FPL: {fp_link}, FNN: {fn_node}, FNL: {fn_link}, User ID: {user_id}")
|
155 |
+
|
156 |
+
|
157 |
+
def update_row_dropdown(disaster_type=None, country=None):
|
158 |
+
# Start with the entire dataframe
|
159 |
filtered_df = df
|
160 |
+
|
161 |
+
# Step 1: Filter by Disaster Type
|
162 |
+
if disaster_type:
|
163 |
+
filtered_df = filtered_df[filtered_df['Disaster Type'] == disaster_type]
|
164 |
+
|
165 |
+
# Step 2: Further filter by Country
|
166 |
if country:
|
167 |
filtered_df = filtered_df[filtered_df['Country'] == country]
|
168 |
|
169 |
+
# Step 3: Generate the DisNo. choices based on the filtered DataFrame
|
170 |
+
choices = filtered_df['DisNo.'].tolist() if not filtered_df.empty else []
|
171 |
+
|
172 |
+
# Add a placeholder option at the beginning
|
173 |
+
choices = ["Select a Disaster Event"] + choices
|
174 |
|
175 |
+
print(f"Available DisNo. for {disaster_type} in {country}: {choices}")
|
176 |
+
|
177 |
+
# Return the update for the dropdown, defaulting to the placeholder
|
178 |
+
return gr.update(choices=choices, value=choices[0] if choices else None)
|
179 |
+
|
180 |
+
|
181 |
+
def display_info(selected_row_str, country):
|
182 |
+
if not selected_row_str or selected_row_str == 'Select a Disaster Event':
|
183 |
+
print("No valid disaster event selected.")
|
184 |
+
return ('No valid event selected.', '<div>No graph available.</div>', '', '')
|
185 |
+
|
186 |
+
print(f"Selected Country: {country}, Selected Row: {selected_row_str}")
|
187 |
+
|
188 |
+
# Filter the dataframe for the selected disaster number
|
189 |
+
row_data = df[df['DisNo.'] == selected_row_str].squeeze()
|
190 |
|
191 |
if not row_data.empty:
|
192 |
print(f"Row data: {row_data}")
|
193 |
+
|
194 |
+
# Combine the relevant columns into a single storyline with labels
|
195 |
+
storyline_parts = [
|
196 |
+
f"Key Information: {row_data.get('key information', '')}",
|
197 |
+
f"Severity: {row_data.get('severity', '')}",
|
198 |
+
f"Key Drivers: {row_data.get('key drivers', '')}",
|
199 |
+
f"Main Impacts, Exposure, and Vulnerability: {row_data.get('main impacts, exposure, and vulnerability', '')}",
|
200 |
+
f"Likelihood of Multi-Hazard Risks: {row_data.get('likelihood of multi-hazard risks', '')}",
|
201 |
+
f"Best Practices for Managing This Risk: {row_data.get('best practices for managing this risk', '')}",
|
202 |
+
f"Recommendations and Supportive Measures for Recovery: {row_data.get('recommendations and supportive measures for recovery', '')}"
|
203 |
+
]
|
204 |
+
storyline = "\n\n".join(part for part in storyline_parts if part.split(': ')[1]) # Include only non-empty parts
|
205 |
+
cleaned_storyline = gpt_story(storyline)
|
206 |
+
causal_graph_caption = row_data.get('llama graph', '')
|
|
|
207 |
grp = ast.literal_eval(causal_graph_caption) if causal_graph_caption else []
|
208 |
causal_graph_html = plot_cgraph_pyvis(grp)
|
209 |
|
210 |
# Parse and format the start date
|
211 |
+
start_date_str = f"{row_data['Start Year']}-{row_data['Start Month']}-{row_data['Start Day']}"
|
|
|
212 |
|
213 |
# Parse and format the end date
|
214 |
+
end_date_str = f"{row_data['End Year']}-{row_data['End Month']}-{row_data['End Day']}"
|
|
|
|
|
|
|
215 |
|
216 |
return (
|
217 |
+
cleaned_storyline,
|
|
|
|
|
|
|
|
|
|
|
|
|
218 |
causal_graph_html,
|
219 |
start_date_str,
|
220 |
end_date_str
|
221 |
+
)
|
222 |
else:
|
223 |
print("No valid data found for the selection.")
|
224 |
+
return ('No valid data found.', '<div>No graph available.</div>', '', '')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
225 |
|
226 |
|
227 |
def build_interface():
|
228 |
+
with gr.Blocks() as interface:
|
|
|
229 |
gr.Markdown(
|
230 |
+
"""
|
231 |
+
# From Complexity to Clarity: Leveraging AI to Decode Interconnected Risks
|
232 |
+
|
233 |
+
Welcome to our Gradio application, developed and maintained by [JRC](https://joint-research-centre.ec.europa.eu/index_en/) Units: **E1**, **F7**, and **T5**. This is part of the **EMBRACE Portfolio on Risks**. <br><br>
|
234 |
+
|
235 |
+
**Overview**:
|
236 |
+
This application employs advanced AI techniques like Retrieval-Augmented Generation (RAG) on [EMM](https://emm.newsbrief.eu/) news. It extracts relevant media content on disaster events recorded in [EM-DAT](https://www.emdat.be/), including floods, wildfires, droughts, epidemics, and disease outbreaks. <br><br>
|
237 |
+
|
238 |
+
**How It Works**:
|
239 |
+
For each selected event (filterable by Disaster Type, Country, and Disaster Number), the app:
|
240 |
+
- Retrieves pertinent news chunks via the EMM RAG service.
|
241 |
+
- Uses multiple LLMs from the [GPT@JRC](https://gpt.jrc.ec.europa.eu/) portfolio to:
|
242 |
+
- Extract critical impact data (e.g., fatalities, affected populations).
|
243 |
+
- Transform unstructured news into coherent, structured storylines.
|
244 |
+
- Build causal knowledge graphs — *impact chains* — highlighting drivers, impacts, and interactions. <br><br>
|
245 |
+
|
246 |
+
**Explore Events**:
|
247 |
+
Use the selectors below to explore events by **Disaster Type**, **Country**, and **Disaster Number (DisNo)**. <br>
|
248 |
+
Once an event is selected, the app will display the **causal impact-chain graph**, illustrating key factors and their interrelationships. <br>
|
249 |
+
Below the graph, you'll find the **AI-generated narrative**, presenting a structured storyline of the event based on relevant news coverage. <br><br>
|
250 |
+
|
251 |
+
**Outcome**:
|
252 |
+
These outputs offer a deeper understanding of disaster dynamics, supporting practitioners, disaster managers, and policy-makers in identifying patterns, assessing risks, and enhancing preparedness and response strategies.
|
253 |
+
"""
|
254 |
)
|
255 |
|
256 |
+
# Create dropdowns for Disaster Type, Country, and Disaster Event #
|
257 |
+
disaster_type_dropdown = gr.Dropdown(
|
258 |
+
choices=[''] + df['Disaster Type'].unique().tolist(),
|
259 |
+
label="Select Disaster Type"
|
260 |
+
)
|
261 |
+
country_dropdown = gr.Dropdown(
|
262 |
+
choices=[''], # Initially empty; will be populated based on disaster type
|
263 |
+
label="Select Country"
|
264 |
+
)
|
265 |
+
row_dropdown = gr.Dropdown(
|
266 |
+
choices=[],
|
267 |
+
label="Select Disaster Event #",
|
268 |
+
interactive=True
|
269 |
+
)
|
270 |
|
271 |
with gr.Column():
|
272 |
+
disaster_type_dropdown
|
|
|
273 |
country_dropdown
|
|
|
|
|
|
|
274 |
row_dropdown
|
|
|
275 |
|
276 |
+
gr.Markdown("### AI-Generated Storyline:") # Title
|
277 |
outputs = [
|
278 |
+
gr.Textbox(label="Storyline", interactive=False, lines=10),
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
279 |
gr.HTML(label="Causal Graph") # Change from gr.Plot to gr.HTML
|
280 |
]
|
281 |
|
282 |
+
# Inputs for evaluation metrics, placed after the graph
|
283 |
+
with gr.Row():
|
284 |
+
tpn_input = gr.Number(label="Num of Correct Nodes (TPN)", value=0, interactive=True)
|
285 |
+
tpl_input = gr.Number(label="Num of Correct Links (TPL)", value=0, interactive=True)
|
286 |
+
fp_node_input = gr.Number(label="False Positive Nodes (FPN)", value=0, interactive=True)
|
287 |
+
fp_link_input = gr.Number(label="False Positive Links (FPL)", value=0, interactive=True)
|
288 |
+
fn_node_input = gr.Number(label="False Negative Nodes (FNN)", value=0, interactive=True)
|
289 |
+
fn_link_input = gr.Number(label="False Negative Links (FNL)", value=0, interactive=True)
|
290 |
+
|
291 |
+
# Button to save the data
|
292 |
+
save_button = gr.Button("Save Data")
|
293 |
+
|
294 |
+
# Update country choices based on selected disaster type
|
295 |
+
disaster_type_dropdown.change(
|
296 |
+
fn=lambda disaster_type: gr.update(
|
297 |
+
choices=[''] + df[df['Disaster Type'] == disaster_type]['Country'].unique().tolist(),
|
298 |
+
value=''
|
299 |
+
),
|
300 |
+
inputs=disaster_type_dropdown,
|
301 |
+
outputs=country_dropdown
|
302 |
+
)
|
303 |
|
304 |
+
# Update DisNo. choices based on selected disaster type and country
|
305 |
country_dropdown.change(
|
306 |
fn=update_row_dropdown,
|
307 |
+
inputs=[disaster_type_dropdown, country_dropdown],
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
308 |
outputs=row_dropdown
|
309 |
)
|
310 |
|
311 |
+
# Display information based on selected DisNo.
|
312 |
row_dropdown.change(
|
313 |
fn=display_info,
|
314 |
+
inputs=[row_dropdown, country_dropdown],
|
315 |
outputs=outputs
|
316 |
)
|
317 |
+
|
318 |
+
# Handle saving data on button click
|
319 |
+
save_button.click(
|
320 |
+
fn=save_data,
|
321 |
+
inputs=[row_dropdown, tpn_input, tpl_input, fp_node_input, fp_link_input, fn_node_input, fn_link_input],
|
322 |
+
outputs=[]
|
323 |
)
|
324 |
|
325 |
return interface
|
326 |
|
327 |
+
|
328 |
app = build_interface()
|
329 |
app.launch()
|
app_pyvis_old.py
ADDED
@@ -0,0 +1,329 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import pandas as pd
|
3 |
+
from datetime import date
|
4 |
+
import gradio as gr
|
5 |
+
from pyvis.network import Network
|
6 |
+
import ast
|
7 |
+
|
8 |
+
# Load the CSV file
|
9 |
+
df = pd.read_csv("https://jeodpp.jrc.ec.europa.eu/ftp/jrc-opendata/ETOHA/storylines/emdat2.csv", sep=',', header=0,
|
10 |
+
dtype=str, encoding='utf-8')
|
11 |
+
|
12 |
+
|
13 |
+
def try_parse_date(y, m, d):
|
14 |
+
try:
|
15 |
+
if not y or not m or not d:
|
16 |
+
return None
|
17 |
+
return date(int(float(y)), int(float(m)), int(float(d)))
|
18 |
+
except (ValueError, TypeError):
|
19 |
+
return None
|
20 |
+
|
21 |
+
|
22 |
+
def plot_cgraph_pyvis(grp):
|
23 |
+
if not grp:
|
24 |
+
return "<div>No data available to plot.</div>"
|
25 |
+
|
26 |
+
net = Network(notebook=False, directed=True)
|
27 |
+
edge_colors_dict = {"causes": "red", "prevents": "green"}
|
28 |
+
|
29 |
+
for src, rel, tgt in grp:
|
30 |
+
src = str(src)
|
31 |
+
tgt = str(tgt)
|
32 |
+
rel = str(rel)
|
33 |
+
net.add_node(src, shape="circle", label=src)
|
34 |
+
net.add_node(tgt, shape="circle", label=tgt)
|
35 |
+
edge_color = edge_colors_dict.get(rel, 'black')
|
36 |
+
net.add_edge(src, tgt, title=rel, label=rel, color=edge_color)
|
37 |
+
|
38 |
+
net.repulsion(
|
39 |
+
node_distance=200,
|
40 |
+
central_gravity=0.2,
|
41 |
+
spring_length=200,
|
42 |
+
spring_strength=0.05,
|
43 |
+
damping=0.09
|
44 |
+
)
|
45 |
+
net.set_edge_smooth('dynamic')
|
46 |
+
|
47 |
+
html = net.generate_html()
|
48 |
+
html = html.replace("'", "\"")
|
49 |
+
|
50 |
+
html_s = f"""<iframe style="width: 200%; height: 800px;margin:0 auto" name="result" allow="midi; geolocation; microphone; camera;
|
51 |
+
display-capture; encrypted-media;" sandbox="allow-modals allow-forms
|
52 |
+
allow-scripts allow-same-origin allow-popups
|
53 |
+
allow-top-navigation-by-user-activation allow-downloads" allowfullscreen=""
|
54 |
+
allowpaymentrequest="" frameborder="0" srcdoc='{html}'></iframe>"""
|
55 |
+
|
56 |
+
return html_s
|
57 |
+
|
58 |
+
|
59 |
+
def display_info(selected_row_str, country, year, month, day, graph_type):
|
60 |
+
additional_fields = [
|
61 |
+
"Country", "ISO", "Subregion", "Region", "Location", "Origin",
|
62 |
+
"Disaster Group", "Disaster Subgroup", "Disaster Type", "Disaster Subtype", "External IDs",
|
63 |
+
"Event Name", "Associated Types", "OFDA/BHA Response", "Appeal", "Declaration",
|
64 |
+
"AID Contribution ('000 US$)", "Magnitude", "Magnitude Scale", "Latitude",
|
65 |
+
"Longitude", "River Basin", "Total Deaths", "No. Injured",
|
66 |
+
"No. Affected", "No. Homeless", "Total Affected",
|
67 |
+
"Reconstruction Costs ('000 US$)", "Reconstruction Costs, Adjusted ('000 US$)",
|
68 |
+
"Insured Damage ('000 US$)", "Insured Damage, Adjusted ('000 US$)",
|
69 |
+
"Total Damage ('000 US$)", "Total Damage, Adjusted ('000 US$)", "CPI",
|
70 |
+
"Admin Units",
|
71 |
+
]
|
72 |
+
|
73 |
+
if selected_row_str is None or selected_row_str == '':
|
74 |
+
print("No row selected.")
|
75 |
+
return ('', '', '', '', '', '', '', None, '', '') + tuple([''] * len(additional_fields))
|
76 |
+
|
77 |
+
print(f"Selected Country: {country}, Selected Row: {selected_row_str}, Date: {year}-{month}-{day}")
|
78 |
+
|
79 |
+
filtered_df = df
|
80 |
+
if country:
|
81 |
+
filtered_df = filtered_df[filtered_df['Country'] == country]
|
82 |
+
|
83 |
+
# Date filtering logic remains the same...
|
84 |
+
|
85 |
+
# Use the "DisNo." column for selecting the row
|
86 |
+
row_data = filtered_df[filtered_df['DisNo.'] == selected_row_str].squeeze()
|
87 |
+
|
88 |
+
if not row_data.empty:
|
89 |
+
print(f"Row data: {row_data}")
|
90 |
+
key_information = row_data.get('key information', '')
|
91 |
+
severity = row_data.get('severity', '')
|
92 |
+
key_drivers = row_data.get('key drivers', '')
|
93 |
+
impacts_exposure_vulnerability = row_data.get('main impacts, exposure, and vulnerability', '')
|
94 |
+
likelihood_multi_hazard = row_data.get('likelihood of multi-hazard risks', '')
|
95 |
+
best_practices = row_data.get('best practices for managing this risk', '')
|
96 |
+
recommendations = row_data.get('recommendations and supportive measures for recovery', '')
|
97 |
+
if graph_type == "LLaMA Graph":
|
98 |
+
causal_graph_caption = row_data.get('llama graph', '')
|
99 |
+
elif graph_type == "Mixtral Graph":
|
100 |
+
causal_graph_caption = row_data.get('mixtral graph', '')
|
101 |
+
elif graph_type == "Ensemble Graph":
|
102 |
+
causal_graph_caption = row_data.get('ensemble graph', '')
|
103 |
+
else:
|
104 |
+
causal_graph_caption = ''
|
105 |
+
grp = ast.literal_eval(causal_graph_caption) if causal_graph_caption else []
|
106 |
+
causal_graph_html = plot_cgraph_pyvis(grp)
|
107 |
+
|
108 |
+
# Parse and format the start date
|
109 |
+
start_date = try_parse_date(row_data['Start Year'], row_data['Start Month'], row_data['Start Day'])
|
110 |
+
start_date_str = start_date.strftime('%Y-%m-%d') if start_date else str(row_data['Start Year']) + "-" + str(
|
111 |
+
row_data['Start Month']) + "-" + str(row_data['Start Day'])
|
112 |
+
|
113 |
+
# Parse and format the end date
|
114 |
+
end_date = try_parse_date(row_data['End Year'], row_data['End Month'], row_data['End Day'])
|
115 |
+
end_date_str = end_date.strftime('%Y-%m-%d') if end_date else str(row_data['End Year']) + "-" + str(
|
116 |
+
row_data['End Month']) + "-" + str(row_data['End Day'])
|
117 |
+
|
118 |
+
additional_data = [row_data.get(field, '') for field in additional_fields]
|
119 |
+
|
120 |
+
return (
|
121 |
+
key_information,
|
122 |
+
severity,
|
123 |
+
key_drivers,
|
124 |
+
impacts_exposure_vulnerability,
|
125 |
+
likelihood_multi_hazard,
|
126 |
+
best_practices,
|
127 |
+
recommendations,
|
128 |
+
causal_graph_html,
|
129 |
+
start_date_str,
|
130 |
+
end_date_str
|
131 |
+
) + tuple(additional_data)
|
132 |
+
else:
|
133 |
+
print("No valid data found for the selection.")
|
134 |
+
return ('', '', '', '', '', '', '', None, '', '') + tuple([''] * len(additional_fields))
|
135 |
+
|
136 |
+
|
137 |
+
def update_row_dropdown(country, year, month, day):
|
138 |
+
filtered_df = df
|
139 |
+
if country:
|
140 |
+
filtered_df = filtered_df[filtered_df['Country'] == country]
|
141 |
+
|
142 |
+
selected_date = try_parse_date(year, month, day)
|
143 |
+
|
144 |
+
if selected_date:
|
145 |
+
# filtered_rows = []
|
146 |
+
# for idx, row in filtered_df.iterrows():
|
147 |
+
# if (try_parse_date(row['Start Year'], row['Start Month'], row['Start Day']) is not None) and \
|
148 |
+
# (try_parse_date(row['End Year'], row['End Month'], row['End Day']) is not None) and \
|
149 |
+
# (try_parse_date(row['Start Year'], row['Start Month'], row['Start Day']) <= selected_date <= \
|
150 |
+
# try_parse_date(row['End Year'], row['End Month'], row['End Day'])):
|
151 |
+
# filtered_rows.append(row)
|
152 |
+
#
|
153 |
+
# filtered_df = pd.DataFrame(filtered_rows)
|
154 |
+
filtered_df = filtered_df[filtered_df.apply(
|
155 |
+
lambda row: (
|
156 |
+
(try_parse_date(row['Start Year'], "01" if row['Start Month'] == "" else row['Start Month'],
|
157 |
+
"01" if row['Start Day'] == "" else row['Start Day']) is not None) and
|
158 |
+
(try_parse_date(row['End Year'], "01" if row['End Month'] == "" else row['End Month'],
|
159 |
+
"01" if row['End Day'] == "" else row['End Day']) is not None) and
|
160 |
+
(try_parse_date(row['Start Year'], "01" if row['Start Month'] == "" else row['Start Month'],
|
161 |
+
"01" if row['Start Day'] == "" else row['Start Day']) <= selected_date <=
|
162 |
+
try_parse_date(row['End Year'], "01" if row['End Month'] == "" else row['End Month'],
|
163 |
+
"01" if row['End Day'] == "" else row['End Day']))
|
164 |
+
), axis=1)]
|
165 |
+
else:
|
166 |
+
|
167 |
+
if year:
|
168 |
+
sstart = None
|
169 |
+
eend = None
|
170 |
+
if month:
|
171 |
+
try:
|
172 |
+
sstart = try_parse_date(year, month, "01")
|
173 |
+
eend = try_parse_date(year, int(float(month)) + 1, "01")
|
174 |
+
except Exception as err:
|
175 |
+
print("Invalid selected date.")
|
176 |
+
sstart = None
|
177 |
+
eend = None
|
178 |
+
|
179 |
+
if sstart and eend:
|
180 |
+
filtered_df = filtered_df[filtered_df.apply(
|
181 |
+
lambda row: (
|
182 |
+
(try_parse_date(row['Start Year'],
|
183 |
+
"01" if row['Start Month'] == "" else row['Start Month'],
|
184 |
+
"01" if row['Start Day'] == "" else row['Start Day']) is not None) and
|
185 |
+
(sstart <= try_parse_date(row['Start Year'],
|
186 |
+
"01" if row['Start Month'] == "" else row['Start Month'],
|
187 |
+
"01" if row['Start Day'] == "" else row['Start Day']) < eend)
|
188 |
+
), axis=1)]
|
189 |
+
else:
|
190 |
+
try:
|
191 |
+
sstart = try_parse_date(year, "01", "01")
|
192 |
+
eend = try_parse_date(year, "12", "31")
|
193 |
+
except Exception as err:
|
194 |
+
print("Invalid selected date.")
|
195 |
+
sstart = None
|
196 |
+
eend = None
|
197 |
+
|
198 |
+
if sstart and eend:
|
199 |
+
filtered_df = filtered_df[filtered_df.apply(
|
200 |
+
lambda row: (
|
201 |
+
(try_parse_date(row['Start Year'],
|
202 |
+
"01" if row['Start Month'] == "" else row['Start Month'],
|
203 |
+
"01" if row['Start Day'] == "" else row['Start Day']) is not None) and
|
204 |
+
(sstart <= try_parse_date(row['Start Year'],
|
205 |
+
"01" if row['Start Month'] == "" else row['Start Month'],
|
206 |
+
"01" if row['Start Day'] == "" else row['Start Day']) <= eend)
|
207 |
+
), axis=1)]
|
208 |
+
|
209 |
+
else:
|
210 |
+
print("Invalid selected date.")
|
211 |
+
|
212 |
+
# Use the "DisNo." column for choices
|
213 |
+
choices = filtered_df['DisNo.'].tolist() if not filtered_df.empty else []
|
214 |
+
print(f"Available rows for {country} on {year}-{month}-{day}: {choices}")
|
215 |
+
return gr.update(choices=choices, value=choices[0] if choices else None)
|
216 |
+
|
217 |
+
|
218 |
+
def build_interface():
|
219 |
+
with gr.Blocks() as interface:
|
220 |
+
gr.Markdown("## From Data to Narratives: AI-Enhanced Disaster and Health Threats Storylines")
|
221 |
+
gr.Markdown(
|
222 |
+
"This Gradio app complements Health Threats and Disaster event data through generative AI techniques, including the use of Retrieval Augmented Generation (RAG) with the [Europe Media Monitoring (EMM)](https://emm.newsbrief.eu/overview.html) service, "
|
223 |
+
"and Large Language Models (LLMs) from the [GPT@JRC](https://gpt.jrc.ec.europa.eu/) portfolio. <br>"
|
224 |
+
"The app leverages the EMM RAG service to retrieve relevant news chunks for each event data, transforms the unstructured news chunks into structured narratives and causal knowledge graphs using LLMs and text-to-graph techniques, linking health threats and disaster events to their causes and impacts. "
|
225 |
+
"Drawing data from sources like the [EM-DAT](https://www.emdat.be/) database, it augments each event with news-derived information in a storytelling fashion. <br>"
|
226 |
+
"This tool enables decision-makers to better explore health threats and disaster dynamics, identify patterns, and simulate scenarios for improved response and readiness. <br><br>"
|
227 |
+
"Select an event data below. You can filter by country and date period. Below, you will see the AI-generated storyline and causal knowledge graph, while on the right you can see the related EM-DAT data record. <br><br>") # Description -, and constructs disaster-specific ontologies. "
|
228 |
+
|
229 |
+
# Extract and prepare unique years from "Start Year" and "End Year"
|
230 |
+
if not df.empty:
|
231 |
+
start_years = df["Start Year"].dropna().unique()
|
232 |
+
end_years = df["End Year"].dropna().unique()
|
233 |
+
years = set(start_years.astype(int).tolist() + end_years.astype(int).tolist())
|
234 |
+
year_choices = sorted(years)
|
235 |
+
else:
|
236 |
+
year_choices = []
|
237 |
+
|
238 |
+
country_dropdown = gr.Dropdown(choices=[''] + df['Country'].unique().tolist(), label="Select Country")
|
239 |
+
year_dropdown = gr.Dropdown(choices=[""] + [str(year) for year in year_choices], label="Select Year")
|
240 |
+
month_dropdown = gr.Dropdown(choices=[""] + [f"{i:02d}" for i in range(1, 13)], label="Select Month")
|
241 |
+
day_dropdown = gr.Dropdown(choices=[""] + [f"{i:02d}" for i in range(1, 32)], label="Select Day")
|
242 |
+
row_dropdown = gr.Dropdown(choices=[], label="Select Disaster Event #", interactive=True)
|
243 |
+
graph_type_dropdown = gr.Dropdown(
|
244 |
+
choices=["LLaMA Graph", "Mixtral Graph", "Ensemble Graph"],
|
245 |
+
label="Select Graph Type"
|
246 |
+
)
|
247 |
+
|
248 |
+
additional_fields = [
|
249 |
+
"Country", "ISO", "Subregion", "Region", "Location", "Origin",
|
250 |
+
"Disaster Group", "Disaster Subgroup", "Disaster Type", "Disaster Subtype", "External IDs",
|
251 |
+
"Event Name", "Associated Types", "OFDA/BHA Response", "Appeal", "Declaration",
|
252 |
+
"AID Contribution ('000 US$)", "Magnitude", "Magnitude Scale", "Latitude",
|
253 |
+
"Longitude", "River Basin", "Total Deaths", "No. Injured",
|
254 |
+
"No. Affected", "No. Homeless", "Total Affected",
|
255 |
+
"Reconstruction Costs ('000 US$)", "Reconstruction Costs, Adjusted ('000 US$)",
|
256 |
+
"Insured Damage ('000 US$)", "Insured Damage, Adjusted ('000 US$)",
|
257 |
+
"Total Damage ('000 US$)", "Total Damage, Adjusted ('000 US$)", "CPI",
|
258 |
+
"Admin Units",
|
259 |
+
]
|
260 |
+
|
261 |
+
with gr.Column():
|
262 |
+
# with gr.Row():
|
263 |
+
# with gr.Column():
|
264 |
+
country_dropdown
|
265 |
+
year_dropdown
|
266 |
+
month_dropdown
|
267 |
+
day_dropdown
|
268 |
+
row_dropdown
|
269 |
+
graph_type_dropdown
|
270 |
+
|
271 |
+
gr.Markdown("### AI-Generated Storyline:"), # Title
|
272 |
+
outputs = [
|
273 |
+
gr.Textbox(label="Key Information", interactive=False),
|
274 |
+
gr.Textbox(label="Severity", interactive=False),
|
275 |
+
gr.Textbox(label="Key Drivers", interactive=False),
|
276 |
+
gr.Textbox(label="Main Impacts, Exposure, and Vulnerability", interactive=False),
|
277 |
+
gr.Textbox(label="Likelihood of Multi-Hazard Risks", interactive=False),
|
278 |
+
gr.Textbox(label="Best Practices for Managing This Risk", interactive=False),
|
279 |
+
gr.Textbox(label="Recommendations and Supportive Measures for Recovery", interactive=False),
|
280 |
+
# gr.Markdown("### Causal Graph:"), # Title
|
281 |
+
gr.HTML(label="Causal Graph") # Change from gr.Plot to gr.HTML
|
282 |
+
]
|
283 |
+
|
284 |
+
# with gr.Column():
|
285 |
+
gr.Markdown("### EMDAT2 Original Record:") # Title
|
286 |
+
outputs.extend([
|
287 |
+
gr.Textbox(label="Start Date", interactive=False),
|
288 |
+
gr.Textbox(label="End Date", interactive=False)
|
289 |
+
])
|
290 |
+
for field in additional_fields:
|
291 |
+
outputs.append(gr.Textbox(label=field, interactive=False))
|
292 |
+
|
293 |
+
country_dropdown.change(
|
294 |
+
fn=update_row_dropdown,
|
295 |
+
inputs=[country_dropdown, year_dropdown, month_dropdown, day_dropdown],
|
296 |
+
outputs=row_dropdown
|
297 |
+
)
|
298 |
+
year_dropdown.change(
|
299 |
+
fn=update_row_dropdown,
|
300 |
+
inputs=[country_dropdown, year_dropdown, month_dropdown, day_dropdown],
|
301 |
+
outputs=row_dropdown
|
302 |
+
)
|
303 |
+
month_dropdown.change(
|
304 |
+
fn=update_row_dropdown,
|
305 |
+
inputs=[country_dropdown, year_dropdown, month_dropdown, day_dropdown],
|
306 |
+
outputs=row_dropdown
|
307 |
+
)
|
308 |
+
day_dropdown.change(
|
309 |
+
fn=update_row_dropdown,
|
310 |
+
inputs=[country_dropdown, year_dropdown, month_dropdown, day_dropdown],
|
311 |
+
outputs=row_dropdown
|
312 |
+
)
|
313 |
+
|
314 |
+
row_dropdown.change(
|
315 |
+
fn=display_info,
|
316 |
+
inputs=[row_dropdown, country_dropdown, year_dropdown, month_dropdown, day_dropdown, graph_type_dropdown],
|
317 |
+
outputs=outputs
|
318 |
+
)
|
319 |
+
graph_type_dropdown.change(
|
320 |
+
fn=display_info,
|
321 |
+
inputs=[row_dropdown, country_dropdown, year_dropdown, month_dropdown, day_dropdown, graph_type_dropdown],
|
322 |
+
outputs=outputs
|
323 |
+
)
|
324 |
+
|
325 |
+
return interface
|
326 |
+
|
327 |
+
|
328 |
+
app = build_interface()
|
329 |
+
app.launch()
|