Consoli Sergio commited on
Commit
6413247
·
1 Parent(s): d3b0ac9

one style column

Browse files
Files changed (1) hide show
  1. app_pyvis.py +311 -0
app_pyvis.py ADDED
@@ -0,0 +1,311 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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, dtype=str, encoding='utf-8')
10
+
11
+ def try_parse_date(y, m, d):
12
+ try:
13
+ if not y or not m or not d:
14
+ return None
15
+ return date(int(float(y)), int(float(m)), int(float(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>"
22
+
23
+ net = Network(notebook=False, directed=True)
24
+ edge_colors_dict = {"causes": "red", "prevents": "green"}
25
+
26
+ for src, rel, tgt in grp:
27
+ src = str(src)
28
+ tgt = str(tgt)
29
+ rel = str(rel)
30
+ net.add_node(src, shape="circle", label=src)
31
+ net.add_node(tgt, shape="circle", label=tgt)
32
+ edge_color = edge_colors_dict.get(rel, 'black')
33
+ net.add_edge(src, tgt, title=rel, label=rel, color=edge_color)
34
+
35
+ net.repulsion(
36
+ node_distance=200,
37
+ central_gravity=0.2,
38
+ spring_length=200,
39
+ spring_strength=0.05,
40
+ damping=0.09
41
+ )
42
+ net.set_edge_smooth('dynamic')
43
+
44
+ html = net.generate_html()
45
+ html = html.replace("'", "\"")
46
+
47
+ html_s = f"""<iframe style="width: 200%; height: 800px;margin:0 auto" name="result" allow="midi; geolocation; microphone; camera;
48
+ display-capture; encrypted-media;" sandbox="allow-modals allow-forms
49
+ allow-scripts allow-same-origin allow-popups
50
+ allow-top-navigation-by-user-activation allow-downloads" allowfullscreen=""
51
+ allowpaymentrequest="" frameborder="0" srcdoc='{html}'></iframe>"""
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
+ # Date filtering logic remains the same...
80
+
81
+ # Use the "DisNo." column for selecting the row
82
+ row_data = filtered_df[filtered_df['DisNo.'] == selected_row_str].squeeze()
83
+
84
+ if not row_data.empty:
85
+ print(f"Row data: {row_data}")
86
+ key_information = row_data.get('key information', '')
87
+ severity = row_data.get('severity', '')
88
+ key_drivers = row_data.get('key drivers', '')
89
+ impacts_exposure_vulnerability = row_data.get('main impacts, exposure, and vulnerability', '')
90
+ likelihood_multi_hazard = row_data.get('likelihood of multi-hazard risks', '')
91
+ best_practices = row_data.get('best practices for managing this risk', '')
92
+ recommendations = row_data.get('recommendations and supportive measures for recovery', '')
93
+ if graph_type == "LLaMA Graph":
94
+ causal_graph_caption = row_data.get('llama graph', '')
95
+ elif graph_type == "Mixtral Graph":
96
+ causal_graph_caption = row_data.get('mixtral graph', '')
97
+ elif graph_type == "Ensemble Graph":
98
+ causal_graph_caption = row_data.get('ensemble graph', '')
99
+ else:
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
+ start_date = try_parse_date(row_data['Start Year'], row_data['Start Month'], row_data['Start Day'])
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
+ end_date = try_parse_date(row_data['End Year'], row_data['End Month'], row_data['End Day'])
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
+ key_information,
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
+ ) + tuple(additional_data)
126
+ else:
127
+ print("No valid data found for the selection.")
128
+ return ('', '', '', '', '', '', '', None, '', '') + tuple([''] * len(additional_fields))
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
+ "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, "
206
+ "and Large Language Models (LLMs) from the [GPT@JRC](https://gpt.jrc.ec.europa.eu/) portfolio. <br>"
207
+ "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. "
208
+ "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>"
209
+ "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>"
210
+ "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. "
211
+
212
+ # Extract and prepare unique years from "Start Year" and "End Year"
213
+ if not df.empty:
214
+ start_years = df["Start Year"].dropna().unique()
215
+ end_years = df["End Year"].dropna().unique()
216
+ years = set(start_years.astype(int).tolist() + end_years.astype(int).tolist())
217
+ year_choices = sorted(years)
218
+ else:
219
+ year_choices = []
220
+
221
+ country_dropdown = gr.Dropdown(choices=[''] + df['Country'].unique().tolist(), label="Select Country")
222
+ year_dropdown = gr.Dropdown(choices=[""] + [str(year) for year in year_choices], label="Select Year")
223
+ month_dropdown = gr.Dropdown(choices=[""] + [f"{i:02d}" for i in range(1, 13)], label="Select Month")
224
+ day_dropdown = gr.Dropdown(choices=[""] + [f"{i:02d}" for i in range(1, 32)], label="Select Day")
225
+ row_dropdown = gr.Dropdown(choices=[], label="Select Disaster Event #", interactive=True)
226
+ graph_type_dropdown = gr.Dropdown(
227
+ choices=["LLaMA Graph", "Mixtral Graph", "Ensemble Graph"],
228
+ label="Select Graph Type"
229
+ )
230
+
231
+ additional_fields = [
232
+ "Country", "ISO", "Subregion", "Region", "Location", "Origin",
233
+ "Disaster Group", "Disaster Subgroup", "Disaster Type", "Disaster Subtype", "External IDs",
234
+ "Event Name", "Associated Types", "OFDA/BHA Response", "Appeal", "Declaration",
235
+ "AID Contribution ('000 US$)", "Magnitude", "Magnitude Scale", "Latitude",
236
+ "Longitude", "River Basin", "Total Deaths", "No. Injured",
237
+ "No. Affected", "No. Homeless", "Total Affected",
238
+ "Reconstruction Costs ('000 US$)", "Reconstruction Costs, Adjusted ('000 US$)",
239
+ "Insured Damage ('000 US$)", "Insured Damage, Adjusted ('000 US$)",
240
+ "Total Damage ('000 US$)", "Total Damage, Adjusted ('000 US$)", "CPI",
241
+ "Admin Units",
242
+ ]
243
+
244
+ with gr.Column():
245
+ #with gr.Row():
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:"), # Title
255
+ outputs = [
256
+ gr.Textbox(label="Key Information", interactive=False),
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
+ #with gr.Column():
268
+ gr.Markdown("### EMDAT2 Original Record:") # Title
269
+ outputs.extend([
270
+ gr.Textbox(label="Start Date", interactive=False),
271
+ gr.Textbox(label="End Date", interactive=False)
272
+ ])
273
+ for field in additional_fields:
274
+ outputs.append(gr.Textbox(label=field, interactive=False))
275
+
276
+ country_dropdown.change(
277
+ fn=update_row_dropdown,
278
+ inputs=[country_dropdown, year_dropdown, month_dropdown, day_dropdown],
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, year_dropdown, month_dropdown, day_dropdown, graph_type_dropdown],
300
+ outputs=outputs
301
+ )
302
+ graph_type_dropdown.change(
303
+ fn=display_info,
304
+ inputs=[row_dropdown, country_dropdown, year_dropdown, month_dropdown, day_dropdown, graph_type_dropdown],
305
+ outputs=outputs
306
+ )
307
+
308
+ return interface
309
+
310
+ app = build_interface()
311
+ app.launch()