File size: 6,719 Bytes
9a7ccba
 
9beb9e3
 
ba9ed60
 
 
35351fe
09e145b
e87b617
c747902
7315647
9a7ccba
55e40d9
 
 
 
 
 
 
 
9a7ccba
55e40d9
 
fbe81da
 
 
55e40d9
 
fbe81da
55e40d9
fbe81da
ba9ed60
 
 
 
 
 
 
 
 
 
 
 
 
09e145b
 
 
 
 
 
 
 
 
 
7315647
 
 
 
 
 
 
 
 
09e145b
 
 
 
c747902
7315647
c747902
7315647
e87b617
09e145b
 
 
7315647
09e145b
 
 
7315647
09e145b
 
 
7315647
09e145b
 
 
7315647
09e145b
 
7315647
09e145b
 
 
c747902
09e145b
c747902
 
 
 
 
09e145b
 
 
 
 
 
c747902
 
 
09e145b
ba9ed60
21adb3e
 
55e40d9
 
9beb9e3
0c0ed04
 
beeaade
9beb9e3
beeaade
 
0c0ed04
9beb9e3
 
 
 
 
 
 
55e40d9
9a7ccba
 
09e145b
 
 
 
 
55e40d9
ba9ed60
 
 
55e40d9
 
 
09e145b
 
ba9ed60
21adb3e
09e145b
9a7ccba
 
55e40d9
 
 
 
9beb9e3
 
 
55e40d9
 
 
 
 
 
 
 
 
 
9beb9e3
55e40d9
 
 
09e145b
55e40d9
 
ba9ed60
09e145b
55e40d9
 
 
 
21adb3e
dc15a5c
 
21adb3e
55e40d9
 
dc15a5c
55e40d9
09e145b
55e40d9
8fae716
 
beeaade
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
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
import gradio as gr
from transformers import pipeline
import PyPDF2
import markdown
import matplotlib.pyplot as plt
import io
import base64
import torch
from fpdf import FPDF
import os
import tempfile
import glob

# Preload models
models = {
    "distilbert-base-uncased-distilled-squad": "distilbert-base-uncased-distilled-squad",
    "roberta-base-squad2": "deepset/roberta-base-squad2",
    "bert-large-uncased-whole-word-masking-finetuned-squad": "bert-large-uncased-whole-word-masking-finetuned-squad",
    "albert-base-v2": "twmkn9/albert-base-v2-squad2",
    "xlm-roberta-large-squad2": "deepset/xlm-roberta-large-squad2"
}

loaded_models = {}

# Ensure we're using the CPU if GPU isn't available or necessary
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

def load_model(model_name):
    if model_name not in loaded_models:
        loaded_models[model_name] = pipeline("question-answering", model=models[model_name], device=0 if torch.cuda.is_available() else -1)
    return loaded_models[model_name]
    
def generate_score_chart(score):
    plt.figure(figsize=(6, 4))
    plt.bar(["Confidence Score"], [score], color='skyblue')
    plt.ylim(0, 1)
    plt.ylabel("Score")
    plt.title("Confidence Score")
    
    buf = io.BytesIO()
    plt.savefig(buf, format='png')
    plt.close()
    buf.seek(0)
    return base64.b64encode(buf.getvalue()).decode()

def highlight_relevant_text(context, start, end):
    highlighted_text = (
        context[:start] + 
        '<mark style="background-color: yellow;">' + 
        context[start:end] + 
        '</mark>' + 
        context[end:]
    )
    return highlighted_text

def find_system_font():
    # Search common directories for TrueType fonts
    font_dirs = ["/usr/share/fonts", "/usr/local/share/fonts"]
    for font_dir in font_dirs:
        ttf_files = glob.glob(os.path.join(font_dir, "**/*.ttf"), recursive=True)
        if ttf_files:
            return ttf_files[0]  # Return the first found font
    raise FileNotFoundError("No TTF font file found in system font directories.")

