Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions AI-chatbot/chatbot.py
Original file line number Diff line number Diff line change
Expand Up @@ -461,6 +461,16 @@ def health_check():
def handle_chatbot_request(data):
data = data or {}
user_message = str(data.get("message", "")).strip()
lang = data.get("lang", "en")

try:
if lang and lang != "en":
from deep_translator import GoogleTranslator
user_message = GoogleTranslator(source=lang, target='en').translate(user_message)
except Exception as e:
print("Chatbot translation error (input):", e)
pass

context = data.get('context') # will be None if no analysis has been run yet

context_summary = ""
Expand Down Expand Up @@ -540,6 +550,14 @@ def level(val):
if response is None:
response = generate_response(user_message, context_summary)

try:
if lang and lang != "en":
from deep_translator import GoogleTranslator
response = GoogleTranslator(source='en', target=lang).translate(response)
except Exception as e:
print("Chatbot translation error (response):", e)
pass

return {
"success": True,
"response": response
Expand Down
190 changes: 104 additions & 86 deletions Frontend/Analysis/analysis.html

Large diffs are not rendered by default.

65 changes: 65 additions & 0 deletions Frontend/i18n.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
i18next
.use(i18nextHttpBackend)
.use(i18nextBrowserLanguageDetector)
.init({
fallbackLng: 'en',
backend: {
loadPath: '/locales/{{lng}}/translation.json',
}
}).then(() => {
const initLangSync = () => {
updateContent();
const langSelect = document.getElementById('langSelect');
if (langSelect && i18next.language) {
const baseLang = i18next.language.split('-')[0];
langSelect.value = baseLang;
}
};

if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', initLangSync);
} else {
initLangSync();
}
});

function updateContent() {
document.querySelectorAll('[data-i18n]').forEach(el => {
const key = el.getAttribute('data-i18n');
if (el.tagName === 'INPUT' && el.placeholder) {
el.placeholder = i18next.t(key);
} else {
el.innerHTML = i18next.t(key);
}
});
}

window.changeLanguage = function(lng) {
i18next.changeLanguage(lng).then(() => {
updateContent();
const langSelect = document.getElementById('langSelect');
if (langSelect && i18next.language) {
const baseLang = i18next.language.split('-')[0];
langSelect.value = baseLang;
}
});
}

// Intercept chatbot submissions to pass current language
document.addEventListener('DOMContentLoaded', () => {
// Override the native fetch to append language if hitting our endpoints
const originalFetch = window.fetch;
window.fetch = function() {
let [resource, config] = arguments;
if (typeof resource === 'string' && (resource.includes('/chatbot') || resource.includes('/weather'))) {
if (config && config.body && typeof config.body === 'string') {
try {
let bodyObj = JSON.parse(config.body);
bodyObj.lang = i18next.language || 'en';
config.body = JSON.stringify(bodyObj);
} catch(e) {}
}
}
return originalFetch.apply(this, arguments);
};
});
147 changes: 83 additions & 64 deletions Frontend/index.html

Large diffs are not rendered by default.

