andreeabodea commited on
Commit
a2f836f
·
verified ·
1 Parent(s): 163d63d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +90 -59
app.py CHANGED
@@ -1,14 +1,8 @@
1
- import gradio as gr
2
  import os
3
- import pandas as pd
4
  import pdfplumber
5
  import re
6
- import fitz # PyMuPDF
7
- import json
8
- import io
9
-
10
- # #files = [f for f in os.listdir("/Users/andreeabodea/") if f.endswith(".pdf")]
11
- # #print(files)
12
 
13
  """
14
  Extract the text from a section of a PDF file between 'wanted_section' and 'next_section'.
@@ -19,80 +13,117 @@ Parameters:
19
  Returns:
20
  - text (str): The extracted text from the specified section range.
21
  """
 
 
22
  def get_section(path, wanted_section, next_section):
23
  print(wanted_section)
24
 
25
  # Open the PDF file
26
- doc = pdfplumber.open(io.BytesIO(path))
27
  start_page = []
28
  end_page = []
29
 
30
  # Find the all the pages for the specified sections
31
  for page in range(len(doc.pages)):
32
- if len(doc.pages[page].search(wanted_section, return_chars = False, case = False)) > 0:
33
  start_page.append(page)
34
- if len(doc.pages[page].search(next_section, return_chars = False, case = False)) > 0:
35
  end_page.append(page)
36
- print(max(start_page))
37
- print(max(end_page))
38
 
39
  # Extract the text between the start and end page of the wanted section
40
  text = []
41
- for page_num in range(max(start_page), max(end_page)):
42
  page = doc.pages[page_num]
43
  text.append(page.extract_text())
44
  text = " ".join(text)
45
- new_text = text.replace("\n", " ")
46
- special_char_unicode_list = ["\u00e4", "\u00f6", "\u00fc", "\u00df"]
47
- special_char_replacement_list = ["ae", "oe", "ue", "ss"]
48
- for index, special_char in enumerate(special_char_unicode_list):
49
- final_text = new_text.replace(special_char, special_char_replacement_list[index])
50
  return final_text
51
 
52
 
53
- def process_pdf(path):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55
  results_dict = {}
56
- results_dict["2.1 Aktualisierte Einordnung des Moduls in das EZ-Programm"] = \
57
- get_section(path, "2.1 Aktualisierte Einordnung des Moduls in das EZ-Programm", "2.2 Andere Entwicklungsmaßnahmen im konkreten Interventionsbereich des Moduls")
58
- """
59
- results_dict["2.1 Aktualisierte Einordnung des Moduls in das EZ-Programm"] = \
60
- get_section(path,"2.1 Aktualisierte Einordnung des Moduls in das EZ-Programm", "2.2 Andere Entwicklungsmaßnahmen im konkreten Interventionsbereich des Moduls")
61
- results_dict["2.2 Andere Entwicklungsmaßnahmen im konkreten Interventionsbereich des Moduls"] = \
62
- get_section(path, "2.2 Andere Entwicklungsmaßnahmen im konkreten Interventionsbereich des Moduls", "3. Entwicklungen im Interventionsbereich")
63
- results_dict["3. Entwicklungen im Interventionsbereich"] = \
64
- get_section(path, "3. Entwicklungen im Interventionsbereich", "4.1 Bewertungen von Zielen, Zielgruppen, Wirkungshypothesen und Indikatoren")
65
- results_dict["4.1 Bewertungen von Zielen, Zielgruppen, Wirkungshypothesen und Indikatoren"] = \
66
- get_section(path, "4.1 Bewertungen von Zielen, Zielgruppen, Wirkungshypothesen und Indikatoren", "4.2 Umgesetzte Maßnahmen / Aktivitäten während des Berichtszeitraums")
67
- results_dict["4.2 Umgesetzte Maßnahmen / Aktivitäten während des Berichtszeitraums"] = \
68
- get_section(path, "4.2 Umgesetzte Maßnahmen / Aktivitäten während des Berichtszeitraums", "4.3 Umsetzung von Maßnahmen zur Sicherstellung der nachhaltigen Wirksamkeit")
69
- results_dict["4.3 Umsetzung von Maßnahmen zur Sicherstellung der nachhaltigen Wirksamkeit des Vorhabens"] = \
70
- get_section(path, "4.3 Umsetzung von Maßnahmen zur Sicherstellung der nachhaltigen Wirksamkeit", "4.4 Laufzeit und Zeitplan")
71
- results_dict["4.4 Laufzeit und Zeitplan"] = \
72
- get_section(path, "4.4 Laufzeit und Zeitplan", "4.5 Entstandene Kosten und Kostenverschiebungen")
73
- results_dict["4.5 Entstandene Kosten und Kostenverschiebungen"] = \
74
- get_section(path, "4.5 Entstandene Kosten und Kostenverschiebungen", "4.6 Bewertung der Wirkungen und Risiken")
75
- results_dict["4.6 Bewertung der Wirkungen und Risiken"] = \
76
- get_section(path, "4.6 Bewertung der Wirkungen und Risiken", "5. Übergeordnete Empfehlungen")
77
- results_dict["5.1 Empfehlungen und Merkposten für den Politik- und Schwerpunktdialog"] = \
78
- get_section(path, "5.1 Empfehlungen und Merkposten für den Politik- und Schwerpunktdialog", "5.2 Lernerfahrungen, die für die Länderstrategie und zukünftige EZ-Programme")
79
- results_dict["5.2 Lernerfahrungen, die für die Länderstrategie und zukünftige EZ-Programme interessant sein könnten"] = \
80
- get_section(path, "5.2 Lernerfahrungen", "6. Testat")
81
- results_dict["6. Testat (TZ)"] = \
82
- get_section(path, "6. Testat", "Anlage 1: Wirkungsmatrix des Moduls")
83
- """
84
- return results_dict
85
-
86
- #json_string = json.dumps(results_dict, indent=4)
87
- #print(json_string)
88
-
89
-
90
-
91
- # Define the Gradio interface
92
- iface = gr.Interface(fn=get_first_page_text,
93
  inputs=gr.File(type="binary", label="Upload PDF"),
94
  outputs=gr.Textbox(label="Extracted Text"),
95
  title="PDF Text Extractor",
96
- description="Upload a PDF file to extract all its text.")
 
 
 
 
 
97
 
98
- iface.launch()
 
 
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'.
 
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
+ if __name__ == "__main__":
116
+
117
+ # Define the Gradio interface
118
+ # iface = gr.Interface(fn=process_pdf,
119
+ demo = gr.Interface(fn=get_first_page_text,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
120
  inputs=gr.File(type="binary", label="Upload PDF"),
121
  outputs=gr.Textbox(label="Extracted Text"),
122
  title="PDF Text Extractor",
123
+ description="Upload a PDF file to extract.")
124
+ demo.launch()
125
+
126
+
127
+
128
+
129