Spaces:
GIZ
/
Running on CPU Upgrade

Romulan12 commited on
Commit
0b1d4d1
·
1 Parent(s): a4b0a09

changed stats fetching

Browse files
Files changed (1) hide show
  1. app.py +81 -27
app.py CHANGED
@@ -30,13 +30,16 @@ def format_whisp_statistics(df):
30
  # Extract required indicators from API response
31
  country = df['Country'].iloc[0]
32
  admin_level = df['Admin_Level_1'].iloc[0]
33
- area = round(df['Area'].iloc[0], 2)
 
34
  risk_level = df['risk_level'].iloc[0] if 'risk_level' in df.columns else "Not available"
35
  risk_pcrop = df['risk_pcrop'].iloc[0] if 'risk_pcrop' in df.columns else "Not available"
36
  risk_acrop = df['risk_acrop'].iloc[0] if 'risk_acrop' in df.columns else "Not available"
37
  risk_timber = df['risk_timber'].iloc[0] if 'risk_timber' in df.columns else "Not available"
38
- deforestation_after_2020 = df['TMF_def_after_2020'].iloc[0] if 'TMF_def_after_2020' in df.columns else 0
39
-
 
 
40
  # Format the text output
41
  output = f"""📊 Analysis Results for Your Plot
42
 
@@ -52,12 +55,46 @@ Risk Assessment:
52
  - Timber Risk: {risk_timber}
53
 
54
  Deforestation Analysis:
55
- - Deforestation after 2020: {round(deforestation_after_2020, 2)} hectares
56
  """
57
  return output
58
  except Exception as e:
59
  return f"Error formatting statistics: {str(e)}"
60
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
  def handle_geojson_upload(file):
62
  """Handle GeoJSON file upload and call WHISP API"""
63
  if file is not None:
@@ -99,30 +136,32 @@ def handle_geojson_upload(file):
99
 
100
  def retrieve_paragraphs(query):
101
  """Connect to retriever and retrieve paragraphs"""
102
- if file is not None:
103
- try:
104
- # Initialize WHISP API client
105
- client = Client("https://giz-eudr-retriever.hf.space/")
106
-
107
- # Call the API with the uploaded file
108
- result = client.predict(
109
  query=query,
 
 
 
 
110
  api_name="/retrieve"
111
- )
112
-
113
- return (
114
- results, # Keep formatted statistics for chat
115
  gr.update(visible=True), # Keep status visible
116
  gr.update(visible=False) # Always hide results table
117
  )
118
 
119
- except Exception as e:
120
- error_msg=(f"Error retrieving paragraphs: {str(e)}")
121
- return (
122
- error_msg,
123
- gr.update(visible=True), # upload_status
124
- gr.update(visible=False) # results_table
125
- )
126
  else:
