isana25 commited on
Commit
c5ab3c5
Β·
verified Β·
1 Parent(s): db5c75f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +74 -56
app.py CHANGED
@@ -1,76 +1,94 @@
 
 
1
  import streamlit as st
2
  from transformers import pipeline
3
  import requests
4
 
5
- # --- Must Be First: Set Page Config ---
6
- st.set_page_config(page_title="ClimateGPT 🌱", layout="centered")
7
 
8
- # --- Streamlit App UI ---
9
  st.title("🌍 ClimateGPT: Your Eco-Education Buddy")
10
- st.markdown("Learn about recycling, eco habits, carbon emissions and how to help the planet.")
11
- st.markdown("---")
 
 
12
 
13
- # --- Set API Key from Streamlit Secrets ---
14
- CLIMATIQ_API_KEY = st.secrets["climate_api"]
 
 
 
15
 
16
- # --- Load Lightweight, Fast Model ---
17
- @st.cache_resource
18
- def load_model():
19
- return pipeline("text2text-generation", model="google/flan-t5-small")
20
 
21
- llm = load_model()
 
22
 
23
- # --- Emission Calculator ---
24
- def get_emissions(distance_km=100):
25
- url = "https://beta3.api.climatiq.io/estimate"
26
- headers = {"Authorization": f"Bearer {CLIMATIQ_API_KEY}"}
27
- payload = {
28
- "emission_factor": {
29
- "activity_id": "passenger_vehicle-vehicle_type_car-fuel_source_na-engine_size_na-vehicle_age_na-vehicle_weight_na"
30
- },
31
- "parameters": {
32
- "distance": distance_km,
33
- "distance_unit": "km"
34
- }
35
- }
36
- try:
37
- response = requests.post(url, json=payload, headers=headers, timeout=10)
38
- data = response.json()
39
- co2 = data.get('co2e', 0)
40
- return f"{co2:.2f} kg COβ‚‚ for {distance_km} km"
41
- except requests.exceptions.RequestException:
42
- return "Emission data not available."
43
 
44
- # --- Optional: Translation using LibreTranslate ---
45
- def translate_text(text, target_lang="es"):
46
- if target_lang == "en":
47
- return text
48
  try:
49
- response = requests.post("https://libretranslate.de/translate", json={
 
 
50
  "q": text,
51
  "source": "en",
52
  "target": target_lang,
53
  "format": "text"
54
- }, timeout=8)
55
- return response.json().get('translatedText', text)
56
- except requests.exceptions.RequestException:
57
- return "Translation service is currently unavailable."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58
 
59
- # --- Chatbot Logic ---
60
- st.markdown("### πŸ’¬ Ask a climate-related question:")
61
- user_query = st.text_input("For example: How can I reduce plastic use? Or: How much COβ‚‚ is emitted in a 100km car trip?")
62
- target_language = st.selectbox("🌐 Translate the response to:", ["None", "en", "es", "fr", "de", "ur", "zh"], index=0)
63
 
64
- if st.button("🌿 Get Response") and user_query:
65
- with st.spinner("Generating eco-friendly answer..."):
66
- response = llm(user_query, max_length=200)[0]['generated_text']
 
 
67
 
68
- if target_language != "None":
69
- translated = translate_text(response, target_lang=target_language)
70
- st.success(translated)
71
- else:
72
- st.success(response)
 
73
 
74
- if any(word in user_query.lower() for word in ["carbon", "co2", "emission"]):
75
- emission = get_emissions()
76
- st.info(f"πŸš— Estimated Emissions: {emission}")
 
1
+ # app.py
2
+
3
  import streamlit as st
4
  from transformers import pipeline
5
  import requests
6
 
7
+ # 🟒 Streamlit Page Configuration (must be first Streamlit command)
8
+ st.set_page_config(page_title="ClimateGPT", layout="centered")
9
 
