Update app.py
Browse files
app.py
CHANGED
@@ -1,80 +1,81 @@
|
|
1 |
import streamlit as st
|
2 |
-
import
|
3 |
-
from database import KodeksProcessor
|
4 |
-
from config import DATABASE_DIR
|
5 |
import os
|
6 |
-
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
15 |
|
16 |
def main():
|
17 |
-
st.title("
|
18 |
|
19 |
-
|
|
|
|
|
|
|
|
|
20 |
|
21 |
-
|
22 |
-
|
23 |
-
with st.spinner("Inicjalizacja bazy danych..."):
|
24 |
-
processor = KodeksProcessor()
|
25 |
-
if not os.path.exists(DATABASE_DIR):
|
26 |
-
logger.info(f"Przetwarzanie plik贸w w katalogu: data/kodeksy")
|
27 |
-
processor.process_all_files("data/kodeksy")
|
28 |
-
else:
|
29 |
-
logger.info(f"Baza danych ju偶 istnieje w {DATABASE_DIR}")
|
30 |
-
st.session_state.db_initialized = True
|
31 |
|
32 |
-
#
|
33 |
-
if st.
|
34 |
st.session_state.messages = []
|
35 |
-
st.rerun()
|
36 |
|
37 |
-
#
|
38 |
for message in st.session_state.messages:
|
39 |
with st.chat_message(message["role"]):
|
40 |
st.markdown(message["content"])
|
41 |
|
42 |
-
#
|
43 |
if prompt := st.chat_input("Zadaj pytanie dotycz膮ce prawa..."):
|
44 |
-
# Dodaj pytanie u偶ytkownika do historii
|
45 |
st.session_state.messages.append({"role": "user", "content": prompt})
|
46 |
-
|
47 |
with st.chat_message("user"):
|
48 |
st.markdown(prompt)
|
49 |
|
50 |
-
#
|
51 |
-
|
52 |
-
relevant_chunks = processor.search(prompt)
|
53 |
|
54 |
-
#
|
55 |
-
|
56 |
-
|
57 |
-
|
|
|
58 |
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
st.write(f"
|
73 |
-
|
74 |
-
|
75 |
-
st.success("Przetwarzanie zako艅czone")
|
76 |
-
if st.button("Poka偶 wszystkie dokumenty"):
|
77 |
-
processor.list_all_documents()
|
78 |
|
79 |
if __name__ == "__main__":
|
80 |
main()
|
|
|
1 |
import streamlit as st
|
2 |
+
import json
|
|
|
|
|
3 |
import os
|
4 |
+
from sentence_transformers import SentenceTransformer, util
|
5 |
+
import torch
|
6 |
+
|
7 |
+
# Load the processed legal code data
|
8 |
+
@st.cache_resource
|
9 |
+
def load_data(file_path):
|
10 |
+
with open(file_path, 'r', encoding='utf-8') as f:
|
11 |
+
return json.load(f)
|
12 |
+
|
13 |
+
# Initialize the sentence transformer model
|
14 |
+
@st.cache_resource
|
15 |
+
def load_model():
|
16 |
+
return SentenceTransformer('distiluse-base-multilingual-cased-v1')
|
17 |
+
|
18 |
+
def search_relevant_chunks(query, chunks, model, top_k=3):
|
19 |
+
query_embedding = model.encode(query, convert_to_tensor=True)
|
20 |
+
chunk_embeddings = model.encode([chunk['text'] for chunk in chunks], convert_to_tensor=True)
|
21 |
+
|
22 |
+
cos_scores = util.pytorch_cos_sim(query_embedding, chunk_embeddings)[0]
|
23 |
+
top_results = torch.topk(cos_scores, k=top_k)
|
24 |
+
|
25 |
+
return [chunks[idx] for idx in top_results.indices]
|
26 |
|
27 |
def main():
|
28 |
+
st.title("Chatbot Prawny")
|
29 |
|
30 |
+
# Load data and model
|
31 |
+
data_file = "processed_kodeksy.json"
|
32 |
+
if not os.path.exists(data_file):
|
33 |
+
st.error(f"Plik {data_file} nie istnieje. Najpierw przetw贸rz dane kodeks贸w.")
|
34 |
+
return
|
35 |
|
36 |
+
chunks = load_data(data_file)
|
37 |
+
model = load_model()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
38 |
|
39 |
+
# Initialize chat history
|
40 |
+
if "messages" not in st.session_state:
|
41 |
st.session_state.messages = []
|
|
|
42 |
|
43 |
+
# Display chat history
|
44 |
for message in st.session_state.messages:
|
45 |
with st.chat_message(message["role"]):
|
46 |
st.markdown(message["content"])
|
47 |
|
48 |
+
# User input
|
49 |
if prompt := st.chat_input("Zadaj pytanie dotycz膮ce prawa..."):
|
|
|
50 |
st.session_state.messages.append({"role": "user", "content": prompt})
|
|
|
51 |
with st.chat_message("user"):
|
52 |
st.markdown(prompt)
|
53 |
|
54 |
+
# Search for relevant chunks
|
55 |
+
relevant_chunks = search_relevant_chunks(prompt, chunks, model)
|
|
|
56 |
|
57 |
+
# Generate response
|
58 |
+
response = "Oto co znalaz艂em w kodeksie:\n\n"
|
59 |
+
for chunk in relevant_chunks:
|
60 |
+
response += f"**{chunk['metadata']['nazwa']} - Artyku艂 {chunk['metadata']['article']}**\n"
|
61 |
+
response += f"{chunk['text']}\n\n"
|
62 |
|
63 |
+
# Display assistant response
|
64 |
+
with st.chat_message("assistant"):
|
65 |
+
st.markdown(response)
|
66 |
+
st.session_state.messages.append({"role": "assistant", "content": response})
|
67 |
+
|
68 |
+
# Sidebar for additional options
|
69 |
+
with st.sidebar:
|
70 |
+
st.subheader("Opcje")
|
71 |
+
if st.button("Wyczy艣膰 histori臋 czatu"):
|
72 |
+
st.session_state.messages = []
|
73 |
+
st.experimental_rerun()
|
74 |
+
|
75 |
+
st.subheader("Informacje o bazie danych")
|
76 |
+
st.write(f"Liczba chunk贸w: {len(chunks)}")
|
77 |
+
st.write(f"Przyk艂adowy chunk:")
|
78 |
+
st.json(chunks[0] if chunks else {})
|
|
|
|
|
|
|
79 |
|
80 |
if __name__ == "__main__":
|
81 |
main()
|