Engineer786 commited on
Commit
1309c36
·
verified ·
1 Parent(s): 28af0c5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +55 -46
app.py CHANGED
@@ -1,9 +1,27 @@
1
  import streamlit as st
 
2
  import requests
3
  from bs4 import BeautifulSoup
4
  import urllib3
5
  import pandas as pd
6
  import tempfile
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
 
8
  def simple_web_scraper(url, scrape_option):
9
  try:
@@ -17,64 +35,55 @@ def simple_web_scraper(url, scrape_option):
17
  if response.status == 200:
18
  # Parse the HTML content of the page
19
  soup = BeautifulSoup(response.data, 'html.parser')
20
-
21
- # Extract information from the HTML based on user's choice
 
 
22
  if scrape_option == 'data':
23
  # Extract all text content from the page
24
  all_text = soup.get_text()
25
-
26
- # Prepare data for the table (split text by lines)
27
- table_data = [{'Data': line.strip()} for line in all_text.split('\n') if line.strip()]
28
-
29
- # Display the data in a table
30
- st.table(table_data)
31
-
32
- # Save data to a temporary CSV file
33
- df = pd.DataFrame(table_data)
34
- csv_file = tempfile.NamedTemporaryFile(delete=False, suffix=".csv")
35
- df.to_csv(csv_file.name, index=False)
36
-
37
- # Provide a download button for the CSV file
38
- st.download_button(
39
- label="Download Data as CSV",
40
- data=open(csv_file.name, "rb").read(),
41
- file_name="scraped_data.csv",
42
- mime="text/csv",
43
- )
44
  elif scrape_option == 'links':
45
- # Example: Extract all the links on the page
46
  links = soup.find_all('a')
47
-
48
- # Prepare data for the table
49
- table_data = [{'Links': link.get('href')} for link in links if link.get('href')]
50
-
51
- # Display the data in a table
52
- st.table(table_data)
53
 
54
- # Save links to a temporary CSV file
55
- df = pd.DataFrame(table_data)
56
- csv_file = tempfile.NamedTemporaryFile(delete=False, suffix=".csv")
57
- df.to_csv(csv_file.name, index=False)
58
 
59
- # Provide a download button for the CSV file
60
- st.download_button(
61
- label="Download Links as CSV",
62
- data=open(csv_file.name, "rb").read(),
63
- file_name="scraped_links.csv",
64
- mime="text/csv",
65
- )
66
- else:
67
- st.write('Invalid scrape option. Please choose "data" or "links".')
 
 
 
 
 
 
 
 
 
 
 
68
  else:
69
- st.write(f'Error: {response.status}')
70
-
71
  except Exception as e:
72
- st.write(f'An error occurred: {e}')
73
 
74
  # Streamlit UI
75
- st.title("Web Scraping Tool")
76
  website_url = st.text_input("Enter the URL to scrape:")
77
  scrape_option = st.selectbox("Select what to scrape:", ['data', 'links'])
78
 
79
- if st.button("Scrape"):
80
  simple_web_scraper(website_url, scrape_option)
 
1
  import streamlit as st
2
+ import os
3
  import requests
4
  from bs4 import BeautifulSoup
5
  import urllib3
6
  import pandas as pd
7
  import tempfile
8
+ from groq import Groq
9
+
10
+ # Initialize Groq client
11
+ client = Groq(api_key=os.environ.get('GroqApi'))
12
+
13
+ def process_with_groq(content):
14
+ """Use Groq API to process content and generate insights."""
15
+ try:
16
+ response = client.chat.completions.create(
17
+ messages=[
18
+ {"role": "user", "content": content}
19
+ ],
20
+ model="llama3-8b-8192",
21
+ )
22
+ return response.choices[0].message.content
23
+ except Exception as e:
24
+ return f"Error processing with Groq: {e}"
25
 
26
  def simple_web_scraper(url, scrape_option):
27
  try:
 
35
  if response.status == 200:
36
  # Parse the HTML content of the page
37
  soup = BeautifulSoup(response.data, 'html.parser')
38
+
39
+ # Prepare the output data
40
+ output_data = []
41
+
42
  if scrape_option == 'data':
43
  # Extract all text content from the page
44
  all_text = soup.get_text()
45
+ output_data = [{'Data': line.strip()} for line in all_text.split('\n') if line.strip()]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46
  elif scrape_option == 'links':
47
+ # Extract all links from the page
48
  links = soup.find_all('a')
49
+ output_data = [{'Links': link.get('href')} for link in links if link.get('href')]
50
+
51
+ if not output_data:
52
+ st.write("No relevant data found on the page.")
53
+ return
 
54
 
55
+ # Display the data in a table
56
+ st.table(output_data)
 
 
57
 
58
+ # Save data to a temporary CSV file
59
+ df = pd.DataFrame(output_data)
60
+ csv_file = tempfile.NamedTemporaryFile(delete=False, suffix=".csv")
61
+ df.to_csv(csv_file.name, index=False)
62
+
63
+ # Provide a download button for the CSV file
64
+ st.download_button(
65
+ label="Download Data as CSV",
66
+ data=open(csv_file.name, "rb").read(),
67
+ file_name="scraped_data.csv",
68
+ mime="text/csv",
69
+ )
70
+
71
+ # Process the data using Groq API
72
+ if scrape_option == 'data':
73
+ combined_text = "\n".join([item['Data'] for item in output_data])
74
+ st.subheader("Processing with Groq Model")
75
+ groq_output = process_with_groq(combined_text)
76
+ st.write("**Insights from Groq:**")
77
+ st.write(groq_output)
78
  else:
79
+ st.write(f"Error: {response.status}")
 
80
  except Exception as e:
81
+ st.write(f"An error occurred: {e}")
82
 
83
  # Streamlit UI
84
+ st.title("Web Scraping and Processing Tool")
85
  website_url = st.text_input("Enter the URL to scrape:")
86
  scrape_option = st.selectbox("Select what to scrape:", ['data', 'links'])
87
 
88
+ if st.button("Scrape and Process"):
89
  simple_web_scraper(website_url, scrape_option)