127
  return (
128
  "",
@@ -140,6 +179,7 @@ def finish_chat():
140
  return gr.update(interactive=True, value="")
141
 
142
  async def chat_response(query, history, method, country, uploaded_file):
 
143
  """Generate chat response based on method and inputs"""
144
 
145
  # Validate inputs based on method
@@ -164,12 +204,26 @@ async def chat_response(query, history, method, country, uploaded_file):
164
  response = formatted_stats
165
  except Exception as e:
166
  response = f"Error processing file: {str(e)}"
167
- else:
168
- # Default response for other queries
169
- if method == "Upload GeoJSON":
170
- 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."
171
- else:
172
  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."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
173
 
174
  # Simulate streaming response
175
  words = response.split()
 
30
  # Extract required indicators from API response
31
  country = df['Country'].iloc[0]
32
  admin_level = df['Admin_Level_1'].iloc[0]
33
+ area = round(float(df['Area'].iloc[0]), 2) if 'Area' in df.columns else "Not available"
34
+
35
  risk_level = df['risk_level'].iloc[0] if 'risk_level' in df.columns else "Not available"
36
  risk_pcrop = df['risk_pcrop'].iloc[0] if 'risk_pcrop' in df.columns else "Not available"
37
  risk_acrop = df['risk_acrop'].iloc[0] if 'risk_acrop' in df.columns else "Not available"
38
  risk_timber = df['risk_timber'].iloc[0] if 'risk_timber' in df.columns else "Not available"
39
+
40
+ # TMF_def_after_2020 is a risk category, not hectares
41
+ def_after_2020 = df['TMF_def_after_2020'].iloc[0] if 'TMF_def_after_2020' in df.columns else "Not available"
42
+
43
  # Format the text output
44
  output = f"""📊 Analysis Results for Your Plot
45
 
 
55
  - Timber Risk: {risk_timber}
56
 
57
  Deforestation Analysis:
58
+ - Deforestation risk after 2020: {def_after_2020}
59
  """
60
  return output
61
  except Exception as e:
62
  return f"Error formatting statistics: {str(e)}"
63
 
64
+ # def format_whisp_statistics(df):
65
+ # """Format WhispAPI statistics into a standardized, readable text"""
66
+ # try:
67
+ # # Extract required indicators from API response
68
+ # country = df['Country'].iloc[0]
69
+ # admin_level = df['Admin_Level_1'].iloc[0]
70
+ # area = round(df['Area'].iloc[0], 2)
71
+ # risk_level = df['risk_level'].iloc[0] if 'risk_level' in df.columns else "Not available"
72
+ # risk_pcrop = df['risk_pcrop'].iloc[0] if 'risk_pcrop' in df.columns else "Not available"
73
+ # risk_acrop = df['risk_acrop'].iloc[0] if 'risk_acrop' in df.columns else "Not available"
74
+ # risk_timber = df['risk_timber'].iloc[0] if 'risk_timber' in df.columns else "Not available"
75
+ # deforestation_after_2020 = df['TMF_def_after_2020'].iloc[0] if 'TMF_def_after_2020' in df.columns else 0
76
+
77
+ # # Format the text output
78
+ # output = f"""📊 Analysis Results for Your Plot
79
+
80
+ # Plot Information:
81
+ # - Country: {country}
82
+ # - Administrative Region: {admin_level}
83
+ # - Total Area: {area} hectares
84
+
85
+ # Risk Assessment:
86
+ # - Overall Risk Level: {risk_level}
87
+ # - Permanent Crop Risk: {risk_pcrop}
88
+ # - Annual Crop Risk: {risk_acrop}
89
+ # - Timber Risk: {risk_timber}
90
+
91
+ # Deforestation Analysis:
92
+ # - Deforestation after 2020: {round(deforestation_after_2020, 2)} hectares
93
+ # """
94
+ # return output
95
+ # except Exception as e:
96
+ # return f"Error formatting statistics: {str(e)}"
97
+
98
  def handle_geojson_upload(file):
99
  """Handle GeoJSON file upload and call WHISP API"""
100
  if file is not None:
 
136
 
137
  def retrieve_paragraphs(query):
138
  """Connect to retriever and retrieve paragraphs"""
139
+
140
+ try:
141
+ # Call the API with the uploaded file
142
+ client = Client("https://giz-eudr-retriever.hf.space/")
143
+ result = client.predict(
 
 
144
  query=query,
145
+ reports_filter="",
146
+ sources_filter="",
147
+ subtype_filter="",
148
+ year_filter="",
149
  api_name="/retrieve"
150
+ )
151
+
152
+ return (
153
+ results,
154
  gr.update(visible=True), # Keep status visible
155
  gr.update(visible=False) # Always hide results table
156
  )
157
 
158
+ except Exception as e:
159
+ error_msg=(f"Error retrieving paragraphs: {str(e)}")
160
+ return (
161
+ error_msg,
162
+ gr.update(visible=True), # upload_status
163
+ gr.update(visible=False) # results_table
164
+ )
165
  else:
166
  return (
167
  "",
 
179
  return gr.update(interactive=True, value="")
180
 
181
  async def chat_response(query, history, method, country, uploaded_file):
182
+
183
  """Generate chat response based on method and inputs"""
184
 
185
  # Validate inputs based on method
 
204
  response = formatted_stats
205
  except Exception as e:
206
  response = f"Error processing file: {str(e)}"
207
+
208
+ # Talk to report
209
+ else:
210
+ try:
 
211
  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."
212
+
213
+ # Retrieve info
214
+ retrieved_info = retrieve_paragraphs(query)[0]
215
+ response = retrieved_info
216
+
217
+ except Exception as e:
218
+ response = f"Error retrieving information: {str(e)}"
219
+
220
+
221
+ # else:
222
+ # # Default response for other queries
223
+ # if method == "Upload GeoJSON":
224
+ # 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."
225
+ # else:
226
+ # 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."
227
 
228
  # Simulate streaming response
229
  words = response.split()