reyemhorts commited on
Commit
8701b59
·
1 Parent(s): 65ef71e

only read pdf

Browse files
__pycache__/load_db.cpython-311.pyc ADDED
Binary file (2.24 kB). View file
 
__pycache__/oai.cpython-311.pyc ADDED
Binary file (3.37 kB). View file
 
app.py CHANGED
@@ -6,7 +6,7 @@ import json
6
 
7
  from load_db import load_vectorestore_from_pdf
8
  from oai import chat_prompt, get_comparison
9
-
10
 
11
  TEMP_PDF_PATH = "temp.pdf"
12
  retriever = None
@@ -25,7 +25,7 @@ def get_course(code:str)->str|None:
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:str, page_num:Optional[int]=None):
29
  reader = PdfReader(file_path)
30
  if page_num:
31
  return reader.pages[page_num-1].extract_text()
@@ -42,110 +42,111 @@ def load_vectore_store():
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
- text = pdf_to_text(TEMP_PDF_PATH)
49
- load_vectore_store()
 
50
  #print(text)
51
  return text
52
 
53
- def compare_with_gpt(iu_code:str,text:str, model_name:Optional[str]=None)->str|None:
54
- iu_course = get_course(iu_code)
55
- if iu_course == None:
56
- print("IU Course not found")
57
- return None
58
- if model_name != None:
59
- return get_comparison(iu_course,text,model_name=model_name)
60
- return get_comparison(iu_course,text,model_name="gpt-4")
61
-
62
- def get_relevant_docs(search:str, iu_course:str):
63
- global db, retriever, documents
64
- documents = []
65
- final_res = ""
66
- documents = retriever.get_relevant_documents(f"Wo ist Modul/Kurs: {search.strip()}")
67
- for document_ in documents:
68
- print(f'\n>{document_.metadata["source"]} (Page {document_.metadata["page"]})')
69
- #print(">",document.page_content,"\n\n")
70
- final_res = f'{final_res}\n>{document_.metadata["source"]} (Page {document_.metadata["page"]}) :'
71
- get_relevant_docs_promt = f"""
72
-
73
- Du wirst 4 verschiedene Objecte in JSON erhalten und musst herausfinden welches ich suche.
74
- Es handelt sich dabei um Ausschnitte eines Modulhandbuches einer Hochschule.
75
- Ich suche die Modulbeschreibung von '{search}'. Suche danach in dem property 'page_content'
76
- Nenne die Page in den Metadaten des richtigen Objektes. Denk dir keinen Quatsch aus, wenn du die Modulbeschreibung nicht findest, sag es.
77
- Antworte in JSON format und fülle die werte page_found (bool) und page (int|None) aus.
78
- """.strip()
79
- messages = [
80
- {
81
- "role": "system", "content": f"{get_relevant_docs_promt}"
82
- },
83
- {
84
- "role": "system", "content": f"Das sind die 4 Dokumente:\n{documents}"
85
- }
86
- ]
87
- res = chat_prompt(messages=messages,model_name="gpt-4") #gpt-3.5-turbo-16k doesnt understand the task
88
-
89
- final_res = f'{final_res}\n\n{res}\n'
90
- res = json.loads(res)
91
- if res["page_found"] ==False:
92
- return final_res
93
- page_num = int(res["page"])
94
 
95
- final_res = f'{final_res}\n\nDocument auf Seite >{page_num} identifiziert.\nPrüfe auf Vollständigkeit...\n'
96
-
97
- for doc in documents:
98
- if page_num == doc.metadata["page"]:
99
- print(page_num,"==",doc.metadata["page"])
100
- document = doc
101
- break
102
- next_page = documents = db.get(where={"page":page_num+1}) #pdf_to_text("temp.pdf",page_num=page_num+1)
103
- if len(next_page["documents"]) > 0:
104
- next_page = next_page["documents"][0]
105
- words = next_page.split()
106
- first_40_words = words[:40]
107
- first_40_words_str = ' '.join(first_40_words)
108
-
109
- # get the 50 last words of the description
110
- words = document.page_content.split()
111
- last_50_words = words[-50:]
112
- # Join the words back into a string
113
- last_50_words_str = ' '.join(last_50_words)
114
-
115
- check_doc_complete_prompt= f"""
116
- 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
117
- 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.
118
- Wenn der Auszug mit den Literaturangaben endet, ist die Modulbeschreibung vollständig.
119
- Antworte nur mit 'vollständig' und 'unvollständig'.
120
- Das Modul heißt [{search}]. Ist die Beschreibung vollständig oder fehlt etwas? Hier ist der Text: \n[{last_50_words_str}].
121
- Das ist hier ist der Text der nächsten Seite:\n[{first_40_words_str}]
122
- """.strip()
123
-
124
- messages = [
125
- {
126
- "role": "system", "content": f"{check_doc_complete_prompt}"
127
- }
128
- ]
129
-
130
- res = chat_prompt(messages=messages,model_name="gpt-3.5-turbo-16k") #gpt-3.5-turbo-16k
131
- #print("\nDie Beschreibung ist: ",res,"\n")
132
- final_res = f'{final_res}\nDie Beschreibung ist: {res}\n'
133
-
134
- description = f"{document.page_content}"
135
-
136
- if res == "unvollständig":
137
- description = f"{description}\n{next_page}"
138
- else:
139
 
140
- description = f"{document.page_content}"
141
- final_res = f'{final_res}\nDie Beschreibung ist: {description}\n'
142
 
143
- final_res = f'{final_res}\nSuche nach: {search}\nBeschreibung: {description}\n\n'
144
- res = compare_with_gpt(iu_course,description,model_name="gpt-3.5-turbo-16k")
145
 
146
- final_res = f'{final_res}\nIU-Kurs:{iu_course}\nErgebnis: {res}\n'
147
 
148
- return final_res
149
 
150
  with gr.Blocks() as app:
151
  file = gr.File(type="binary")
@@ -156,14 +157,14 @@ with gr.Blocks() as app:
156
  load_file_button.click(load_pdf,inputs=file,outputs=handbook)
157
 
158
 
159
- with gr.Accordion("Kurse finden",open=False):
160
- with gr.Row():
161
- course_query = gr.Textbox(label="Kursnamen der zu prüfenden Kurse")
162
- iu_ccode = gr.Textbox(label="IU Kurscode")
163
- course_description = gr.TextArea(label="Ergebnis der Prüfung")
164
 
165
 
166
- course_query.submit(get_relevant_docs,inputs=[course_query,iu_ccode],outputs=course_description)
167
 
168
 
169
 
 
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
 
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()
 
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")
 
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
 
temp.pdf ADDED
Binary file (736 kB). View file