JishnuSetia commited on
Commit
415c6f1
·
verified ·
1 Parent(s): 6435326

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +82 -38
src/streamlit_app.py CHANGED
@@ -1,40 +1,84 @@
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 os
 
 
2
  import streamlit as st
3
+ import requests
4
+ import json
5
+ from bs4 import BeautifulSoup
6
+ import re
7
+ from difflib import SequenceMatcher
8
 
9
+ # Fix Streamlit permission issue
10
+ os.environ['STREAMLIT_HOME'] = '/tmp/.streamlit'
11
+
12
+ API_URL = "https://jishnusetia-ollama-server.hf.space/api/generate"
13
+ MODEL = "llama3.2"
14
+
15
+ st.title("🌐 Chat with a Website (Ollama)")
16
+
17
+ # Store website content in memory
18
+ if "chunks" not in st.session_state:
19
+ st.session_state.chunks = []
20
+ if "chat_history" not in st.session_state:
21
+ st.session_state.chat_history = []
22
+
23
+ # Helper: clean and chunk text
24
+ def clean_and_chunk(text, chunk_size=800):
25
+ text = re.sub(r'\s+', ' ', text).strip()
26
+ return [text[i:i+chunk_size] for i in range(0, len(text), chunk_size)]
27
+
28
+ # Helper: get top N relevant chunks
29
+ def get_relevant_chunks(query, chunks, top_n=3):
30
+ scored = [(SequenceMatcher(None, query, chunk).ratio(), chunk) for chunk in chunks]
31
+ scored.sort(key=lambda x: x[0], reverse=True)
32
+ return [chunk for _, chunk in scored[:top_n]]
33
+
34
+ # Step 1: User inputs website
35
+ url = st.text_input("Enter website URL:")
36
+
37
+ if st.button("Fetch Website") and url:
38
+ try:
39
+ resp = requests.get(url, timeout=10)
40
+ soup = BeautifulSoup(resp.text, 'html.parser')
41
+ for script in soup(["script", "style"]):
42
+ script.extract()
43
+ text = soup.get_text()
44
+ st.session_state.chunks = clean_and_chunk(text)
45
+ st.success(f"Website fetched! {len(st.session_state.chunks)} chunks ready.")
46
+ except Exception as e:
47
+ st.error(f"Error fetching website: {e}")
48
+
49
+ # Step 2: Function to send query to Ollama
50
+ def send_message(message, context):
51
+ prompt = f"Answer the following question based on this context:\n{context}\n\nQuestion: {message}"
52
+ payload = {"model": MODEL, "prompt": prompt}
53
+ response = requests.post(API_URL, json=payload, stream=True)
54
+
55
+ if response.ok:
56
+ reply = ""
57
+ for line in response.iter_lines():
58
+ if line:
59
+ data = json.loads(line.decode('utf-8'))
60
+ reply += data.get("response", "")
61
+ return reply.strip()
62
+ else:
63
+ return "⚠️ Error: Failed to get response from Ollama API."
64
+
65
+ # Step 3: Chat input
66
+ user_input = st.text_input("Ask a question about the website:")
67
+
68
+ if st.button("Send Question") and user_input.strip():
69
+ if not st.session_state.chunks:
70
+ st.error("Please fetch a website first.")
71
+ else:
72
+ st.session_state.chat_history.append(("You", user_input))
73
+ with st.spinner("Thinking..."):
74
+ context = "\n".join(get_relevant_chunks(user_input, st.session_state.chunks))
75
+ bot_reply = send_message(user_input, context)
76
+ st.session_state.chat_history.append(("Ollama", bot_reply))
77
+
78
+ # Step 4: Display chat history
79
+ st.subheader("Chat History")
80
+ for speaker, message in st.session_state.chat_history:
81
+ if speaker == "You":
82
+ st.markdown(f"**You:** {message}")
83
+ else:
84
+ st.markdown(f"**🤖 Ollama:** {message}")