Update src/streamlit_app.py
Browse files- src/streamlit_app.py +57 -116
src/streamlit_app.py
CHANGED
|
@@ -1,4 +1,3 @@
|
|
| 1 |
-
import os
|
| 2 |
import tempfile
|
| 3 |
import logging
|
| 4 |
import urllib.parse
|
|
@@ -6,78 +5,36 @@ import urllib.parse
|
|
| 6 |
import requests
|
| 7 |
import streamlit as st
|
| 8 |
from gtts import gTTS
|
| 9 |
-
from dotenv import load_dotenv
|
| 10 |
from translatepy import Translator
|
| 11 |
|
| 12 |
-
# --------------------
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
# -------------------- Configuration --------------------
|
| 16 |
-
WIKIPEDIA_API_BASE_URL_PREFIX = ".wikipedia.org/w/api.php"
|
| 17 |
-
ENGLISH_SUMMARY_SENTENCES = 5
|
| 18 |
-
WIKIMEDIA_HEADERS = {
|
| 19 |
-
'User-Agent': 'WikiHealthNavigator/1.0 (contact@example.com)'
|
| 20 |
-
}
|
| 21 |
-
REQUEST_TIMEOUT = 30
|
| 22 |
translator = Translator()
|
| 23 |
|
| 24 |
-
|
| 25 |
-
logger.setLevel(logging.DEBUG)
|
| 26 |
|
| 27 |
-
# --------------------
|
| 28 |
@st.cache_data(ttl=3600)
|
| 29 |
-
def
|
| 30 |
if not query:
|
| 31 |
-
return None, None
|
| 32 |
|
| 33 |
-
title = query.strip()
|
| 34 |
-
|
| 35 |
|
| 36 |
-
rest_url = f"https://{lang}.wikipedia.org/api/rest_v1/page/summary/{encoded_title}"
|
| 37 |
try:
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
return summary, full_url, lang
|
| 45 |
-
except Exception as e:
|
| 46 |
-
logger.debug("REST failed: %s", e)
|
| 47 |
|
| 48 |
-
|
| 49 |
-
api = f"https://{lang}{WIKIPEDIA_API_BASE_URL_PREFIX}"
|
| 50 |
-
params = {
|
| 51 |
-
"action": "query",
|
| 52 |
-
"format": "json",
|
| 53 |
-
"formatversion": 2,
|
| 54 |
-
"prop": "extracts|info",
|
| 55 |
-
"inprop": "url",
|
| 56 |
-
"titles": title,
|
| 57 |
-
"redirects": 1,
|
| 58 |
-
"explaintext": True,
|
| 59 |
-
**({"exsentences": ENGLISH_SUMMARY_SENTENCES} if lang == "en" else {})
|
| 60 |
-
}
|
| 61 |
-
res = requests.get(api, params=params, headers=WIKIMEDIA_HEADERS, timeout=REQUEST_TIMEOUT)
|
| 62 |
-
res.raise_for_status()
|
| 63 |
-
pages = res.json().get("query", {}).get("pages", [])
|
| 64 |
-
if pages and not pages[0].get("missing"):
|
| 65 |
-
return pages[0].get("extract"), pages[0].get("fullurl"), lang
|
| 66 |
-
except Exception as e:
|
| 67 |
-
logger.debug("Query API failed: %s", e)
|
| 68 |
-
|
| 69 |
-
if not is_fallback and lang != "en":
|
| 70 |
-
return fetch_wikipedia_content(query, lang="en", is_fallback=True)
|
| 71 |
-
|
| 72 |
-
return None, None, lang
|
| 73 |
-
|
| 74 |
-
# -------------------- Wikipedia Image Fetch --------------------
|
| 75 |
@st.cache_data(ttl=3600)
|
| 76 |
-
def
|
| 77 |
-
|
| 78 |
-
return []
|
| 79 |
-
|
| 80 |
-
api = f"https://{lang}.wikipedia.org/w/api.php"
|
| 81 |
params = {
|
| 82 |
"action": "query",
|
| 83 |
"format": "json",
|
|
@@ -88,88 +45,72 @@ def fetch_wikipedia_images(query, lang="en", max_images=3):
|
|
| 88 |
}
|
| 89 |
|
| 90 |
try:
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
pages =
|
| 94 |
images = []
|
| 95 |
|
| 96 |
-
for
|
| 97 |
-
if "original" in
|
| 98 |
-
images.append(
|
| 99 |
|
| 100 |
return images[:max_images]
|
| 101 |
-
except Exception
|
| 102 |
-
logger.debug("Image fetch failed: %s", e)
|
| 103 |
return []
|
| 104 |
|
| 105 |
-
# --------------------
|
| 106 |
-
def
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
return
|
| 112 |
-
|
| 113 |
-
tts = gTTS(text=clean, lang=lang_code)
|
| 114 |
-
with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as fp:
|
| 115 |
-
tts.save(fp.name)
|
| 116 |
-
audio_path = fp.name
|
| 117 |
-
|
| 118 |
-
st.audio(audio_path, format="audio/mp3")
|
| 119 |
-
except Exception as e:
|
| 120 |
-
st.error(f"Narration error: {e}")
|
| 121 |
-
|
| 122 |
-
# -------------------- Translation --------------------
|
| 123 |
-
def translate_summary(text, target_lang):
|
| 124 |
-
try:
|
| 125 |
-
return translator.translate(text, target_lang).result
|
| 126 |
-
except Exception:
|
| 127 |
-
return text
|
| 128 |
|
| 129 |
-
# --------------------
|
| 130 |
-
st.set_page_config(
|
| 131 |
st.title("🩺 WikiHealth Navigator")
|
| 132 |
-
st.markdown("Search health topics using Wikipedia (with images & audio)")
|
| 133 |
|
| 134 |
languages = {
|
| 135 |
"English": "en",
|
| 136 |
-
"
|
| 137 |
-
"
|
| 138 |
-
"
|
| 139 |
}
|
| 140 |
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
selected = st.selectbox("Select Language:", list(languages.keys()))
|
| 144 |
-
lang_code = languages[selected]
|
| 145 |
-
with col2:
|
| 146 |
-
query = st.text_input("Enter a health topic:")
|
| 147 |
|
| 148 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 149 |
with st.spinner("Searching Wikipedia..."):
|
| 150 |
-
summary, url
|
|
|
|
|
|
|
|
|
|
| 151 |
|
| 152 |
if summary:
|
| 153 |
-
if
|
| 154 |
-
summary =
|
| 155 |
|
| 156 |
st.subheader("📝 Summary")
|
| 157 |
st.write(summary)
|
| 158 |
|
| 159 |
-
st.subheader("🖼️
|
| 160 |
-
images =
|
| 161 |
|
| 162 |
if images:
|
| 163 |
cols = st.columns(len(images))
|
| 164 |
-
for
|
| 165 |
-
|
| 166 |
else:
|
| 167 |
st.info("No images found.")
|
| 168 |
|
| 169 |
-
if st.button("🔊 Narrate
|
| 170 |
-
|
| 171 |
|
| 172 |
if url:
|
| 173 |
-
st.markdown(f"[Read full article
|
| 174 |
else:
|
| 175 |
-
st.
|
|
|
|
|
|
|
| 1 |
import tempfile
|
| 2 |
import logging
|
| 3 |
import urllib.parse
|
|
|
|
| 5 |
import requests
|
| 6 |
import streamlit as st
|
| 7 |
from gtts import gTTS
|
|
|
|
| 8 |
from translatepy import Translator
|
| 9 |
|
| 10 |
+
# -------------------- CONFIG --------------------
|
| 11 |
+
REQUEST_TIMEOUT = 20
|
| 12 |
+
HEADERS = {'User-Agent': 'WikiHealthNavigator/1.0'}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
translator = Translator()
|
| 14 |
|
| 15 |
+
logging.basicConfig(level=logging.INFO)
|
|
|
|
| 16 |
|
| 17 |
+
# -------------------- FETCH SUMMARY --------------------
|
| 18 |
@st.cache_data(ttl=3600)
|
| 19 |
+
def fetch_summary(query, lang):
|
| 20 |
if not query:
|
| 21 |
+
return None, None
|
| 22 |
|
| 23 |
+
title = urllib.parse.quote(query.strip())
|
| 24 |
+
url = f"https://{lang}.wikipedia.org/api/rest_v1/page/summary/{title}"
|
| 25 |
|
|
|
|
| 26 |
try:
|
| 27 |
+
r = requests.get(url, headers=HEADERS, timeout=REQUEST_TIMEOUT)
|
| 28 |
+
r.raise_for_status()
|
| 29 |
+
data = r.json()
|
| 30 |
+
return data.get("extract"), data.get("content_urls", {}).get("desktop", {}).get("page")
|
| 31 |
+
except Exception:
|
| 32 |
+
return None, None
|
|
|
|
|
|
|
|
|
|
| 33 |
|
| 34 |
+
# -------------------- FETCH IMAGES (EN ONLY – STABLE) --------------------
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
@st.cache_data(ttl=3600)
|
| 36 |
+
def fetch_images(query, max_images=3):
|
| 37 |
+
api = "https://en.wikipedia.org/w/api.php"
|
|
|
|
|
|
|
|
|
|
| 38 |
params = {
|
| 39 |
"action": "query",
|
| 40 |
"format": "json",
|
|
|
|
| 45 |
}
|
| 46 |
|
| 47 |
try:
|
| 48 |
+
r = requests.get(api, params=params, headers=HEADERS, timeout=REQUEST_TIMEOUT)
|
| 49 |
+
r.raise_for_status()
|
| 50 |
+
pages = r.json()["query"]["pages"]
|
| 51 |
images = []
|
| 52 |
|
| 53 |
+
for p in pages.values():
|
| 54 |
+
if "original" in p:
|
| 55 |
+
images.append(p["original"]["source"])
|
| 56 |
|
| 57 |
return images[:max_images]
|
| 58 |
+
except Exception:
|
|
|
|
| 59 |
return []
|
| 60 |
|
| 61 |
+
# -------------------- NARRATION --------------------
|
| 62 |
+
def narrate(text, lang):
|
| 63 |
+
tts = gTTS(text=text, lang=lang)
|
| 64 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as f:
|
| 65 |
+
tts.save(f.name)
|
| 66 |
+
st.audio(f.name)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
|
| 68 |
+
# -------------------- UI --------------------
|
| 69 |
+
st.set_page_config("WikiHealth Navigator", layout="centered")
|
| 70 |
st.title("🩺 WikiHealth Navigator")
|
|
|
|
| 71 |
|
| 72 |
languages = {
|
| 73 |
"English": "en",
|
| 74 |
+
"Hindi": "hi",
|
| 75 |
+
"Telugu": "te",
|
| 76 |
+
"Tamil": "ta"
|
| 77 |
}
|
| 78 |
|
| 79 |
+
lang_name = st.selectbox("Select Language", list(languages.keys()))
|
| 80 |
+
lang_code = languages[lang_name]
|
|
|
|
|
|
|
|
|
|
|
|
|
| 81 |
|
| 82 |
+
query = st.text_input("Enter health topic")
|
| 83 |
+
|
| 84 |
+
search = st.button("🔍 Search")
|
| 85 |
+
|
| 86 |
+
if search and query:
|
| 87 |
with st.spinner("Searching Wikipedia..."):
|
| 88 |
+
summary, url = fetch_summary(query, lang_code)
|
| 89 |
+
|
| 90 |
+
if not summary and lang_code != "en":
|
| 91 |
+
summary, url = fetch_summary(query, "en")
|
| 92 |
|
| 93 |
if summary:
|
| 94 |
+
if lang_code != "en":
|
| 95 |
+
summary = translator.translate(summary, lang_code).result
|
| 96 |
|
| 97 |
st.subheader("📝 Summary")
|
| 98 |
st.write(summary)
|
| 99 |
|
| 100 |
+
st.subheader("🖼️ Images")
|
| 101 |
+
images = fetch_images(query)
|
| 102 |
|
| 103 |
if images:
|
| 104 |
cols = st.columns(len(images))
|
| 105 |
+
for c, img in zip(cols, images):
|
| 106 |
+
c.image(img, use_container_width=True)
|
| 107 |
else:
|
| 108 |
st.info("No images found.")
|
| 109 |
|
| 110 |
+
if st.button("🔊 Narrate"):
|
| 111 |
+
narrate(summary, lang_code)
|
| 112 |
|
| 113 |
if url:
|
| 114 |
+
st.markdown(f"[Read full article]({url})")
|
| 115 |
else:
|
| 116 |
+
st.error("No data found.")
|