File size: 5,256 Bytes
8e55c5a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 25 18:18:27 2023

@author: alish
"""

import gradio as gr
import fitz  # PyMuPDF
import questiongenerator as qs
import random

from questiongenerator import QuestionGenerator
qg = QuestionGenerator()



def Extract_QA(qlist):
        Q_All=''
        A_All=''
        
        for i in range(len(qlist)):
            question_i= qlist[i]['question']
            Choices_ans= []
            Choice_is_correct=[]
            for j in range(4):
               Choices_ans= Choices_ans+ [qlist[i]['answer'][j]['answer']]
               Choice_is_correct= Choice_is_correct+ [qlist[i]['answer'][j]['correct']]
               
            Q=f"""
                 Q_{i+1}: {question_i}
                 A. {Choices_ans[0]}
                 B. {Choices_ans[1]}
                 C. {Choices_ans[2]}
                 D. {Choices_ans[3]} 
                                  
                """
            xs=['A','B','C','D']
            result = [x for x, y in zip(xs, Choice_is_correct) if y ]
            A= f"""
                Answer_{i+1}: {result[0]}
                
                
                """
            Q_All= Q_All+Q
            A_All=A_All+ A
            
            
        return (Q_All,A_All)






def extract_text_from_pdf(pdf_file_path):
    # Read the PDF file
    global extracted_text
    text = []
    with fitz.open(pdf_file_path) as doc:
        for page in doc:
            text.append(page.get_text())
    extracted_text= '\n'.join(text)
    extracted_text= get_sub_text(extracted_text)
    
    return ("The pdf is uploaded Successfully from:"+ str(pdf_file_path))

qg = qs.QuestionGenerator()

def get_sub_text(TXT):
   sub_texts= qg._split_into_segments(TXT)
   if isinstance(sub_texts, list):
       return sub_texts
   else:
       return [sub_texts]

def pick_One_txt(sub_texts):
    global selected_extracted_text
    N= len(sub_texts)
    if N==1:
       selected_extracted_text= sub_texts[0] 
       return(selected_extracted_text)
    # Generate a random number between low and high
    random_number = random.uniform(0, N)    
    # Pick the integer part of the random number
    random_number = int(random_number)
    selected_extracted_text= sub_texts[random_number]
        
    return(selected_extracted_text)
 

def pipeline(NoQs):
    global Q,A
    text= selected_extracted_text
    qlist= qg.generate(text, num_questions=NoQs, answer_style="multiple_choice")
    Q,A= Extract_QA(qlist)
    A= A + '\n'+text
    return (Q,A)

def ReurnAnswer():
    return A

def GetQuestion(NoQs):
    NoQs=int(NoQs)
    pick_One_txt(extracted_text)
    Q,A=pipeline(NoQs)
    return Q

with gr.Blocks() as demo:
    
    with gr.Row():
        #input_file=gr.File(type="filepath", label="Upload PDF Document")
        input_file=gr.UploadButton(label='Select a file!', file_types=[".pdf"])
        #upload_btn = gr.Button(value="Upload File")
        #txt= extract_text_from_pdf(input_file)
    with gr.Row():
        with gr.Column():
            upload_btn = gr.Button(value="Upload the pdf File.")
            Gen_Question = gr.Button(value="Show the Question(s)")
            Gen_Answer = gr.Button(value="Show the Answer(s)")
            No_Qs= gr.Slider(minimum=1, maximum=5,step=1, label='No Questions')
            '''
            with gr.Accordion("Instruction"):
                gr.Markdown("Start by selecting a 'pdf' file using 'Select file' tab." )
                gr.Markdown("Upload the selceted 'pdf' file using 'Upload the pdf file' tab." )
                gr.Markdown("The code will randomly select a block of the text and generate N questions form it each time you push 'Show Question(s)" )
            '''
            gr.Markdown(""" **Instruction**                        
                        * Start by selecting a 'pdf' file using 'Select file' tab.                       
                        * Upload the selceted 'pdf' file using 'Upload the pdf file' tab.                       
                        * The code will randomly select a block of the text and generate N questions form it each time you push 'Show Question(s)'. """  )
         
            gr.Image("PupQuizAI.png")
            
            
            
        with gr.Column():
            file_stat= gr.Textbox(label="File Status")
            question = gr.Textbox(label="Question(s)")
            Answer = gr.Textbox(label="Answer(s)")
    '''
    with gr.Accordion("Instruction"):
        gr.Markdown("Start by selecting a 'pdf' file using 'Select file' tab." )
        gr.Markdown("Upload the selceted 'pdf' file using 'Upload the pdf file' tab." )
        gr.Markdown("The code will randomly select a block of the text and generate N questions form it each time you push 'Show Question(s)" )
    '''

    upload_btn.click(extract_text_from_pdf, inputs=input_file, outputs=file_stat, api_name="QuestioGenerator")
    Gen_Question.click(GetQuestion, inputs=No_Qs, outputs=question, api_name="QuestioGenerator")
    Gen_Answer.click(ReurnAnswer, inputs=None, outputs=Answer, api_name="QuestioGenerator")
    #examples = gr.Examples(examples=["I went to the supermarket yesterday.", "Helen is a good swimmer."],
    #                       inputs=[english])

demo.launch()