|
import streamlit as st |
|
import requests |
|
|
|
st.set_page_config(page_title="WikiTrail", layout="wide") |
|
|
|
st.markdown("<h1 style='text-align: center;'>π WikiTrail</h1>", unsafe_allow_html=True) |
|
st.markdown("<p style='text-align: center;'>Explore Wikipedia topics visually and get a summarized journey.</p>", unsafe_allow_html=True) |
|
|
|
topic = st.text_input("Enter a topic", placeholder="e.g., India") |
|
|
|
def fetch_topic_summary(topic): |
|
url = f"https://en.wikipedia.org/api/rest_v1/page/summary/{topic}" |
|
res = requests.get(url) |
|
if res.status_code == 200: |
|
data = res.json() |
|
return { |
|
"title": data.get("title", ""), |
|
"summary": data.get("extract", ""), |
|
"image": data.get("thumbnail", {}).get("source"), |
|
"link": data.get("content_urls", {}).get("desktop", {}).get("page") |
|
} |
|
return None |
|
|
|
def fetch_related_topics(topic): |
|
url = f"https://en.wikipedia.org/w/api.php?action=query&format=json&origin=*&titles={topic}&prop=links&pllimit=5" |
|
res = requests.get(url) |
|
if res.status_code == 200: |
|
data = res.json() |
|
pages = list(data['query']['pages'].values()) |
|
if pages and 'links' in pages[0]: |
|
return [link['title'] for link in pages[0]['links']] |
|
return [] |
|
|
|
def simple_summary(all_summaries, limit=3): |
|
full_text = ' '.join(all_summaries) |
|
sentences = full_text.split('. ') |
|
return '. '.join(sentences[:limit]) + '.' |
|
|
|
if topic: |
|
with st.spinner("π Searching Wikipedia..."): |
|
summaries = [] |
|
|
|
st.subheader("π· Main Topic") |
|
main = fetch_topic_summary(topic) |
|
if main: |
|
summaries.append(main["summary"]) |
|
st.markdown(f"### {main['title']}") |
|
if main["image"]: |
|
st.image(main["image"], width=300) |
|
st.write(main["summary"]) |
|
st.markdown(f"[Read More β]({main['link']})", unsafe_allow_html=True) |
|
else: |
|
st.warning("Couldn't fetch data for the main topic.") |
|
|
|
st.subheader("π Related Topics") |
|
related = fetch_related_topics(topic) |
|
if related: |
|
for rel in related: |
|
data = fetch_topic_summary(rel) |
|
if data: |
|
summaries.append(data["summary"]) |
|
with st.expander(data["title"]): |
|
if data["image"]: |
|
st.image(data["image"], width=200) |
|
st.write(data["summary"]) |
|
st.markdown(f"[Read More β]({data['link']})", unsafe_allow_html=True) |
|
else: |
|
st.info("No related topics found.") |
|
|
|
st.subheader("π§ Combined Summary") |
|
st.success(simple_summary(summaries)) |
|
|