DOMMETI commited on
Commit
5d8edc1
·
verified ·
1 Parent(s): 95b707a

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +95 -38
src/streamlit_app.py CHANGED
@@ -1,40 +1,97 @@
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 asyncio
3
+ from crawl4ai import AsyncWebCrawler
4
+ from crawl4ai.async_configs import BrowserConfig, CrawlerRunConfig
5
+ from langchain_core.documents.base import Document
6
+ from langchain.text_splitter import CharacterTextSplitter
7
+ from langchain_huggingface.embeddings import HuggingFaceEmbeddings
8
+ from langchain.vectorstores.chroma import Chroma
9
+ from langchain_huggingface.chat_models import ChatHuggingFace
10
+ from langchain_huggingface.llms import HuggingFaceEndpoint
11
+ import os
12
 
13
+ # ------------------------------------------------------------------------------
14
+ # Set your API tokens
15
+ # ------------------------------------------------------------------------------
16
+ os.environ['HUGGINGFACEHUB_API_TOKEN'] = os.getenv("key")
17
+ os.environ['HF_TOKEN'] = os.getenv("key")
18
+
19
+
20
+ # ------------------------------------------------------------------------------
21
+ # Streamlit App
22
+ # ------------------------------------------------------------------------------
23
+ st.title("Web Crawler + Semantic Search + Conversational Model")
24
+
25
+ # Input for the website to crawl
26
+ url = st.text_input("Enter a website URL to crawl:")
27
+
28
+ # Input for semantic search
29
+ query = st.text_input("Enter your semantic search query:")
30
+
31
+
32
+ # Button to start the process
33
+ if st.button("Analyze and Query"):
34
+
35
+ if not url or not query:
36
+ st.error("Please provide both a URL and a semantic search query.")
37
+ else:
38
+ with st.spinner("Crawling website, retrieving documents, and generating a response..."):
39
+
40
+ async def main():
41
+ # Crawling
42
+ browser_config = BrowserConfig()
43
+ run_config = CrawlerRunConfig()
44
+
45
+ async with AsyncWebCrawler(config=browser_config) as crawler:
46
+ result = await crawler.arun(url=url, config=run_config)
47
+ doc = Document(page_content=result.markdown.raw_markdown)
48
+
49
+ # Split documents into chunks
50
+ text_splitter = CharacterTextSplitter(
51
+ chunk_size=1000,
52
+ chunk_overlap=100,
53
+ )
54
+
55
+ chunks = text_splitter.split_documents([doc])
56
+
57
+ # Embedding and Vector Store
58
+ emb = HuggingFaceEmbeddings(model='avsolatorio/GIST-small-Embedding-v0')
59
+ db = Chroma.from_documents(chunks, emb, persist_directory='chroma_db')
60
+
61
+ docs = db.similarity_search(query, k=3)
62
+
63
+ context = " ".join([d.page_content for d in docs])
64
+
65
+ # Prepare and call the chat model
66
+ deepseek_endpoint = HuggingFaceEndpoint(
67
+ repo_id='deepseek-ai/DeepSeek-Prover-V2-671B',
68
+ provider='sambanova',
69
+ temperature=0.5,
70
+ max_new_tokens=50,
71
+ task='conversational'
72
+ )
73
+
74
+ deep_seek = ChatHuggingFace(
75
+ llm=deepseek_endpoint,
76
+ repo_id='deepseek-ai/DeepSeek-Prover-V2-671B',
77
+ provider='sambanova',
78
+ temperature=0.5,
79
+ max_new_tokens=50,
80
+ task='conversational'
81
+ )
82
+
83
+ message = f"""Context:\n{context}\nQuestion:\n{query}"""
84
+ response = deep_seek.invoke([{"role": "user", "content": message}])
85
+
86
+ return response.content
87
+
88
+ response = asyncio.run(main())
89
+
90
+ st.success("Done.")
91
+ st.write("**Response from Model:**")
92
+ st.write(response)
93
+
94
+
95
+ # ------------------------------------------------------------------------------
96
+ # End of Streamlit App
97
+ # ------------------------------------------------------------------------------