Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
import gradio as gr
|
| 3 |
+
import pdfplumber
|
| 4 |
+
from transformers import pipeline
|
| 5 |
+
from io import BytesIO
|
| 6 |
+
import re
|
| 7 |
+
|
| 8 |
+
# Initialize the question-answering pipeline with a specific pre-trained model
|
| 9 |
+
qa_pipeline = pipeline("question-answering", model="deepset/gelectra-large-germanquad")
|
| 10 |
+
|
| 11 |
+
def extract_text_from_pdf(file_obj):
|
| 12 |
+
"""Extracts text from a PDF file."""
|
| 13 |
+
text = []
|
| 14 |
+
with pdfplumber.open(file_obj) as pdf:
|
| 15 |
+
for page in pdf.pages:
|
| 16 |
+
page_text = page.extract_text()
|
| 17 |
+
if page_text: # Make sure there's text on the page
|
| 18 |
+
text.append(page_text)
|
| 19 |
+
return " ".join(text)
|
| 20 |
+
|
| 21 |
+
def answer_questions(context):
|
| 22 |
+
"""Generates answers to predefined questions based on the provided context."""
|
| 23 |
+
questions = [
|
| 24 |
+
"Welches ist das Titel des Moduls?",
|
| 25 |
+
"Welches ist das Sektor oder das Kernthema?",
|
| 26 |
+
"Welches ist das Land?",
|
| 27 |
+
"Zu welchem Program oder EZ-Programm gehört das Projekt?"
|
| 28 |
+
]
|
| 29 |
+
answers = {q: qa_pipeline(question=q, context=context)['answer'] for q in questions}
|
| 30 |
+
return answers
|
| 31 |
+
|
| 32 |
+
def process_pdf(file):
|
| 33 |
+
"""Process a PDF file to extract text and then use the text to answer questions."""
|
| 34 |
+
# Read the PDF file from Gradio's file input, which is a temporary file path
|
| 35 |
+
with file as file_path:
|
| 36 |
+
text = extract_text_from_pdf(BytesIO(file_path.read()))
|
| 37 |
+
results = answer_questions(text)
|
| 38 |
+
return "\n".join(f"{q}: {a}" for q, a in results.items())
|
| 39 |
+
|
| 40 |
+
# Define the Gradio interface
|
| 41 |
+
iface = gr.Interface(
|
| 42 |
+
fn=process_pdf,
|
| 43 |
+
inputs=gr.inputs.File(type="pdf", label="Upload your PDF file"),
|
| 44 |
+
outputs=gr.outputs.Textbox(label="Extracted Information and Answers"),
|
| 45 |
+
title="PDF Text Extractor and Question Answerer",
|
| 46 |
+
description="Upload a PDF file to extract text and answer predefined questions based on the content."
|
| 47 |
+
)
|
| 48 |
+
|
| 49 |
+
if __name__ == "__main__":
|
| 50 |
+
iface.launch()
|