Muhammad Anas Akhtar
commited on
Update app.py
Browse files
app.py
CHANGED
@@ -7,19 +7,21 @@ question_answer = pipeline("question-answering", model="deepset/roberta-base-squ
|
|
7 |
|
8 |
def read_file_content(file_obj):
|
9 |
"""
|
10 |
-
Reads the content of a file object
|
11 |
"""
|
12 |
try:
|
13 |
-
with
|
14 |
-
|
|
|
15 |
return context
|
16 |
except Exception as e:
|
17 |
return f"An error occurred: {e}"
|
18 |
|
19 |
def get_answer(file, question):
|
20 |
context = read_file_content(file)
|
|
|
21 |
if isinstance(context, str) and context.startswith("An error occurred"):
|
22 |
-
return context # Return file reading
|
23 |
|
24 |
if not question.strip():
|
25 |
return "Please provide a valid question."
|
@@ -27,11 +29,14 @@ def get_answer(file, question):
|
|
27 |
try:
|
28 |
print(f"Context:\n{context}") # Debug
|
29 |
print(f"Question: {question}") # Debug
|
|
|
|
|
30 |
answer = question_answer(question=question, context=context)
|
31 |
return answer["answer"]
|
32 |
except Exception as e:
|
33 |
return f"An error occurred during question answering: {e}"
|
34 |
|
|
|
35 |
demo = gr.Interface(
|
36 |
fn=get_answer,
|
37 |
inputs=[gr.File(label="Upload your file"), gr.Textbox(label="Input your question", lines=1)],
|
|
|
7 |
|
8 |
def read_file_content(file_obj):
|
9 |
"""
|
10 |
+
Reads the content of a file object with error handling for encoding issues.
|
11 |
"""
|
12 |
try:
|
13 |
+
# Try reading with a lenient encoding (ISO-8859-1) and handle errors gracefully
|
14 |
+
with open(file_obj.name, 'r', encoding='utf-8', errors='ignore') as file:
|
15 |
+
context = file.read().strip() # Remove extra spaces or newlines
|
16 |
return context
|
17 |
except Exception as e:
|
18 |
return f"An error occurred: {e}"
|
19 |
|
20 |
def get_answer(file, question):
|
21 |
context = read_file_content(file)
|
22 |
+
|
23 |
if isinstance(context, str) and context.startswith("An error occurred"):
|
24 |
+
return context # Return the error message from file reading
|
25 |
|
26 |
if not question.strip():
|
27 |
return "Please provide a valid question."
|
|
|
29 |
try:
|
30 |
print(f"Context:\n{context}") # Debug
|
31 |
print(f"Question: {question}") # Debug
|
32 |
+
|
33 |
+
# Get the answer using the question-answering pipeline
|
34 |
answer = question_answer(question=question, context=context)
|
35 |
return answer["answer"]
|
36 |
except Exception as e:
|
37 |
return f"An error occurred during question answering: {e}"
|
38 |
|
39 |
+
# Define the Gradio interface
|
40 |
demo = gr.Interface(
|
41 |
fn=get_answer,
|
42 |
inputs=[gr.File(label="Upload your file"), gr.Textbox(label="Input your question", lines=1)],
|