muzammil-eds commited on
Commit
1c426a0
Β·
1 Parent(s): 6e17a46

Upload 2 files

Browse files
Files changed (2) hide show
  1. law.py +171 -0
  2. requirements.txt +7 -0
law.py ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import os
3
+ import pickle
4
+ import time
5
+ import g4f
6
+ import tempfile
7
+ import PyPDF2
8
+ from pdf2image import convert_from_path
9
+ import pytesseract
10
+
11
+ st.set_page_config(page_title="LEGAL ASSISTANT")
12
+
13
+ st.markdown(
14
+ """
15
+ <style>
16
+ .title {
17
+ text-align: center;
18
+ font-size: 2em;
19
+ font-weight: bold;
20
+ }
21
+ </style>
22
+ <div class="title"> βš–οΈ LEGAL ASSISTANT βš–οΈ</div>
23
+ """,
24
+ unsafe_allow_html=True
25
+ )
26
+ # Load and Save Conversations
27
+ conversations_file = "conversations.pkl"
28
+
29
+
30
+ @st.cache_data
31
+ def load_conversations():
32
+ try:
33
+ with open(conversations_file, "rb") as f:
34
+ return pickle.load(f)
35
+ except (FileNotFoundError, EOFError):
36
+ return []
37
+
38
+
39
+ def save_conversations(conversations):
40
+ temp_conversations_file = conversations_file
41
+ with open(temp_conversations_file, "wb") as f:
42
+ pickle.dump(conversations, f)
43
+ os.replace(temp_conversations_file, conversations_file)
44
+
45
+
46
+ if 'conversations' not in st.session_state:
47
+ st.session_state.conversations = load_conversations()
48
+
49
+ if 'current_conversation' not in st.session_state:
50
+ st.session_state.current_conversation = [{"role": "assistant", "content": "How may I assist you today?"}]
51
+
52
+
53
+ def truncate_string(s, length=30):
54
+ return s[:length].rstrip() + "..." if len(s) > length else s
55
+
56
+
57
+ def display_chats_sidebar():
58
+ with st.sidebar.container():
59
+ st.header('Settings')
60
+ col1, col2 = st.columns([1, 1])
61
+
62
+ with col1:
63
+ if col1.button('Start New Chat', key="new_chat"):
64
+ st.session_state.current_conversation = []
65
+ st.session_state.conversations.append(st.session_state.current_conversation)
66
+
67
+ with col2:
68
+ if col2.button('Clear All Chats', key="clear_all"):
69
+ st.session_state.conversations = []
70
+ st.session_state.current_conversation = []
71
+
72
+ if st.sidebar.button('Summarize Agreements', key="summarize_bills", use_container_width=True):
73
+ st.session_state.page = "summarize_bills"
74
+
75
+ with st.sidebar.container():
76
+ st.header('Conversations')
77
+ for idx, conversation in enumerate(st.session_state.conversations):
78
+ if conversation:
79
+ chat_title_raw = next((msg["content"] for msg in conversation if msg["role"] == "user"), "New Chat")
80
+ chat_title = truncate_string(chat_title_raw)
81
+ if st.sidebar.button(f"{chat_title}", key=f"chat_button_{idx}"):
82
+ st.session_state.current_conversation = st.session_state.conversations[idx]
83
+
84
+
85
+ def summarize_bill():
86
+ st.header("πŸ“œ Summarize Agreements πŸ“œ")
87
+
88
+ if st.button("Back to Chat"):
89
+ st.session_state.page = "chat"
90
+
91
+ uploaded_file = st.file_uploader("Upload an Agreement", type=['pdf'])
92
+ if uploaded_file is not None:
93
+ with tempfile.NamedTemporaryFile(delete=False) as tmp_file:
94
+ tmp_file.write(uploaded_file.read())
95
+ extracted_text = extract_text_from_pdf(tmp_file.name)
96
+
97
+ if st.button('Summarize'):
98
+ # Assuming g4f.ChatCompletion can be used for summarization
99
+ # Replace with appropriate summarization logic if needed
100
+ summary = g4f.ChatCompletion.create(
101
+ model="gpt-3.5-turbo",
102
+ messages=[{"role": "user", "content": "Please Summarize this Agreement: \n" +extracted_text}],
103
+ temperature=0.5, # You can adjust parameters as needed
104
+ max_tokens=150 # Adjust the token limit as needed
105
+ )
106
+ st.text_area("Summary", summary, height=400)
107
+
108
+
109
+ def extract_text_from_pdf(file_path: str) -> str:
110
+ try:
111
+ with open(file_path, 'rb') as file:
112
+ reader = PyPDF2.PdfReader(file)
113
+ text = ''
114
+ for page_number in range(len(reader.pages)):
115
+ page = reader.pages[page_number]
116
+ text += page.extract_text()
117
+ return text
118
+ except Exception as e:
119
+ try:
120
+ images = convert_from_path(file_path)
121
+ extracted_texts = [pytesseract.image_to_string(image) for image in images]
122
+ return "\n".join(extracted_texts)
123
+ except Exception as e:
124
+ raise ValueError(f"Failed to process {file_path} using PDF Reader and OCR. Error: {e}")
125
+
126
+
127
+ def main_app():
128
+ for message in st.session_state.current_conversation:
129
+ with st.chat_message(message["role"]):
130
+ st.write(message["content"])
131
+
132
+ def generate_response(prompt_input):
133
+ string_dialogue = "You are a helpful Medical Assistant. You will Only respond to Medical related Queries. Say Sorry to any other Type of Queries."
134
+ for dict_message in st.session_state.current_conversation:
135
+ string_dialogue += dict_message["role"].capitalize() + ": " + dict_message["content"] + "\\n\\n"
136
+
137
+ prompt = f"{string_dialogue}\n {prompt_input} Assistant: "
138
+ response_generator = g4f.ChatCompletion.create(
139
+ model="gpt-3.5-turbo",
140
+ messages=[{"role": "user", "content": prompt}],
141
+ stream=True,
142
+ )
143
+ return response_generator
144
+
145
+ if prompt := st.chat_input('Send a Message'):
146
+ st.session_state.current_conversation.append({"role": "user", "content": prompt})
147
+ with st.chat_message("user"):
148
+ st.write(prompt)
149
+
150
+ with st.chat_message("assistant"):
151
+ with st.spinner("Thinking..."):
152
+ response = generate_response(prompt)
153
+ placeholder = st.empty()
154
+ full_response = ''
155
+ for item in response:
156
+ full_response += item
157
+ time.sleep(0.003)
158
+ placeholder.markdown(full_response)
159
+ placeholder.markdown(full_response)
160
+ st.session_state.current_conversation.append({"role": "assistant", "content": full_response})
161
+ save_conversations(st.session_state.conversations)
162
+
163
+
164
+ display_chats_sidebar()
165
+ if st.session_state.get('page') == "summarize_bills":
166
+ summarize_bill()
167
+ elif st.session_state.get('page') == "chat":
168
+ main_app()
169
+ else:
170
+ # Default page when the app starts or when the state is not set
171
+ main_app()
requirements.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ gpt4all==1.0.8
2
+ streamlit
3
+ g4f
4
+ docx2txt
5
+ pypdf2
6
+ pytesseract
7
+ pdf2image