File size: 1,896 Bytes
adf29ba
 
4d2c093
adf29ba
 
d399ffa
0321323
 
adf29ba
 
 
 
 
 
4d2c093
 
 
 
0321323
2f7310c
 
0321323
 
2f7310c
adf29ba
 
 
 
0321323
 
 
 
 
 
adf29ba
 
 
 
0321323
31d7389
0321323
 
adf29ba
 
0321323
 
adf29ba
 
 
 
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
import gradio as gr
from transformers import pipeline
import chardet

# Initialize the question-answering pipeline
#qa_pipeline = pipeline("question-answering",model="deepset/roberta-base-squad2")
qa_pipeline = pipeline("question-answering", model="distilbert-base-cased-distilled-squad")

def answer_question(context, question):
    result = qa_pipeline(question=question, context=context)
    return result['answer']

def process(context_file, question):
    # Read the context from the uploaded file
    with open(context_file.name, 'rb') as file:
        raw_data = file.read()
        result = chardet.detect(raw_data)
        encoding = result['encoding']

        # Fallback to a default encoding if detection fails
        if encoding is None:
            encoding = 'utf-8'  # Default encoding

        context = raw_data.decode(encoding, errors='replace')  # Replace errors with a placeholder

    answer = answer_question(context, question)
    return answer

# Example context file content
example_context = """Saudi Arabia, officially known as the Kingdom of Saudi Arabia (KSA), is a country in Western Asia. Riyadh is its capital and largest city. The country is known for its vast deserts and rich cultural heritage."""

# Save example context to a file
with open("example_context.txt", "w", encoding="utf-8") as f:
    f.write(example_context)

# Gradio interface
demo = gr.Interface(
    fn=process,
    inputs=[
        gr.File(label="Upload Context File", file_types=[".txt"]),
        gr.Textbox(label="Question", value="What is the capital city of Saudia Arabia?")
    ],
    outputs=[gr.Textbox(label="Answer")],
    title="Question Answering",
    description="Upload a file with context and ask a question. The answer will be displayed.",
    examples=[["example_context.txt", "What is the capital city of Saudia Arabia?"]]
)

if __name__ == "__main__":
    demo.launch()