Spaces:
Running
on
CPU Upgrade
Running
on
CPU Upgrade
extend whisp output + translate
Browse files
app.py
CHANGED
@@ -13,6 +13,7 @@ from utils.logger import ChatLogger
|
|
13 |
from pathlib import Path
|
14 |
from huggingface_hub import CommitScheduler, HfApi
|
15 |
import os
|
|
|
16 |
# fetch tokens from Gradio secrets
|
17 |
SPACES_LOG = os.environ.get("EUDR_SPACES_LOG")
|
18 |
if not SPACES_LOG:
|
@@ -113,12 +114,7 @@ async def chat_response(query, history, method, country, uploaded_file, request=
|
|
113 |
history[-1] = (query, warning_message)
|
114 |
yield history, ""
|
115 |
return
|
116 |
-
|
117 |
-
# if not country:
|
118 |
-
# warning_message = "⚠️ **No se ha seleccionado ningún país.** Seleccione un país para analizar los informes."
|
119 |
-
# history[-1] = (query, warning_message)
|
120 |
-
# yield history, ""
|
121 |
-
# return
|
122 |
|
123 |
# Handle GeoJSON upload → use cached results
|
124 |
if method == "Subir GeoJson" and uploaded_file:
|
|
|
13 |
from pathlib import Path
|
14 |
from huggingface_hub import CommitScheduler, HfApi
|
15 |
import os
|
16 |
+
|
17 |
# fetch tokens from Gradio secrets
|
18 |
SPACES_LOG = os.environ.get("EUDR_SPACES_LOG")
|
19 |
if not SPACES_LOG:
|
|
|
114 |
history[-1] = (query, warning_message)
|
115 |
yield history, ""
|
116 |
return
|
117 |
+
|
|
|
|
|
|
|
|
|
|
|
118 |
|
119 |
# Handle GeoJSON upload → use cached results
|
120 |
if method == "Subir GeoJson" and uploaded_file:
|
utils/__pycache__/generator.cpython-310.pyc
CHANGED
Binary files a/utils/__pycache__/generator.cpython-310.pyc and b/utils/__pycache__/generator.cpython-310.pyc differ
|
|
utils/__pycache__/retriever.cpython-310.pyc
CHANGED
Binary files a/utils/__pycache__/retriever.cpython-310.pyc and b/utils/__pycache__/retriever.cpython-310.pyc differ
|
|
utils/__pycache__/whisp_api.cpython-310.pyc
CHANGED
Binary files a/utils/__pycache__/whisp_api.cpython-310.pyc and b/utils/__pycache__/whisp_api.cpython-310.pyc differ
|
|
utils/whisp_api.py
CHANGED
@@ -8,7 +8,7 @@ def get_value(df, colname):
|
|
8 |
match = df.loc[df["Column"] == colname, "Value"]
|
9 |
if not match.empty:
|
10 |
return match.values[0]
|
11 |
-
return "
|
12 |
|
13 |
def format_whisp_statistics(df):
|
14 |
"""Format WhispAPI statistics into readable text for end-users"""
|
@@ -36,13 +36,13 @@ def format_whisp_statistics(df):
|
|
36 |
try:
|
37 |
area_num = float(area_raw)
|
38 |
if area_num < 1:
|
39 |
-
area_text = f"{area_num:.3f}
|
40 |
elif area_num < 100:
|
41 |
-
area_text = f"{area_num:.2f}
|
42 |
else:
|
43 |
-
area_text = f"{area_num:,.1f}
|
44 |
except:
|
45 |
-
area_text = str(area_raw) if area_raw != "Not available" else "
|
46 |
|
47 |
risk_level = get_value(df, "risk_level")
|
48 |
risk_pcrop = get_value(df, "risk_pcrop")
|
@@ -53,19 +53,19 @@ def format_whisp_statistics(df):
|
|
53 |
# Helper function to format risk levels with colors/emojis
|
54 |
def format_risk(risk_val):
|
55 |
if not risk_val or risk_val in ["Not available", "not available"]:
|
56 |
-
return "
|
57 |
elif isinstance(risk_val, str):
|
58 |
risk_lower = risk_val.lower().strip()
|
59 |
if risk_lower == "low":
|
60 |
-
return "🟢
|
61 |
elif risk_lower == "medium":
|
62 |
-
return "🟡
|
63 |
elif risk_lower == "high":
|
64 |
-
return "🟠
|
65 |
elif risk_lower == "very high":
|
66 |
-
return "🔴
|
67 |
elif risk_lower == "more_info_needed":
|
68 |
-
return "
|
69 |
else:
|
70 |
return f"ℹ️ **{risk_val.title()}**"
|
71 |
return str(risk_val)
|
@@ -73,15 +73,15 @@ def format_whisp_statistics(df):
|
|
73 |
# Format deforestation data
|
74 |
def format_deforestation(def_val):
|
75 |
if not def_val or def_val in ["Not available", "not available"]:
|
76 |
-
return "
|
77 |
try:
|
78 |
def_num = float(def_val)
|
79 |
if def_num == 0:
|
80 |
-
return "
|
81 |
elif def_num < 0.1:
|
82 |
-
return f"
|
83 |
else:
|
84 |
-
return f"
|
85 |
except:
|
86 |
return f"ℹ️ **{def_val}**"
|
87 |
|
@@ -90,40 +90,39 @@ def format_whisp_statistics(df):
|
|
90 |
try:
|
91 |
def_num = float(def_after_2020)
|
92 |
if def_num == 0:
|
93 |
-
return "
|
94 |
elif def_num > 0:
|
95 |
-
return "
|
96 |
except:
|
97 |
-
return "
|
98 |
|
99 |
deforestation_formatted = format_deforestation(def_after_2020_raw)
|
100 |
compliance_status = get_compliance_status(def_after_2020_raw)
|
101 |
|
102 |
output = f""" **AI-Generated Response:** \n\n
|
103 |
|
104 |
-
|
105 |
|
106 |
-
|
107 |
-
- **Country**: {country} \n\n
|
108 |
-
- **Administrative Region**: {admin_level} \n\n
|
109 |
-
- **Total Area**: {area_text} \n\n
|
110 |
|
111 |
-
|
112 |
-
|
|
|
|
|
113 |
|
114 |
-
|
115 |
-
|
116 |
-
*Coffee, cocoa, palm oil, fruit trees* \n\n
|
117 |
-
- **Annual Crops**: {format_risk(risk_acrop)} \n\n
|
118 |
-
*Soy, corn, rice, vegetables* \n\n
|
119 |
-
- **Timber Extraction**: {format_risk(risk_timber)} \n\n
|
120 |
-
*Logging and wood harvesting* \n\n
|
121 |
|
122 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
123 |
|
124 |
-
💡 **Key Insights**
|
125 |
-
- **Risk Factors**: Focus on {', '.join([t.split('*')[1].strip('*') for t in [risk_pcrop, risk_acrop, risk_timber] if 'High' in format_risk(t)])} if any high-risk activities detected \n
|
126 |
-
- **Next Steps**: {"Conduct additional due diligence if recent deforestation is detected" if "ATTENTION" in compliance_status else "Continue monitoring and maintain documentation"} \n\n
|
127 |
"""
|
128 |
return output
|
129 |
except Exception as e:
|
|
|
8 |
match = df.loc[df["Column"] == colname, "Value"]
|
9 |
if not match.empty:
|
10 |
return match.values[0]
|
11 |
+
return "No disponible"
|
12 |
|
13 |
def format_whisp_statistics(df):
|
14 |
"""Format WhispAPI statistics into readable text for end-users"""
|
|
|
36 |
try:
|
37 |
area_num = float(area_raw)
|
38 |
if area_num < 1:
|
39 |
+
area_text = f"{area_num:.3f} hectáreas"
|
40 |
elif area_num < 100:
|
41 |
+
area_text = f"{area_num:.2f} hectáreas"
|
42 |
else:
|
43 |
+
area_text = f"{area_num:,.1f} hectáreas"
|
44 |
except:
|
45 |
+
area_text = str(area_raw) if area_raw != "Not available" else "No disponible"
|
46 |
|
47 |
risk_level = get_value(df, "risk_level")
|
48 |
risk_pcrop = get_value(df, "risk_pcrop")
|
|
|
53 |
# Helper function to format risk levels with colors/emojis
|
54 |
def format_risk(risk_val):
|
55 |
if not risk_val or risk_val in ["Not available", "not available"]:
|
56 |
+
return "**No disponible**"
|
57 |
elif isinstance(risk_val, str):
|
58 |
risk_lower = risk_val.lower().strip()
|
59 |
if risk_lower == "low":
|
60 |
+
return "🟢 *riesgo bajo*"
|
61 |
elif risk_lower == "medium":
|
62 |
+
return "🟡 *riesgo medio*"
|
63 |
elif risk_lower == "high":
|
64 |
+
return "🟠 *riesgo alto*"
|
65 |
elif risk_lower == "very high":
|
66 |
+
return "🔴 *riesgo muy alto*"
|
67 |
elif risk_lower == "more_info_needed":
|
68 |
+
return "*❓Se necesita más información.*"
|
69 |
else:
|
70 |
return f"ℹ️ **{risk_val.title()}**"
|
71 |
return str(risk_val)
|
|
|
73 |
# Format deforestation data
|
74 |
def format_deforestation(def_val):
|
75 |
if not def_val or def_val in ["Not available", "not available"]:
|
76 |
+
return "*No disponible*"
|
77 |
try:
|
78 |
def_num = float(def_val)
|
79 |
if def_num == 0:
|
80 |
+
return "* 🌳 No se detectó deforestación después de 2020.*"
|
81 |
elif def_num < 0.1:
|
82 |
+
return f"🌳 *{def_num:.3f} hectáreas de deforestación detectadas después de 2020*"
|
83 |
else:
|
84 |
+
return f" 🌳*{def_num:.2f} hectáreas de deforestación detectadas después de 2020*"
|
85 |
except:
|
86 |
return f"ℹ️ **{def_val}**"
|
87 |
|
|
|
90 |
try:
|
91 |
def_num = float(def_after_2020)
|
92 |
if def_num == 0:
|
93 |
+
return "**No se detectó deforestación después de 2020.**"
|
94 |
elif def_num > 0:
|
95 |
+
return "**Deforestación reciente detectada**"
|
96 |
except:
|
97 |
+
return "**Datos insuficientes para determinar el cumplimiento"
|
98 |
|
99 |
deforestation_formatted = format_deforestation(def_after_2020_raw)
|
100 |
compliance_status = get_compliance_status(def_after_2020_raw)
|
101 |
|
102 |
output = f""" **AI-Generated Response:** \n\n
|
103 |
|
104 |
+
**Resultados del análisis geográfico** \n\n
|
105 |
|
106 |
+
La siguiente información ha sido generada por la [WhispAPI creada por Forest Data Partnership (FDaP)](https://openforis.org/solutions/whisp/).
|
|
|
|
|
|
|
107 |
|
108 |
+
📍 **Detalles de la ubicación**
|
109 |
+
- **País**: {country} \n\n
|
110 |
+
- **Región administrativa**: {admin_level} \n\n
|
111 |
+
- **Área total**: {area_text} \n\n
|
112 |
|
113 |
+
⚠️ **Evaluación del riesgo de deforestación**
|
114 |
+
*Los niveles de riesgo se basan en patrones históricos, factores ambientales y datos sobre el uso del suelo. Si una zona tenía bosques saludables antes de 2020 y muestra deforestación después, se clasificará como de "alto riesgo".* \n\n
|
|
|
|
|
|
|
|
|
|
|
115 |
|
116 |
+
**Cultivos permanentes** (Café, cacao, aceite de palma, árboles frutales): \n\n
|
117 |
+
- {format_risk(risk_pcrop)} \n\n
|
118 |
+
**Cultivos anuales** (Soja, maíz, arroz, verduras): \n\n
|
119 |
+
- {format_risk(risk_acrop)} \n\n
|
120 |
+
**Extracción de madera** (Tala y recolección de madera): \n\n
|
121 |
+
- {format_risk(risk_timber)} \n\n
|
122 |
+
|
123 |
+
**Deforestación reciente (2020-presente):** \n\n
|
124 |
+
- {deforestation_formatted} \n\n
|
125 |
|
|
|
|
|
|
|
126 |
"""
|
127 |
return output
|
128 |
except Exception as e:
|