NCTCMumbai commited on
Commit
24d1627
1 Parent(s): 9700457

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +3 -392
app.py CHANGED
@@ -1,394 +1,4 @@
1
 
2
- # from ragatouille import RAGPretrainedModel
3
- # import subprocess
4
- # import json
5
- # import spaces
6
- # import firebase_admin
7
- # from firebase_admin import credentials, firestore
8
- # import logging
9
- # from pathlib import Path
10
- # from time import perf_counter
11
- # from datetime import datetime
12
- # import gradio as gr
13
- # from jinja2 import Environment, FileSystemLoader
14
- # import numpy as np
15
-
16
- # from huggingface_hub import InferenceClient
17
- # from os import getenv
18
-
19
- # from backend.query_llm import generate_hf, generate_openai
20
-
21
- # from huggingface_hub import InferenceClient
22
-
23
-
24
- # VECTOR_COLUMN_NAME = "vector"
25
- # TEXT_COLUMN_NAME = "text"
26
- # HF_TOKEN = getenv("HUGGING_FACE_HUB_TOKEN")
27
- # proj_dir = Path(__file__).parent
28
- # # Setting up the logging
29
- # logging.basicConfig(level=logging.INFO)
30
- # logger = logging.getLogger(__name__)
31
- # client = InferenceClient("mistralai/Mixtral-8x7B-Instruct-v0.1",token=HF_TOKEN)
32
- # # Set up the template environment with the templates directory
33
- # env = Environment(loader=FileSystemLoader(proj_dir / 'templates'))
34
-
35
- # # Load the templates directly from the environment
36
- # template = env.get_template('template.j2')
37
- # template_html = env.get_template('template_html.j2')
38
-
39
- # def system_instructions(question_difficulty, topic,documents_str):
40
- # return f"""<s> [INST] Your are a great teacher and your task is to create 10 questions with 4 choices with a {question_difficulty} difficulty about topic request " {topic} " only from the below given documents, {documents_str} then create an answers. Index in JSON format, the questions as "Q#":"" to "Q#":"", the four choices as "Q#:C1":"" to "Q#:C4":"", and the answers as "A#":"Q#:C#" to "A#":"Q#:C#". [/INST]"""
41
-
42
-
43
- # RAG_db=gr.State()
44
-
45
- # with gr.Blocks(title="Quiz Maker", theme=gr.themes.Default(primary_hue="green", secondary_hue="green"), css="style.css") as QUIZBOT:
46
- # def load_model():
47
- # RAG= RAGPretrainedModel.from_pretrained("colbert-ir/colbertv2.0")
48
- # RAG_db.value=RAG.from_index('.ragatouille/colbert/indexes/cbseclass10index')
49
- # return 'Ready to Go!!'
50
- # with gr.Column(scale=4):
51
- # gr.HTML("""
52
- # <center>
53
- # <h1><span style="color: purple;">ADWITIYA</span> Customs Manual Quizbot</h1>
54
- # <h2>Generative AI-powered Capacity building for Training Officers</h2>
55
- # <i>⚠️ NACIN Faculties create quiz from any topic dynamically for classroom evaluation after their sessions ! ⚠️</i>
56
- # </center>
57
- # """)
58
- # #gr.Warning('Retrieving using ColBERT.. First time query will take a minute for model to load..pls wait')
59
- # with gr.Column(scale=2):
60
- # load_btn = gr.Button("Click to Load!🚀")
61
- # load_text=gr.Textbox()
62
- # load_btn.click(load_model,[],load_text)
63
-
64
-
65
- # topic = gr.Textbox(label="Enter the Topic for Quiz", placeholder="Write any topic/details from Customs Manual")
66
-
67
- # with gr.Row():
68
- # radio = gr.Radio(
69
- # ["easy", "average", "hard"], label="How difficult should the quiz be?"
70
- # )
71
-
72
-
73
- # generate_quiz_btn = gr.Button("Generate Quiz!🚀")
74
- # quiz_msg=gr.Textbox()
75
-
76
- # question_radios = [gr.Radio(visible=False), gr.Radio(visible=False), gr.Radio(
77
- # visible=False), gr.Radio(visible=False), gr.Radio(visible=False), gr.Radio(visible=False), gr.Radio(visible=False), gr.Radio(
78
- # visible=False), gr.Radio(visible=False), gr.Radio(visible=False)]
79
-
80
- # print(question_radios)
81
-
82
- # @spaces.GPU
83
- # @generate_quiz_btn.click(inputs=[radio, topic], outputs=[quiz_msg]+question_radios, api_name="generate_quiz")
84
- # def generate_quiz(question_difficulty, topic):
85
- # top_k_rank=10
86
- # RAG_db_=RAG_db.value
87
- # documents_full=RAG_db_.search(topic,k=top_k_rank)
88
- # gr.Warning('Generation of Quiz may take 1 to 2 minute. Pls wait')
89
-
90
-
91
- # generate_kwargs = dict(
92
- # temperature=0.2,
93
- # max_new_tokens=4000,
94
- # top_p=0.95,
95
- # repetition_penalty=1.0,
96
- # do_sample=True,
97
- # seed=42,
98
- # )
99
- # question_radio_list = []
100
- # count=0
101
- # while count<=3:
102
- # try:
103
- # documents=[item['content'] for item in documents_full]
104
- # document_summaries = [f"[DOCUMENT {i+1}]: {summary}{count}" for i, summary in enumerate(documents)]
105
- # documents_str='\n'.join(document_summaries)
106
- # formatted_prompt = system_instructions(
107
- # question_difficulty, topic,documents_str)
108
- # print(formatted_prompt)
109
- # pre_prompt = [
110
- # {"role": "system", "content": formatted_prompt}
111
- # ]
112
- # response = client.text_generation(
113
- # formatted_prompt, **generate_kwargs, stream=False, details=False, return_full_text=False,
114
- # )
115
- # output_json = json.loads(f"{response}")
116
-
117
-
118
- # print(response)
119
- # print('output json', output_json)
120
-
121
- # global quiz_data
122
-
123
- # quiz_data = output_json
124
-
125
-
126
-
127
- # for question_num in range(1, 11):
128
- # question_key = f"Q{question_num}"
129
- # answer_key = f"A{question_num}"
130
-
131
- # question = quiz_data.get(question_key)
132
- # answer = quiz_data.get(quiz_data.get(answer_key))
133
-
134
- # if not question or not answer:
135
- # continue
136
-
137
- # choice_keys = [f"{question_key}:C{i}" for i in range(1, 5)]
138
- # choice_list = []
139
- # for choice_key in choice_keys:
140
- # choice = quiz_data.get(choice_key, "Choice not found")
141
- # choice_list.append(f"{choice}")
142
-
143
- # radio = gr.Radio(choices=choice_list, label=question,
144
- # visible=True, interactive=True)
145
-
146
- # question_radio_list.append(radio)
147
- # if len(question_radio_list)==10:
148
- # break
149
- # else:
150
- # print('10 questions not generated . So trying again!')
151
- # count+=1
152
- # continue
153
- # except Exception as e:
154
- # count+=1
155
- # print(f"Exception occurred: {e}")
156
- # if count==3:
157
- # print('Retry exhausted')
158
- # gr.Warning('Sorry. Pls try with another topic !')
159
- # else:
160
- # print(f"Trying again..{count} time...please wait")
161
- # continue
162
-
163
- # print('Question radio list ' , question_radio_list)
164
-
165
- # return ['Quiz Generated!']+ question_radio_list
166
-
167
- # check_button = gr.Button("Check Score")
168
-
169
- # score_textbox = gr.Markdown()
170
-
171
- # @check_button.click(inputs=question_radios, outputs=score_textbox)
172
- # def compare_answers(*user_answers):
173
- # user_anwser_list = []
174
- # user_anwser_list = user_answers
175
-
176
- # answers_list = []
177
-
178
- # for question_num in range(1, 20):
179
- # answer_key = f"A{question_num}"
180
- # answer = quiz_data.get(quiz_data.get(answer_key))
181
- # if not answer:
182
- # break
183
- # answers_list.append(answer)
184
-
185
- # score = 0
186
-
187
- # for item in user_anwser_list:
188
- # if item in answers_list:
189
- # score += 1
190
- # if score>5:
191
- # message = f"### Good ! You got {score} over 10!"
192
- # elif score>7:
193
- # message = f"### Excellent ! You got {score} over 10!"
194
- # else:
195
- # message = f"### You got {score} over 10! Dont worry . You can prepare well and try better next time !"
196
-
197
- # return message
198
-
199
-
200
- # QUIZBOT.queue()
201
- # QUIZBOT.launch(debug=True)
202
-
203
-
204
- # ################################################
205
- # from ragatouille import RAGPretrainedModel
206
- # import subprocess
207
- # import json
208
- # import spaces
209
- # import firebase_admin
210
- # from firebase_admin import credentials, firestore
211
- # import logging
212
- # from pathlib import Path
213
- # from time import perf_counter
214
- # from datetime import datetime
215
- # import gradio as gr
216
- # from jinja2 import Environment, FileSystemLoader
217
- # import numpy as np
218
- # from sentence_transformers import CrossEncoder
219
- # from os import getenv
220
- # from backend.query_llm import generate_hf, generate_openai
221
- # from backend.semantic_search import table, retriever
222
- # from gradio_client import Client # Modified here
223
-
224
- # VECTOR_COLUMN_NAME = "vector"
225
- # TEXT_COLUMN_NAME = "text"
226
- # proj_dir = Path(__file__).parent
227
-
228
- # # Setting up the logging
229
- # logging.basicConfig(level=logging.INFO)
230
- # logger = logging.getLogger(__name__)
231
-
232
- # # Replace Mixtral client with Qwen Client
233
- # client = Client("Qwen/Qwen1.5-110B-Chat-demo") # Modified here
234
-
235
- # # Set up the template environment with the templates directory
236
- # env = Environment(loader=FileSystemLoader(proj_dir / 'templates'))
237
-
238
- # # Load the templates directly from the environment
239
- # template = env.get_template('template.j2')
240
- # template_html = env.get_template('template_html.j2')
241
-
242
- # def system_instructions(question_difficulty, topic, documents_str):
243
- # return f"""<s> [INST] You are a great teacher and your task is to create 10 questions with 4 choices with {question_difficulty} difficulty about the topic request "{topic}" only from the below given documents, {documents_str}. Then create answers. Index in JSON format, the questions as "Q#":"" to "Q#":"", the four choices as "Q#:C1":"" to "Q#:C4":"", and the answers as "A#":"Q#:C#" to "A#":"Q#:C#". example is 'A10':'Q10:C3' [/INST]"""
244
-
245
- # # RA
246
- # RAG_db = gr.State()
247
-
248
- # with gr.Blocks(title="Quiz Maker", theme=gr.themes.Default(primary_hue="green", secondary_hue="green"), css="style.css") as QUIZBOT:
249
- # def load_model():
250
- # RAG = RAGPretrainedModel.from_pretrained("colbert-ir/colbertv2.0")
251
- # RAG_db.value = RAG.from_index('.ragatouille/colbert/indexes/cbseclass10index')
252
- # return 'Ready to Go!!'
253
-
254
- # with gr.Column(scale=4):
255
- # gr.HTML("""
256
- # <center>
257
- # <h1><span style="color: purple;">ADWITIYA</span> Customs Manual Quizbot</h1>
258
- # <h2>Generative AI-powered Capacity building for Training Officers</h2>
259
- # <i>⚠️ NACIN Faculties create quiz from any topic dynamically for classroom evaluation after their sessions ! ⚠️</i>
260
- # </center>
261
- # """)
262
-
263
- # with gr.Column(scale=2):
264
- # load_btn = gr.Button("Click to Load!🚀")
265
- # load_text = gr.Textbox()
266
- # load_btn.click(load_model, [], load_text)
267
-
268
- # topic = gr.Textbox(label="Enter the Topic for Quiz", placeholder="Write any topic/details from Customs Manual")
269
-
270
- # with gr.Row():
271
- # radio = gr.Radio(["easy", "average", "hard"], label="How difficult should the quiz be?")
272
-
273
- # generate_quiz_btn = gr.Button("Generate Quiz!🚀")
274
- # quiz_msg = gr.Textbox()
275
-
276
- # question_radios = [gr.Radio(visible=False) for _ in range(10)]
277
-
278
- # @spaces.GPU
279
- # @generate_quiz_btn.click(inputs=[radio, topic], outputs=[quiz_msg] + question_radios, api_name="generate_quiz")
280
- # def generate_quiz(question_difficulty, topic):
281
- # top_k_rank = 10
282
- # RAG_db_ = RAG_db.value
283
- # documents_full = RAG_db_.search(topic, k=top_k_rank)
284
-
285
- # gr.Warning('Generation of Quiz may take 1 to 2 minutes. Please wait.')
286
-
287
- # question_radio_list = []
288
- # count = 0
289
- # while count <= 3:
290
- # try:
291
- # documents = [item['content'] for item in documents_full]
292
- # document_summaries = [f"[DOCUMENT {i + 1}]: {summary}{count}" for i, summary in enumerate(documents)]
293
- # documents_str = '\n'.join(document_summaries)
294
- # formatted_prompt = system_instructions(question_difficulty, topic, documents_str)
295
-
296
- # print(formatted_prompt)
297
-
298
- # # Use Qwen Client for quiz generation
299
- # response = client.predict(
300
- # query=formatted_prompt,
301
- # history=[],
302
- # system="You are a helpful assistant.", # Modified to match Qwen's API
303
- # api_name="/model_chat"
304
- # )
305
- # print(response)
306
- # response1=response[1][0][1]
307
- # # Find the first and last curly braces
308
- # start_index = response1.find('{')
309
- # end_index = response1.rfind('}')
310
-
311
- # # Extract only the JSON part
312
- # if start_index != -1 and end_index != -1:
313
- # cleaned_response = response1[start_index:end_index + 1] # Include the last closing brace
314
-
315
- # # Try parsing the cleaned JSON
316
- # try:
317
- # output_json = json.loads(cleaned_response)
318
- # print('Parsed JSON:', output_json) # Successfully print the dictionary
319
- # except json.JSONDecodeError as e:
320
- # print(f"Failed to decode JSON: {e}")
321
- # else:
322
- # print("No valid JSON found in the response.")
323
- # # output_json = json.loads(f"{response}")
324
- # # print('output json', output_json)
325
-
326
- # global quiz_data
327
- # quiz_data = output_json
328
-
329
- # for question_num in range(1, 11):
330
- # question_key = f"Q{question_num}"
331
- # answer_key = f"A{question_num}"
332
-
333
- # question = quiz_data.get(question_key)
334
- # answer = quiz_data.get(quiz_data.get(answer_key))
335
-
336
- # if not question or not answer:
337
- # continue
338
-
339
- # choice_keys = [f"{question_key}:C{i}" for i in range(1, 5)]
340
- # choice_list = [quiz_data.get(choice_key, "Choice not found") for choice_key in choice_keys]
341
-
342
- # radio = gr.Radio(choices=choice_list, label=question, visible=True, interactive=True)
343
- # question_radio_list.append(radio)
344
- # print('question_radio_list',question_radio_list)
345
-
346
- # if len(question_radio_list) == 10:
347
- # break
348
- # else:
349
- # print('10 questions not generated. Trying again!')
350
- # count += 1
351
- # continue
352
- # except Exception as e:
353
- # count += 1
354
- # print(f"Exception occurred: {e}")
355
- # if count == 3:
356
- # print('Retry exhausted')
357
- # gr.Warning('Sorry. Please try with another topic!')
358
- # else:
359
- # print(f"Trying again.. {count} time... please wait")
360
- # continue
361
-
362
- # return ['Quiz Generated!'] + question_radio_list
363
-
364
- # check_button = gr.Button("Check Score")
365
- # score_textbox = gr.Markdown()
366
-
367
- # @check_button.click(inputs=question_radios, outputs=score_textbox)
368
- # def compare_answers(*user_answers):
369
- # user_anwser_list = list(user_answers)
370
- # answers_list = []
371
-
372
- # for question_num in range(1, 20):
373
- # answer_key = f"A{question_num}"
374
- # answer = quiz_data.get(quiz_data.get(answer_key))
375
- # if not answer:
376
- # break
377
- # answers_list.append(answer)
378
-
379
- # score = sum(1 for item in user_anwser_list if item in answers_list)
380
-
381
- # if score > 5:
382
- # message = f"### Good! You got {score} out of 10!"
383
- # elif score > 7:
384
- # message = f"### Excellent! You got {score} out of 10!"
385
- # else:
386
- # message = f"### You got {score} out of 10! Don't worry. You can prepare well and try better next time!"
387
-
388
- # return message
389
-
390
- # QUIZBOT.queue()
391
- # QUIZBOT.launch(debug=True)
392
  # ##############??????????????????????????????
393
  # import pandas as pd
394
  # import json
@@ -667,8 +277,9 @@ def json_to_excel(output_json):
667
 
668
  question = output_json.get(question_key, '')
669
  correct_answer_key = output_json.get(answer_key, '')
670
- correct_answer = correct_answer_key.split(':')[-1] if correct_answer_key else ''
671
-
 
672
  # Extract options
673
  option_keys = [f"{question_key}:C{i}" for i in range(1, 6)]
674
  options = [output_json.get(key, '') for key in option_keys]
 
1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
  # ##############??????????????????????????????
3
  # import pandas as pd
4
  # import json
 
277
 
278
  question = output_json.get(question_key, '')
279
  correct_answer_key = output_json.get(answer_key, '')
280
+ #correct_answer = correct_answer_key.split(':')[-1] if correct_answer_key else ''
281
+ correct_answer = correct_answer_key.split(':')[-1].replace('C', '').strip() if correct_answer_key else ''
282
+
283
  # Extract options
284
  option_keys = [f"{question_key}:C{i}" for i in range(1, 6)]
285
  options = [output_json.get(key, '') for key in option_keys]