Abhaykoul commited on
Commit
655f4c3
·
1 Parent(s): 4af0666

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +82 -0
app.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import requests
3
+
4
+ # Set the page title and icon
5
+ st.set_page_config(page_title="Wikipedia Microbot", page_icon=":mag:")
6
+
7
+ # Define a CSS style for better layout
8
+ st.markdown(
9
+ """
10
+ <style>
11
+ .stTextInput, .stButton, .stProgress { margin: 10px 0; }
12
+ .stButton { width: 100%; }
13
+ .stAlert { padding: 10px; }
14
+ .stMarkdown img { max-width: 100%; }
15
+ .stText { font-weight: bold; }
16
+ </style>
17
+ """,
18
+ unsafe_allow_html=True
19
+ )
20
+
21
+ WIKIPEDIA_API_URL = "https://en.wikipedia.org/w/api.php"
22
+
23
+ st.title("Wikipedia Microbot")
24
+
25
+ # Create a sidebar for better organization
26
+ st.sidebar.header("Options")
27
+
28
+ # Create widgets in the sidebar
29
+ query = st.sidebar.text_input("Enter a Query")
30
+ search_button = st.sidebar.button("Search")
31
+ clear_output_button = st.sidebar.button("Clear Output")
32
+
33
+ # Create a container for the main content
34
+ main_container = st.container()
35
+
36
+ if search_button:
37
+ if query:
38
+ try:
39
+ # Search Wikipedia for the query
40
+ params = {
41
+ "action": "query",
42
+ "format": "json",
43
+ "prop": "extracts|images|info|pageviews",
44
+ "exintro": True,
45
+ "explaintext": True,
46
+ "exsectionformat": "plain",
47
+ "titles": query,
48
+ "utf8": 1,
49
+ "formatversion": 2,
50
+ "pvipdays": 7, # Get page views statistics for the last 7 days
51
+ }
52
+
53
+ response = requests.get(WIKIPEDIA_API_URL, params=params)
54
+
55
+ if response.status_code == 200:
56
+ data = response.json()
57
+
58
+ if "error" in data:
59
+ st.sidebar.error(f"Error: {data['error']['info']}")
60
+ else:
61
+ page = data["query"]["pages"][0]
62
+
63
+ summary = page.get("extract", "")
64
+ html_content = ""
65
+ for image in page.get("images", []):
66
+ image_url = f"https://en.wikipedia.org/wiki/{image['title']}"
67
+ # Display the images using st.image
68
+ st.sidebar.image(image_url, caption=image['title'], use_column_width=True)
69
+
70
+ # Display page views statistics
71
+ views = page.get("pageviews", {}).get(query, "Data not available")
72
+ views_text = f"Page Views (Last 7 days): {views}"
73
+
74
+ result = f"# {page['title']}\n{views_text}\n{summary}\n{html_content}"
75
+ main_container.markdown(result, unsafe_allow_html=True)
76
+ else:
77
+ st.sidebar.error("Error: Unable to retrieve data from Wikipedia. Please try again later.")
78
+ except Exception as e:
79
+ st.sidebar.error(f"Error: {e}")
80
+
81
+ if clear_output_button:
82
+ main_container.text("Output Cleared")