jayanth-2005 commited on
Commit
83dc7fc
Β·
verified Β·
1 Parent(s): 206fec3

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +155 -38
src/streamlit_app.py CHANGED
@@ -1,40 +1,157 @@
1
- import altair as alt
2
- import numpy as np
3
- import pandas as pd
4
  import streamlit as st
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
 
6
- """
7
- # Welcome to Streamlit!
8
-
9
- Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.
10
- If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
11
- forums](https://discuss.streamlit.io).
12
-
13
- In the meantime, below is an example of what you can do with just a few lines of code:
14
- """
15
-
16
- num_points = st.slider("Number of points in spiral", 1, 10000, 1100)
17
- num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
18
-
19
- indices = np.linspace(0, 1, num_points)
20
- theta = 2 * np.pi * num_turns * indices
21
- radius = indices
22
-
23
- x = radius * np.cos(theta)
24
- y = radius * np.sin(theta)
25
-
26
- df = pd.DataFrame({
27
- "x": x,
28
- "y": y,
29
- "idx": indices,
30
- "rand": np.random.randn(num_points),
31
- })
32
-
33
- st.altair_chart(alt.Chart(df, height=700, width=700)
34
- .mark_point(filled=True)
35
- .encode(
36
- x=alt.X("x", axis=None),
37
- y=alt.Y("y", axis=None),
38
- color=alt.Color("idx", legend=None, scale=alt.Scale()),
39
- size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),
40
- ))
 
 
 
 
1
  import streamlit as st
2
+ import requests
3
+ from bs4 import BeautifulSoup
4
+ import pandas as pd
5
+ import re
6
+ import urllib3
7
+
8
+ urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
9
+
10
+ st.set_page_config(page_title="Faculty Scraper", layout="wide")
11
+
12
+ st.title("πŸŽ“ Universal Faculty Scraper (Robust Mode)")
13
+ st.write("Handles even badly structured faculty pages.")
14
+
15
+ # -------- REGEX --------
16
+ EMAIL_REGEX = r"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}"
17
+ PHONE_REGEX = r"\+?\d[\d\s\-]{8,15}"
18
+
19
+ BAD_NAMES = [
20
+ "welcome", "faculty", "central", "activities",
21
+ "department", "areas of interest", "important links"
22
+ ]
23
+
24
+ # -------- NAME FROM EMAIL --------
25
+ def name_from_email(email):
26
+ name_part = email.split("@")[0]
27
+ name_part = name_part.replace(".", " ").replace("_", " ")
28
+ return " ".join([w.capitalize() for w in name_part.split()])
29
+
30
+ # -------- MAIN SCRAPER --------
31
+ def scrape_faculty(url):
32
+ headers = {"User-Agent": "Mozilla/5.0"}
33
+
34
+ try:
35
+ response = requests.get(url, headers=headers, verify=False, timeout=10)
36
+ except:
37
+ return pd.DataFrame(), "❌ Failed to load page"
38
+
39
+ soup = BeautifulSoup(response.text, "html.parser")
40
+
41
+ # -------- METHOD 1: BLOCK PARSING --------
42
+ blocks = soup.find_all(["div", "li", "tr", "section"])
43
+ raw_data = []
44
+
45
+ for block in blocks:
46
+ text = block.get_text(" ", strip=True)
47
+
48
+ if len(text) < 30:
49
+ continue
50
+
51
+ email_match = re.search(EMAIL_REGEX, text)
52
+ if not email_match:
53
+ continue
54
+
55
+ email = email_match.group()
56
+
57
+ phone_match = re.search(PHONE_REGEX, text)
58
+ phone = phone_match.group() if phone_match else "Not Available"
59
+
60
+ name = None
61
+ for tag in block.find_all(["h1", "h2", "h3", "h4", "strong", "b"]):
62
+ candidate = tag.get_text(strip=True)
63
+
64
+ if (
65
+ 3 < len(candidate) < 60
66
+ and not re.search(EMAIL_REGEX, candidate)
67
+ and not any(b in candidate.lower() for b in BAD_NAMES)
68
+ ):
69
+ name = candidate
70
+ break
71
+
72
+ raw_data.append([name, email, phone])
73
+
74
+ df = pd.DataFrame(raw_data, columns=["Name", "Email", "Phone"])
75
+
76
+ # -------- METHOD 2: FALLBACK (GLOBAL EXTRACTION) --------
77
+ if df.empty or len(df) < 5:
78
+ text = soup.get_text(" ", strip=True)
79
+
80
+ emails = re.findall(EMAIL_REGEX, text)
81
+ phones = re.findall(PHONE_REGEX, text)
82
+
83
+ emails = list(set(emails))
84
+ phones = list(set(phones))
85
+
86
+ data = []
87
+
88
+ for i, email in enumerate(emails):
89
+ name = name_from_email(email)
90
+
91
+ phone = phones[i] if i < len(phones) else "Not Available"
92
+
93
+ data.append([name, email, phone])
94
+
95
+ df = pd.DataFrame(data, columns=["Name", "Email", "Phone"])
96
+
97
+ # -------- CLEANING --------
98
+ cleaned_data = []
99
+
100
+ for email, group in df.groupby("Email"):
101
+ names = group["Name"].dropna().tolist()
102
+ phones = group["Phone"].dropna().tolist()
103
+
104
+ best_name = None
105
+
106
+ for n in names:
107
+ if n and not any(b in n.lower() for b in BAD_NAMES):
108
+ if any(t in n.lower() for t in ["dr", "mr", "ms", "prof"]):
109
+ best_name = n
110
+ break
111
+
112
+ if not best_name and names:
113
+ valid = [n for n in names if not any(b in str(n).lower() for b in BAD_NAMES)]
114
+ if valid:
115
+ best_name = max(valid, key=len)
116
+
117
+ if not best_name:
118
+ best_name = name_from_email(email)
119
+
120
+ best_phone = "Not Available"
121
+ for p in phones:
122
+ if p != "Not Available":
123
+ best_phone = p
124
+ break
125
+
126
+ cleaned_data.append([best_name, email, best_phone])
127
+
128
+ final_df = pd.DataFrame(cleaned_data, columns=["Name", "Email", "Phone"])
129
+
130
+ return final_df, "βœ… Data Extracted Successfully"
131
+
132
+
133
+ # -------- UI --------
134
+ url = st.text_input("πŸ”— Enter Faculty Page URL")
135
+
136
+ if st.button("πŸš€ Scrape Data"):
137
+ if not url:
138
+ st.warning("Please enter a URL")
139
+ else:
140
+ with st.spinner("Scraping..."):
141
+ df, status = scrape_faculty(url)
142
+
143
+ st.success(status)
144
+
145
+ if not df.empty:
146
+ st.dataframe(df, use_container_width=True)
147
+
148
+ csv = df.to_csv(index=False).encode("utf-8")
149
 
150
+ st.download_button(
151
+ "πŸ“₯ Download CSV",
152
+ csv,
153
+ "faculty_data.csv",
154
+ "text/csv"
155
+ )
156
+ else:
157
+ st.error("No data found.")