File size: 7,758 Bytes
74571d9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2b4654b
74571d9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53bcaf4
74571d9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
import gradio as gr 
import os
from pypdf import PdfReader
from typing import Optional
import json

#from load_db import load_vectorestore_from_pdf
#from oai import chat_prompt, get_comparison
from io import BytesIO

TEMP_PDF_PATH = "temp.pdf"
retriever = None
db = None
documents = None

# with open("all_unique_modules.json","r",encoding="UTF-8") as f:
#     courses = json.load(f)

# def get_course(code:str)->str|None:
#     #print(len(courses))
#     for c in courses:
#         if not "Kurscode" in c:
#             continue
#         if c["Kurscode"].strip()==code.strip():
#             return f"Kursbeschreibung:\n{c['Description']}\nKursziele:\n{c['Kursziele']}\nKursinhalte:\n{c['Kursinhalt']}"
#     return None

def pdf_to_text(file_path, page_num:Optional[int]=None):
    reader = PdfReader(file_path)
    if page_num:
        return reader.pages[page_num-1].extract_text()
    text = ""
    for page in reader.pages:
        page_text = page.extract_text()
        text += page_text
    return text

def api_pdf_to_text(file_path, page_num:Optional[int]=None):
    reader = PdfReader(file_path)
    pages = []
    if page_num:
        return reader.pages[page_num-1].extract_text()
    
    for i, page in enumerate(reader.pages):
        page_text = page.extract_text()
        pages.append({
            "page":i,
            "text":page_text
        })
    return pages

# def load_vectore_store():
#     global retriever, db
#     db = load_vectorestore_from_pdf(TEMP_PDF_PATH,persist=False)
#     retriever = db.as_retriever(search_kwargs={"k": 4})

def load_pdf(inp):
    # Convert bytes back to a PDF file
    # with open(TEMP_PDF_PATH, "wb") as f:
    #     f.write(inp)
    # Extract text from the PDF file
    s = BytesIO(inp)
    text = pdf_to_text(s)
    #load_vectore_store()
    #print(text)
    return text

def api_load_pdf(inp):
    # Extract text from the PDF file
    s = BytesIO(inp)
    text = api_pdf_to_text(s)

    return json.dumps(text)

# def compare_with_gpt(iu_code:str,text:str, model_name:Optional[str]=None)->str|None:
#     iu_course = get_course(iu_code)
#     if iu_course == None:
#         print("IU Course not found")
#         return None 
#     if model_name != None:
#         return get_comparison(iu_course,text,model_name=model_name)
#     return get_comparison(iu_course,text,model_name="gpt-4")

# def get_relevant_docs(search:str, iu_course:str):
#     global db, retriever, documents
#     documents = []
#     final_res = ""
#     documents = retriever.get_relevant_documents(f"Wo ist Modul/Kurs: {search.strip()}")
#     for document_ in documents:
#         print(f'\n>{document_.metadata["source"]} (Page {document_.metadata["page"]})')
#         #print(">",document.page_content,"\n\n")
#         final_res = f'{final_res}\n>{document_.metadata["source"]} (Page {document_.metadata["page"]}) :'
#     get_relevant_docs_promt = f"""

#     Du wirst 4 verschiedene Objecte in JSON erhalten und musst herausfinden welches ich suche.
#     Es handelt sich dabei um Ausschnitte eines Modulhandbuches einer Hochschule.
#     Ich suche die Modulbeschreibung von '{search}'. Suche danach in dem property 'page_content'
#     Nenne die Page in den Metadaten des richtigen Objektes. Denk dir keinen Quatsch aus, wenn du die Modulbeschreibung nicht findest, sag es.
#     Antworte in JSON format und fülle die werte page_found (bool) und page (int|None) aus.
#     """.strip()
#     messages = [
#         {
#             "role": "system", "content": f"{get_relevant_docs_promt}"
#         },
#         {
#             "role": "system", "content": f"Das sind die 4 Dokumente:\n{documents}"
#         }
#     ]
#     res = chat_prompt(messages=messages,model_name="gpt-4") #gpt-3.5-turbo-16k doesnt understand the task

