NCTCMumbai commited on
Commit
a941cf4
1 Parent(s): 24f3b2d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +248 -119
app.py CHANGED
@@ -273,165 +273,294 @@ with gr.Blocks(theme='NoCrypt/miku') as CHATBOT:
273
  gr.Examples(examples, txt)
274
 
275
 
276
- RAG_db=gr.State()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
277
 
278
  with gr.Blocks(title="Quiz Maker", theme=gr.themes.Default(primary_hue="green", secondary_hue="green"), css="style.css") as QUIZBOT:
279
- def load_model():
280
- RAG= RAGPretrainedModel.from_pretrained("colbert-ir/colbertv2.0")
281
- RAG_db.value=RAG.from_index('.ragatouille/colbert/indexes/cbseclass10index')
282
- return 'Ready to Go!!'
283
  with gr.Column(scale=4):
284
  gr.HTML("""
285
- <center>
286
- <h1><span style="color: purple;">ADWITIYA</span> Customs Manual Quizbot</h1>
287
- <h2>Generative AI-powered Capacity building for Training Officers</h2>
288
- <i>⚠️ NACIN Faculties create quiz from any topic dynamically for classroom evaluation after their sessions ! ⚠️</i>
289
- </center>
290
- """)
291
- #gr.Warning('Retrieving using ColBERT.. First time query will take a minute for model to load..pls wait')
292
  with gr.Column(scale=2):
293
  load_btn = gr.Button("Click to Load!🚀")
294
- load_text=gr.Textbox()
295
- load_btn.click(load_model,[],load_text)
296
-
297
-
298
  topic = gr.Textbox(label="Enter the Topic for Quiz", placeholder="Write any topic/details from Customs Manual")
299
 
300
  with gr.Row():
