Maarten Van Segbroeck commited on
Commit
4bd2901
1 Parent(s): 9839cba

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +292 -0
app.py ADDED
@@ -0,0 +1,292 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import requests
3
+ import os
4
+ import markdownify
5
+ import fitz # PyMuPDF
6
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
7
+ import pandas as pd
8
+ import random
9
+ from gretel_client import Gretel
10
+ from gretel_client.config import GretelClientConfigurationError
11
+
12
+ # Directory for saving processed PDFs
13
+ output_dir = 'processed_pdfs'
14
+ os.makedirs(output_dir, exist_ok=True)
15
+
16
+ # Function to download and convert a PDF to text
17
+ def pdf_to_text(pdf_path):
18
+ pdf_document = fitz.open(pdf_path)
19
+ text = ''
20
+ for page_num in range(pdf_document.page_count):
21
+ page = pdf_document.load_page(page_num)
22
+ text += page.get_text()
23
+ return text
24
+
25
+ # Function to split text into chunks
26
+ def split_text_into_chunks(text, chunk_size=25, chunk_overlap=5, min_chunk_chars=50):
27
+ text_splitter = RecursiveCharacterTextSplitter.from_tiktoken_encoder(chunk_size=chunk_size, chunk_overlap=chunk_overlap)
28
+ chunks = text_splitter.split_text(text)
29
+ return [chunk for chunk in chunks if len(chunk) >= min_chunk_chars]
30
+
31
+ # Function to save chunks to files
32
+ def save_chunks(file_id, chunks, output_dir):
33
+ for i, chunk in enumerate(chunks):
34
+ chunk_filename = f"{file_id}_chunk_{i+1}.md"
35
+ chunk_path = os.path.join(output_dir, chunk_filename)
36
+ with open(chunk_path, 'w') as file:
37
+ file.write(chunk)
38
+
39
+ # Function to read chunks from files
40
+ def read_chunks_from_files(output_dir):
41
+ pdf_chunks_dict = {}
42
+ for filename in os.listdir(output_dir):
43
+ if filename.endswith('.md') and 'chunk' in filename:
44
+ file_id = filename.split('_chunk_')[0]
45
+ chunk_path = os.path.join(output_dir, filename)
46
+ with open(chunk_path, 'r') as file:
47
+ chunk = file.read()
48
+ if file_id not in pdf_chunks_dict:
49
+ pdf_chunks_dict[file_id] = []
50
+ pdf_chunks_dict[file_id].append(chunk)
51
+ return pdf_chunks_dict
52
+
53
+ def process_pdfs(uploaded_files, use_example, chunk_size, chunk_overlap, min_chunk_chars, current_chunk, direction):
54
+ selected_pdfs = []
55
+ if use_example:
56
+ example_file_url = "https://gretel-datasets.s3.us-west-2.amazonaws.com/rag/GDPR_2016.pdf"
57
+ pdf_path = os.path.join(output_dir, example_file_url.split('/')[-1])
58
+ if not os.path.exists(pdf_path):
59
+ response = requests.get(example_file_url)
60
+ with open(pdf_path, 'wb') as file:
61
+ file.write(response.content)
62
+ selected_pdfs = [pdf_path]
63
+ elif uploaded_files is not None:
64
+ for uploaded_file in uploaded_files:
65
+ pdf_path = os.path.join(output_dir, uploaded_file.name)
66
+ selected_pdfs.append(pdf_path)
67
+ else:
68
+ chunk_text = "No PDFs processed"
69
+ return None, 0, chunk_text, None
70
+
71
+ pdf_chunks_dict = {}
72
+ for pdf_path in selected_pdfs:
73
+ text = pdf_to_text(pdf_path)
74
+ markdown_text = markdownify.markdownify(text)
75
+ file_id = os.path.splitext(os.path.basename(pdf_path))[0]
76
+ markdown_path = os.path.join(output_dir, f"{file_id}.md")
77
+ with open(markdown_path, 'w') as file:
78
+ file.write(markdown_text)
79
+ chunks = split_text_into_chunks(markdown_text, chunk_size=chunk_size, chunk_overlap=chunk_overlap, min_chunk_chars=min_chunk_chars)
80
+ save_chunks(file_id, chunks, output_dir)
81
+ pdf_chunks_dict[file_id] = chunks
82
+
83
+ file_id = os.path.splitext(os.path.basename(selected_pdfs[0]))[0]
84
+ chunks = pdf_chunks_dict.get(file_id, [])
85
+
86
+ current_chunk += direction
87
+ if current_chunk < 0:
88
+ current_chunk = 0
89
+ elif current_chunk >= len(chunks):
90
+ current_chunk = len(chunks) - 1
91
+
92
+ chunk_text = chunks[current_chunk] if chunks else "No chunks available."
93
+ # use_example_update = gr.update(
94
+ # value=False,
95
+ # interactive=uploaded_files is None or len(uploaded_files) == 0
96
+ # )
97
+
98
+ return pdf_chunks_dict, selected_pdfs, chunk_text, current_chunk#, use_example_update
99
+
100
+ def show_chunks(pdf_chunks_dict, selected_pdfs, current_chunk, direction):
101
+ if selected_pdfs:
102
+ file_id = os.path.splitext(os.path.basename(selected_pdfs[0]))[0]
103
+ chunks = pdf_chunks_dict.get(file_id, [])
104
+
105
+ current_chunk += direction
106
+ if current_chunk < 0:
107
+ current_chunk = 0
108
+ elif current_chunk >= len(chunks):
109
+ current_chunk = len(chunks) - 1
110
+
111
+ chunk_text = chunks[current_chunk] if chunks else "No chunks available."
112
+ return chunk_text, current_chunk
113
+ else:
114
+ return "No PDF processed.", 0
115
+
116
+ # Validate API key and return button state
117
+ def check_api_key(api_key):
118
+ try:
119
+ Gretel(api_key=api_key, validate=True, clear=True)
120
+ is_valid = True
121
+ status_message = "Valid"
122
+ except GretelClientConfigurationError:
123
+ is_valid = False
124
+ status_message = "Invalid"
125
+ return gr.update(interactive=is_valid), status_message
126
+
127
+ def generate_synthetic_records(api_key, pdf_chunks_dict, num_records):
128
+
129
+ gretel = Gretel(api_key=api_key, validate=True, clear=True)
130
+
131
+ navigator = gretel.factories.initialize_inference_api("navigator")
132
+
133
+ INTRO_PROMPT = "From the source text below, create a dataset with the following columns:\n"
134
+ COLUMN_DETAILS = (
135
+ "* `topic`: Select a topic relevant for the given source text.\n"
136
+ "* `user_profile`: The complexity level of the question and truth, categorized into beginner, intermediate, and expert.\n"
137
+ " - Beginner users are about building foundational knowledge about the product and ask about basic features, benefits, and uses of the product.\n"
138
+ " - Intermediate users have a deep understanding of the product and are focusing on practical applications, comparisons with other products, and intermediate-level features and benefits.\n"
139
+ " - Expert users demonstrate in-depth technical knowledge, strategic application, and advanced troubleshooting. This level is for those who need to know the product inside and out, possibly for roles in sales, technical support, or product development.\n"
140
+ "* `question`: Ask a set of unique questions related to the topic that a user might ask. "
141
+ "Questions should be relatively complex and specific enough to be addressed in a short answer.\n"
142
+ "* `answer`: Respond to the question with a clear, textbook quality answer that provides relevant details to fully address the question.\n"
143
+ "* `context`: Copy the exact sentence(s) from the source text and surrounding details from where the answer can be derived.\n"
144
+ )
145
+ PROMPT = INTRO_PROMPT + COLUMN_DETAILS
146
+
147
+ GENERATE_PARAMS = {
148
+ "temperature": 0.7,
149
+ "top_p": 0.9,
150
+ "top_k": 40
151
+ }
152
+
153
+ df_in = pd.DataFrame()
154
+ documents = list(pdf_chunks_dict.keys())
155
+ all_chunks = [(doc, chunk) for doc in documents for chunk in pdf_chunks_dict[doc]]
156
+
157
+ for _ in range(num_records):
158
+ doc, chunk = random.choice(all_chunks)
159
+ df_doc = pd.DataFrame({'document': [doc], 'text': [chunk]})
160
+ df_in = pd.concat([df_in, df_doc], ignore_index=True)
161
+
162
+ df = navigator.edit(PROMPT, seed_data=df_in, **GENERATE_PARAMS)
163
+ df = df.drop(columns=['text'])
164
+
165
+ return gr.update(value=df, visible=True)
166
+
167
+ # CSS styling to center the logo and prevent right-click download
168
+ css = """
169
+ <style>
170
+ #logo-container {
171
+ display: flex;
172
+ justify-content: center;
173
+ width: 100%;
174
+ }
175
+ #logo-container svg {
176
+ pointer-events: none; /* Disable pointer events on the SVG */
177
+ }
178
+ </style>
179
+ """
180
+
181
+ # HTML content to include the logo
182
+ html_content = f"""
183
+ {css}
184
+ <div id="logo-container">
185
+ <svg width="181" height="72" viewBox="0 0 181 72" fill="none" xmlns="http://www.w3.org/2000/svg">
186
+ <g clip-path="url(#clip0_849_78)">
187
+ <path d="M53.4437 41.3178V53.5794H44.4782V18.8754H53.4437V27.0498C55.1339 21.1048 58.9552 18.1323 63.144 18.1323C65.3487 18.1323 67.2593 18.5782 68.8025 19.3956L67.2593 27.57C65.863 26.9011 64.0993 26.604 62.0417 26.604C56.3097 26.604 53.4437 31.5085 53.4437 41.3178Z" fill="#3C1AE6"/>
188
+ <path fill-rule="evenodd" clip-rule="evenodd" d="M103.383 45.9252C100.444 51.573 94.1975 54.3226 87.3631 54.3226C82.366 54.3226 78.1773 52.6134 74.7234 49.2693C71.2694 45.8509 69.5793 41.4664 69.5793 36.1159C69.5793 30.7654 71.2694 26.4553 74.7234 23.1112C78.1773 19.7671 82.366 18.1323 87.3631 18.1323C92.3603 18.1323 96.4755 19.7671 99.7824 23.1112C103.089 26.4553 104.78 30.7654 104.78 36.1159C104.78 37.019 104.715 37.987 104.647 39.0198L104.633 39.2371H78.4712C79.0591 43.7701 82.8805 46.6684 87.951 46.6684C91.5519 46.6684 95.0058 45.1078 96.549 42.2097L103.383 45.9252ZM78.3978 33.0691H96.0346C95.3733 28.3875 91.9194 25.7122 87.4366 25.7122C82.66 25.7122 79.0591 28.5361 78.3978 33.0691Z" fill="#3C1AE6"/>
189
+ <path d="M121.87 26.158V53.5794H112.979V26.158H106.732V18.8754H112.979V5.64777H121.87V18.8754H129.146V26.158H121.87Z" fill="#3C1AE6"/>
190
+ <path fill-rule="evenodd" clip-rule="evenodd" d="M164.903 45.9252C161.963 51.573 155.716 54.3226 148.882 54.3226C143.885 54.3226 139.696 52.6134 136.242 49.2693C132.789 45.8509 131.098 41.4664 131.098 36.1159C131.098 30.7654 132.789 26.4553 136.242 23.1112C139.696 19.7671 143.885 18.1323 148.882 18.1323C153.879 18.1323 157.994 19.7671 161.301 23.1112C164.609 26.4553 166.299 30.7654 166.299 36.1159C166.299 37.0174 166.235 37.9834 166.167 39.0141L166.152 39.2371H139.99C140.578 43.7701 144.399 46.6684 149.47 46.6684C153.072 46.6684 156.525 45.1078 158.069 42.2097L164.903 45.9252ZM139.917 33.0691H157.554C156.893 28.3875 153.439 25.7122 148.956 25.7122C144.179 25.7122 140.578 28.5361 139.917 33.0691Z" fill="#3C1AE6"/>
191
+ <path d="M180.597 0V53.5794H171.631V0H180.597Z" fill="#3C1AE6"/>
192
+ <path d="M27.1716 19.3782C27.1716 14.947 30.7321 11.3548 35.1241 11.3548V19.3782C35.1764 19.3959 27.1716 19.3782 27.1716 19.3782Z" fill="#3C1AE6"/>
193
+ <path d="M34.7984 54.5253C34.7984 64.11 27.2527 71.9206 17.8936 71.9206C8.62804 71.9206 1.13987 64.2655 0.991031 54.8122L0.988777 54.5253H8.94397C8.94397 59.7209 12.9737 63.8921 17.8936 63.8921C22.746 63.8921 26.7325 59.8342 26.8409 54.7381L26.8431 54.5253H34.7984Z" fill="#3C1AE6"/>
194
+ <path fill-rule="evenodd" clip-rule="evenodd" d="M35.7872 36.4522C35.7872 26.4724 27.7758 18.3822 17.8936 18.3822C8.01121 18.3822 0 26.4724 0 36.4522C0 46.4322 8.01121 54.5224 17.8936 54.5224C27.7758 54.5224 35.7872 46.4322 35.7872 36.4522ZM8.61542 36.4522C8.61542 31.2775 12.7694 27.0826 17.8936 27.0826C23.0178 27.0826 27.1716 31.2775 27.1716 36.4522C27.1716 41.6271 23.0178 45.822 17.8936 45.822C12.7694 45.822 8.61542 41.6271 8.61542 36.4522Z" fill="#3C1AE6"/>
195
+ </g>
196
+ <defs>
197
+ <clipPath id="clip0_849_78">
198
+ <rect width="181" height="72" fill="white"/>
199
+ </clipPath>
200
+ </defs>
201
+ </svg>
202
+ </div>
203
+ """
204
+
205
+ # Gradio interface
206
+ with gr.Blocks() as demo:
207
+ with gr.Row():
208
+ with gr.Column(scale=3):
209
+ # gr.Markdown("# Upload PDFs")
210
+ # gr.Image("gretel_logo.svg", elem_id="logo", show_label=False)
211
+ gr.HTML(html_content)
212
+
213
+ with gr.Tab("Upload PDF"):
214
+ use_example = gr.Checkbox(label="Continue with Example PDF", value=False, interactive=True)
215
+ uploaded_files = gr.File(label="Upload your PDF files", file_count="multiple")
216
+ # if uploaded_files:
217
+ # use_example = gr.Checkbox(label="Continue with Example PDF", value=False, interactive=False)
218
+
219
+ chunk_size = gr.Slider(label="Chunk Size (tokens)", minimum=10, maximum=1500, step=10, value=500)
220
+ chunk_overlap = gr.Slider(label="Chunk Overlap (tokens)", minimum=0, maximum=500, step=5, value=100)
221
+ min_chunk_chars = gr.Slider(label="Minimum Chunk Characters", minimum=10, maximum=2500, step=10, value=750)
222
+
223
+ process_button = gr.Button("Process PDFs")
224
+
225
+ pdf_chunks_dict = gr.State()
226
+ selected_pdfs = gr.State()
227
+ current_chunk = gr.State(value=0)
228
+
229
+ chunk_text = gr.Textbox(label="Chunk Text", lines=10)
230
+
231
+ def toggle_use_example(file_list):
232
+ return gr.update(
233
+ value = False,
234
+ interactive=file_list is None or len(file_list) == 0
235
+ )
236
+
237
+ uploaded_files.change(
238
+ toggle_use_example,
239
+ inputs=[uploaded_files],
240
+ outputs=[use_example]
241
+ )
242
+
243
+ process_button.click(
244
+ process_pdfs,
245
+ inputs=[uploaded_files, use_example, chunk_size, chunk_overlap, min_chunk_chars, current_chunk, gr.State(0)],
246
+ outputs=[pdf_chunks_dict, selected_pdfs, chunk_text, current_chunk]
247
+ )
248
+
249
+ with gr.Row():
250
+ prev_button = gr.Button("Previous Chunk", scale=1)
251
+ next_button = gr.Button("Next Chunk", scale=1)
252
+
253
+ prev_button.click(
254
+ show_chunks,
255
+ inputs=[pdf_chunks_dict, selected_pdfs, current_chunk, gr.State(-1)],
256
+ outputs=[chunk_text, current_chunk]
257
+ )
258
+
259
+ next_button.click(
260
+ show_chunks,
261
+ inputs=[pdf_chunks_dict, selected_pdfs, current_chunk, gr.State(1)],
262
+ outputs=[chunk_text, current_chunk]
263
+ )
264
+
265
+ with gr.Column(scale=7):
266
+ gr.Markdown("# Generate Question-Answer pairs")
267
+
268
+ with gr.Row():
269
+ api_key_input = gr.Textbox(label="API Key", type="password", placeholder="Enter your API key", scale=2)
270
+ validate_status = gr.Textbox(label="Validation Status", interactive=False, scale=1)
271
+
272
+ # User-specific settings
273
+ num_records = gr.Number(label="Number of Records", value=10)
274
+
275
+ generate_button = gr.Button("Generate Synthetic Records", interactive=False)
276
+
277
+ # Validate API key on input change and update button interactivity
278
+ api_key_input.change(
279
+ fn=check_api_key,
280
+ inputs=[api_key_input],
281
+ outputs=[generate_button, validate_status]
282
+ )
283
+
284
+ output_df = gr.Dataframe(headers=["document", "topic", "user_profile", "question", "answer", "context"], wrap=True, visible=True)
285
+
286
+ generate_button.click(
287
+ fn=generate_synthetic_records,
288
+ inputs=[api_key_input, pdf_chunks_dict, num_records],
289
+ outputs=[output_df]
290
+ )
291
+
292
+ demo.launch()