husseinhug321 commited on
Commit
28d4dca
·
verified ·
1 Parent(s): 2fae179

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +201 -165
app.py CHANGED
@@ -1,165 +1,201 @@
1
- import gradio as gr
2
- import logging
3
-
4
- from config import SHARE_GRADIO_WITH_PUBLIC_URL
5
- from chains import qa_chain, summarization_chain
6
-
7
- logger = logging.getLogger(__name__)
8
-
9
- # Translation dictionary
10
- TRANSLATIONS = {
11
- "en": {
12
- "title": "# 📚 Study Buddy: AI Learning Assistant",
13
- "subtitle": "## 🤖 A smart, user-friendly chatbot for students!",
14
- "summary_subtitle": "## 📄 Upload Notes for Summarization",
15
- "chat_input_label": "Type your question here:",
16
- "chat_placeholder": "e.g., Explain Newton's laws",
17
- "chat_button_label": "Get Answer",
18
- "summary_button_label": "Summarize Notes",
19
- "upload_file_label": "Upload .txt or .pdf file",
20
- "summary_output_label": "Summary",
21
- "language_label": "Language / Langue",
22
- "ai_response_label": "AI Response"
23
- },
24
- "fr": {
25
- "title": "# 📚 Study Buddy: Assistant d'apprentissage IA",
26
- "subtitle": "## 🤖 Un chatbot intelligent et convivial pour les étudiants!",
27
- "summary_subtitle": "## 📄 Subir notas para resumir",
28
- "chat_input_label": "Tapez votre question ici:",
29
- "chat_placeholder": "ex : Expliquez les lois de Newton",
30
- "chat_button_label": "Obtenir une réponse",
31
- "summary_button_label": "Résumer les notes",
32
- "upload_file_label": "Téléchargez un fichier .txt ou .pdf",
33
- "summary_output_label": "Résumé",
34
- "language_label": "Langue / Language",
35
- "ai_response_label": "Réponse de l'IA"
36
- }
37
- }
38
-
39
- # Function to process user queries
40
- def chatbot_response(user_input, lang):
41
- try:
42
- response = qa_chain.invoke({"question": user_input})
43
- logger.info("chatbot_response completed")
44
- return response
45
- except Exception as e:
46
- msg = f"Error : {e}"
47
- logger.exception(msg)
48
- return TRANSLATIONS[lang].get("error_message", "Sorry, an error occurred while processing your request.")
49
-
50
- # Function to summarize notes
51
- def summarize_text(text, lang):
52
- try:
53
- summary = summarization_chain.invoke({"document_text": text})
54
- logger.info("summarize_text completed")
55
- return summary
56
- except Exception as e:
57
- msg = f"Error : {e}"
58
- logger.exception(msg)
59
- return TRANSLATIONS[lang].get("error_message", "Sorry, an error occurred while summarizing your notes.")
60
-
61
- # Function to update UI labels dynamically
62
- def update_language(lang):
63
- return (
64
- TRANSLATIONS[lang]["title"],
65
- TRANSLATIONS[lang]["subtitle"],
66
- TRANSLATIONS[lang]["chat_input_label"],
67
- TRANSLATIONS[lang]["chat_placeholder"],
68
- TRANSLATIONS[lang]["chat_button_label"],
69
- TRANSLATIONS[lang]["upload_file_label"],
70
- TRANSLATIONS[lang]["summary_button_label"],
71
- TRANSLATIONS[lang]["summary_output_label"],
72
- TRANSLATIONS[lang]["ai_response_label"]
73
- )
74
-
75
- # Gradio UI
76
- def create_interface():
77
- with gr.Blocks(css="body { font-family: sans-serif; background-color: #f9f9f9; }") as study_buddy:
78
-
79
- # Default to English
80
- lang = "en"
81
-
82
- title = gr.Markdown(f"{TRANSLATIONS[lang]['title']}")
83
-
84
- with gr.Row():
85
- with gr.Column():
86
- gr.Markdown("", height=4)
87
-
88
- language = gr.Radio(
89
- choices=["en", "fr"],
90
- value=lang,
91
- label=TRANSLATIONS[lang]["language_label"]
92
- )
93
-
94
- gr.Markdown("", height=4)
95
-
96
- subtitle = gr.Markdown(f"{TRANSLATIONS[lang]['subtitle']}")
97
-
98
- chat_input = gr.Textbox(
99
- label=TRANSLATIONS[lang]["chat_input_label"],
100
- lines=4,
101
- placeholder=TRANSLATIONS[lang]["chat_placeholder"]
102
- )
103
-
104
- with gr.Column():
105
- gr.Markdown("", height=4)
106
- summary_subtitle = gr.Markdown(f"{TRANSLATIONS[lang]['summary_subtitle']}")
107
- file_input = gr.File(file_types=[".pdf", ".txt"])
108
- file_label = gr.Markdown(TRANSLATIONS[lang]["upload_file_label"]) # Separate label
109
-
110
- with gr.Row():
111
- with gr.Column():
112
-
113
- chat_button = gr.Button(TRANSLATIONS[lang]["chat_button_label"], variant="primary")
114
- chat_output = gr.Textbox(label=TRANSLATIONS[lang]["ai_response_label"], lines=5, interactive=True)
115
-
116
- # Bind chatbot response function
117
- chat_button.click(
118
- chatbot_response,
119
- inputs=[chat_input, language],
120
- outputs=chat_output
121
- )
122
-
123
- with gr.Column():
124
-
125
- summary_button = gr.Button(TRANSLATIONS[lang]["summary_button_label"], variant="primary")
126
- summary_output = gr.Textbox(label=TRANSLATIONS[lang]["summary_output_label"], lines=5, interactive=True)
127
-
128
- # Bind summarization function
129
- summary_button.click(
130
- summarize_text,
131
- inputs=[file_input, language],
132
- outputs=summary_output
133
- )
134
-
135
- # Update labels dynamically when the language changes
136
- def update_labels(lang):
137
- return (
138
- TRANSLATIONS[lang]["title"],
139
- TRANSLATIONS[lang]["subtitle"],
140
- TRANSLATIONS[lang]["summary_subtitle"],
141
- TRANSLATIONS[lang]["chat_input_label"],
142
- TRANSLATIONS[lang]["chat_placeholder"],
143
- TRANSLATIONS[lang]["chat_button_label"],
144
- TRANSLATIONS[lang]["summary_button_label"],
145
- TRANSLATIONS[lang]["summary_output_label"],
146
- TRANSLATIONS[lang]["ai_response_label"],
147
- TRANSLATIONS[lang]["upload_file_label"]
148
- )
149
-
150
- language.change(
151
- update_labels,
152
- inputs=[language],
153
- outputs=[
154
- title, subtitle, summary_subtitle,
155
- chat_input, chat_input,
156
- chat_button,
157
- summary_button, summary_output, chat_output, file_label # Update file label separately
158
- ]
159
- )
160
-
161
- return study_buddy
162
-
163
- if __name__ == "__main__":
164
- study_buddy = create_interface()
165
- study_buddy.launch(share=SHARE_GRADIO_WITH_PUBLIC_URL)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import logging
3
+ import PyPDF2
4
+
5
+ from config import SHARE_GRADIO_WITH_PUBLIC_URL
6
+ from chains import qa_chain, summarization_chain
7
+
8
+ logger = logging.getLogger(__name__)
9
+
10
+ # Translation dictionary
11
+ TRANSLATIONS = {
12
+ "en": {
13
+ "title": "# 📚 Study Buddy: AI Learning Assistant",
14
+ "subtitle": "## 🤖 A smart, user-friendly chatbot for students!",
15
+ "summary_subtitle": "## 📄 Upload Notes for Summarization",
16
+ "chat_input_label": "Type your question here:",
17
+ "chat_placeholder": "e.g., Explain Newton's laws",
18
+ "chat_button_label": "Get Answer",
19
+ "summary_button_label": "Summarize Notes",
20
+ "upload_file_label": "Upload .txt or .pdf file",
21
+ "summary_output_label": "Summary",
22
+ "language_label": "Language / Langue",
23
+ "ai_response_label": "AI Response"
24
+ },
25
+ "fr": {
26
+ "title": "# 📚 Study Buddy: Assistant d'apprentissage IA",
27
+ "subtitle": "## 🤖 Un chatbot intelligent et convivial pour les étudiants!",
28
+ "summary_subtitle": "## 📄 Subir notas para resumir",
29
+ "chat_input_label": "Tapez votre question ici:",
30
+ "chat_placeholder": "ex : Expliquez les lois de Newton",
31
+ "chat_button_label": "Obtenir une réponse",
32
+ "summary_button_label": "Résumer les notes",
33
+ "upload_file_label": "Téléchargez un fichier .txt ou .pdf",
34
+ "summary_output_label": "Résumé",
35
+ "language_label": "Langue / Language",
36
+ "ai_response_label": "Réponse de l'IA"
37
+ }
38
+ }
39
+
40
+ # Function to process user queries
41
+ def chatbot_response(user_input, lang):
42
+ try:
43
+ response_output = qa_chain.invoke({"question": user_input})
44
+ response = response_output.content
45
+ logger.info("chatbot_response completed")
46
+ print("> chatbot_response completed")
47
+ return response
48
+ except Exception as e:
49
+ msg = f"Error : {e}"
50
+ logger.exception(msg)
51
+ print(msg)
52
+ return TRANSLATIONS[lang].get("error_message", "Sorry, an error occurred while processing your request.")
53
+
54
+ # Function to summarize notes
55
+ def summarize_pdf(pdf, lang):
56
+ try:
57
+ with open(pdf, "rb") as file:
58
+ reader = PyPDF2.PdfReader(file)
59
+ page = reader.pages[0] # Get the first page
60
+ text = page.extract_text()
61
+ print(text)
62
+ summary = summarize_text(text, lang)
63
+ logger.info("summarize_pdf completed")
64
+ print("> summarize_pdf completed")
65
+ return summary
66
+ except Exception as e:
67
+ msg = f"Error : {e}"
68
+ logger.exception(msg)
69
+ print(msg)
70
+ return TRANSLATIONS[lang].get("error_message", "Sorry, an error occurred while summarizing your notes.")
71
+
72
+ # Function to summarize notes
73
+ def summarize_text(text, lang):
74
+ try:
75
+ summary_output = summarization_chain.invoke({"document_text": text})
76
+ print(summary_output)
77
+ summary = summary_output.content
78
+ logger.info("summarize_text completed")
79
+ print("> summarize_text completed")
80
+ return summary
81
+ except Exception as e:
82
+ msg = f"Error : {e}"
83
+ logger.exception(msg)
84
+ print(msg)
85
+ return TRANSLATIONS[lang].get("error_message", "Sorry, an error occurred while summarizing your notes.")
86
+
87
+ # Function to update UI labels dynamically
88
+ def update_language(lang):
89
+ return (
90
+ TRANSLATIONS[lang]["title"],
91
+ TRANSLATIONS[lang]["subtitle"],
92
+ TRANSLATIONS[lang]["chat_input_label"],
93
+ TRANSLATIONS[lang]["chat_placeholder"],
94
+ TRANSLATIONS[lang]["chat_button_label"],
95
+ TRANSLATIONS[lang]["upload_file_label"],
96
+ TRANSLATIONS[lang]["summary_button_label"],
97
+ TRANSLATIONS[lang]["summary_output_label"],
98
+ TRANSLATIONS[lang]["ai_response_label"]
99
+ )
100
+
101
+ # Gradio UI
102
+ def create_interface():
103
+ with gr.Blocks(css="body { font-family: sans-serif; background-color: #f9f9f9; }") as study_buddy:
104
+
105
+ # Default to English
106
+ lang = "en"
107
+
108
+ title = gr.Markdown(f"{TRANSLATIONS[lang]['title']}")
109
+
110
+ with gr.Row():
111
+ with gr.Column():
112
+ gr.Markdown("", height=4)
113
+
114
+ language = gr.Radio(
115
+ choices=["en", "fr"],
116
+ value=lang,
117
+ label=TRANSLATIONS[lang]["language_label"]
118
+ )
119
+
120
+ gr.Markdown("", height=4)
121
+
122
+ subtitle = gr.Markdown(f"{TRANSLATIONS[lang]['subtitle']}")
123
+
124
+ chat_input = gr.Textbox(
125
+ # label=TRANSLATIONS[lang]["chat_input_label"]
126
+ label= "Type your question here: / Tapez votre question ici:",
127
+ lines=4,
128
+ placeholder=TRANSLATIONS[lang]["chat_placeholder"]
129
+ )
130
+
131
+ with gr.Column():
132
+ gr.Markdown("", height=4)
133
+ summary_subtitle = gr.Markdown(f"{TRANSLATIONS[lang]['summary_subtitle']}")
134
+ file_input = gr.File(label="File / Fichier",file_types=[".pdf", ".txt"])
135
+ file_label = gr.Markdown(TRANSLATIONS[lang]["upload_file_label"]) # Separate label
136
+
137
+ with gr.Row():
138
+ with gr.Column():
139
+
140
+ chat_button = gr.Button(TRANSLATIONS[lang]["chat_button_label"], variant="primary")
141
+ chat_output = gr.Textbox(
142
+ # label=TRANSLATIONS[lang]["ai_response_label"],
143
+ label = "AI Response / Réponse de l'IA",
144
+ lines=5, interactive=True
145
+ )
146
+
147
+ # Bind chatbot response function
148
+ chat_button.click(
149
+ chatbot_response,
150
+ inputs=[chat_input, language],
151
+ outputs=chat_output
152
+ )
153
+
154
+ with gr.Column():
155
+
156
+ summary_button = gr.Button(TRANSLATIONS[lang]["summary_button_label"], variant="primary")
157
+ summary_output = gr.Textbox(
158
+ # label=TRANSLATIONS[lang]["summary_output_label"],
159
+ label="Summary / Résumé",
160
+ lines=5,
161
+ interactive=True
162
+ )
163
+
164
+ # Bind summarization function
165
+ summary_button.click(
166
+ summarize_pdf,
167
+ inputs=[file_input, language],
168
+ outputs=summary_output
169
+ )
170
+
171
+ # Update labels dynamically when the language changes
172
+ def update_labels(lang):
173
+ return (
174
+ TRANSLATIONS[lang]["title"],
175
+ TRANSLATIONS[lang]["subtitle"],
176
+ TRANSLATIONS[lang]["summary_subtitle"],
177
+ TRANSLATIONS[lang]["chat_input_label"],
178
+ TRANSLATIONS[lang]["chat_placeholder"],
179
+ TRANSLATIONS[lang]["chat_button_label"],
180
+ TRANSLATIONS[lang]["summary_button_label"],
181
+ TRANSLATIONS[lang]["summary_output_label"],
182
+ TRANSLATIONS[lang]["ai_response_label"],
183
+ TRANSLATIONS[lang]["upload_file_label"]
184
+ )
185
+
186
+ language.change(
187
+ update_labels,
188
+ inputs=[language],
189
+ outputs=[
190
+ title, subtitle, summary_subtitle,
191
+ chat_input, chat_input,
192
+ chat_button,
193
+ summary_button, summary_output, chat_output, file_label # Update file label separately
194
+ ]
195
+ )
196
+
197
+ return study_buddy
198
+
199
+ if __name__ == "__main__":
200
+ study_buddy = create_interface()
201
+ study_buddy.launch(share=SHARE_GRADIO_WITH_PUBLIC_URL)