charantejapolavarapu commited on
Commit
b3d4408
·
verified ·
1 Parent(s): 30bf4b5

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +24 -20
src/streamlit_app.py CHANGED
@@ -8,24 +8,31 @@ from translatepy import Translator
8
  # -------------------- CONFIG --------------------
9
  REQUEST_TIMEOUT = 20
10
  HEADERS = {
11
- "User-Agent": "WikiHealthNavigator/1.0 (edu-project)"
12
  }
13
  translator = Translator()
14
 
15
- # -------------------- FETCH SUMMARY --------------------
16
  @st.cache_data(ttl=3600)
17
  def fetch_summary(query, lang):
18
  try:
19
  title = urllib.parse.quote(query.strip())
20
  url = f"https://{lang}.wikipedia.org/api/rest_v1/page/summary/{title}"
21
  r = requests.get(url, headers=HEADERS, timeout=REQUEST_TIMEOUT)
22
- r.raise_for_status()
 
 
 
 
23
  data = r.json()
24
- return data.get("extract"), data.get("content_urls", {}).get("desktop", {}).get("page")
 
 
 
25
  except Exception:
26
  return None, None
27
 
28
- # -------------------- FETCH IMAGES (SAFE VERSION) --------------------
29
  @st.cache_data(ttl=3600)
30
  def fetch_images(query, max_images=4):
31
  api = "https://commons.wikimedia.org/w/api.php"
@@ -43,18 +50,13 @@ def fetch_images(query, max_images=4):
43
  try:
44
  r = requests.get(api, params=params, headers=HEADERS, timeout=REQUEST_TIMEOUT)
45
 
46
- # ✅ Ensure response is JSON
47
  if r.status_code != 200:
48
  return []
49
 
50
  if "application/json" not in r.headers.get("Content-Type", ""):
51
  return []
52
 
53
- try:
54
- data = r.json()
55
- except ValueError:
56
- return []
57
-
58
  pages = data.get("query", {}).get("pages", {})
59
  images = []
60
 
@@ -63,7 +65,6 @@ def fetch_images(query, max_images=4):
63
  images.append(page["imageinfo"][0]["url"])
64
 
65
  return images
66
-
67
  except Exception:
68
  return []
69
 
@@ -77,16 +78,16 @@ def narrate(text, lang):
77
  except Exception as e:
78
  st.error(f"Audio error: {e}")
79
 
80
- # -------------------- SESSION STATE --------------------
81
  for key in ["summary", "images", "url", "lang"]:
82
  if key not in st.session_state:
83
  st.session_state[key] = None
84
 
85
  # -------------------- UI --------------------
86
- st.set_page_config("WikiHealth Navigator", layout="centered")
87
  st.title("🩺 WikiHealth Navigator")
88
  st.markdown(
89
- "Health search using Wikipedia text + "
90
  "**** images"
91
  )
92
 
@@ -104,13 +105,16 @@ query = st.text_input("Enter health topic")
104
 
105
  # -------------------- SEARCH --------------------
106
  if st.button("🔍 Search") and query:
 
107
  summary, url = fetch_summary(query, lang_code)
108
 
109
- if not summary and lang_code != "en":
 
110
  summary, url = fetch_summary(query, "en")
111
 
112
- if summary and lang_code != "en":
113
- summary = translator.translate(summary, lang_code).result
 
114
 
115
  st.session_state.summary = summary
116
  st.session_state.images = fetch_images(query)
@@ -125,8 +129,8 @@ if st.session_state.summary:
125
  st.subheader("🖼️ Related Images")
126
  if st.session_state.images:
127
  cols = st.columns(len(st.session_state.images))
128
- for c, img in zip(cols, st.session_state.images):
129
- c.image(img, use_container_width=True)
130
  else:
131
  st.info("Images temporarily unavailable. Please try again.")
132
 
 
8
  # -------------------- CONFIG --------------------
9
  REQUEST_TIMEOUT = 20
10
  HEADERS = {
11
+ "User-Agent": "WikiHealthNavigator/1.0 (educational-project)"
12
  }
13
  translator = Translator()
14
 
15
+ # -------------------- FETCH SUMMARY (SAFE + FALLBACK) --------------------
16
  @st.cache_data(ttl=3600)
17
  def fetch_summary(query, lang):
18
  try:
19
  title = urllib.parse.quote(query.strip())
20
  url = f"https://{lang}.wikipedia.org/api/rest_v1/page/summary/{title}"
21
  r = requests.get(url, headers=HEADERS, timeout=REQUEST_TIMEOUT)
22
+
23
+ # Handle missing pages (404 etc.)
24
+ if r.status_code != 200:
25
+ return None, None
26
+
27
  data = r.json()
28
+ return (
29
+ data.get("extract"),
30
+ data.get("content_urls", {}).get("desktop", {}).get("page")
31
+ )
32
  except Exception:
33
  return None, None
34
 
35
+ # -------------------- FETCH IMAGES (WIKIMEDIA COMMONS – SAFE) --------------------
36
  @st.cache_data(ttl=3600)
37
  def fetch_images(query, max_images=4):
38
  api = "https://commons.wikimedia.org/w/api.php"
 
50
  try:
51
  r = requests.get(api, params=params, headers=HEADERS, timeout=REQUEST_TIMEOUT)
52
 
 
53
  if r.status_code != 200:
54
  return []
55
 
56
  if "application/json" not in r.headers.get("Content-Type", ""):
57
  return []
58
 
59
+ data = r.json()
 
 
 
 
60
  pages = data.get("query", {}).get("pages", {})
61
  images = []
62
 
 
65
  images.append(page["imageinfo"][0]["url"])
66
 
67
  return images
 
68
  except Exception:
69
  return []
70
 
 
78
  except Exception as e:
79
  st.error(f"Audio error: {e}")
80
 
81
+ # -------------------- SESSION STATE INIT --------------------
82
  for key in ["summary", "images", "url", "lang"]:
83
  if key not in st.session_state:
84
  st.session_state[key] = None
85
 
86
  # -------------------- UI --------------------
87
+ st.set_page_config(page_title="WikiHealth Navigator", layout="centered")
88
  st.title("🩺 WikiHealth Navigator")
89
  st.markdown(
90
+ "Health topic search using **Wikipedia** text and "
91
  "**** images"
92
  )
93
 
 
105
 
106
  # -------------------- SEARCH --------------------
107
  if st.button("🔍 Search") and query:
108
+ # 1️⃣ Try selected language
109
  summary, url = fetch_summary(query, lang_code)
110
 
111
+ # 2️⃣ Fallback to English if page not found
112
+ if not summary:
113
  summary, url = fetch_summary(query, "en")
114
 
115
+ # 3️⃣ Translate English selected language
116
+ if summary and lang_code != "en":
117
+ summary = translator.translate(summary, lang_code).result
118
 
119
  st.session_state.summary = summary
120
  st.session_state.images = fetch_images(query)
 
129
  st.subheader("🖼️ Related Images")
130
  if st.session_state.images:
131
  cols = st.columns(len(st.session_state.images))
132
+ for col, img in zip(cols, st.session_state.images):
133
+ col.image(img, use_container_width=True)
134
  else:
135
  st.info("Images temporarily unavailable. Please try again.")
136