Abdul-Haseeb commited on
Commit
9115055
·
verified ·
1 Parent(s): 788cc27

Updated wiki function

Browse files
Files changed (1) hide show
  1. app.py +22 -2
app.py CHANGED
@@ -45,13 +45,33 @@ def save_chat_history(messages):
45
  with shelve.open("chat_history") as db:
46
  db["messages"] = messages
47
 
48
- def fetch_wikipedia_link(topic):
49
  api_url = f"https://en.wikipedia.org/api/rest_v1/page/summary/{topic}"
50
  response = requests.get(api_url)
51
  if response.status_code == 200:
52
  return response.json()['content_urls']['desktop']['page']
53
  st.error("Failed to fetch Wikipedia content.")
54
- return None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55
 
56
  load_css()
57
  initialize_session_state()
 
45
  with shelve.open("chat_history") as db:
46
  db["messages"] = messages
47
 
48
+ '''def fetch_wikipedia_link(topic):
49
  api_url = f"https://en.wikipedia.org/api/rest_v1/page/summary/{topic}"
50
  response = requests.get(api_url)
51
  if response.status_code == 200:
52
  return response.json()['content_urls']['desktop']['page']
53
  st.error("Failed to fetch Wikipedia content.")
54
+ return None'''
55
+
56
+ from urllib.parse import quote
57
+
58
+ def fetch_wikipedia_link(topic: str) -> str | None:
59
+ try:
60
+ encoded_topic = quote(topic)
61
+ api_url = f"https://en.wikipedia.org/api/rest_v1/page/summary/{encoded_topic}"
62
+ response = requests.get(api_url, timeout=5)
63
+
64
+ if response.status_code != 200:
65
+ return None
66
+
67
+ data = response.json()
68
+ return data.get("content_urls", {}) \
69
+ .get("desktop", {}) \
70
+ .get("page")
71
+
72
+ except requests.RequestException:
73
+ return None
74
+
75
 
76
  load_css()
77
  initialize_session_state()