10
+ # 🌍 App Title and Intro
11
  st.title("🌍 ClimateGPT: Your Eco-Education Buddy")
12
+ st.markdown("""
13
+ Welcome to **ClimateGPT**, your personal assistant for learning about climate change, sustainability, and carbon footprint.
14
+ Ask a question in any supported language, and get informative answers with optional translation!
15
+ """)
16
 
17
+ # 🌐 Climate Topics for Filtering
18
+ CLIMATE_TOPICS = [
19
+ "climate", "carbon", "recycle", "emission", "eco", "green",
20
+ "pollution", "environment", "sustainability", "energy", "co2"
21
+ ]
22
 
23
+ # βœ… Relevance Check
24
+ def is_relevant_query(query):
25
+ return any(word in query.lower() for word in CLIMATE_TOPICS)
 
26
 
27
+ # 🧠 Load the lightweight model for faster response
28
+ llm = pipeline("text2text-generation", model="google/flan-t5-small")
29
 
30
+ # 🌍 Language Mapping for LibreTranslate
31
+ LANGUAGES = {
32
+ "English": "en",
33
+ "Urdu": "ur",
34
+ "Spanish": "es",
35
+ "French": "fr",
36
+ "German": "de",
37
+ "Chinese": "zh"
38
+ }
39
+
40
+ # πŸ“Œ LibreTranslate API Endpoint
41
+ TRANSLATE_API = "https://libretranslate.de/translate"
 
 
 
 
 
 
 
 
42
 
43
+ # πŸš€ Translation function
44
+ def translate_text(text, target_lang):
 
 
45
  try:
46
+ if target_lang == "en":
47
+ return text
48
+ payload = {
49
  "q": text,
50
  "source": "en",
51
  "target": target_lang,
52
  "format": "text"
53
+ }
54
+ response = requests.post(TRANSLATE_API, json=payload, timeout=10)
55
+ return response.json().get("translatedText", text)
56
+ except Exception as e:
57
+ return f"Translation failed: {e}"
58
+
59
+ # πŸš— Carbon Emission Estimation via Climatiq API
60
+ def get_carbon_estimate(distance_km):
61
+ headers = {
62
+ "Authorization": f"Bearer {st.secrets['climate_api']}"
63
+ }
64
+ payload = {
65
+ "emission_factor": {"activity_id": "passenger_vehicle-vehicle_type_car-fuel_source_na-engine_size_na-vehicle_age_na"},
66
+ "parameters": {"distance": distance_km, "distance_unit": "km"}
67
+ }
68
+ try:
69
+ response = requests.post("https://beta3.api.climatiq.io/estimate", headers=headers, json=payload)
70
+ emissions = response.json()["co2e"]
71
+ return f"Estimated COβ‚‚ Emission: {emissions:.2f} kg for {distance_km} km"
72
+ except:
73
+ return "Failed to fetch emission estimate."
74
 
75
+ # 🧾 User Inputs
76
+ user_query = st.text_input("Ask your climate-related question:")
77
+ language = st.selectbox("Choose output language:", list(LANGUAGES.keys()))
 
78
 
79
+ # ✈️ Optional Carbon Estimate
80
+ with st.expander("Optional: Estimate COβ‚‚ emissions for travel"):
81
+ distance = st.number_input("Enter travel distance in kilometers:", min_value=0.0, step=1.0)
82
+ if distance:
83
+ st.info(get_carbon_estimate(distance))
84
 
85
+ # πŸ“€ Process Query
86
+ if user_query:
87
+ if is_relevant_query(user_query):
88
+ response = llm(user_query, max_length=200, do_sample=False)[0]['generated_text']
89
+ else:
90
+ response = "❗ This chatbot only answers questions related to climate, sustainability, and eco-friendly habits."
91
 
92
+ translated_response = translate_text(response, LANGUAGES[language])
93
+ st.markdown("---")
94
+ st.markdown(f"**Response:** {translated_response}")