muzammil-eds commited on
Commit
a72c9c1
β€’
1 Parent(s): c586572

Upload 2 files

Browse files
Files changed (2) hide show
  1. education.py +183 -0
  2. requirements.txt +7 -0
education.py ADDED
@@ -0,0 +1,183 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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="EDUCATIONAL 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"> πŸ“š EDUCATIONAL 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('Solve Assignment', 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("πŸ“š Solve PDF Assignments πŸ“œ")
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('Solve'):
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 solve 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 = '''
134
+ You are an educational assistant chatbot, designed to provide insightful and accurate answers in the educational domain. Your responses should be engaging and emulate a human educator to create a comfortable learning environment. Instead of simply presenting facts, aim to inspire curiosity and deeper understanding.
135
+
136
+ Context:
137
+
138
+ Understand the essence of the user's educational query.
139
+ Consider the academic level and subject matter of the question.
140
+ Access a broad knowledge base to provide well-informed responses.
141
+ Organize the response clearly and logically.
142
+ Deliver the answer in a manner that is both educational and relatable to human interaction.
143
+
144
+ Human:
145
+ '''
146
+ for dict_message in st.session_state.current_conversation:
147
+ string_dialogue += dict_message["role"].capitalize() + ": " + dict_message["content"] + "\\n\\n"
148
+
149
+ prompt = f"{string_dialogue}\n {prompt_input} Assistant: "
150
+ response_generator = g4f.ChatCompletion.create(
151
+ model="gpt-3.5-turbo",
152
+ messages=[{"role": "user", "content": prompt}],
153
+ stream=True,
154
+ )
155
+ return response_generator
156
+
157
+ if prompt := st.chat_input('Send a Message'):
158
+ st.session_state.current_conversation.append({"role": "user", "content": prompt})
159
+ with st.chat_message("user"):
160
+ st.write(prompt)
161
+
162
+ with st.chat_message("assistant"):
163
+ with st.spinner("Thinking..."):
164
+ response = generate_response(prompt)
165
+ placeholder = st.empty()
166
+ full_response = ''
167
+ for item in response:
168
+ full_response += item
169
+ time.sleep(0.003)
170
+ placeholder.markdown(full_response)
171
+ placeholder.markdown(full_response)
172
+ st.session_state.current_conversation.append({"role": "assistant", "content": full_response})
173
+ save_conversations(st.session_state.conversations)
174
+
175
+
176
+ display_chats_sidebar()
177
+ if st.session_state.get('page') == "summarize_bills":
178
+ summarize_bill()
179
+ elif st.session_state.get('page') == "chat":
180
+ main_app()
181
+ else:
182
+ # Default page when the app starts or when the state is not set
183
+ main_app()
requirements.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ gpt4all
2
+ streamlit
3
+ g4f
4
+ docx2txt
5
+ pypdf2
6
+ pytesseract
7
+ pdf2image