Spaces:
Sleeping
Sleeping
Update src/streamlit_app.py
Browse files- src/streamlit_app.py +82 -38
src/streamlit_app.py
CHANGED
|
@@ -1,40 +1,84 @@
|
|
| 1 |
-
import
|
| 2 |
-
import numpy as np
|
| 3 |
-
import pandas as pd
|
| 4 |
import streamlit as st
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 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}")
|