136 changes: 136 additions & 0 deletions Frontend/locales/en/translation.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
{
"nav_features": "Features",
"nav_analyze": "Analyze",
"nav_contact": "Contact",
"nav_github": "GitHub",
"nav_start_analysis": "Start Analysis",
"brand_subtitle": "Climate intelligence, instantly",
"hero_eyebrow": "Real-time weather risk monitoring",
"hero_title": "Predict climate threats before they interrupt your day.",
"hero_desc": "Climate Shield combines live weather signals with fast risk scoring to highlight flood and heatwave exposure in seconds.",
"hero_analyze_btn": "Analyze a location",
"hero_insights_btn": "View insights",
"stat_live": "live monitoring",
"stat_risk": "risk types tracked",
"stat_alert": "alert delivery",
"step_heading1": "3 steps to climate resilience",
"step_heading2": "Build stronger readiness with climate-smart actions.",
"step1_title": "Step 1",
"step1_desc": "Open the analysis page",
"step2_title": "Step 2",
"step2_desc": "Enter city, state, and country",
"step3_title": "Step 3",
"step3_desc": "Review weather, risk, and alerts",
"feat_heading1": "Why it helps",
"feat_heading2": "Built for quick decisions when weather conditions change.",
"feat1_title": "Live weather context",
"feat1_desc": "See current temperature, humidity, rainfall, and wind in one clean snapshot.",
"feat2_title": "Risk-first summary",
"feat2_desc": "Flood and heat risks are presented as clear signals, not just raw numbers.",
"feat3_title": "Actionable alerts",
"feat3_desc": "Important warnings are surfaced immediately so users can react faster.",
"cap_heading1": "Platform Capabilities",
"cap_heading2": "Powerful climate intelligence for proactive decision-making.",
"cap1_title": "Climate Risk Prediction",
"cap1_desc": "Predict potential climate threats using weather patterns and risk scoring models.",
"cap2_title": "Flood & Heatwave Analysis",
"cap2_desc": "Evaluate flood and heatwave risks with easy-to-understand climate indicators.",
"cap3_title": "AI-Powered Climate Assistant",
"cap3_desc": "Get instant answers and climate safety guidance through ClimateBot.",
"cap4_title": "Location-Based Insights",
"cap4_desc": "Analyze climate conditions for specific cities and regions worldwide.",
"cap5_title": "Environmental Intelligence",
"cap5_desc": "Access real-time environmental information to support informed decisions.",
"chatbot_title": "ClimateBot Assistant",
"chatbot_desc": "Ask about floods, heatwaves, cyclones, and climate change.",
"chatbot_placeholder": "Type your question...",
"chatbot_send": "Send",
"analysis_search_title": "Analyze Location Risk",
"analysis_search_desc": "Enter a location to receive instant risk scores for flood, heatwave, and other climate hazards.",
"analysis_city": "City",
"analysis_state": "State",
"analysis_country": "Country",
"analysis_btn": "Analyze Risks",
"analysis_loading": "Loading...",
"analysis_summary_title": "Climate Risk Summary",
"analysis_risk_score": "Risk Score",
"analysis_temperature": "Temperature",
"analysis_humidity": "Humidity",
"analysis_rainfall": "Rainfall",
"analysis_wind": "Wind",
"analysis_alerts_title": "Active Alerts",
"analysis_forecast_title": "Forecast",
"nav_analyze_now": "Analyze now",
"analysis_hero_eyebrow": "Weather analysis workspace",
"analysis_hero_h1": "Check flood and heat risk for any location in seconds.",
"analysis_hero_p": "Enter a city, state, and country to pull live weather data, summarize risk, and surface alerts in a clean, readable format.",
"stat_live_strong": "Live",
"stat_weather_fetch": "Weather fetch",
"stat_fast_strong": "Fast",
"stat_risk_scoring": "Risk scoring",
"stat_clear_strong": "Clear",
"stat_alert_feedback": "Alert feedback",
"analysis_workflow_lbl": "Analysis workflow",
"analysis_workflow_h2": "One focused workspace for live weather, risk summaries, and alerts.",
"analysis_workflow_p": "Use the form below to generate the report. The results panel appears beneath it so the flow reads like a clean report.",
"meta_live_fetch": "Live fetch",
"meta_weather_res": "Backend weather response",
"meta_risk_view": "Risk view",
"meta_signals": "Flood and heat signals",
"meta_alerts": "Alerts",
"meta_clear_output": "Clear output for action",
"analysis_use_loc": "Use Current Location",
"analysis_clear_all": "🗑 Clear All",
"analysis_recent_searches": "Recent Searches ▼",
"analysis_clear_history": "🗑 Clear History",
"analysis_complete_kicker": "Analysis complete",
"analysis_ready_review": "Ready to review location risk",
"analysis_waiting_input": "Waiting for input",
"analysis_loc_under": "📌 Location Under Analysis",
"analysis_demo_mode": "⚠️ Demo Mode Active: Serving simulated weather parameters.",
"analysis_live_weather_report": "📍 Live Weather Report",
"analysis_risk_analysis": "⚠ Climate Risk Analysis",
"analysis_map": "🗺 Interactive GIS Climate Map",
"analysis_recommendations": "🛡 Safety Recommendations",
"analysis_forecast_desc": "Forecast metrics modeled at 12:00 PM daily. Hover over values to inspect trends.",
"analysis_forecast_temp": "📈 Temperature & Rainfall Forecast",
"analysis_forecast_risk": "🛡 Daily Climate Risk Index Trends",
"analysis_subscribe_warnings": "🔔 Subscribe to Local Warnings",
"analysis_subscribe_desc": "Register your email to receive simulated notification dispatches when local risk levels exceed safety thresholds.",
"analysis_opt_all": "All Warnings",
"analysis_opt_flood": "Flooding Only",
"analysis_opt_heat": "Extreme Heat Only",
"analysis_opt_wildfire": "Wildfire Danger Only",
"analysis_activate_alert": "Activate Alert Stream",
"analysis_sub_active": "✓ Subscription active! Emergency dispatches will be routed to the live logs.",
"analysis_dispatch_title": "🛡 Climate Shield Emergency Dispatch",
"analysis_dispatch_desc": "Live alert logs processed for this region:",
"analysis_log1": "Monitoring node activated. No active hazards detected.",
"analysis_log2": "Moisture deficit elevated. Local crop warning active.",
"analysis_log3": "Flood threshold exceeded. Immediate action required.",
"widget_weather_status": "Weather Status",
"widget_flood_risk": "Flood Risk Gauge",
"widget_regional_alert": "REGIONAL EXPOSURE ALERT",
"analysis_flood_risk": "Flood Risk",
"analysis_heat_risk": "Heat Risk",
"analysis_wildfire_risk": "Wildfire Risk",
"analysis_cyclone_risk": "Cyclone Risk",
"analysis_drought_risk": "Drought Risk",
"brand_desc_short": "Real-time weather risk monitoring for flood and heatwave awareness.",
"brand_tagline": "Protecting communities with fast, simple climate risk visibility.",
"footer_nav": "Navigate",
"footer_nav_home": "Home",
"footer_nav_features": "Features",
"footer_nav_analysis": "Analysis",
"footer_nav_bot": "Climate Bot",
"footer_resources": "Resources",
"footer_res_issue": "Report an Issue",
"footer_res_discuss": "Discussions",
"footer_res_contrib": "Contributing",
"footer_res_docs": "Documentation",
"footer_community": "Community",
"footer_comm_contribs": "Contributors",
"footer_comm_github": "GitHub Repository",
"footer_comm_license": "MIT License",
"footer_made_by": "Made with ♥ by The Tech Guardians"
}
136 changes: 136 additions & 0 deletions Frontend/locales/es/translation.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
{
"nav_features": "Características",
"nav_analyze": "Analizar",
"nav_contact": "Contacto",
"nav_github": "GitHub",
"nav_start_analysis": "Iniciar análisis",
"brand_subtitle": "Inteligencia climática, al instante",
"hero_eyebrow": "Monitoreo de riesgos climáticos en tiempo real",
"hero_title": "Predice las amenazas climáticas antes de que interrumpan tu día.",
"hero_desc": "Climate Shield combina señales meteorológicas en vivo con una puntuación de riesgo rápida para resaltar la exposición a inundaciones y olas de calor en segundos.",
"hero_analyze_btn": "Analizar una ubicación",
"hero_insights_btn": "Ver estadísticas",
"stat_live": "monitoreo en vivo",
"stat_risk": "tipos de riesgo rastreados",
"stat_alert": "entrega de alerta",
"step_heading1": "Tres pasos para la resiliencia climática",
"step_heading2": "Fortalecer la preparación con acciones climáticamente inteligentes.",
"step1_title": "Paso 1",
"step1_desc": "Abrir la página de análisis",
"step2_title": "Paso 2",
"step2_desc": "Ingrese ciudad, estado y país",
"step3_title": "Paso 3",
"step3_desc": "Revisar el clima, el riesgo y las alertas.",
"feat_heading1": "Por qué ayuda",
"feat_heading2": "Diseñado para tomar decisiones rápidas cuando cambian las condiciones climáticas.",
"feat1_title": "Contexto meteorológico en vivo",
"feat1_desc": "Vea la temperatura, la humedad, las precipitaciones y el viento actuales en una instantánea clara.",
"feat2_title": "Resumen de riesgo primero",
"feat2_desc": "Los riesgos de inundaciones y calor se presentan como señales claras, no simplemente como números brutos.",
"feat3_title": "Alertas procesables",
"feat3_desc": "Las advertencias importantes aparecen inmediatamente para que los usuarios puedan reaccionar más rápido.",
"cap_heading1": "Capacidades de la plataforma",
"cap_heading2": "Potente inteligencia climática para la toma de decisiones proactiva.",
"cap1_title": "Predicción del riesgo climático",
"cap1_desc": "Prediga posibles amenazas climáticas utilizando patrones climáticos y modelos de puntuación de riesgos.",
"cap2_title": "Análisis de inundaciones y olas de calor",
"cap2_desc": "Evalúe los riesgos de inundaciones y olas de calor con indicadores climáticos fáciles de entender.",
"cap3_title": "Asistente climático impulsado por IA",
"cap3_desc": "Obtenga respuestas instantáneas y orientación sobre seguridad climática a través de ClimateBot.",
"cap4_title": "Información basada en la ubicación",
"cap4_desc": "Analice las condiciones climáticas de ciudades y regiones específicas de todo el mundo.",
"cap5_title": "Inteligencia ambiental",
"cap5_desc": "Acceda a información ambiental en tiempo real para respaldar decisiones informadas.",
"chatbot_title": "Asistente de ClimateBot",
"chatbot_desc": "Pregunte sobre inundaciones, olas de calor, ciclones y cambio climático.",
"chatbot_placeholder": "Escribe tu pregunta...",
"chatbot_send": "Enviar",
"analysis_search_title": "Analizar el riesgo de ubicación",
"analysis_search_desc": "Ingrese una ubicación para recibir puntuaciones de riesgo instantáneas de inundaciones, olas de calor y otros peligros climáticos.",
"analysis_city": "Ciudad",
"analysis_state": "Estado",
"analysis_country": "País",
"analysis_btn": "Analizar riesgos",
"analysis_loading": "Cargando...",
"analysis_summary_title": "Resumen de riesgos climáticos",
"analysis_risk_score": "Puntuación de riesgo",
"analysis_temperature": "Temperatura",
"analysis_humidity": "Humedad",
"analysis_rainfall": "Lluvia",
"analysis_wind": "Viento",
"analysis_alerts_title": "Alertas activas",
"analysis_forecast_title": "Pronóstico",
"nav_analyze_now": "Analizar ahora",
"analysis_hero_eyebrow": "Espacio de trabajo de análisis meteorológico",
"analysis_hero_h1": "Verifique el riesgo de inundaciones y calor en cualquier ubicación en segundos.",
"analysis_hero_p": "Ingrese una ciudad, estado y país para obtener datos meteorológicos en vivo, resumir riesgos y alertas de superficie en un formato limpio y legible.",
"stat_live_strong": "Vivir",
"stat_weather_fetch": "Búsqueda del tiempo",
"stat_fast_strong": "Rápido",
"stat_risk_scoring": "Puntuación de riesgo",
"stat_clear_strong": "Claro",
"stat_alert_feedback": "Comentarios de alerta",
"analysis_workflow_lbl": "Flujo de trabajo de análisis",
"analysis_workflow_h2": "Un espacio de trabajo enfocado para el clima en vivo, resúmenes de riesgos y alertas.",
"analysis_workflow_p": "Utilice el siguiente formulario para generar el informe. El panel de resultados aparece debajo para que el flujo se lea como un informe limpio.",
"meta_live_fetch": "búsqueda en vivo",
"meta_weather_res": "Respuesta meteorológica de backend",
"meta_risk_view": "Vista de riesgo",
"meta_signals": "Señales de inundaciones y calor",
"meta_alerts": "Alertas",
"meta_clear_output": "Resultados claros para la acción",
"analysis_use_loc": "Usar ubicación actual",
"analysis_clear_all": "🗑 Borrar todo",
"analysis_recent_searches": "Búsquedas recientes ▼",
"analysis_clear_history": "🗑 Borrar historial",
"analysis_complete_kicker": "Análisis completo",
"analysis_ready_review": "Listo para revisar el riesgo de ubicación",
"analysis_waiting_input": "Esperando entrada",
"analysis_loc_under": "📌 Ubicación bajo análisis",
"analysis_demo_mode": "⚠️ Modo de demostración activo: ofrece parámetros meteorológicos simulados.",
"analysis_live_weather_report": "📍 Informe meteorológico en vivo",
"analysis_risk_analysis": "⚠ Análisis de Riesgo Climático",
"analysis_map": "🗺 Mapa climático SIG interactivo",
"analysis_recommendations": "🛡 Recomendaciones de seguridad",
"analysis_forecast_desc": "Métricas de pronóstico modeladas a las 12:00 p.m. diariamente. Pase el cursor sobre los valores para inspeccionar las tendencias.",
"analysis_forecast_temp": "📈 Pronóstico de temperatura y precipitaciones",
"analysis_forecast_risk": "🛡 Tendencias diarias del índice de riesgo climático",
"analysis_subscribe_warnings": "🔔 Suscríbete a las advertencias locales",
"analysis_subscribe_desc": "Registre su correo electrónico para recibir envíos de notificaciones simuladas cuando los niveles de riesgo locales excedan los umbrales de seguridad.",
"analysis_opt_all": "Todas las advertencias",
"analysis_opt_flood": "Sólo inundaciones",
"analysis_opt_heat": "Sólo calor extremo",
"analysis_opt_wildfire": "Sólo peligro de incendio forestal",
"analysis_activate_alert": "Activar flujo de alerta",
"analysis_sub_active": "✓ ¡Suscripción activa! Los despachos de emergencia se enviarán a los registros activos.",
"analysis_dispatch_title": "🛡 Despacho de emergencia del Escudo Climático",
"analysis_dispatch_desc": "Registros de alertas en vivo procesados ​​para esta región:",
"analysis_log1": "Nodo de monitoreo activado. No se detectaron peligros activos.",
"analysis_log2": "Déficit de humedad elevado. Aviso de cultivo local activo.",
"analysis_log3": "Se superó el umbral de inundación. Se requiere acción inmediata.",
"widget_weather_status": "Estado del clima",
"widget_flood_risk": "Medidor de riesgo de inundaciones",
"widget_regional_alert": "ALERTA DE EXPOSICIÓN REGIONAL",
"analysis_flood_risk": "Riesgo de inundación",
"analysis_heat_risk": "Riesgo de calor",
"analysis_wildfire_risk": "Riesgo de incendios forestales",
"analysis_cyclone_risk": "Riesgo de ciclón",
"analysis_drought_risk": "Riesgo de sequía",
"brand_desc_short": "Monitoreo de riesgos climáticos en tiempo real para generar conciencia sobre inundaciones y olas de calor.",
"brand_tagline": "Proteger a las comunidades con una visibilidad rápida y sencilla del riesgo climático.",
"footer_nav": "Navegar por",
"footer_nav_home": "Hogar",
"footer_nav_features": "Características",
"footer_nav_analysis": "Análisis",
"footer_nav_bot": "Robot climático",
"footer_resources": "Recursos",
"footer_res_issue": "Informar un problema",
"footer_res_discuss": "Discusiones",
"footer_res_contrib": "Contribuyendo",
"footer_res_docs": "Documentación",
"footer_community": "Comunidad",
"footer_comm_contribs": "Colaboradores",
"footer_comm_github": "Repositorio GitHub",
"footer_comm_license": "Licencia MIT",
"footer_made_by": "Hecho con ♥ por The Tech Guardians"
}
Loading