adowu commited on
Commit
13a4ba2
verified
1 Parent(s): dde9d2b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +58 -57
app.py CHANGED
@@ -1,80 +1,81 @@
1
  import streamlit as st
2
- import logging
3
- from database import KodeksProcessor
4
- from config import DATABASE_DIR
5
  import os
6
-
7
- logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
8
- logger = logging.getLogger(__name__)
9
-
10
- def initialize_session_state():
11
- if 'chatbot' not in st.session_state:
12
- st.session_state.chatbot = None
13
- if 'messages' not in st.session_state:
14
- st.session_state.messages = []
 
 
 
 
 
 
 
 
 
 
 
 
 
15
 
16
  def main():
17
- st.title("Asystent Prawny")
18
 
19
- initialize_session_state()
 
 
 
 
20
 
21
- # Inicjalizacja bazy danych (je艣li potrzebna)
22
- if 'db_initialized' not in st.session_state:
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
- # Przycisk do czyszczenia historii
33
- if st.sidebar.button("Wyczy艣膰 histori臋"):
34
  st.session_state.messages = []
35
- st.rerun()
36
 
37
- # Wy艣wietlenie historii czatu
38
  for message in st.session_state.messages:
39
  with st.chat_message(message["role"]):
40
  st.markdown(message["content"])
41
 
42
- # Input u偶ytkownika
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
- # Wyszukaj odpowiednie fragmenty w bazie
51
- processor = KodeksProcessor()
52
- relevant_chunks = processor.search(prompt)
53
 
54
- # Wygeneruj odpowied藕
55
- with st.chat_message("assistant"):
56
- message_placeholder = st.empty()
57
- full_response = "Oto co znalaz艂em w bazie danych:\n\n"
 
58
 
59
- for doc, metadata in zip(relevant_chunks['documents'][0], relevant_chunks['metadatas'][0]):
60
- full_response += f"**Artyku艂 {metadata['article']}**\n{doc}\n\n"
61
-
62
- message_placeholder.markdown(full_response)
63
-
64
- # Dodaj odpowied藕 asystenta do historii
65
- st.session_state.messages.append({"role": "assistant", "content": full_response})
66
-
67
- # Sekcja debugowania
68
- if st.sidebar.checkbox("Poka偶 informacje debugowania"):
69
- st.subheader("Informacje debugowania")
70
- processor = KodeksProcessor()
71
- doc_count = processor.collection.count()
72
- st.write(f"Ca艂kowita liczba dokument贸w w bazie danych: {doc_count}")
73
- if st.button("Przetw贸rz pliki ponownie"):
74
- processor.process_all_files("data/kodeksy")
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()