301
- radio = gr.Radio(
302
- ["easy", "average", "hard"], label="How difficult should the quiz be?"
303
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
304
 
 
 
 
305
 
306
- generate_quiz_btn = gr.Button("Generate Quiz!🚀")
307
- quiz_msg=gr.Textbox()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
308
 
309
- question_radios = [gr.Radio(visible=False), gr.Radio(visible=False), gr.Radio(
310
- visible=False), gr.Radio(visible=False), gr.Radio(visible=False), gr.Radio(visible=False), gr.Radio(visible=False), gr.Radio(
311
- visible=False), gr.Radio(visible=False), gr.Radio(visible=False)]
 
312
 
313
- print(question_radios)
314
 
315
- @spaces.GPU
316
- @generate_quiz_btn.click(inputs=[radio, topic], outputs=[quiz_msg]+question_radios, api_name="generate_quiz")
317
- def generate_quiz(question_difficulty, topic):
318
- top_k_rank=10
319
- RAG_db_=RAG_db.value
320
- documents_full=RAG_db_.search(topic,k=top_k_rank)
 
 
 
 
 
 
 
 
 
321
 
322
 
323
 
324
- generate_kwargs = dict(
325
- temperature=0.2,
326
- max_new_tokens=4000,
327
- top_p=0.95,
328
- repetition_penalty=1.0,
329
- do_sample=True,
330
- seed=42,
331
- )
332
- question_radio_list = []
333
- count=0
334
- while count<=3:
335
- try:
336
- documents=[item['content'] for item in documents_full]
337
- document_summaries = [f"[DOCUMENT {i+1}]: {summary}{count}" for i, summary in enumerate(documents)]
338
- documents_str='\n'.join(document_summaries)
339
- formatted_prompt = system_instructions(
340
- question_difficulty, topic,documents_str)
341
- print(formatted_prompt)
342
- pre_prompt = [
343
- {"role": "system", "content": formatted_prompt}
344
- ]
345
- response = client.text_generation(
346
- formatted_prompt, **generate_kwargs, stream=False, details=False, return_full_text=False,
347
- )
348
- output_json = json.loads(f"{response}")
349
 
350
 
351
- print(response)
352
- print('output json', output_json)
353
 
354
- global quiz_data
355
 
356
- quiz_data = output_json
357
 
358
 
359
 
360
- for question_num in range(1, 11):
361
- question_key = f"Q{question_num}"
362
- answer_key = f"A{question_num}"
363
 
364
- question = quiz_data.get(question_key)
365
- answer = quiz_data.get(quiz_data.get(answer_key))
366
 
367
- if not question or not answer:
368
- continue
369
 
370
- choice_keys = [f"{question_key}:C{i}" for i in range(1, 5)]
371
- choice_list = []
372
- for choice_key in choice_keys:
373
- choice = quiz_data.get(choice_key, "Choice not found")
374
- choice_list.append(f"{choice}")
375
 
376
- radio = gr.Radio(choices=choice_list, label=question,
377
- visible=True, interactive=True)
378
 
379
- question_radio_list.append(radio)
380
- if len(question_radio_list)==10:
381
- break
382
- else:
383
- print('10 questions not generated . So trying again!')
384
- count+=1
385
- continue
386
- except Exception as e:
387
- count+=1
388
- print(f"Exception occurred: {e}")
389
- if count==3:
390
- print('Retry exhausted')
391
- gr.Warning('Sorry. Pls try with another topic !')
392
- else:
393
- print(f"Trying again..{count} time...please wait")
394
- continue
395
 
396
- print('Question radio list ' , question_radio_list)
397
 
398
- return ['Quiz Generated!']+ question_radio_list
399
 
400
- check_button = gr.Button("Check Score")
401
 
402
- score_textbox = gr.Markdown()
403
 
404
- @check_button.click(inputs=question_radios, outputs=score_textbox)
405
- def compare_answers(*user_answers):
406
- user_anwser_list = []
407
- user_anwser_list = user_answers
408
 
409
- answers_list = []
410
 
411
- for question_num in range(1, 20):
412
- answer_key = f"A{question_num}"
413
- answer = quiz_data.get(quiz_data.get(answer_key))
414
- if not answer:
415
- break
416
- answers_list.append(answer)
417
 
418
- score = 0
419
 
420
- for item in user_anwser_list:
421
- if item in answers_list:
422
- score += 1
423
- if score>5:
424
- message = f"### Good ! You got {score} over 10!"
425
- elif score>7:
426
- message = f"### Excellent ! You got {score} over 10!"
427
- else:
428
- message = f"### You got {score} over 10! Dont worry . You can prepare well and try better next time !"
429
 
430
- return message
431
 
432
 
433
 
434
- demo = gr.TabbedInterface([CHATBOT,QUIZBOT], ["AI ChatBot", "AI Quizbot"])
435
 
436
- demo.queue()
437
- demo.launch(debug=True)
 
273
  gr.Examples(examples, txt)
274
 
275
 
276
+
277
+ RAG_db = gr.State()
278
+
279
+ def load_model():
280
+ RAG = RAGPretrainedModel.from_pretrained("colbert-ir/colbertv2.0")
281
+ RAG_db.value = RAG.from_index('.ragatouille/colbert/indexes/cbseclass10index')
282
+ return 'Ready to Go!!'
283
+
284
+ def generate_quiz(question_difficulty, topic):
285
+ top_k_rank = 10
286
+ RAG_db_ = RAG_db.value
287
+ documents_full = RAG_db_.search(topic, k=top_k_rank)
288
+
289
+ generate_kwargs = dict(
290
+ temperature=0.2,
291
+ max_new_tokens=4000,
292
+ top_p=0.95,
293
+ repetition_penalty=1.0,
294
+ do_sample=True,
295
+ seed=42,
296
+ )
297
+
298
+ question_radio_list = []
299
+ count = 0
300
+ while count <= 3:
301
+ try:
302
+ documents = [item['content'] for item in documents_full]
303
+ document_summaries = [f"[DOCUMENT {i+1}]: {summary}{count}" for i, summary in enumerate(documents)]
304
+ documents_str = '\n'.join(document_summaries)
305
+ formatted_prompt = system_instructions(question_difficulty, topic, documents_str)
306
+
307
+ pre_prompt = [
308
+ {"role": "system", "content": formatted_prompt}
309
+ ]
310
+ response = client.text_generation(
311
+ formatted_prompt, **generate_kwargs, stream=False, details=False, return_full_text=False,
312
+ )
313
+ output_json = json.loads(f"{response}")
314
+
315
+ global quiz_data
316
+ quiz_data = output_json
317
+
318
+ for question_num in range(1, 11):
319
+ question_key = f"Q{question_num}"
320
+ answer_key = f"A{question_num}"
321
+ question = quiz_data.get(question_key)
322
+ answer = quiz_data.get(quiz_data.get(answer_key))
323
+
324
+ if not question or not answer:
325
+ continue
326
+
327
+ choice_keys = [f"{question_key}:C{i}" for i in range(1, 5)]
328
+ choice_list = [quiz_data.get(choice_key, "Choice not found") for choice_key in choice_keys]
329
+
330
+ radio = gr.Radio(choices=choice_list, label=question, visible=True, interactive=True)
331
+ question_radio_list.append(radio)
332
+
333
+ if len(question_radio_list) == 10:
334
+ break
335
+ else:
336
+ count += 1
337
+ continue
338
+ except Exception as e:
339
+ count += 1
340
+ if count == 3:
341
+ return ['Sorry. Pls try with another topic!'] + [gr.Radio(visible=False) for _ in range(10)]
342
+ continue
343
+
344
+ return ['Quiz Generated!'] + question_radio_list
345
+
346
+ def compare_answers(*user_answers):
347
+ user_answer_list = user_answers
348
+ answers_list = [quiz_data.get(quiz_data.get(f"A{question_num}")) for question_num in range(1, 11)]
349
+
350
+ score = sum(1 for answer in user_answer_list if answer in answers_list)
351
+
352
+ if score > 7:
353
+ message = f"### Excellent! You got {score} out of 10!"
354
+ elif score > 5:
355
+ message = f"### Good! You got {score} out of 10!"
356
+ else:
357
+ message = f"### You got {score} out of 10! Don’t worry, you can prepare well and try better next time!"
358
+
359
+ return message
360
 
361
  with gr.Blocks(title="Quiz Maker", theme=gr.themes.Default(primary_hue="green", secondary_hue="green"), css="style.css") as QUIZBOT:
 
 
 
 
362
  with gr.Column(scale=4):
363
  gr.HTML("""
364
+ <center>
365
+ <h1><span style="color: purple;">ADWITIYA</span> Customs Manual Quizbot</h1>
366
+ <h2>Generative AI-powered Capacity building for Training Officers</h2>
367
+ <i>⚠️ NACIN Faculties create quiz from any topic dynamically for classroom evaluation after their sessions! ⚠️</i>
368
+ </center>
369
+ """)
370
+
371
  with gr.Column(scale=2):
372
  load_btn = gr.Button("Click to Load!🚀")
373
+ load_text = gr.Textbox()
374
+ load_btn.click(fn=load_model, inputs=[], outputs=load_text)
375
+
 
376
  topic = gr.Textbox(label="Enter the Topic for Quiz", placeholder="Write any topic/details from Customs Manual")
377
 
378
  with gr.Row():
379
+ radio = gr.Radio(["easy", "average", "hard"], label="How difficult should the quiz be?")
380
+
381
+ generate_quiz_btn = gr.Button("Generate Quiz!🚀")
382
+ quiz_msg = gr.Textbox()
383
+
384
+ question_radios = [gr.Radio(visible=False) for _ in range(10)]
385
+
386
+ generate_quiz_btn.click(
387
+ fn=generate_quiz,
388
+ inputs=[radio, topic],
389
+ outputs=[quiz_msg] + question_radios
390
+ )
391
+
392
+ check_button = gr.Button("Check Score")
393
+ score_textbox = gr.Markdown()
394
+
395
+ check_button.click(
396
+ fn=compare_answers,
397
+ inputs=question_radios,
398
+ outputs=score_textbox
399
+ )
400
 
401
+ demo = gr.TabbedInterface([CHATBOT, QUIZBOT], ["AI ChatBot", "AI Quizbot"])
402
+ demo.queue()
403
+ demo.launch(debug=True)
404
 
405
+ # RAG_db=gr.State()
406
+
407
+ # with gr.Blocks(title="Quiz Maker", theme=gr.themes.Default(primary_hue="green", secondary_hue="green"), css="style.css") as QUIZBOT:
408
+ # def load_model():
409
+ # RAG= RAGPretrainedModel.from_pretrained("colbert-ir/colbertv2.0")
410
+ # RAG_db.value=RAG.from_index('.ragatouille/colbert/indexes/cbseclass10index')
411
+ # return 'Ready to Go!!'
412
+ # with gr.Column(scale=4):
413
+ # gr.HTML("""
414
+ # <center>
415
+ # <h1><span style="color: purple;">ADWITIYA</span> Customs Manual Quizbot</h1>
416
+ # <h2>Generative AI-powered Capacity building for Training Officers</h2>
417
+ # <i>⚠️ NACIN Faculties create quiz from any topic dynamically for classroom evaluation after their sessions ! ⚠️</i>
418
+ # </center>
419
+ # """)
420
+ # #gr.Warning('Retrieving using ColBERT.. First time query will take a minute for model to load..pls wait')
421
+ # with gr.Column(scale=2):
422
+ # load_btn = gr.Button("Click to Load!🚀")
423
+ # load_text=gr.Textbox()
424
+ # load_btn.click(load_model,[],load_text)
425
+
426
+
427
+ # topic = gr.Textbox(label="Enter the Topic for Quiz", placeholder="Write any topic/details from Customs Manual")
428
 
429
+ # with gr.Row():
430
+ # radio = gr.Radio(
431
+ # ["easy", "average", "hard"], label="How difficult should the quiz be?"
432
+ # )
433
 
 
434
 
435
+ # generate_quiz_btn = gr.Button("Generate Quiz!🚀")
436
+ # quiz_msg=gr.Textbox()
437
+
438
+ # question_radios = [gr.Radio(visible=False), gr.Radio(visible=False), gr.Radio(
439
+ # visible=False), gr.Radio(visible=False), gr.Radio(visible=False), gr.Radio(visible=False), gr.Radio(visible=False), gr.Radio(
440
+ # visible=False), gr.Radio(visible=False), gr.Radio(visible=False)]
441
+
442
+ # print(question_radios)
443
+
444
+ # @spaces.GPU
445
+ # @generate_quiz_btn.click(inputs=[radio, topic], outputs=[quiz_msg]+question_radios, api_name="generate_quiz")
446
+ # def generate_quiz(question_difficulty, topic):
447
+ # top_k_rank=10
448
+ # RAG_db_=RAG_db.value
449
+ # documents_full=RAG_db_.search(topic,k=top_k_rank)
450
 
451
 
452
 
453
+ # generate_kwargs = dict(
454
+ # temperature=0.2,
455
+ # max_new_tokens=4000,
456
+ # top_p=0.95,
457
+ # repetition_penalty=1.0,
458
+ # do_sample=True,
459
+ # seed=42,
460
+ # )
461
+ # question_radio_list = []
462
+ # count=0
463
+ # while count<=3:
464
+ # try:
465
+ # documents=[item['content'] for item in documents_full]
466
+ # document_summaries = [f"[DOCUMENT {i+1}]: {summary}{count}" for i, summary in enumerate(documents)]
467
+ # documents_str='\n'.join(document_summaries)
468
+ # formatted_prompt = system_instructions(
469
+ # question_difficulty, topic,documents_str)
470
+ # print(formatted_prompt)
471
+ # pre_prompt = [
472
+ # {"role": "system", "content": formatted_prompt}
473
+ # ]
474
+ # response = client.text_generation(
475
+ # formatted_prompt, **generate_kwargs, stream=False, details=False, return_full_text=False,
476
+ # )
477
+ # output_json = json.loads(f"{response}")
478
 
479
 
480
+ # print(response)
481
+ # print('output json', output_json)
482
 
483
+ # global quiz_data
484
 
485
+ # quiz_data = output_json
486
 
487
 
488
 
489
+ # for question_num in range(1, 11):
490
+ # question_key = f"Q{question_num}"
491
+ # answer_key = f"A{question_num}"
492
 
493
+ # question = quiz_data.get(question_key)
494
+ # answer = quiz_data.get(quiz_data.get(answer_key))
495
 
496
+ # if not question or not answer:
497
+ # continue
498
 
499
+ # choice_keys = [f"{question_key}:C{i}" for i in range(1, 5)]
500
+ # choice_list = []
501
+ # for choice_key in choice_keys:
502
+ # choice = quiz_data.get(choice_key, "Choice not found")
503
+ # choice_list.append(f"{choice}")
504
 
505
+ # radio = gr.Radio(choices=choice_list, label=question,
506
+ # visible=True, interactive=True)
507
 
508
+ # question_radio_list.append(radio)
509
+ # if len(question_radio_list)==10:
510
+ # break
511
+ # else:
512
+ # print('10 questions not generated . So trying again!')
513
+ # count+=1
514
+ # continue
515
+ # except Exception as e:
516
+ # count+=1
517
+ # print(f"Exception occurred: {e}")
518
+ # if count==3:
519
+ # print('Retry exhausted')
520
+ # gr.Warning('Sorry. Pls try with another topic !')
521
+ # else:
522
+ # print(f"Trying again..{count} time...please wait")
523
+ # continue
524
 
525
+ # print('Question radio list ' , question_radio_list)
526
 
527
+ # return ['Quiz Generated!']+ question_radio_list
528
 
529
+ # check_button = gr.Button("Check Score")
530
 
531
+ # score_textbox = gr.Markdown()
532
 
533
+ # @check_button.click(inputs=question_radios, outputs=score_textbox)
534
+ # def compare_answers(*user_answers):
535
+ # user_anwser_list = []
536
+ # user_anwser_list = user_answers
537
 
538
+ # answers_list = []
539
 
540
+ # for question_num in range(1, 20):
541
+ # answer_key = f"A{question_num}"
542
+ # answer = quiz_data.get(quiz_data.get(answer_key))
543
+ # if not answer:
544
+ # break
545
+ # answers_list.append(answer)
546
 
547
+ # score = 0
548
 
549
+ # for item in user_anwser_list:
550
+ # if item in answers_list:
551
+ # score += 1
552
+ # if score>5:
553
+ # message = f"### Good ! You got {score} over 10!"
554
+ # elif score>7:
555
+ # message = f"### Excellent ! You got {score} over 10!"
556
+ # else:
557
+ # message = f"### You got {score} over 10! Dont worry . You can prepare well and try better next time !"
558
 
559
+ # return message
560
 
561
 
562
 
563
+ # demo = gr.TabbedInterface([CHATBOT,QUIZBOT], ["AI ChatBot", "AI Quizbot"])
564
 
565
+ # demo.queue()
566
+ # demo.launch(debug=True)