Update app.py
Browse files
app.py
CHANGED
@@ -1,122 +1,67 @@
|
|
1 |
import streamlit as st
|
2 |
-
import
|
|
|
3 |
import os
|
4 |
-
from sentence_transformers import SentenceTransformer, util
|
5 |
-
import torch
|
6 |
-
from huggingface_hub import InferenceClient
|
7 |
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
# Load the processed legal code data
|
14 |
-
@st.cache_resource
|
15 |
-
def load_data(file_path):
|
16 |
-
with open(file_path, 'r', encoding='utf-8') as f:
|
17 |
-
return json.load(f)
|
18 |
-
|
19 |
-
# Initialize the sentence transformer model
|
20 |
-
@st.cache_resource
|
21 |
-
def load_model():
|
22 |
-
return SentenceTransformer('distiluse-base-multilingual-cased-v1')
|
23 |
-
|
24 |
-
def generate_keywords(query):
|
25 |
-
client = InferenceClient(token=HF_TOKEN)
|
26 |
-
|
27 |
-
prompt = f"Na podstawie poniższego pytania, wygeneruj 3-5 słów kluczowych, które najlepiej opisują główne tematy i koncepcje prawne zawarte w pytaniu. Podaj tylko słowa kluczowe, oddzielone przecinkami.\n\nPytanie: {query}\n\nSłowa kluczowe:"
|
28 |
-
|
29 |
-
response = client.text_generation(
|
30 |
-
model="Qwen/Qwen2.5-72B-Instruct",
|
31 |
-
prompt=prompt,
|
32 |
-
max_new_tokens=50,
|
33 |
-
temperature=0.3,
|
34 |
-
top_p=0.9
|
35 |
-
)
|
36 |
-
|
37 |
-
keywords = [keyword.strip() for keyword in response.split(',')]
|
38 |
-
return keywords
|
39 |
|
40 |
-
def
|
41 |
-
|
42 |
-
chunk_embeddings = model.encode([chunk['text'] for chunk in chunks], convert_to_tensor=True)
|
43 |
|
44 |
-
|
45 |
-
top_results = torch.topk(cos_scores.mean(dim=0), k=top_k)
|
46 |
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
context += f"{chunk['metadata']['nazwa']} - Artykuł {chunk['metadata']['article']}:\n"
|
55 |
-
context += f"{chunk['text']}\n\n"
|
56 |
-
|
57 |
-
prompt = f"Jesteś asystentem prawniczym. Odpowiedz na poniższe pytanie na podstawie podanego kontekstu prawnego.\n\nKontekst: {context}\n\nPytanie: {query}\n\nOdpowiedź:"
|
58 |
-
|
59 |
-
response = client.text_generation(
|
60 |
-
model="Qwen/Qwen2.5-72B-Instruct",
|
61 |
-
prompt=prompt,
|
62 |
-
max_new_tokens=2048,
|
63 |
-
temperature=0.5,
|
64 |
-
top_p=0.7
|
65 |
-
)
|
66 |
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
st.title("Chatbot Prawny z AI")
|
71 |
-
|
72 |
-
# Load data and model
|
73 |
-
data_file = "processed_kodeksy.json"
|
74 |
-
if not os.path.exists(data_file):
|
75 |
-
st.error(f"Plik {data_file} nie istnieje. Najpierw przetwórz dane kodeksów.")
|
76 |
-
return
|
77 |
-
|
78 |
-
chunks = load_data(data_file)
|
79 |
-
model = load_model()
|
80 |
-
|
81 |
-
# Initialize chat history
|
82 |
-
if "messages" not in st.session_state:
|
83 |
st.session_state.messages = []
|
|
|
84 |
|
85 |
-
#
|
86 |
for message in st.session_state.messages:
|
87 |
with st.chat_message(message["role"]):
|
88 |
st.markdown(message["content"])
|
89 |
|
90 |
-
#
|
91 |
if prompt := st.chat_input("Zadaj pytanie dotyczące prawa..."):
|
|
|
92 |
st.session_state.messages.append({"role": "user", "content": prompt})
|
|
|
93 |
with st.chat_message("user"):
|
94 |
st.markdown(prompt)
|
95 |
|
96 |
-
#
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
-
|
101 |
-
# Generate AI response
|
102 |
with st.chat_message("assistant"):
|
103 |
message_placeholder = st.empty()
|
104 |
-
full_response =
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
105 |
message_placeholder.markdown(full_response)
|
106 |
|
|
|
107 |
st.session_state.messages.append({"role": "assistant", "content": full_response})
|
108 |
|
109 |
-
# Sidebar for additional options
|
110 |
-
with st.sidebar:
|
111 |
-
st.subheader("Opcje")
|
112 |
-
if st.button("Wyczyść historię czatu"):
|
113 |
-
st.session_state.messages = []
|
114 |
-
st.experimental_rerun()
|
115 |
-
|
116 |
-
st.subheader("Informacje o bazie danych")
|
117 |
-
st.write(f"Liczba chunków: {len(chunks)}")
|
118 |
-
st.write(f"Przykładowy chunk:")
|
119 |
-
st.json(chunks[0] if chunks else {})
|
120 |
-
|
121 |
if __name__ == "__main__":
|
122 |
main()
|
|
|
1 |
import streamlit as st
|
2 |
+
from database import KodeksProcessor
|
3 |
+
from chatbot import Chatbot
|
4 |
import os
|
|
|
|
|
|
|
5 |
|
6 |
+
def initialize_session_state():
|
7 |
+
if 'chatbot' not in st.session_state:
|
8 |
+
st.session_state.chatbot = Chatbot()
|
9 |
+
if 'messages' not in st.session_state:
|
10 |
+
st.session_state.messages = []
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
11 |
|
12 |
+
def main():
|
13 |
+
st.title("Asystent Prawny")
|
|
|
14 |
|
15 |
+
initialize_session_state()
|
|
|
16 |
|
17 |
+
# Inicjalizacja bazy danych (jeśli potrzebna)
|
18 |
+
if 'db_initialized' not in st.session_state:
|
19 |
+
with st.spinner("Inicjalizacja bazy danych..."):
|
20 |
+
processor = KodeksProcessor()
|
21 |
+
if not os.path.exists("chroma_db"):
|
22 |
+
processor.process_all_files("data/kodeksy")
|
23 |
+
st.session_state.db_initialized = True
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
24 |
|
25 |
+
# Przycisk do czyszczenia historii
|
26 |
+
if st.sidebar.button("Wyczyść historię"):
|
27 |
+
st.session_state.chatbot.clear_history()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
28 |
st.session_state.messages = []
|
29 |
+
st.rerun()
|
30 |
|
31 |
+
# Wyświetlenie historii czatu
|
32 |
for message in st.session_state.messages:
|
33 |
with st.chat_message(message["role"]):
|
34 |
st.markdown(message["content"])
|
35 |
|
36 |
+
# Input użytkownika
|
37 |
if prompt := st.chat_input("Zadaj pytanie dotyczące prawa..."):
|
38 |
+
# Dodaj pytanie użytkownika do historii
|
39 |
st.session_state.messages.append({"role": "user", "content": prompt})
|
40 |
+
|
41 |
with st.chat_message("user"):
|
42 |
st.markdown(prompt)
|
43 |
|
44 |
+
# Wyszukaj odpowiednie fragmenty w bazie
|
45 |
+
processor = KodeksProcessor()
|
46 |
+
relevant_chunks = processor.search(prompt)
|
47 |
+
|
48 |
+
# Wygeneruj odpowiedź
|
|
|
49 |
with st.chat_message("assistant"):
|
50 |
message_placeholder = st.empty()
|
51 |
+
full_response = ""
|
52 |
+
|
53 |
+
context = st.session_state.chatbot.generate_context(
|
54 |
+
[{"text": doc} for doc in relevant_chunks['documents'][0]]
|
55 |
+
)
|
56 |
+
|
57 |
+
for response_chunk in st.session_state.chatbot.get_response(prompt, context):
|
58 |
+
full_response += response_chunk
|
59 |
+
message_placeholder.markdown(full_response + "▌")
|
60 |
+
|
61 |
message_placeholder.markdown(full_response)
|
62 |
|
63 |
+
# Dodaj odpowiedź asystenta do historii
|
64 |
st.session_state.messages.append({"role": "assistant", "content": full_response})
|
65 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
66 |
if __name__ == "__main__":
|
67 |
main()
|