RChaubey16 commited on
Commit
c22f035
·
verified ·
1 Parent(s): b1b7242

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +75 -0
app.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import requests
3
+ import re
4
+ from bs4 import BeautifulSoup
5
+ from langchain_text_splitters import RecursiveCharacterTextSplitter
6
+ from langchain.docstore.document import Document
7
+ import chromadb
8
+ from sentence_transformers import SentenceTransformer
9
+ import google.generativeai as genai
10
+
11
+ genai.configure(api_key="AIzaSyAxUd2tS-qj9C7frYuHRsv92tziXHgIvLo")
12
+
13
+ CHROMA_PATH = "chroma_db"
14
+ chroma_client = chromadb.PersistentClient(path=CHROMA_PATH)
15
+ collection = chroma_client.get_or_create_collection(name="formula_1")
16
+ embedding_model = SentenceTransformer("all-MiniLM-L6-v2")
17
+
18
+ def clean_text(text):
19
+ text = re.sub(r'http\S+', '', text)
20
+ text = re.sub(r'\s+', ' ', text).strip()
21
+ return text
22
+
23
+ def split_content_into_chunks(content):
24
+ text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200, length_function=len)
25
+ documents = [Document(page_content=content)]
26
+ return text_splitter.split_documents(documents)
27
+
28
+ def add_chunks_to_db(chunks):
29
+ documents = [chunk.page_content for chunk in chunks]
30
+ ids = [f"ID{i}" for i in range(len(chunks))]
31
+ embeddings = embedding_model.encode(documents, convert_to_list=True)
32
+ collection.upsert(documents=documents, ids=ids, embeddings=embeddings)
33
+
34
+ def scrape_text(url):
35
+ try:
36
+ response = requests.get(url)
37
+ response.raise_for_status()
38
+ soup = BeautifulSoup(response.text, 'html.parser')
39
+ text = clean_text(soup.get_text())
40
+ chunks = split_content_into_chunks(text)
41
+ add_chunks_to_db(chunks)
42
+ return "Scraping and processing complete. You can now ask questions!"
43
+ except requests.exceptions.RequestException as e:
44
+ return f"Error scraping {url}: {e}"
45
+
46
+ def ask_question(query):
47
+ query_embedding = embedding_model.encode(query, convert_to_list=True)
48
+ results = collection.query(query_embeddings=[query_embedding], n_results=2)
49
+ top_chunks = results.get("documents", [[]])[0]
50
+ system_prompt = """
51
+ You are a Formula 1 expert. You answer questions about Formula 1.
52
+ But you only answer based on knowledge I'm providing you. You don't use your internal
53
+ knowledge and you don't make things up.
54
+ If you don't know the answer, just say: I don't know.
55
+ """ + str(top_chunks)
56
+ full_prompt = system_prompt + "\nUser Query: " + query
57
+ model = genai.GenerativeModel('gemini-2.0-flash')
58
+ response = model.generate_content(full_prompt)
59
+ return response.text
60
+
61
+ st.title("Web Scraping & Chatbot")
62
+
63
+ url = st.text_input("Enter a URL:")
64
+ if url:
65
+ if st.button("Scrape & Process"):
66
+ result = scrape_text(url)
67
+ st.success(result)
68
+
69
+ if 'scraped' in st.session_state and st.session_state.scraped:
70
+ st.subheader("Ask a Question")
71
+ query = st.text_input("Enter your question:")
72
+ if query:
73
+ if st.button("Get Answer"):
74
+ answer = ask_question(query)
75
+ st.write(answer)