reyemhorts commited on
Commit
74571d9
·
1 Parent(s): b41f71a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +202 -172
app.py CHANGED
@@ -1,172 +1,202 @@
1
- import gradio as gr
2
- import os
3
- from pypdf import PdfReader
4
- from typing import Optional
5
- import json
6
-
7
- #from load_db import load_vectorestore_from_pdf
8
- #from oai import chat_prompt, get_comparison
9
- from io import BytesIO
10
-
11
- TEMP_PDF_PATH = "temp.pdf"
12
- retriever = None
13
- db = None
14
- documents = None
15
-
16
- # with open("all_unique_modules.json","r",encoding="UTF-8") as f:
17
- # courses = json.load(f)
18
-
19
- # def get_course(code:str)->str|None:
20
- # #print(len(courses))
21
- # for c in courses:
22
- # if not "Kurscode" in c:
23
- # continue
24
- # if c["Kurscode"].strip()==code.strip():
25
- # return f"Kursbeschreibung:\n{c['Description']}\nKursziele:\n{c['Kursziele']}\nKursinhalte:\n{c['Kursinhalt']}"
26
- # return None
27
-
28
- def pdf_to_text(file_path, page_num:Optional[int]=None):
29
- reader = PdfReader(file_path)
30
- if page_num:
31
- return reader.pages[page_num-1].extract_text()
32
- text = ""
33
- for page in reader.pages:
34
- page_text = page.extract_text()
35
- text += page_text
36
- return text
37
-
38
- # def load_vectore_store():
39
- # global retriever, db
40
- # db = load_vectorestore_from_pdf(TEMP_PDF_PATH,persist=False)
41
- # retriever = db.as_retriever(search_kwargs={"k": 4})
42
-
43
- def load_pdf(inp):
44
- # Convert bytes back to a PDF file
45
- # with open(TEMP_PDF_PATH, "wb") as f:
46
- # f.write(inp)
47
- # Extract text from the PDF file
48
- s = BytesIO(inp)
49
- text = pdf_to_text(s)
50
- #load_vectore_store()
51
- #print(text)
52
- return text
53
-
54
- # def compare_with_gpt(iu_code:str,text:str, model_name:Optional[str]=None)->str|None:
55
- # iu_course = get_course(iu_code)
56
- # if iu_course == None:
57
- # print("IU Course not found")
58
- # return None
59
- # if model_name != None:
60
- # return get_comparison(iu_course,text,model_name=model_name)
61
- # return get_comparison(iu_course,text,model_name="gpt-4")
62
-
63
- # def get_relevant_docs(search:str, iu_course:str):
64
- # global db, retriever, documents
65
- # documents = []
66
- # final_res = ""
67
- # documents = retriever.get_relevant_documents(f"Wo ist Modul/Kurs: {search.strip()}")
68
- # for document_ in documents:
69
- # print(f'\n>{document_.metadata["source"]} (Page {document_.metadata["page"]})')
70
- # #print(">",document.page_content,"\n\n")
71
- # final_res = f'{final_res}\n>{document_.metadata["source"]} (Page {document_.metadata["page"]}) :'
72
- # get_relevant_docs_promt = f"""
73
-
74
- # Du wirst 4 verschiedene Objecte in JSON erhalten und musst herausfinden welches ich suche.
75
- # Es handelt sich dabei um Ausschnitte eines Modulhandbuches einer Hochschule.
76
- # Ich suche die Modulbeschreibung von '{search}'. Suche danach in dem property 'page_content'
77
- # Nenne die Page in den Metadaten des richtigen Objektes. Denk dir keinen Quatsch aus, wenn du die Modulbeschreibung nicht findest, sag es.
78
- # Antworte in JSON format und fülle die werte page_found (bool) und page (int|None) aus.
79
- # """.strip()
80
- # messages = [
81
- # {
82
- # "role": "system", "content": f"{get_relevant_docs_promt}"
83
- # },
84
- # {
85
- # "role": "system", "content": f"Das sind die 4 Dokumente:\n{documents}"
86
- # }
87
- # ]
88
- # res = chat_prompt(messages=messages,model_name="gpt-4") #gpt-3.5-turbo-16k doesnt understand the task
89
-
90
- # final_res = f'{final_res}\n\n{res}\n'
91
- # res = json.loads(res)
92
- # if res["page_found"] ==False:
93
- # return final_res
94
- # page_num = int(res["page"])
95
-
96
- # final_res = f'{final_res}\n\nDocument auf Seite >{page_num} identifiziert.\nPrüfe auf Vollständigkeit...\n'
97
-
98
- # for doc in documents:
99
- # if page_num == doc.metadata["page"]:
100
- # print(page_num,"==",doc.metadata["page"])
101
- # document = doc
102
- # break
103
- # next_page = documents = db.get(where={"page":page_num+1}) #pdf_to_text("temp.pdf",page_num=page_num+1)
104
- # if len(next_page["documents"]) > 0:
105
- # next_page = next_page["documents"][0]
106
- # words = next_page.split()
107
- # first_40_words = words[:40]
108
- # first_40_words_str = ' '.join(first_40_words)
109
-
110
- # # get the 50 last words of the description
111
- # words = document.page_content.split()
112
- # last_50_words = words[-50:]
113
- # # Join the words back into a string
114
- # last_50_words_str = ' '.join(last_50_words)
115
-
116
- # check_doc_complete_prompt= f"""
117
- # Du wirst einen Auszug einer Modulbeschreibung eines Modules von einer Hochschule erhalten und sollst herausfinden, ob diese vollständig ist oder ob eventuell die nächste
118
- # Seite auch noch Inhalte zum Modul hat. Solltest du eine Auflistung der Kompetenzen und Inhalte finden, ist die Modulbeschreibung vollständig. Wenn auf der Folgeseite nur noch Literaturangaben sind, ist die Modulbeschreibung bereits vollständig.
119
- # Wenn der Auszug mit den Literaturangaben endet, ist die Modulbeschreibung vollständig.
120
- # Antworte nur mit 'vollständig' und 'unvollständig'.
121
- # Das Modul heißt [{search}]. Ist die Beschreibung vollständig oder fehlt etwas? Hier ist der Text: \n[{last_50_words_str}].
122
- # Das ist hier ist der Text der nächsten Seite:\n[{first_40_words_str}]
123
- # """.strip()
124
-
125
- # messages = [
126
- # {
127
- # "role": "system", "content": f"{check_doc_complete_prompt}"
128
- # }
129
- # ]
130
-
131
- # res = chat_prompt(messages=messages,model_name="gpt-3.5-turbo-16k") #gpt-3.5-turbo-16k
132
- # #print("\nDie Beschreibung ist: ",res,"\n")
133
- # final_res = f'{final_res}\nDie Beschreibung ist: {res}\n'
134
-
135
- # description = f"{document.page_content}"
136
-
137
- # if res == "unvollständig":
138
- # description = f"{description}\n{next_page}"
139
- # else:
140
-
141
- # description = f"{document.page_content}"
142
- # final_res = f'{final_res}\nDie Beschreibung ist: {description}\n'
143
-
144
- # final_res = f'{final_res}\nSuche nach: {search}\nBeschreibung: {description}\n\n'
145
- # res = compare_with_gpt(iu_course,description,model_name="gpt-3.5-turbo-16k")
146
-
147
- # final_res = f'{final_res}\nIU-Kurs:{iu_course}\nErgebnis: {res}\n'
148
-
149
- # return final_res
150
-
151
- with gr.Blocks() as app:
152
- file = gr.File(type="binary")
153
- load_file_button = gr.Button("Load")
154
- with gr.Accordion("Text anzeigen",open=False):
155
- handbook = gr.TextArea(label="Modulhandbuch")
156
-
157
- load_file_button.click(load_pdf,inputs=file,outputs=handbook)
158
-
159
-
160
- # with gr.Accordion("Kurse finden",open=False):
161
- # with gr.Row():
162
- # course_query = gr.Textbox(label="Kursnamen der zu prüfenden Kurse")
163
- # iu_ccode = gr.Textbox(label="IU Kurscode")
164
- # course_description = gr.TextArea(label="Ergebnis der Prüfung")
165
-
166
-
167
- # course_query.submit(get_relevant_docs,inputs=[course_query,iu_ccode],outputs=course_description)
168
-
169
-
170
-
171
- if __name__ == "__main__":
172
- app.launch(debug=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import os
3
+ from pypdf import PdfReader
4
+ from typing import Optional
5
+ import json
6
+
7
+ #from load_db import load_vectorestore_from_pdf
8
+ #from oai import chat_prompt, get_comparison
9
+ from io import BytesIO
10
+
11
+ TEMP_PDF_PATH = "temp.pdf"
12
+ retriever = None
13
+ db = None
14
+ documents = None
15
+
16
+ # with open("all_unique_modules.json","r",encoding="UTF-8") as f:
17
+ # courses = json.load(f)
18
+
19
+ # def get_course(code:str)->str|None:
20
+ # #print(len(courses))
21
+ # for c in courses:
22
+ # if not "Kurscode" in c:
23
+ # continue
24
+ # if c["Kurscode"].strip()==code.strip():
25
+ # return f"Kursbeschreibung:\n{c['Description']}\nKursziele:\n{c['Kursziele']}\nKursinhalte:\n{c['Kursinhalt']}"
26
+ # return None
27
+
28
+ def pdf_to_text(file_path, page_num:Optional[int]=None):
29
+ reader = PdfReader(file_path)
30
+ if page_num:
31
+ return reader.pages[page_num-1].extract_text()
32
+ text = ""
33
+ for page in reader.pages:
34
+ page_text = page.extract_text()
35
+ text += page_text
36
+ return text
37
+
38
+ def api_pdf_to_text(file_path, page_num:Optional[int]=None):
39
+ reader = PdfReader(file_path)
40
+ pages = []
41
+ if page_num:
42
+ return reader.pages[page_num-1].extract_text()
43
+
44
+ for i, page in enumerate(reader.pages):
45
+ page_text = page.extract_text()
46
+ pages.append({
47
+ "page":i,
48
+ "text":page_text
49
+ })
50
+ return pages
51
+
52
+ # def load_vectore_store():
53
+ # global retriever, db
54
+ # db = load_vectorestore_from_pdf(TEMP_PDF_PATH,persist=False)
55
+ # retriever = db.as_retriever(search_kwargs={"k": 4})
56
+
57
+ def load_pdf(inp):
58
+ # Convert bytes back to a PDF file
59
+ # with open(TEMP_PDF_PATH, "wb") as f:
60
+ # f.write(inp)
61
+ # Extract text from the PDF file
62
+ s = BytesIO(inp)
63
+ text = pdf_to_text(s)
64
+ #load_vectore_store()
65
+ #print(text)
66
+ return text
67
+
68
+ def api_load_pdf(inp):
69
+ # Extract text from the PDF file
70
+ s = BytesIO(inp)
71
+ text = api_pdf_to_text(s)
72
+
73
+ return text
74
+
75
+ # def compare_with_gpt(iu_code:str,text:str, model_name:Optional[str]=None)->str|None:
76
+ # iu_course = get_course(iu_code)
77
+ # if iu_course == None:
78
+ # print("IU Course not found")
79
+ # return None
80
+ # if model_name != None:
81
+ # return get_comparison(iu_course,text,model_name=model_name)
82
+ # return get_comparison(iu_course,text,model_name="gpt-4")
83
+
84
+ # def get_relevant_docs(search:str, iu_course:str):
85
+ # global db, retriever, documents
86
+ # documents = []
87
+ # final_res = ""
88
+ # documents = retriever.get_relevant_documents(f"Wo ist Modul/Kurs: {search.strip()}")
89
+ # for document_ in documents:
90
+ # print(f'\n>{document_.metadata["source"]} (Page {document_.metadata["page"]})')
91
+ # #print(">",document.page_content,"\n\n")
92
+ # final_res = f'{final_res}\n>{document_.metadata["source"]} (Page {document_.metadata["page"]}) :'
93
+ # get_relevant_docs_promt = f"""
94
+
95
+ # Du wirst 4 verschiedene Objecte in JSON erhalten und musst herausfinden welches ich suche.
96
+ # Es handelt sich dabei um Ausschnitte eines Modulhandbuches einer Hochschule.
97
+ # Ich suche die Modulbeschreibung von '{search}'. Suche danach in dem property 'page_content'
98
+ # Nenne die Page in den Metadaten des richtigen Objektes. Denk dir keinen Quatsch aus, wenn du die Modulbeschreibung nicht findest, sag es.
99
+ # Antworte in JSON format und fülle die werte page_found (bool) und page (int|None) aus.
100
+ # """.strip()
101
+ # messages = [
102
+ # {
103
+ # "role": "system", "content": f"{get_relevant_docs_promt}"
104
+ # },
105
+ # {
106
+ # "role": "system", "content": f"Das sind die 4 Dokumente:\n{documents}"
107
+ # }
108
+ # ]
109
+ # res = chat_prompt(messages=messages,model_name="gpt-4") #gpt-3.5-turbo-16k doesnt understand the task
110
+
111
+ # final_res = f'{final_res}\n\n{res}\n'
112
+ # res = json.loads(res)
113
+ # if res["page_found"] ==False:
114
+ # return final_res
115
+ # page_num = int(res["page"])
116
+
117
+ # final_res = f'{final_res}\n\nDocument auf Seite >{page_num} identifiziert.\nPrüfe auf Vollständigkeit...\n'
118
+
119
+ # for doc in documents:
120
+ # if page_num == doc.metadata["page"]:
121
+ # print(page_num,"==",doc.metadata["page"])
122
+ # document = doc
123
+ # break
124
+ # next_page = documents = db.get(where={"page":page_num+1}) #pdf_to_text("temp.pdf",page_num=page_num+1)
125
+ # if len(next_page["documents"]) > 0:
126
+ # next_page = next_page["documents"][0]
127
+ # words = next_page.split()
128
+ # first_40_words = words[:40]
129
+ # first_40_words_str = ' '.join(first_40_words)
130
+
131
+ # # get the 50 last words of the description
132
+ # words = document.page_content.split()
133
+ # last_50_words = words[-50:]
134
+ # # Join the words back into a string
135
+ # last_50_words_str = ' '.join(last_50_words)
136
+
137
+ # check_doc_complete_prompt= f"""
138
+ # Du wirst einen Auszug einer Modulbeschreibung eines Modules von einer Hochschule erhalten und sollst herausfinden, ob diese vollständig ist oder ob eventuell die nächste
139
+ # Seite auch noch Inhalte zum Modul hat. Solltest du eine Auflistung der Kompetenzen und Inhalte finden, ist die Modulbeschreibung vollständig. Wenn auf der Folgeseite nur noch Literaturangaben sind, ist die Modulbeschreibung bereits vollständig.
140
+ # Wenn der Auszug mit den Literaturangaben endet, ist die Modulbeschreibung vollständig.
141
+ # Antworte nur mit 'vollständig' und 'unvollständig'.
142
+ # Das Modul heißt [{search}]. Ist die Beschreibung vollständig oder fehlt etwas? Hier ist der Text: \n[{last_50_words_str}].
143
+ # Das ist hier ist der Text der nächsten Seite:\n[{first_40_words_str}]
144
+ # """.strip()
145
+
146
+ # messages = [
147
+ # {
148
+ # "role": "system", "content": f"{check_doc_complete_prompt}"
149
+ # }
150
+ # ]
151
+
152
+ # res = chat_prompt(messages=messages,model_name="gpt-3.5-turbo-16k") #gpt-3.5-turbo-16k
153
+ # #print("\nDie Beschreibung ist: ",res,"\n")
154
+ # final_res = f'{final_res}\nDie Beschreibung ist: {res}\n'
155
+
156
+ # description = f"{document.page_content}"
157
+
158
+ # if res == "unvollständig":
159
+ # description = f"{description}\n{next_page}"
160
+ # else:
161
+
162
+ # description = f"{document.page_content}"
163
+ # final_res = f'{final_res}\nDie Beschreibung ist: {description}\n'
164
+
165
+ # final_res = f'{final_res}\nSuche nach: {search}\nBeschreibung: {description}\n\n'
166
+ # res = compare_with_gpt(iu_course,description,model_name="gpt-3.5-turbo-16k")
167
+
168
+ # final_res = f'{final_res}\nIU-Kurs:{iu_course}\nErgebnis: {res}\n'
169
+
170
+ # return final_res
171
+
172
+ with gr.Blocks() as app:
173
+ file = gr.File(type="binary")
174
+ load_file_button = gr.Button("Load")
175
+ with gr.Accordion("Text anzeigen",open=False):
176
+ handbook = gr.TextArea(label="Modulhandbuch")
177
+
178
+ load_file_button.click(load_pdf,inputs=file,outputs=handbook)
179
+
180
+ with gr.Accordion(visible=False):
181
+ api_file = gr.File(type="binary")
182
+ api_load_file_button = gr.Button("Load")
183
+ api_handbook = gr.TextArea(label="Modulhandbuch")
184
+ api_load_file_button.click(
185
+ api_load_pdf,
186
+ inputs=api_file,
187
+ outputs=api_handbook,
188
+ api_name="file-to-text")
189
+
190
+ # with gr.Accordion("Kurse finden",open=False):
191
+ # with gr.Row():
192
+ # course_query = gr.Textbox(label="Kursnamen der zu prüfenden Kurse")
193
+ # iu_ccode = gr.Textbox(label="IU Kurscode")
194
+ # course_description = gr.TextArea(label="Ergebnis der Prüfung")
195
+
196
+
197
+ # course_query.submit(get_relevant_docs,inputs=[course_query,iu_ccode],outputs=course_description)
198
+
199
+
200
+
201
+ if __name__ == "__main__":
202
+ app.launch(debug=True)