Spaces:
Running
Running
File size: 14,939 Bytes
d62fe22 fac2879 8934a69 d62fe22 c5b1871 d62fe22 c5b1871 d62fe22 878f6a7 d62fe22 c5b1871 d62fe22 c5b1871 d62fe22 794f0ae d62fe22 c5b1871 d62fe22 c5b1871 fe5e3fc d62fe22 4c0921d d62fe22 69e1ac7 d62fe22 ce74011 d62fe22 794f0ae d62fe22 ef2d491 d62fe22 ce74011 d62fe22 4d28cc3 d62fe22 4d28cc3 d62fe22 878f6a7 d62fe22 ce74011 4c0921d d62fe22 8035dd0 4d28cc3 4c0921d 4d28cc3 d62fe22 4d28cc3 d62fe22 4d28cc3 8035dd0 4d28cc3 d62fe22 878f6a7 c5b1871 d62fe22 c5b1871 d62fe22 c5b1871 d62fe22 c5b1871 d62fe22 c5b1871 d62fe22 c5b1871 d62fe22 4c0921d d62fe22 c5b1871 d62fe22 4c0921d d62fe22 ce74011 d62fe22 4c0921d d62fe22 4c0921d d62fe22 4c0921d 939a035 d62fe22 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 | import os
import requests
from io import BytesIO
from PyPDF2 import PdfReader
import streamlit as st
import folium
from streamlit_folium import st_folium
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain_community.embeddings import HuggingFaceEmbeddings
from langchain_community.vectorstores import FAISS
from groq import Groq
from dotenv import load_dotenv
load_dotenv()
# ------------------------------
# 🔐 API Keys
# ------------------------------
OPENWEATHER_API_KEY = os.environ.get("OPENWEATHER_API_KEY")
AQICN_TOKEN = os.environ.get("AQICN_TOKEN")
GROQ_API_KEY = os.environ.get("GROQ_API_KEY")
# ------------------------------
# ⚙️ Groq Client
# ------------------------------
@st.cache_resource
def get_groq_client():
return Groq(api_key=GROQ_API_KEY)
client = get_groq_client()
# ------------------------------
# 📚 RAG Functions
# ------------------------------
@st.cache_data
def get_drive_links():
return [
"https://drive.google.com/file/d/1wF5W8AcFhMgUUhaI7REAB-v780dL0b_B/view?usp=sharing",
"https://drive.google.com/file/d/1fLArYioom1V79kTlMcB2f8Ha9Q1pnK6e/view?usp=sharing",
"https://drive.google.com/file/d/1_dgKjKJ_uLHEzmofiXQplsNd3Dufh7GU/view?usp=sharing",
"https://drive.google.com/file/d/1EaLHe5Si_oS49-5NI-IkMjnWzNq-B6dR/view?usp=sharing",
"https://drive.google.com/file/d/1DhKj_tFqYpOK3uKZp2kqwuSfcn5QJfyr/view?usp=sharing",
"https://drive.google.com/file/d/1QqHjS7SUwA2HS1Px3Z-vEsR9X2qdTlF0/view?usp=sharing",
"https://drive.google.com/file/d/1BEzmnRmJweGVB6owFs6eteL9MYMn2VlX/view?usp=sharing",
"https://drive.google.com/file/d/1njXr8ubr42e5pEBCPeafc-frAMQO59UY/view?usp=sharing",
"https://drive.google.com/file/d/1ULrCcBuCrWL9OTr7ffFJbLQoQ9I2D2hJ/view?usp=sharing",
"https://drive.google.com/file/d/1kVQut_f-D5itnvTKzk5ZtFeGpW6oO9Lo/view?usp=sharing"
]
def download_pdf_from_drive(link):
file_id = link.split("/d/")[1].split("/")[0]
url = f"https://drive.google.com/uc?id={file_id}&export=download"
response = requests.get(url)
if response.status_code == 200:
return BytesIO(response.content)
raise Exception("Failed to download PDF.")
def extract_text_from_pdf(pdf_stream):
reader = PdfReader(pdf_stream)
text = ""
for page in reader.pages:
extracted = page.extract_text()
if extracted:
text += extracted
return text
def chunk_text(text, chunk_size=500, chunk_overlap=50):
splitter = RecursiveCharacterTextSplitter(
chunk_size=chunk_size, chunk_overlap=chunk_overlap
)
return splitter.split_text(text)
@st.cache_data(show_spinner="📚 Loading and processing all PDFs...")
def process_all_documents():
links = get_drive_links()
all_chunks = []
for link in links:
pdf = download_pdf_from_drive(link)
text = extract_text_from_pdf(pdf)
chunks = chunk_text(text)
all_chunks.extend(chunks)
return all_chunks
@st.cache_resource(show_spinner="🔍 Creating FAISS vector store...")
def build_vector_db(chunks):
embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
return FAISS.from_texts(chunks, embedding=embeddings)
def query_vector_db(query, vector_db):
docs = vector_db.similarity_search(query, k=3)
context = "\n".join([doc.page_content for doc in docs])
completion = client.chat.completions.create(
model="llama3-8b-8192",
messages=[
{"role": "system", "content": f"Use the following context:\n{context}"},
{"role": "user", "content": query},
]
)
return completion.choices[0].message.content
# ------------------------------
# 🛰 Weather & Risk Functions
# ------------------------------
def get_coordinates(province):
url = f"http://api.openweathermap.org/geo/1.0/direct?q={province}&limit=1&appid={OPENWEATHER_API_KEY}"
res = requests.get(url).json()
if res:
return res[0]['lat'], res[0]['lon']
return None, None
def get_weather(lat, lon):
url = f"https://api.openweathermap.org/data/2.5/weather?lat={lat}&lon={lon}&appid={OPENWEATHER_API_KEY}&units=metric"
res = requests.get(url).json()
return res['main']['temp'], res['weather'][0]['description']
def get_aqi(lat, lon):
url = f"https://api.waqi.info/feed/geo:{lat};{lon}/?token={AQICN_TOKEN}"
res = requests.get(url).json()
if res["status"] == "ok":
return res["data"]["aqi"]
return "Unavailable"
def get_heatwaves_risk(province):
data = {
"Nghe An": ("High heatwaves risk", "July–August"),
"Ha Noi": ("Moderate heatwaves risk", "June–August"),
"Gia Lai": ("Potential during peak summer", "July"),
}
return data.get(province.title(), ("No heatwaves alert", "N/A"))
def get_flood_risk(province):
data = {
"Son La": ("Mountainous flood risk (monsoon)", "July–September"),
"Quang Tri": ("Localized flooding in low-lying areas", "July–August"),
"An Giang": ("Saltwater intrusion risk due to sea level rise", "August–September"),
}
return data.get(province.title(), ("No flood alert", "N/A"))
def get_climate_advice(province, season, age, interest):
prompt = f"""As a climate adaptation advisor, suggest realistic, long-term actions someone can take in {province} during the {season} season to reduce their climate vulnerability.
The person is {age} years old and interested in {interest}. Consider disaster risks, water scarcity, heat, flooding, and energy challenges in {province}.
Make the advice practical, location-aware, and future-focused in Vietnamese."""
chat = client.chat.completions.create(
model="llama3-8b-8192",
messages=[{"role": "user", "content": prompt}]
)
return chat.choices[0].message.content
st.title("🌿 GXS-VietClimate (Trung tâm Nâng cao nhận thức về Biến đổi khí hậu và Thích ứng)")
# ------------------------------
# 🧭 Tabs
# ------------------------------
tabs = st.tabs(["🏠 Trang chủ", "🤖 Chatbot truy vấn", "🌍 Bản đồ Thông tin Khí hậu", "🧠 Cố vấn Thích ứng Khí hậu"])
# ------------------------------
# 🏠 Home Tab
# ------------------------------
with tabs[0]:
st.markdown("""
### 🧠 Nền tảng nâng cao nhận thức về biến đổi khí hậu ở Việt Nam
Việt Nam đang phải đối mặt với những thách thức nghiêm trọng về khí hậu:
- 🌡️ Nhiệt độ tăng cao và nắng nóng
- 🌊 Bão và lũ lụt
- 🚱 Nước biển dâng, xâm nhập mặn, sạt lở
- 💨 Chất lượng không khí kém
Những mối đe dọa khí hậu này:
- 🧒 Gây nguy hiểm cho sức khỏe cộng đồng, đặc biệt là trẻ em và người già
- 🌾 Gây gián đoạn cho nông nghiệp và an ninh lương thực, làm giảm năng suất cây trồng và đe dọa sinh kế
- 🏙️ Cơ sở hạ tầng đô thị quá tải, gây hư hại nhà cửa, đường sá và hệ thống thoát nước
- 💧 Làm cạn kiệt nguồn nước ngọt, khiến nước sạch trở nên khan hiếm đối với hàng triệu người
- ⚡ Hệ thống năng lượng căng thẳng, nhu cầu tăng trong khi nguồn cung năng lượng không theo kịp
- 🏞️ Đe dọa sự đa dạng sinh học và hệ sinh thái, từ vùng núi, cao nguyên đến bờ biển
- 🏠 Cộng đồng phải di dời, đặc biệt là ở những vùng dễ bị lũ lụt và hạn hán
Ứng dụng này cung cấp thông tin và trao quyền cho các cơ quan, tổ chức, cộng đồng, người dân và những người quan tâm để hiểu và hành động trước các rủi ro về khí hậu bằng cách sử dụng dữ liệu thời gian thực và hướng dẫn dài hạn.
Chúng ta cùng tạo ra sự thay đổi!
""")
st.markdown("### Tác động là rất lớn...")
image_files = ["img1.jpg", "img2.jpg", "img3.jpg"]
cols = st.columns(3)
for col, img in zip(cols, image_files):
if os.path.exists(img):
col.image(img, use_container_width=True)
else:
col.warning(f"Missing: {img}")
# ------------------------------
# 🤖 RAG Chatbot Tab
# ------------------------------
with tabs[1]:
st.title("📄 Chúng ta cùng tìm hiểu về Biến đổi khí hậu")
VECTOR_DB_PATH = "vector_store"
@st.cache_resource(show_spinner="🔍 Loading FAISS vector store or building it if not found...")
def get_or_load_vector_db():
embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
if os.path.exists(VECTOR_DB_PATH):
return FAISS.load_local(VECTOR_DB_PATH, embeddings, allow_dangerous_deserialization=True)
chunks = process_all_documents()
db = FAISS.from_texts(chunks, embedding=embeddings)
db.save_local(VECTOR_DB_PATH)
return db
if "vector_db" not in st.session_state:
st.session_state.vector_db = get_or_load_vector_db()
if "chat_history" not in st.session_state:
st.session_state.chat_history = []
st.markdown("#### 💡 Hãy hỏi một trong số câu thường gặp sau:")
faqs = [
"Biến đổi khí hậu là gì?",
"Tác động của Biến đổi khí hậu đến các đối tượng dễ bị tổn thương ở Việt Nam là gì?",
"Biến đổi khí hậu ảnh hưởng thế nào đến vấn đề di cư ở Việt Nam?",
"Chính phủ Việt Nam nhìn nhận vấn đề biến đổi khí hậu như thế nào?",
"Các hành động thích ứng với biến đổi khí hậu của Việt Nam?",
"Tài trợ cho nghiên cứu khoa học và phát triển công nghệ thích ứng như thế nào?",
"Cách tiếp cận trong đánh giá tác động của biến đổi khí hậu?",
"Xây dựng cộng đồng ứng phó hiệu quả với biến đổi khí hậu như thế nào?"
]
faq_cols = st.columns(2)
for i, faq in enumerate(faqs):
if faq_cols[i % 2].button(faq):
st.session_state.faq_query = faq
query = st.text_input("💬 Any other...", value=st.session_state.get("faq_query", ""))
col1, col2 = st.columns([1, 4])
with col1:
if st.button("🧹 Xóa hội thoại"):
st.session_state.chat_history = []
st.session_state.faq_query = ""
query = ""
if query:
response = query_vector_db(query, st.session_state.vector_db)
st.session_state.chat_history.append(("You", query))
st.session_state.chat_history.append(("AI", response))
st.session_state.faq_query = ""
if st.session_state.chat_history:
st.subheader("💬 Chat Conversation")
for role, msg in st.session_state.chat_history:
if role == "You":
st.markdown(f"**🧑 {role}:** {msg}")
else:
st.markdown(f"**🤖 {role}:** {msg}")
# ------------------------------
# 🌍 Climate Map Tab
# ------------------------------
with tabs[2]:
st.subheader("📍 Bản đồ Thời tiết & Rủi ro Khí hậu Thời gian thực")
province = st.text_input("🏙️ Hãy nhập tên một địa phương ở Việt Nam (VD: Lai Chau, Son La, Quang Tri, Hue, Quang Ngai, An Giang):")
if province:
lat, lon = get_coordinates(province)
if lat is not None:
temp, weather = get_weather(lat, lon)
aqi = get_aqi(lat, lon)
flood_alert, flood_period = get_flood_risk(province)
heatwaves_alert, heatwaves_period = get_heatwaves_risk(province)
st.markdown(f"""
**📍 Province:** {province.title()}
**🌡️ Temperature:** {temp}°C
**🌤️ Weather:** {weather}
**🌫️ AQI:** {aqi}
**🌊 Flood Risk:** {flood_alert}
⏰ *Active during:* {flood_period}
**🧊 Heatwaves Risk:** {heatwaves_alert}
⏰ *Active during:* {heatwaves_period}
""")
m = folium.Map(location=[lat, lon], zoom_start=6, tiles="cartodbpositron")
folium.raster_layers.WmsTileLayer(
url='https://firms.modaps.eosdis.nasa.gov/wms/',
name='FIRMS - Active Fires (MODIS)',
layers='fires_modis',
fmt='image/png',
transparent=True,
attr="NASA FIRMS"
).add_to(m)
folium.raster_layers.WmsTileLayer(
url='https://gibs.earthdata.nasa.gov/wms/epsg4326/best/wms.cgi?',
name='MODIS Snow/Ice Daily',
layers='MODIS_Terra_Snow_Cover_Daily',
fmt='image/png',
transparent=True,
attr="NASA GIBS"
).add_to(m)
folium.raster_layers.WmsTileLayer(
url='https://sedac.ciesin.columbia.edu/geoserver/wms',
name='Flood Hazard Frequency',
layers='ndh:flood-hazard-frequency-distribution',
fmt='image/png',
transparent=True,
attr="SEDAC"
).add_to(m)
folium.Marker([lat, lon], tooltip=f"{province.title()} | Temp: {temp}°C | AQI: {aqi}",
icon=folium.Icon(color="blue")).add_to(m)
for z in ["Nghe An", "Ha Noi", "Gia Lai"]:
z_lat, z_lon = get_coordinates(z)
folium.Marker([z_lat, z_lon], tooltip=z, icon=folium.Icon(color="red")).add_to(m)
for z in ["Son La", "Quang Tri", "An Giang"]:
z_lat, z_lon = get_coordinates(z)
folium.Marker([z_lat, z_lon], tooltip=z, icon=folium.Icon(color="orange")).add_to(m)
folium.LayerControl().add_to(m)
st_folium(m, width=700, height=500)
else:
st.error("❌ Không tìm thấy địa phương. Hãy viết lại!")
# ------------------------------
# 🧠 Climate Advisor Tab
# ------------------------------
with tabs[3]:
st.markdown("### 🧠 Cố vấn Thích ứng Khí hậu")
col1, col2 = st.columns(2)
with col1:
province = st.text_input("Tỉnh/Thành phố", "Dak Lak")
season = st.selectbox("Season", ["Hè - Summer", "Đông - Winter", "Xuân - Spring", "Thu - Autumn"])
with col2:
age = st.slider("Tuổi của Bạn - Your Age", 10, 80, 25)
interest = st.text_input("Quan tâm của Bạn - Your Interest", "Sức khỏe - Health")
if st.button("Tạo hướng dẫn"):
advice = get_climate_advice(province, season, age, interest)
st.success("✅ Climate Advice Generated:")
st.write(advice)
|