Pavanmanagoli commited on
Commit
f6697f7
·
verified ·
1 Parent(s): 4903d4b

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +122 -38
src/streamlit_app.py CHANGED
@@ -1,40 +1,124 @@
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
+ os.environ["TOKENIZERS_PARALLELISM"] = "false"
3
+ os.environ["STREAMLIT_WATCHER_TYPE"] = "none"
4
+
5
+ import re
6
+ import warnings
7
+ import logging
8
  import streamlit as st
9
+ from langdetect import detect
10
+
11
+ from langchain_community.chat_models import ChatOpenAI
12
+ from langchain_community.embeddings import HuggingFaceEmbeddings
13
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
14
+ from langchain_community.document_loaders import PyPDFLoader
15
+ from langchain.indexes import VectorstoreIndexCreator
16
+ from langchain.chains import RetrievalQA
17
+ from langchain_core.prompts import ChatPromptTemplate
18
+
19
+ # 🔐 Embed your API key directly for Streamlit Cloud deployment
20
+ OPENAI_API_KEY = "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"
21
+ warnings.filterwarnings("ignore")
22
+ logging.getLogger("transformers").setLevel(logging.ERROR)
23
+
24
+ st.set_page_config(page_title="RegioWizard KI", layout="centered")
25
+ st.title('🧠 RegioWizard KI')
26
+
27
+ if 'messages' not in st.session_state:
28
+ st.session_state.messages = []
29
+
30
+ for message in st.session_state.messages:
31
+ st.chat_message(message['role']).markdown(message['content'])
32
+
33
+ def is_greeting(text):
34
+ return text.lower().strip() in ["hi", "hello", "hey", "greetings", "hallo", "servus", "moin"]
35
+
36
+ def detect_language(text):
37
+ try:
38
+ return detect(text)
39
+ except:
40
+ return "en"
41
+
42
+ @st.cache_resource
43
+ def get_vectorstore():
44
+ pdf_path = "/workspaces/RegioWizard-KI/RegiowizardBot/bad_breisig_docs.pdf" # Ensure this path is correct on Streamlit Cloud
45
+ loaders = [PyPDFLoader(pdf_path)]
46
+ return VectorstoreIndexCreator(
47
+ embedding=HuggingFaceEmbeddings(model_name='all-MiniLM-L12-v2'),
48
+ text_splitter=RecursiveCharacterTextSplitter(
49
+ chunk_size=600, chunk_overlap=300, separators=["\n\n", "\n", ".", "•"]
50
+ )
51
+ ).from_loaders(loaders).vectorstore
52
+
53
+ def extract_political_groups(text):
54
+ pattern = re.compile(r'(AsF|CDU|SPD|FDP|Junge Union|Senioren-Union|Freie W[aä]hlergruppe)[^\n]*', re.IGNORECASE)
55
+ return '\n'.join(sorted(set([m.group(0).strip() for m in pattern.finditer(text)])))
56
+
57
+ prompt = st.chat_input('Pass your prompt here')
58
+
59
+ if prompt:
60
+ st.chat_message('user').markdown(prompt)
61
+ st.session_state.messages.append({'role': 'user', 'content': prompt})
62
+
63
+ try:
64
+ openai_chat = ChatOpenAI(
65
+ model_name="gpt-3.5-turbo",
66
+ temperature=0,
67
+ openai_api_key=OPENAI_API_KEY
68
+ )
69
+
70
+ lang = detect_language(prompt)
71
+
72
+ if is_greeting(prompt):
73
+ response = "Hallo, ich bin der RegioWizard_KI Chatbot! 😊 Frag mich alles über Bad Breisig!" if lang == "de" else "Hi, I'm RegioWizard_KI Chatbot! 😊 Ask me anything about Bad Breisig!"
74
+ else:
75
+ vectorstore = get_vectorstore()
76
+
77
+ qa_prompt = ChatPromptTemplate.from_template("""
78
+ {prefix}
79
+
80
+ Context:
81
+ {context}
82
+
83
+ {q_prefix}: {question}
84
+
85
+ {a_prefix}:
86
+ """).partial(
87
+ prefix="Du bist ein hilfsbereiter Assistent mit Wissen über Bad Breisig. Verwende AUSSCHLIESSLICH den untenstehenden Kontext, um die Frage des Nutzers zu beantworten." if lang == "de" else "You are a helpful assistant knowledgeable about Bad Breisig. Use ONLY the context below to answer the user's question.",
88
+ q_prefix="Frage" if lang == "de" else "Question",
89
+ a_prefix="Antwort" if lang == "de" else "Answer"
90
+ )
91
+
92
+ chain = RetrievalQA.from_chain_type(
93
+ llm=openai_chat,
94
+ chain_type='stuff',
95
+ retriever=vectorstore.as_retriever(search_kwargs={'k': 12}),
96
+ chain_type_kwargs={"prompt": qa_prompt},
97
+ return_source_documents=True
98
+ )
99
+
100
+ result = chain({"query": prompt})
101
+ response = result["result"].strip()
102
+
103
+ if any(x in prompt.lower() for x in ["partei", "gruppierung", "gruppen", "parties", "political"]):
104
+ fallback_docs = result.get("source_documents", [])
105
+ combined_text = "\n".join(doc.page_content for doc in fallback_docs)
106
+ filtered = extract_political_groups(combined_text)
107
+ if filtered:
108
+ response = f"Die politischen Gruppierungen in Bad Breisig sind:\n\n{filtered}" if lang == "de" else f"The political groups in Bad Breisig are:\n\n{filtered}"
109
+
110
+ if not response or "not found" in response.lower() or "nicht im kontext" in response.lower():
111
+ fallback_docs = vectorstore.similarity_search_with_score(prompt, k=3)
112
+ keyword_hits = list({doc.page_content.strip()[:300] for doc, _ in fallback_docs})
113
+
114
+ if keyword_hits:
115
+ response = "Hier sind die relevantesten Informationen:\n\n" if lang == "de" else "Here’s the most relevant information found:\n\n"
116
+ response += "\n\n".join(keyword_hits)
117
+ else:
118
+ response = "Nicht im bereitgestellten Dokument gefunden." if lang == "de" else "Not found in the provided document."
119
+
120
+ st.chat_message('assistant').markdown(response)
121
+ st.session_state.messages.append({'role': 'assistant', 'content': response})
122
 
123
+ except Exception as e:
124
+ st.error(f"❌ Error: {str(e)}")