andreeabodea commited on
Commit
651d696
1 Parent(s): e7359bf

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +123 -0
app.py ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import pdfplumber
3
+ import re
4
+ import gradio as gr
5
+ from transformers import pipeline, AutoModelForQuestionAnswering, AutoTokenizer
6
+
7
+ """
8
+ Extract the text from a section of a PDF file between 'wanted_section' and 'next_section'.
9
+ Parameters:
10
+ - path (str): The file path to the PDF file.
11
+ - wanted_section (str): The section to start extracting text from.
12
+ - next_section (str): The section to stop extracting text at.
13
+ Returns:
14
+ - text (str): The extracted text from the specified section range.
15
+ """
16
+
17
+
18
+ def get_section(path, wanted_section, next_section):
19
+ print(wanted_section)
20
+
21
+ # Open the PDF file
22
+ doc = pdfplumber.open(BytesIO(path))
23
+ start_page = []
24
+ end_page = []
25
+
26
+ # Find the all the pages for the specified sections
27
+ for page in range(len(doc.pages)):
28
+ if len(doc.pages[page].search(wanted_section, return_chars=False, case=False)) > 0:
29
+ start_page.append(page)
30
+ if len(doc.pages[page].search(next_section, return_chars=False, case=False)) > 0:
31
+ end_page.append(page)
32
+
33
+ # Extract the text between the start and end page of the wanted section
34
+ text = []
35
+ for page_num in range(max(start_page), max(end_page)+1):
36
+ page = doc.pages[page_num]
37
+ text.append(page.extract_text())
38
+ text = " ".join(text)
39
+ final_text = text.replace("\n", " ")
40
+ return final_text
41
+
42
+
43
+ def extract_between(big_string, start_string, end_string):
44
+ # Use a non-greedy match for content between start_string and end_string
45
+ pattern = re.escape(start_string) + '(.*?)' + re.escape(end_string)
46
+ match = re.search(pattern, big_string, re.DOTALL)
47
+
48
+ if match:
49
+ # Return the content without the start and end strings
50
+ return match.group(1)
51
+ else:
52
+ # Return None if the pattern is not found
53
+ return None
54
+
55
+ def format_section1(section1_text):
56
+ result_section1_dict = {}
57
+
58
+ result_section1_dict['TOPIC'] = extract_between(section1_text, "Sektor", "EZ-Programm")
59
+ result_section1_dict['PROGRAM'] = extract_between(section1_text, "Sektor", "EZ-Programm")
60
+ result_section1_dict['PROJECT DESCRIPTION'] = extract_between(section1_text, "EZ-Programmziel", "Datum der letzten BE")
61
+ result_section1_dict['PROJECT NAME'] = extract_between(section1_text, "Modul", "Modulziel")
62
+ result_section1_dict['OBJECTIVE'] = extract_between(section1_text, "Modulziel", "Berichtszeitraum")
63
+ result_section1_dict['PROGRESS'] = extract_between(section1_text, "Zielerreichung des Moduls", "Massnahme im Zeitplan")
64
+ result_section1_dict['STATUS'] = extract_between(section1_text, "Massnahme im Zeitplan", "Risikoeinschätzung")
65
+ result_section1_dict['RECOMMENDATIONS'] = extract_between(section1_text, "Vorschläge zur Modulanpas-", "Voraussichtliche")
66
+
67
+ return result_section1_dict
68
+
69
+ def answer_questions(text,language="de"):
70
+ # Initialize the zero-shot classification pipeline
71
+ model_name = "deepset/gelectra-large-germanquad"
72
+ model = AutoModelForQuestionAnswering.from_pretrained(model_name)
73
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
74
+
75
+ # Initialize the QA pipeline
76
+ qa_pipeline = pipeline("question-answering", model=model, tokenizer=tokenizer)
77
+ questions = [
78
+ "Welches ist das Titel des Moduls?",
79
+ "Welches ist das Sektor oder das Kernthema?",
80
+ "Welches ist das Land?",
81
+ "Zu welchem Program oder EZ-Programm gehort das Projekt?"
82
+ #"Welche Durchführungsorganisation aus den 4 Varianten 'giz', 'kfw', 'ptb' und 'bgr' implementiert das Projekt?"
83
+ # "In dem Dokument was steht bei Sektor?",
84
+ # "In dem Dokument was steht von 'EZ-Programm' bis 'EZ-Programmziel'?",
85
+ # "In dem Dokument was steht bei EZ-Programmziel?",
86
+ # "In dem Dokument in dem Abschnitt '1. Kurzbeschreibung' was steht bei Modul?",
87
+ # "In dem Dokument was steht bei Zielerreichung des Moduls?",
88
+ # "In dem Dokument in dem Abschnitt '1. Kurzbeschreibung' was steht bei Maßnahme im Zeitplan?",
89
+ # "In dem Dokument was steht bei Vorschläge zur Modulanpassung?",
90
+ # "In dem Dokument in dem Abschnitt 'Anlage 1: Wirkungsmatrix des Moduls' was steht unter Laufzeit als erstes Datum?",
91
+ # "In dem Dokument in dem Abschnitt 'Anlage 1: Wirkungsmatrix des Moduls' was steht unter Laufzeit als zweites Datum?"
92
+ ]
93
+
94
+ # Iterate over each question and get answers
95
+ for question in questions:
96
+ result = qa_pipeline(question=question, context=text)
97
+ # print(f"Question: {question}")
98
+ # print(f"Answer: {result['answer']}\n")
99
+ answers_dict[question] = result['answer']
100
+ return answers_dict
101
+
102
+
103
+ def process_pdf(path):
104
+ results_dict = {}
105
+ results_dict["1. Kurzbeschreibung"] = \
106
+ get_section(path, "1. Kurzbeschreibung", "2. Einordnung des Moduls")
107
+ answers = answer_questions(results_dict["1. Kurzbeschreibung"])
108
+ return result_section1_dict['TOPIC']
109
+
110
+ def get_first_page_text(file_data):
111
+ doc = pdfplumber.open(BytesIO(file_data))
112
+ if len(doc.pages):
113
+ return doc.pages[0].extract_text()
114
+
115
+ # Define the Gradio interface
116
+ # iface = gr.Interface(fn=process_pdf,
117
+ iface = gr.Interface(fn=get_first_page_text,
118
+ inputs=gr.File(type="binary", label="Upload PDF"),
119
+ outputs=gr.Textbox(label="Extracted Text"),
120
+ title="PDF Text Extractor",
121
+ description="Upload a PDF file to extract.")
122
+
123
+ iface.launch()