Spaces:
GIZ
/
Running on CPU Upgrade

Romulan12 commited on
Commit
a1c7621
·
1 Parent(s): c71c0cf

added UI changes

Browse files
Files changed (1) hide show
  1. app.py +65 -36
app.py CHANGED
@@ -1,6 +1,7 @@
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
 
@@ -23,6 +24,40 @@ 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:
@@ -39,10 +74,13 @@ def handle_geojson_upload(file):
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:
@@ -59,15 +97,12 @@ def handle_geojson_upload(file):
59
  gr.update(visible=False) # results_table
60
  )
61
 
62
-
63
- def retrieve_paragraphs(query):
64
-
65
  """Connect to retriever and retrieve paragraphs"""
66
-
67
  if file is not None:
68
  try:
69
  # Initialize WHISP API client
70
- client = Client("https://giz-eudr-retriever.hf.space/")
71
 
72
  # Call the API with the uploaded file
73
  result = client.predict(
@@ -75,27 +110,14 @@ def retrieve_paragraphs(query):
75
  api_name="/retrieve"
76
  )
77
 
78
- return (
79
- "These are the most relevant findings.",
80
- gr.update(visible=True), # upload_status
81
- gr.update(value=results, visible=True) # results_table
82
- )
83
 
84
  except Exception as e:
85
- error_msg = f"Error creating a response {str(e)}"
86
- return (
87
- error_msg,
88
- gr.update(visible=True), # upload_status
89
- gr.update(visible=False) # results_table
90
- )
91
-
92
- else:
93
- return (
94
- "",
95
- gr.update(visible=False), # upload_status
96
- gr.update(visible=False) # results_table
97
- )
98
-
99
 
100
  def start_chat(query, history):
101
  """Start a new chat interaction"""
@@ -123,18 +145,25 @@ async def chat_response(query, history, method, country, uploaded_file):
123
  yield history, ""
124
  return
125
 
126
- # Simulate processing time
127
- response = ""
128
- if method == "Upload GeoJSON":
129
- 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."
 
 
 
 
130
  else:
131
- 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."
 
 
 
 
132
 
133
  # Simulate streaming response
134
- words = full_response.split()
135
  for word in words:
136
- response += word + " "
137
- history[-1] = (query, response)
138
  yield history, "**Sources:** Sample source documents would appear here..."
139
  await asyncio.sleep(0.05)
140
 
@@ -469,4 +498,4 @@ with gr.Blocks(title="EUDR Q&A", theme=theme, css=custom_css) as demo:
469
 
470
  # Launch the app
471
  if __name__ == "__main__":
472
- 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
 
 
24
  ]
25
  }
26
 
27
+ def format_whisp_statistics(df):
28
+ """Format WhispAPI statistics into a standardized, readable text"""
29
+ try:
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
+
43
+ Plot Information:
44
+ - Country: {country}
45
+ - Administrative Region: {admin_level}
46
+ - Total Area: {area} hectares
47
+
48
+ Risk Assessment:
49
+ - Overall Risk Level: {risk_level}
50
+ - Permanent Crop Risk: {risk_pcrop}
51
+ - Annual Crop Risk: {risk_acrop}
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:
 
74
  # Convert result to DataFrame
75
  df = pd.DataFrame(result['data'], columns=result['headers'])
76
 
77
+ # Format statistics into readable text
78
+ formatted_stats = format_whisp_statistics(df)
79
+
80
  return (
81
+ formatted_stats, # Keep formatted statistics for chat
82
+ gr.update(visible=True), # Keep status visible
83
+ gr.update(visible=False) # Always hide results table
84
  )
85
 
86
  except Exception as e:
 
97
  gr.update(visible=False) # results_table
98
  )
99
 
100
+ def retrieve_paragraphs(file):
 
 
101
  """Connect to retriever and retrieve paragraphs"""
 
102
  if file is not None:
103
  try:
104
  # Initialize WHISP API client
105
+ client = Client("https://g...content-available-to-author-only...f.space/")
106
 
107
  # Call the API with the uploaded file
108
  result = client.predict(
 
110
  api_name="/retrieve"
111
  )
112
 
113
+ # Convert result to DataFrame
114
+ df = pd.DataFrame(result['data'], columns=result['headers'])
115
+ return df
 
 
116
 
117
  except Exception as e:
118
+ print(f"Error retrieving paragraphs: {str(e)}")
119
+ return None
120
+ return None
 
 
 
 
 
 
 
 
 
 
 
121
 
122
  def start_chat(query, history):
123
  """Start a new chat interaction"""
 
145
  yield history, ""
146
  return
147
 
148
+ # Get the formatted statistics if a file was just uploaded
149
+ if method == "Upload GeoJSON" and uploaded_file:
150
+ try:
151
+ stats_result = handle_geojson_upload(uploaded_file)
152
+ formatted_stats = stats_result[0] # Get the formatted statistics
153
+ response = formatted_stats
154
+ except Exception as e:
155
+ response = f"Error processing file: {str(e)}"
156
  else:
157
+ # Default response for other queries
158
+ if method == "Upload GeoJSON":
159
+ 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."
160
+ else:
161
+ 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."
162
 
163
  # Simulate streaming response
164
+ words = response.split()
165
  for word in words:
166
+ history[-1] = (query, " ".join(words[:words.index(word)+1]))
 
167
  yield history, "**Sources:** Sample source documents would appear here..."
168
  await asyncio.sleep(0.05)
169
 
 
498
 
499
  # Launch the app
500
  if __name__ == "__main__":
501
+ demo.launch()