Engineer786 commited on
Commit
2387360
·
verified ·
1 Parent(s): a27ad46

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +57 -48
app.py CHANGED
@@ -1,6 +1,5 @@
1
  import streamlit as st
2
  import os
3
- import requests
4
  from bs4 import BeautifulSoup
5
  import urllib3
6
  import pandas as pd
@@ -10,20 +9,11 @@ from groq import Groq
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:
28
  # Create a PoolManager with urllib3 to handle SSL
29
  http = urllib3.PoolManager()
@@ -37,50 +27,69 @@ def simple_web_scraper(url, scrape_option):
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
- # Save data to a temporary CSV file
56
- df = pd.DataFrame(output_data)
57
- csv_file = tempfile.NamedTemporaryFile(delete=False, suffix=".csv")
58
- df.to_csv(csv_file.name, index=False)
59
-
60
- # Provide a download button for the CSV file
61
- st.download_button(
62
- label="Download Scraped Data as CSV",
63
- data=open(csv_file.name, "rb").read(),
64
- file_name="scraped_data.csv",
65
- mime="text/csv",
66
- )
67
-
68
- # Process the data using Groq API
69
- if scrape_option == 'data':
70
- combined_text = "\n".join([item['Data'] for item in output_data])
71
- st.subheader("Processing with Groq Model")
72
- groq_output = process_with_groq(combined_text)
73
- st.write("**Insights from Groq:**")
74
- st.write(groq_output)
75
  else:
76
  st.write(f"Error: {response.status}")
77
  except Exception as e:
78
  st.write(f"An error occurred: {e}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
79
 
80
  # Streamlit UI
81
- st.title("Web Scraping and Processing Tool")
 
 
82
  website_url = st.text_input("Enter the URL to scrape:")
83
  scrape_option = st.selectbox("Select what to scrape:", ['data', 'links'])
84
 
85
- if st.button("Scrape and Process"):
86
- simple_web_scraper(website_url, scrape_option)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import streamlit as st
2
  import os
 
3
  from bs4 import BeautifulSoup
4
  import urllib3
5
  import pandas as pd
 
9
  # Initialize Groq client
10
  client = Groq(api_key=os.environ.get('GroqApi'))
11
 
12
+ # Global variable to store scraped data
13
+ SCRAPED_DATA = None
 
 
 
 
 
 
 
 
 
 
14
 
15
+ def scrape_web_data(url, scrape_option):
16
+ """Scrape data from the given URL based on the scrape option."""
17
  try:
18
  # Create a PoolManager with urllib3 to handle SSL
19
  http = urllib3.PoolManager()
 
27
  soup = BeautifulSoup(response.data, 'html.parser')
28
 
29
  # Prepare the output data
 
 
30
  if scrape_option == 'data':
 
31
  all_text = soup.get_text()
32
+ return [{'Data': line.strip()} for line in all_text.split('\n') if line.strip()]
33
  elif scrape_option == 'links':
 
34
  links = soup.find_all('a')
35
+ return [{'Links': link.get('href')} for link in links if link.get('href')]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
  else:
37
  st.write(f"Error: {response.status}")
38
  except Exception as e:
39
  st.write(f"An error occurred: {e}")
40
+ return []
41
+
42
+ def process_query_with_groq(query, data):
43
+ """Process the user's query with Groq based on the scraped data."""
44
+ try:
45
+ # Combine the scraped data into a single text block
46
+ combined_text = "\n".join([str(item) for sublist in data for item in sublist.values()])
47
+
48
+ # Add the query context
49
+ prompt = f"Context: {combined_text}\n\nUser Query: {query}\nAnswer:"
50
+
51
+ # Call Groq API
52
+ response = client.chat.completions.create(
53
+ messages=[
54
+ {"role": "user", "content": prompt}
55
+ ],
56
+ model="llama3-8b-8192",
57
+ )
58
+ return response.choices[0].message.content
59
+ except Exception as e:
60
+ return f"Error processing query with Groq: {e}"
61
 
62
  # Streamlit UI
63
+ st.title("Web Scraping and Query Tool")
64
+
65
+ # Step 1: Scraping
66
  website_url = st.text_input("Enter the URL to scrape:")
67
  scrape_option = st.selectbox("Select what to scrape:", ['data', 'links'])
68
 
69
+ if st.button("Scrape Data"):
70
+ SCRAPED_DATA = scrape_web_data(website_url, scrape_option)
71
+ if SCRAPED_DATA:
72
+ st.write(f"Scraping completed. {len(SCRAPED_DATA)} items found.")
73
+
74
+ # Save data to a temporary CSV file
75
+ df = pd.DataFrame(SCRAPED_DATA)
76
+ csv_file = tempfile.NamedTemporaryFile(delete=False, suffix=".csv")
77
+ df.to_csv(csv_file.name, index=False)
78
+
79
+ # Provide a download button for the CSV file
80
+ st.download_button(
81
+ label="Download Scraped Data as CSV",
82
+ data=open(csv_file.name, "rb").read(),
83
+ file_name="scraped_data.csv",
84
+ mime="text/csv",
85
+ )
86
+ else:
87
+ st.write("No data found.")
88
+
89
+ # Step 2: Querying
90
+ if SCRAPED_DATA:
91
+ user_query = st.text_input("Enter your query:")
92
+ if st.button("Get Answer"):
93
+ answer = process_query_with_groq(user_query, SCRAPED_DATA)
94
+ st.write("**Answer:**")
95
+ st.write(answer)