#     final_res = f'{final_res}\n\n{res}\n'
#     res = json.loads(res)
#     if res["page_found"] ==False:
#         return final_res
#     page_num = int(res["page"])
    
#     final_res = f'{final_res}\n\nDocument auf Seite >{page_num} identifiziert.\nPrüfe auf Vollständigkeit...\n'

#     for doc in documents:
#         if page_num == doc.metadata["page"]:
#             print(page_num,"==",doc.metadata["page"])
#             document = doc
#             break 
#     next_page = documents = db.get(where={"page":page_num+1}) #pdf_to_text("temp.pdf",page_num=page_num+1)
#     if len(next_page["documents"]) > 0:
#         next_page = next_page["documents"][0]
#         words = next_page.split()
#         first_40_words = words[:40]
#         first_40_words_str = ' '.join(first_40_words)

#         # get the 50 last words of the description
#         words = document.page_content.split()
#         last_50_words = words[-50:]
#         # Join the words back into a string
#         last_50_words_str = ' '.join(last_50_words)

#         check_doc_complete_prompt= f"""
#             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
#             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.
#             Wenn der Auszug mit den Literaturangaben endet, ist die Modulbeschreibung vollständig.
#             Antworte nur mit 'vollständig' und 'unvollständig'.
#             Das Modul heißt [{search}]. Ist die Beschreibung vollständig oder fehlt etwas? Hier ist der Text: \n[{last_50_words_str}].
#             Das ist hier ist der Text der nächsten Seite:\n[{first_40_words_str}]
#         """.strip()

#         messages = [
#             {
#                 "role": "system", "content": f"{check_doc_complete_prompt}"
#             }
#         ]

#         res = chat_prompt(messages=messages,model_name="gpt-3.5-turbo-16k") #gpt-3.5-turbo-16k
#         #print("\nDie Beschreibung ist: ",res,"\n")
#         final_res = f'{final_res}\nDie Beschreibung ist: {res}\n'

#         description = f"{document.page_content}"

#         if res == "unvollständig":
#             description = f"{description}\n{next_page}"
#     else:
        
#         description = f"{document.page_content}"
#         final_res = f'{final_res}\nDie Beschreibung ist: {description}\n'
    
#     final_res = f'{final_res}\nSuche nach: {search}\nBeschreibung: {description}\n\n'
#     res = compare_with_gpt(iu_course,description,model_name="gpt-3.5-turbo-16k")

#     final_res = f'{final_res}\nIU-Kurs:{iu_course}\nErgebnis: {res}\n'

#     return final_res

with gr.Blocks() as app:
    file = gr.File(type="binary") 
    load_file_button = gr.Button("Load")
    with gr.Accordion("Text anzeigen",open=False):
        handbook = gr.TextArea(label="Modulhandbuch")

    load_file_button.click(load_pdf,inputs=file,outputs=handbook)

    with gr.Accordion("API",visible=False):
        api_file = gr.File(type="binary") 
        api_load_file_button = gr.Button("Load")
        api_handbook = gr.TextArea(label="Modulhandbuch")
        api_load_file_button.click(
            api_load_pdf,
            inputs=api_file,
            outputs=api_handbook,
            api_name="file-to-text")

    # with gr.Accordion("Kurse finden",open=False):
    #     with gr.Row():
    #         course_query = gr.Textbox(label="Kursnamen der zu prüfenden Kurse")
    #         iu_ccode = gr.Textbox(label="IU Kurscode")
    #     course_description = gr.TextArea(label="Ergebnis der Prüfung")
        

    #     course_query.submit(get_relevant_docs,inputs=[course_query,iu_ccode],outputs=course_description)



if __name__ == "__main__":
    app.launch(debug=True)