def generate_pdf_report(question, answer, score, score_explanation, score_chart, highlighted_context):
    pdf = FPDF()
    pdf.add_page()

    # Add the Unicode font (e.g., DejaVuSans)
    font_path = find_system_font()
    pdf.add_font("SystemFont", "", font_path)
    pdf.set_font("SystemFont", size=12)

    pdf.multi_cell(0, 10, f"Question: {question}")
    pdf.ln()

    pdf.set_font("SystemFont", size=12)
    pdf.multi_cell(0, 10, f"Answer: {answer}")
    pdf.ln()

    pdf.set_font("SystemFont", size=12)
    pdf.multi_cell(0, 10, f"Confidence Score: {score}")
    pdf.ln()

    pdf.set_font("SystemFont", size=12)
    pdf.multi_cell(0, 10, f"Score Explanation: {score_explanation}")
    pdf.ln()

    pdf.set_font("SystemFont", size=12)
    pdf.multi_cell(0, 10, "Highlighted Context:")
    pdf.ln()
    pdf.set_font("SystemFont", size=10)
    pdf.multi_cell(0, 10, highlighted_context)
    pdf.ln()

    # Decode and save the score chart image to a temporary file
    score_chart_image = io.BytesIO(base64.b64decode(score_chart))
    with tempfile.NamedTemporaryFile(delete=False, suffix='.png') as tmpfile:
        tmpfile.write(score_chart_image.read())
        tmpfile.flush()
        tmpfile.close()
        pdf.image(tmpfile.name, x=10, y=pdf.get_y(), w=100)

    # Save PDF to memory
    pdf_output = io.BytesIO()
    pdf.output(pdf_output)
    pdf_output.seek(0)

    # Clean up temporary file
    os.remove(tmpfile.name)

    return pdf_output

def answer_question(model_name, file, question, status):
    status = "Loading model..."
    model = load_model(model_name)
    
    if file is not None:
        file_name = file.name
        if file_name.endswith(".pdf"):
            pdf_reader = PyPDF2.PdfReader(file)
            context = ""
            for page_num in range(len(pdf_reader.pages)):
                context += pdf_reader.pages[page_num].extract_text()
        elif file_name.endswith(".md"):
            context = file.read().decode('utf-8')
            context = markdown.markdown(context)
        else:
            context = file.read().decode('utf-8')
    else:
        context = ""
    
    result = model(question=question, context=context)
    answer = result['answer']
    score = result['score']
    start = result['start']
    end = result['end']
    
    # Highlight relevant text
    highlighted_context = highlight_relevant_text(context, start, end)
    
    # Generate the score chart
    score_chart = generate_score_chart(score)
    
    # Explain score
    score_explanation = f"The confidence score ranges from 0 to 1, where a higher score indicates higher confidence in the answer's correctness. In this case, the score is {score:.2f}. A score closer to 1 implies the model is very confident about the answer."
    
    # Generate the PDF report
    pdf_report = generate_pdf_report(question, answer, f"{score:.2f}", score_explanation, score_chart, highlighted_context)
    
    status = "Model loaded"
    return highlighted_context, f"{score:.2f}", score_explanation, score_chart, pdf_report, status

# Define the Gradio interface
with gr.Blocks() as interface:
    gr.Markdown(
        """
        # Question Answering System
        Upload a document (text, PDF, or Markdown) and ask questions to get answers based on the context.
        
        **Supported File Types**: `.txt`, `.pdf`, `.md`
        """)
    
    with gr.Row():
        model_dropdown = gr.Dropdown(
            choices=list(models.keys()),
            label="Select Model",
            value="distilbert-base-uncased-distilled-squad"
        )
    
    with gr.Row():
        file_input = gr.File(label="Upload Document", file_types=["text", "pdf", "markdown"])
        question_input = gr.Textbox(lines=2, placeholder="Enter your question here...", label="Question")
    
    with gr.Row():
        answer_output = gr.HTML(label="Highlighted Answer")
        score_output = gr.Textbox(label="Confidence Score")
        explanation_output = gr.Textbox(label="Score Explanation")
        chart_output = gr.Image(label="Score Chart")
        pdf_output = gr.File(label="Download PDF Report")
    
    with gr.Row():
        submit_button = gr.Button("Submit")
    
    status_output = gr.Markdown(value="")

    def on_submit(model_name, file, question):
        return answer_question(model_name, file, question, status="Loading model...")

    submit_button.click(
        on_submit,
        inputs=[model_dropdown, file_input, question_input],
        outputs=[answer_output, score_output, explanation_output, chart_output, pdf_output, status_output]
    )

if __name__ == "__main__":
    interface.launch(share=True)