Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,813 +1,736 @@
|
|
1 |
-
import os
|
2 |
-
import json
|
3 |
-
import pandas as pd
|
4 |
-
import gradio as gr
|
5 |
-
import spaces
|
6 |
-
from transformers import AutoModelForCausalLM, AutoTokenizer
|
7 |
-
import torch
|
8 |
-
import csv
|
9 |
-
import yaml
|
10 |
-
from typing import List, Dict, Any
|
11 |
-
import random
|
12 |
-
from pypdf import PdfReader
|
13 |
-
import re
|
14 |
-
import tempfile
|
15 |
-
from huggingface_hub import HfApi
|
16 |
-
|
17 |
-
# Configuration
|
18 |
-
DEFAULT_MODEL = "
|
19 |
-
DEVICE = "cuda" if torch.cuda.is_available() else "cpu" # Try to use CUDA if available
|
20 |
-
MAX_NEW_TOKENS = 512
|
21 |
-
TEMPERATURE = 0.7
|
22 |
-
HF_TOKEN = os.environ.get("HF_TOKEN") if os.environ.get("HF_TOKEN") else None # Get token from environment variables
|
23 |
-
MAX_RAM_GB = 45 # Set maximum RAM usage to 45GB (below the 70GB limit)
|
24 |
-
|
25 |
-
# Create offload folder for model memory management
|
26 |
-
os.makedirs("offload_folder", exist_ok=True)
|
27 |
-
|
28 |
-
# Setup RAM monitoring
|
29 |
-
def get_process_memory_usage():
|
30 |
-
"""Get the current memory usage of this process in GB"""
|
31 |
-
import psutil
|
32 |
-
process = psutil.Process(os.getpid())
|
33 |
-
return process.memory_info().rss / (1024 * 1024 * 1024) # Convert to GB
|
34 |
-
|
35 |
-
class PdfExtractor:
|
36 |
-
"""Extract text content from PDF files"""
|
37 |
-
|
38 |
-
@staticmethod
|
39 |
-
def extract_text_from_pdf(pdf_file):
|
40 |
-
"""Extract text from a PDF file"""
|
41 |
-
try:
|
42 |
-
reader = PdfReader(pdf_file)
|
43 |
-
text = ""
|
44 |
-
|
45 |
-
for page in reader.pages:
|
46 |
-
text += page.extract_text() + "\n"
|
47 |
-
|
48 |
-
return text
|
49 |
-
except Exception as e:
|
50 |
-
print(f"Error extracting text from PDF: {e}")
|
51 |
-
return None
|
52 |
-
|
53 |
-
@staticmethod
|
54 |
-
def clean_text(text):
|
55 |
-
"""Clean and preprocess extracted text"""
|
56 |
-
if not text:
|
57 |
-
return ""
|
58 |
-
|
59 |
-
# Replace multiple newlines with single newline
|
60 |
-
text = re.sub(r'\n+', '\n', text)
|
61 |
-
|
62 |
-
# Replace multiple spaces with single space
|
63 |
-
text = re.sub(r'\s+', ' ', text)
|
64 |
-
|
65 |
-
return text.strip()
|
66 |
-
|
67 |
-
@staticmethod
|
68 |
-
def chunk_text(text, max_chunk_size=1000, overlap=100):
|
69 |
-
"""Split text into chunks of specified size with overlap"""
|
70 |
-
if not text:
|
71 |
-
return []
|
72 |
-
|
73 |
-
chunks = []
|
74 |
-
start = 0
|
75 |
-
text_length = len(text)
|
76 |
-
|
77 |
-
while start < text_length:
|
78 |
-
end = min(start + max_chunk_size, text_length)
|
79 |
-
|
80 |
-
# If we're not at the end, try to break at a sentence or paragraph
|
81 |
-
if end < text_length:
|
82 |
-
# Look for sentence breaks (period, question mark, exclamation mark followed by space)
|
83 |
-
sentence_break = max(
|
84 |
-
text.rfind('. ', start, end),
|
85 |
-
text.rfind('? ', start, end),
|
86 |
-
text.rfind('! ', start, end),
|
87 |
-
text.rfind('\n', start, end)
|
88 |
-
)
|
89 |
-
|
90 |
-
if sentence_break > start + max_chunk_size // 2:
|
91 |
-
end = sentence_break + 1
|
92 |
-
|
93 |
-
chunks.append(text[start:end].strip())
|
94 |
-
start = end - overlap # Create overlap with previous chunk
|
95 |
-
|
96 |
-
return chunks
|
97 |
-
|
98 |
-
class SyntheticDataGenerator:
|
99 |
-
def __init__(self, model_name=DEFAULT_MODEL):
|
100 |
-
self.model_name = model_name
|
101 |
-
self.model = None
|
102 |
-
self.tokenizer = None
|
103 |
-
self.
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
#
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
torch.
|
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 |
-
|
204 |
-
|
205 |
-
|
206 |
-
|
207 |
-
|
208 |
-
|
209 |
-
|
210 |
-
|
211 |
-
|
212 |
-
|
213 |
-
|
214 |
-
|
215 |
-
|
216 |
-
|
217 |
-
|
218 |
-
|
219 |
-
|
220 |
-
|
221 |
-
|
222 |
-
|
223 |
-
|
224 |
-
|
225 |
-
|
226 |
-
|
227 |
-
|
228 |
-
|
229 |
-
|
230 |
-
|
231 |
-
|
232 |
-
|
233 |
-
|
234 |
-
|
235 |
-
|
236 |
-
|
237 |
-
|
238 |
-
|
239 |
-
|
240 |
-
|
241 |
-
|
242 |
-
|
243 |
-
|
244 |
-
|
245 |
-
|
246 |
-
|
247 |
-
|
248 |
-
|
249 |
-
|
250 |
-
|
251 |
-
|
252 |
-
|
253 |
-
|
254 |
-
|
255 |
-
|
256 |
-
|
257 |
-
|
258 |
-
|
259 |
-
|
260 |
-
|
261 |
-
|
262 |
-
|
263 |
-
|
264 |
-
|
265 |
-
|
266 |
-
|
267 |
-
|
268 |
-
|
269 |
-
|
270 |
-
|
271 |
-
|
272 |
-
|
273 |
-
|
274 |
-
|
275 |
-
|
276 |
-
|
277 |
-
|
278 |
-
|
279 |
-
|
280 |
-
|
281 |
-
|
282 |
-
|
283 |
-
|
284 |
-
|
285 |
-
|
286 |
-
|
287 |
-
|
288 |
-
|
289 |
-
|
290 |
-
|
291 |
-
|
292 |
-
|
293 |
-
|
294 |
-
|
295 |
-
|
296 |
-
|
297 |
-
|
298 |
-
|
299 |
-
|
300 |
-
|
301 |
-
|
302 |
-
|
303 |
-
|
304 |
-
|
305 |
-
|
306 |
-
|
307 |
-
|
308 |
-
|
309 |
-
|
310 |
-
|
311 |
-
|
312 |
-
|
313 |
-
|
314 |
-
|
315 |
-
|
316 |
-
|
317 |
-
|
318 |
-
|
319 |
-
|
320 |
-
|
321 |
-
|
322 |
-
|
323 |
-
|
324 |
-
|
325 |
-
|
326 |
-
|
327 |
-
|
328 |
-
|
329 |
-
|
330 |
-
|
331 |
-
|
332 |
-
|
333 |
-
|
334 |
-
|
335 |
-
|
336 |
-
|
337 |
-
|
338 |
-
|
339 |
-
|
340 |
-
|
341 |
-
|
342 |
-
|
343 |
-
|
344 |
-
|
345 |
-
|
346 |
-
|
347 |
-
|
348 |
-
|
349 |
-
|
350 |
-
|
351 |
-
|
352 |
-
|
353 |
-
|
354 |
-
|
355 |
-
|
356 |
-
|
357 |
-
|
358 |
-
|
359 |
-
|
360 |
-
|
361 |
-
|
362 |
-
|
363 |
-
|
364 |
-
|
365 |
-
|
366 |
-
|
367 |
-
|
368 |
-
|
369 |
-
|
370 |
-
|
371 |
-
|
372 |
-
|
373 |
-
|
374 |
-
|
375 |
-
|
376 |
-
|
377 |
-
|
378 |
-
|
379 |
-
|
380 |
-
|
381 |
-
|
382 |
-
|
383 |
-
|
384 |
-
|
385 |
-
|
386 |
-
|
387 |
-
|
388 |
-
|
389 |
-
|
390 |
-
|
391 |
-
|
392 |
-
|
393 |
-
|
394 |
-
|
395 |
-
|
396 |
-
|
397 |
-
|
398 |
-
|
399 |
-
|
400 |
-
|
401 |
-
|
402 |
-
|
403 |
-
|
404 |
-
|
405 |
-
|
406 |
-
|
407 |
-
|
408 |
-
|
409 |
-
|
410 |
-
|
411 |
-
|
412 |
-
|
413 |
-
|
414 |
-
|
415 |
-
|
416 |
-
|
417 |
-
|
418 |
-
|
419 |
-
|
420 |
-
|
421 |
-
|
422 |
-
|
423 |
-
|
424 |
-
|
425 |
-
|
426 |
-
|
427 |
-
|
428 |
-
|
429 |
-
|
430 |
-
|
431 |
-
|
432 |
-
|
433 |
-
|
434 |
-
|
435 |
-
|
436 |
-
|
437 |
-
|
438 |
-
|
439 |
-
|
440 |
-
|
441 |
-
|
442 |
-
|
443 |
-
|
444 |
-
|
445 |
-
|
446 |
-
|
447 |
-
|
448 |
-
|
449 |
-
|
450 |
-
|
451 |
-
|
452 |
-
|
453 |
-
|
454 |
-
|
455 |
-
|
456 |
-
|
457 |
-
|
458 |
-
|
459 |
-
|
460 |
-
|
461 |
-
|
462 |
-
|
463 |
-
|
464 |
-
|
465 |
-
|
466 |
-
|
467 |
-
|
468 |
-
|
469 |
-
|
470 |
-
|
471 |
-
|
472 |
-
|
473 |
-
|
474 |
-
|
475 |
-
|
476 |
-
|
477 |
-
|
478 |
-
|
479 |
-
|
480 |
-
|
481 |
-
|
482 |
-
|
483 |
-
|
484 |
-
|
485 |
-
|
486 |
-
|
487 |
-
|
488 |
-
|
489 |
-
|
490 |
-
|
491 |
-
|
492 |
-
|
493 |
-
|
494 |
-
|
495 |
-
|
496 |
-
|
497 |
-
|
498 |
-
|
499 |
-
|
500 |
-
|
501 |
-
|
502 |
-
|
503 |
-
|
504 |
-
|
505 |
-
if
|
506 |
-
|
507 |
-
|
508 |
-
|
509 |
-
|
510 |
-
|
511 |
-
|
512 |
-
|
513 |
-
|
514 |
-
|
515 |
-
|
516 |
-
|
517 |
-
|
518 |
-
|
519 |
-
|
520 |
-
|
521 |
-
|
522 |
-
|
523 |
-
|
524 |
-
|
525 |
-
|
526 |
-
|
527 |
-
|
528 |
-
|
529 |
-
|
530 |
-
|
531 |
-
|
532 |
-
|
533 |
-
|
534 |
-
|
535 |
-
|
536 |
-
|
537 |
-
|
538 |
-
|
539 |
-
|
540 |
-
|
541 |
-
|
542 |
-
|
543 |
-
|
544 |
-
|
545 |
-
|
546 |
-
|
547 |
-
|
548 |
-
|
549 |
-
|
550 |
-
|
551 |
-
|
552 |
-
|
553 |
-
|
554 |
-
|
555 |
-
|
556 |
-
|
557 |
-
|
558 |
-
|
559 |
-
|
560 |
-
|
561 |
-
|
562 |
-
|
563 |
-
|
564 |
-
|
565 |
-
|
566 |
-
|
567 |
-
|
568 |
-
|
569 |
-
|
570 |
-
|
571 |
-
|
572 |
-
|
573 |
-
|
574 |
-
|
575 |
-
|
576 |
-
|
577 |
-
|
578 |
-
|
579 |
-
|
580 |
-
|
581 |
-
|
582 |
-
|
583 |
-
|
584 |
-
|
585 |
-
|
586 |
-
|
587 |
-
|
588 |
-
|
589 |
-
|
590 |
-
|
591 |
-
|
592 |
-
|
593 |
-
|
594 |
-
|
595 |
-
|
596 |
-
|
597 |
-
|
598 |
-
|
599 |
-
|
600 |
-
|
601 |
-
|
602 |
-
|
603 |
-
|
604 |
-
|
605 |
-
|
606 |
-
|
607 |
-
|
608 |
-
|
609 |
-
|
610 |
-
|
611 |
-
|
612 |
-
|
613 |
-
|
614 |
-
|
615 |
-
|
616 |
-
|
617 |
-
|
618 |
-
|
619 |
-
|
620 |
-
|
621 |
-
|
622 |
-
|
623 |
-
|
624 |
-
|
625 |
-
|
626 |
-
|
627 |
-
|
628 |
-
|
629 |
-
|
630 |
-
|
631 |
-
|
632 |
-
|
633 |
-
|
634 |
-
|
635 |
-
|
636 |
-
|
637 |
-
|
638 |
-
|
639 |
-
|
640 |
-
|
641 |
-
|
642 |
-
|
643 |
-
|
644 |
-
|
645 |
-
|
646 |
-
|
647 |
-
|
648 |
-
|
649 |
-
|
650 |
-
|
651 |
-
|
652 |
-
|
653 |
-
|
654 |
-
|
655 |
-
|
656 |
-
|
657 |
-
|
658 |
-
|
659 |
-
|
660 |
-
|
661 |
-
|
662 |
-
|
663 |
-
|
664 |
-
|
665 |
-
|
666 |
-
|
667 |
-
|
668 |
-
|
669 |
-
|
670 |
-
|
671 |
-
|
672 |
-
|
673 |
-
|
674 |
-
|
675 |
-
|
676 |
-
|
677 |
-
|
678 |
-
|
679 |
-
|
680 |
-
|
681 |
-
|
682 |
-
|
683 |
-
|
684 |
-
|
685 |
-
|
686 |
-
|
687 |
-
|
688 |
-
|
689 |
-
|
690 |
-
|
691 |
-
|
692 |
-
|
693 |
-
|
694 |
-
|
695 |
-
|
696 |
-
|
697 |
-
|
698 |
-
|
699 |
-
|
700 |
-
|
701 |
-
|
702 |
-
|
703 |
-
|
704 |
-
|
705 |
-
|
706 |
-
|
707 |
-
|
708 |
-
|
709 |
-
|
710 |
-
|
711 |
-
|
712 |
-
|
713 |
-
|
714 |
-
|
715 |
-
|
716 |
-
|
717 |
-
|
718 |
-
|
719 |
-
|
720 |
-
|
721 |
-
|
722 |
-
|
723 |
-
|
724 |
-
|
725 |
-
|
726 |
-
|
727 |
-
|
728 |
-
|
729 |
-
|
730 |
-
|
731 |
-
|
732 |
-
|
733 |
-
|
734 |
-
|
735 |
-
|
736 |
-
|
737 |
-
)
|
738 |
-
|
739 |
-
file_output = gr.Textbox(label="File Output")
|
740 |
-
|
741 |
-
with gr.TabItem("Documentation"):
|
742 |
-
gr.Markdown("""
|
743 |
-
## How to Use
|
744 |
-
|
745 |
-
1. **Upload a PDF**: Select a PDF document containing the content you want to generate questions from.
|
746 |
-
2. **Select a model**: Choose an instruction-tuned language model from the dropdown.
|
747 |
-
3. **Configure settings**:
|
748 |
-
- Set the number of questions to generate per text section
|
749 |
-
- Choose whether to include tags and difficulty levels
|
750 |
-
- Select your preferred output file format
|
751 |
-
4. **Generate dataset**: Click the "Generate Q&A Dataset" button to create your dataset.
|
752 |
-
|
753 |
-
## About This App
|
754 |
-
|
755 |
-
This app uses instruction-tuned language models to generate question and answer pairs from PDF documents. It:
|
756 |
-
|
757 |
-
1. Extracts text from the uploaded PDF
|
758 |
-
2. Splits the text into manageable chunks
|
759 |
-
3. Generates questions, answers, tags, and difficulty levels for each chunk
|
760 |
-
4. Combines all Q&A pairs into a comprehensive dataset
|
761 |
-
|
762 |
-
### Features:
|
763 |
-
- Automatic text extraction from PDFs
|
764 |
-
- Smart text chunking to maintain context
|
765 |
-
- Customizable number of questions per chunk
|
766 |
-
- Optional tagging and difficulty classification
|
767 |
-
- Multiple output formats (JSON, CSV, Excel)
|
768 |
-
|
769 |
-
### Use Cases:
|
770 |
-
- Create educational resources and quiz materials
|
771 |
-
- Generate training data for Q&A systems
|
772 |
-
- Build flashcard datasets for studying
|
773 |
-
- Develop content for educational applications
|
774 |
-
""")
|
775 |
-
|
776 |
-
with gr.TabItem("Status"):
|
777 |
-
gr.Markdown("""
|
778 |
-
## System Status
|
779 |
-
|
780 |
-
This app runs on CPU mode. Some larger models might be slower to load and generate content.
|
781 |
-
If you encounter any issues with a specific model, try switching to a smaller model like `databricks/dolly-v2-3b`.
|
782 |
-
|
783 |
-
### Troubleshooting
|
784 |
-
|
785 |
-
- If the app seems unresponsive after clicking "Generate", please be patient - model loading may take time.
|
786 |
-
- If you get an error about model loading, try refreshing the page and selecting a different model.
|
787 |
-
- Not all PDFs can be properly processed - if text extraction fails, try with a different PDF.
|
788 |
-
""")
|
789 |
-
|
790 |
-
# Event handler for generate button
|
791 |
-
generate_btn.click(
|
792 |
-
process_pdf_generate_qa,
|
793 |
-
inputs=[
|
794 |
-
pdf_file,
|
795 |
-
model_dropdown,
|
796 |
-
num_questions,
|
797 |
-
include_tags,
|
798 |
-
include_difficulty,
|
799 |
-
output_file_format
|
800 |
-
],
|
801 |
-
outputs=[parsed_data_output, formatted_data_output, raw_output, file_output],
|
802 |
-
show_progress=True
|
803 |
-
)
|
804 |
-
|
805 |
-
return app
|
806 |
-
|
807 |
-
# Export the app for Hugging Face Spaces
|
808 |
-
app = create_interface()
|
809 |
-
|
810 |
-
# Launch the app depending on the environment
|
811 |
-
if __name__ == "__main__":
|
812 |
-
app.launch()
|
813 |
-
|
|
|
1 |
+
import os
|
2 |
+
import json
|
3 |
+
import pandas as pd
|
4 |
+
import gradio as gr
|
5 |
+
import spaces
|
6 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
7 |
+
import torch
|
8 |
+
import csv
|
9 |
+
import yaml
|
10 |
+
from typing import List, Dict, Any
|
11 |
+
import random
|
12 |
+
from pypdf import PdfReader
|
13 |
+
import re
|
14 |
+
import tempfile
|
15 |
+
from huggingface_hub import HfApi
|
16 |
+
|
17 |
+
# Configuration
|
18 |
+
DEFAULT_MODEL = "tiiuae/falcon-7b-instruct" # Use Falcon-7B as the default model
|
19 |
+
DEVICE = "cuda" if torch.cuda.is_available() else "cpu" # Try to use CUDA if available
|
20 |
+
MAX_NEW_TOKENS = 512
|
21 |
+
TEMPERATURE = 0.7
|
22 |
+
HF_TOKEN = os.environ.get("HF_TOKEN") if os.environ.get("HF_TOKEN") else None # Get token from environment variables
|
23 |
+
MAX_RAM_GB = 45 # Set maximum RAM usage to 45GB (below the 70GB limit)
|
24 |
+
|
25 |
+
# Create offload folder for model memory management
|
26 |
+
os.makedirs("offload_folder", exist_ok=True)
|
27 |
+
|
28 |
+
# Setup RAM monitoring
|
29 |
+
def get_process_memory_usage():
|
30 |
+
"""Get the current memory usage of this process in GB"""
|
31 |
+
import psutil
|
32 |
+
process = psutil.Process(os.getpid())
|
33 |
+
return process.memory_info().rss / (1024 * 1024 * 1024) # Convert to GB
|
34 |
+
|
35 |
+
class PdfExtractor:
|
36 |
+
"""Extract text content from PDF files"""
|
37 |
+
|
38 |
+
@staticmethod
|
39 |
+
def extract_text_from_pdf(pdf_file):
|
40 |
+
"""Extract text from a PDF file"""
|
41 |
+
try:
|
42 |
+
reader = PdfReader(pdf_file)
|
43 |
+
text = ""
|
44 |
+
|
45 |
+
for page in reader.pages:
|
46 |
+
text += page.extract_text() + "\n"
|
47 |
+
|
48 |
+
return text
|
49 |
+
except Exception as e:
|
50 |
+
print(f"Error extracting text from PDF: {e}")
|
51 |
+
return None
|
52 |
+
|
53 |
+
@staticmethod
|
54 |
+
def clean_text(text):
|
55 |
+
"""Clean and preprocess extracted text"""
|
56 |
+
if not text:
|
57 |
+
return ""
|
58 |
+
|
59 |
+
# Replace multiple newlines with single newline
|
60 |
+
text = re.sub(r'\n+', '\n', text)
|
61 |
+
|
62 |
+
# Replace multiple spaces with single space
|
63 |
+
text = re.sub(r'\s+', ' ', text)
|
64 |
+
|
65 |
+
return text.strip()
|
66 |
+
|
67 |
+
@staticmethod
|
68 |
+
def chunk_text(text, max_chunk_size=1000, overlap=100):
|
69 |
+
"""Split text into chunks of specified size with overlap"""
|
70 |
+
if not text:
|
71 |
+
return []
|
72 |
+
|
73 |
+
chunks = []
|
74 |
+
start = 0
|
75 |
+
text_length = len(text)
|
76 |
+
|
77 |
+
while start < text_length:
|
78 |
+
end = min(start + max_chunk_size, text_length)
|
79 |
+
|
80 |
+
# If we're not at the end, try to break at a sentence or paragraph
|
81 |
+
if end < text_length:
|
82 |
+
# Look for sentence breaks (period, question mark, exclamation mark followed by space)
|
83 |
+
sentence_break = max(
|
84 |
+
text.rfind('. ', start, end),
|
85 |
+
text.rfind('? ', start, end),
|
86 |
+
text.rfind('! ', start, end),
|
87 |
+
text.rfind('\n', start, end)
|
88 |
+
)
|
89 |
+
|
90 |
+
if sentence_break > start + max_chunk_size // 2:
|
91 |
+
end = sentence_break + 1
|
92 |
+
|
93 |
+
chunks.append(text[start:end].strip())
|
94 |
+
start = end - overlap # Create overlap with previous chunk
|
95 |
+
|
96 |
+
return chunks
|
97 |
+
|
98 |
+
class SyntheticDataGenerator:
|
99 |
+
def __init__(self, model_name=DEFAULT_MODEL):
|
100 |
+
self.model_name = model_name
|
101 |
+
self.model = None
|
102 |
+
self.tokenizer = None
|
103 |
+
self.load_model() # Load the model directly during initialization
|
104 |
+
|
105 |
+
def load_model(self):
|
106 |
+
"""Load the specified model."""
|
107 |
+
# Clear CUDA cache if using GPU to prevent memory fragmentation
|
108 |
+
if torch.cuda.is_available():
|
109 |
+
torch.cuda.empty_cache()
|
110 |
+
|
111 |
+
try:
|
112 |
+
print(f"Loading model {self.model_name} on {DEVICE}...")
|
113 |
+
|
114 |
+
# Add token for authentication if available
|
115 |
+
tokenizer_kwargs = {}
|
116 |
+
model_kwargs = {
|
117 |
+
"torch_dtype": torch.float16 if torch.cuda.is_available() else torch.float32,
|
118 |
+
"device_map": "auto" if torch.cuda.is_available() else None,
|
119 |
+
"low_cpu_mem_usage": True, # Added to reduce memory usage on CPU
|
120 |
+
"offload_folder": "offload_folder" # Add offload folder for large models
|
121 |
+
}
|
122 |
+
|
123 |
+
if HF_TOKEN:
|
124 |
+
tokenizer_kwargs["token"] = HF_TOKEN
|
125 |
+
model_kwargs["token"] = HF_TOKEN
|
126 |
+
print("Using Hugging Face token for authentication")
|
127 |
+
|
128 |
+
# Load tokenizer
|
129 |
+
self.tokenizer = AutoTokenizer.from_pretrained(self.model_name, **tokenizer_kwargs)
|
130 |
+
|
131 |
+
# Load the model
|
132 |
+
self.model = AutoModelForCausalLM.from_pretrained(
|
133 |
+
self.model_name,
|
134 |
+
**model_kwargs
|
135 |
+
)
|
136 |
+
|
137 |
+
# Ensure model is on the right device if not using device_map="auto"
|
138 |
+
if not torch.cuda.is_available():
|
139 |
+
self.model = self.model.to(DEVICE)
|
140 |
+
|
141 |
+
print(f"Model {self.model_name} loaded successfully on {DEVICE}")
|
142 |
+
except Exception as e:
|
143 |
+
print(f"Error loading model {self.model_name}: {e}")
|
144 |
+
self.model = None
|
145 |
+
self.tokenizer = None
|
146 |
+
raise
|
147 |
+
|
148 |
+
def generate_qa_prompt(self, context, num_questions=3, include_tags=True, difficulty_levels=True):
|
149 |
+
"""Generate a prompt for creating Q&A pairs from context."""
|
150 |
+
tag_instruction = ""
|
151 |
+
if include_tags:
|
152 |
+
tag_instruction = "Add 1-3 tags for each question that categorize the topic or subject matter."
|
153 |
+
|
154 |
+
difficulty_instruction = ""
|
155 |
+
if difficulty_levels:
|
156 |
+
difficulty_instruction = "For each question, assign a difficulty level (easy, medium, or hard)."
|
157 |
+
|
158 |
+
prompt = f"""Task: Based on the following text, generate {num_questions} question and answer pairs that would be useful for comprehension testing or knowledge assessment.
|
159 |
+
|
160 |
+
CONTEXT:
|
161 |
+
{context}
|
162 |
+
|
163 |
+
For each question:
|
164 |
+
1. Write a clear, specific question about the information in the text
|
165 |
+
2. Provide the correct answer to the question, citing relevant details from the text
|
166 |
+
3. {tag_instruction}
|
167 |
+
4. {difficulty_instruction}
|
168 |
+
|
169 |
+
Format each Q&A pair as a JSON object with the following structure:
|
170 |
+
{{
|
171 |
+
"question": "The question text",
|
172 |
+
"answer": "The answer text",
|
173 |
+
"tags": ["tag1", "tag2"],
|
174 |
+
"difficulty": "easy/medium/hard"
|
175 |
+
}}
|
176 |
+
|
177 |
+
Return all Q&A pairs in a JSON array.
|
178 |
+
"""
|
179 |
+
return prompt
|
180 |
+
|
181 |
+
def generate_data(self, prompt, num_samples=1):
|
182 |
+
"""Generate synthetic data using the loaded model."""
|
183 |
+
if not self.model or not self.tokenizer:
|
184 |
+
return ["Error: Model not loaded properly. Please try again with a different model."]
|
185 |
+
|
186 |
+
outputs = []
|
187 |
+
for sample_idx in range(num_samples):
|
188 |
+
try:
|
189 |
+
# Clear CUDA cache before generating to free up memory
|
190 |
+
if torch.cuda.is_available():
|
191 |
+
torch.cuda.empty_cache()
|
192 |
+
|
193 |
+
# ZeroGPU errors often occur in generate() calls
|
194 |
+
# To mitigate this, try multiple approaches in sequence
|
195 |
+
inputs = self.tokenizer(prompt, return_tensors="pt").to(DEVICE)
|
196 |
+
|
197 |
+
try:
|
198 |
+
# First try: Standard generation with conservative settings
|
199 |
+
with torch.no_grad():
|
200 |
+
output = self.model.generate(
|
201 |
+
**inputs,
|
202 |
+
max_new_tokens=MAX_NEW_TOKENS,
|
203 |
+
temperature=TEMPERATURE,
|
204 |
+
do_sample=True,
|
205 |
+
pad_token_id=self.tokenizer.eos_token_id,
|
206 |
+
num_beams=1, # Use greedy decoding instead of beam search
|
207 |
+
early_stopping=True,
|
208 |
+
no_repeat_ngram_size=3 # Prevent repetition
|
209 |
+
)
|
210 |
+
|
211 |
+
decoded_output = self.tokenizer.decode(output[0], skip_special_tokens=True)
|
212 |
+
except (RuntimeError, Exception) as e:
|
213 |
+
if "CUDA" in str(e) or "GPU" in str(e) or "ZeroGPU" in str(e):
|
214 |
+
print(f"GPU error during generation: {e}")
|
215 |
+
print("Falling back to CPU generation...")
|
216 |
+
|
217 |
+
# Move everything to CPU
|
218 |
+
inputs = {k: v.to('cpu') for k, v in inputs.items()}
|
219 |
+
|
220 |
+
# Create CPU copy of the model if we were using GPU
|
221 |
+
if torch.cuda.is_available():
|
222 |
+
# Temporarily move model to CPU for this generation
|
223 |
+
model_cpu = self.model.to('cpu')
|
224 |
+
|
225 |
+
with torch.no_grad():
|
226 |
+
output = model_cpu.generate(
|
227 |
+
**inputs,
|
228 |
+
max_new_tokens=MAX_NEW_TOKENS,
|
229 |
+
temperature=TEMPERATURE,
|
230 |
+
do_sample=True,
|
231 |
+
pad_token_id=self.tokenizer.eos_token_id,
|
232 |
+
num_return_sequences=1,
|
233 |
+
max_length=MAX_NEW_TOKENS + inputs['input_ids'].shape[1]
|
234 |
+
)
|
235 |
+
decoded_output = self.tokenizer.decode(output[0], skip_special_tokens=True)
|
236 |
+
|
237 |
+
# Move model back to CUDA for future calls
|
238 |
+
self.model = self.model.to(DEVICE)
|
239 |
+
else:
|
240 |
+
# Already on CPU, try with reduced parameters
|
241 |
+
with torch.no_grad():
|
242 |
+
output = self.model.generate(
|
243 |
+
**inputs,
|
244 |
+
max_new_tokens=min(256, MAX_NEW_TOKENS), # Reduce token count
|
245 |
+
temperature=0.5, # Lower temperature
|
246 |
+
do_sample=False, # No sampling
|
247 |
+
num_return_sequences=1,
|
248 |
+
pad_token_id=self.tokenizer.eos_token_id
|
249 |
+
)
|
250 |
+
decoded_output = self.tokenizer.decode(output[0], skip_special_tokens=True)
|
251 |
+
else:
|
252 |
+
# Re-raise non-CUDA errors
|
253 |
+
raise
|
254 |
+
|
255 |
+
# Extract only the generated part (remove prompt)
|
256 |
+
prompt_text = self.tokenizer.decode(inputs.input_ids[0], skip_special_tokens=True)
|
257 |
+
generated_text = decoded_output[len(prompt_text):].strip()
|
258 |
+
outputs.append(generated_text)
|
259 |
+
|
260 |
+
# Clear CUDA cache between samples
|
261 |
+
if torch.cuda.is_available():
|
262 |
+
torch.cuda.empty_cache()
|
263 |
+
|
264 |
+
except Exception as e:
|
265 |
+
error_msg = f"Error generating sample {sample_idx+1}: {str(e)}"
|
266 |
+
print(error_msg)
|
267 |
+
outputs.append(f"Error: {error_msg}")
|
268 |
+
|
269 |
+
return outputs
|
270 |
+
|
271 |
+
def parse_json_data(self, generated_text):
|
272 |
+
"""Extract and parse JSON from generated text."""
|
273 |
+
try:
|
274 |
+
# Find JSON-like content (between [ and ])
|
275 |
+
start_idx = generated_text.find('[')
|
276 |
+
end_idx = generated_text.rfind(']') + 1
|
277 |
+
|
278 |
+
if start_idx >= 0 and end_idx > start_idx:
|
279 |
+
json_str = generated_text[start_idx:end_idx]
|
280 |
+
return json.loads(json_str)
|
281 |
+
|
282 |
+
# Try to find single object format
|
283 |
+
start_idx = generated_text.find('{')
|
284 |
+
end_idx = generated_text.rfind('}') + 1
|
285 |
+
|
286 |
+
if start_idx >= 0 and end_idx > start_idx:
|
287 |
+
json_str = generated_text[start_idx:end_idx]
|
288 |
+
return json.loads(json_str)
|
289 |
+
|
290 |
+
print(f"Could not find JSON content in: {generated_text}")
|
291 |
+
return None
|
292 |
+
except json.JSONDecodeError as e:
|
293 |
+
print(f"JSON parse error: {e}")
|
294 |
+
print(f"Problematic text: {generated_text}")
|
295 |
+
|
296 |
+
# Try to find and fix common JSON formatting errors
|
297 |
+
try:
|
298 |
+
# Replace single quotes with double quotes
|
299 |
+
json_str = generated_text[start_idx:end_idx].replace("'", "\"")
|
300 |
+
return json.loads(json_str)
|
301 |
+
except:
|
302 |
+
pass
|
303 |
+
|
304 |
+
# If still failing, try to extract individual JSON objects
|
305 |
+
try:
|
306 |
+
pattern = r'\{[^{}]*\}'
|
307 |
+
matches = re.findall(pattern, generated_text)
|
308 |
+
if matches:
|
309 |
+
results = []
|
310 |
+
for match in matches:
|
311 |
+
try:
|
312 |
+
# Replace single quotes with double quotes
|
313 |
+
fixed_match = match.replace("'", "\"")
|
314 |
+
obj = json.loads(fixed_match)
|
315 |
+
results.append(obj)
|
316 |
+
except:
|
317 |
+
continue
|
318 |
+
if results:
|
319 |
+
return results
|
320 |
+
except:
|
321 |
+
pass
|
322 |
+
|
323 |
+
return None
|
324 |
+
|
325 |
+
def generate_qa_from_pdf_chunk(self, chunk, num_questions=3, include_tags=True, difficulty_levels=True):
|
326 |
+
"""Generate Q&A pairs from a PDF text chunk."""
|
327 |
+
if not self.model or not self.tokenizer:
|
328 |
+
return [], "Error: Model not loaded properly. Please try again with a different model."
|
329 |
+
|
330 |
+
if not chunk or len(chunk.strip()) < 100: # Skip very small chunks
|
331 |
+
return [], "Chunk too small to generate meaningful Q&A pairs."
|
332 |
+
|
333 |
+
prompt = self.generate_qa_prompt(chunk, num_questions, include_tags, difficulty_levels)
|
334 |
+
raw_outputs = self.generate_data(prompt, num_samples=1)
|
335 |
+
raw_output = raw_outputs[0]
|
336 |
+
|
337 |
+
parsed_data = self.parse_json_data(raw_output)
|
338 |
+
|
339 |
+
# Ensure parsed data is a list
|
340 |
+
if parsed_data and isinstance(parsed_data, dict):
|
341 |
+
parsed_data = [parsed_data]
|
342 |
+
|
343 |
+
# Return both the parsed data and raw output for debugging
|
344 |
+
return parsed_data, raw_output
|
345 |
+
|
346 |
+
def format_data_preview(data):
|
347 |
+
"""Format the data for preview in the UI."""
|
348 |
+
if isinstance(data, list):
|
349 |
+
if len(data) > 0 and isinstance(data[0], dict):
|
350 |
+
# Convert list of dicts to DataFrame for better display
|
351 |
+
return pd.DataFrame(data).to_string()
|
352 |
+
else:
|
353 |
+
return json.dumps(data, indent=2)
|
354 |
+
elif isinstance(data, dict):
|
355 |
+
return json.dumps(data, indent=2)
|
356 |
+
else:
|
357 |
+
return str(data)
|
358 |
+
|
359 |
+
def save_data(data, format, filename_prefix):
|
360 |
+
"""Save data to a file in the specified format."""
|
361 |
+
os.makedirs("synthetic_data", exist_ok=True)
|
362 |
+
timestamp = pd.Timestamp.now().strftime("%Y%m%d_%H%M%S")
|
363 |
+
filename = f"synthetic_data/{filename_prefix}_{timestamp}"
|
364 |
+
|
365 |
+
if isinstance(data, list) and len(data) > 0 and isinstance(data[0], dict):
|
366 |
+
df = pd.DataFrame(data)
|
367 |
+
|
368 |
+
if format.lower() == "csv":
|
369 |
+
full_filename = f"{filename}.csv"
|
370 |
+
df.to_csv(full_filename, index=False)
|
371 |
+
elif format.lower() == "json":
|
372 |
+
full_filename = f"{filename}.json"
|
373 |
+
with open(full_filename, "w") as f:
|
374 |
+
json.dump(data, f, indent=2)
|
375 |
+
elif format.lower() == "excel":
|
376 |
+
full_filename = f"{filename}.xlsx"
|
377 |
+
df.to_excel(full_filename, index=False)
|
378 |
+
else:
|
379 |
+
full_filename = f"{filename}.txt"
|
380 |
+
with open(full_filename, "w") as f:
|
381 |
+
f.write(str(data))
|
382 |
+
else:
|
383 |
+
full_filename = f"{filename}.{format.lower()}"
|
384 |
+
with open(full_filename, "w") as f:
|
385 |
+
if format.lower() == "json":
|
386 |
+
json.dump(data, f, indent=2)
|
387 |
+
else:
|
388 |
+
f.write(str(data))
|
389 |
+
|
390 |
+
return full_filename
|
391 |
+
|
392 |
+
def load_models():
|
393 |
+
"""Return a list of available models."""
|
394 |
+
return [
|
395 |
+
"tiiuae/falcon-7b-instruct"
|
396 |
+
]
|
397 |
+
|
398 |
+
@spaces.GPU
|
399 |
+
def process_pdf_generate_qa(pdf_file, model_name, num_questions_per_chunk, include_tags, include_difficulty, output_file_format, progress=None):
|
400 |
+
"""Process a PDF file and generate Q&A pairs from its content."""
|
401 |
+
if pdf_file is None:
|
402 |
+
return None, "Error: No PDF file uploaded", "", "No file provided"
|
403 |
+
|
404 |
+
try:
|
405 |
+
# Check RAM usage at start
|
406 |
+
current_ram_usage = get_process_memory_usage()
|
407 |
+
print(f"Starting RAM usage: {current_ram_usage:.2f}GB")
|
408 |
+
|
409 |
+
# Clear CUDA cache before starting
|
410 |
+
if torch.cuda.is_available():
|
411 |
+
torch.cuda.empty_cache()
|
412 |
+
|
413 |
+
# Initialize extractor and generator
|
414 |
+
extractor = PdfExtractor()
|
415 |
+
generator = SyntheticDataGenerator(model_name)
|
416 |
+
|
417 |
+
# Wrap model loading in try-except to handle errors
|
418 |
+
try:
|
419 |
+
load_success = generator.load_model()
|
420 |
+
if not load_success:
|
421 |
+
return None, "Error: Failed to load the model. Please try again with a different model.", "", "Model loading failed"
|
422 |
+
except Exception as e:
|
423 |
+
if "ZeroGPU" in str(e) or "GPU task aborted" in str(e) or "CUDA" in str(e):
|
424 |
+
print(f"GPU error during model loading: {e}. Trying with a smaller model...")
|
425 |
+
# If we get a ZeroGPU error, immediately try the smallest model
|
426 |
+
generator.model_name = "tiiuae/falcon-7b-instruct" # Use default model as fallback
|
427 |
+
load_success = generator.load_model()
|
428 |
+
if not load_success:
|
429 |
+
return None, "Error: Failed to load any model even after fallback. Please try again later.", "", "Model loading failed"
|
430 |
+
else:
|
431 |
+
# Re-raise other errors
|
432 |
+
raise
|
433 |
+
|
434 |
+
# Check RAM usage after model loading
|
435 |
+
ram_after_model = get_process_memory_usage()
|
436 |
+
print(f"RAM usage after model loading: {ram_after_model:.2f}GB")
|
437 |
+
|
438 |
+
# Save PDF temporarily if it's a file object
|
439 |
+
if hasattr(pdf_file, 'name'):
|
440 |
+
# It's already a file path
|
441 |
+
pdf_path = pdf_file.name
|
442 |
+
else:
|
443 |
+
# Create a temporary file
|
444 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix='.pdf') as tmp:
|
445 |
+
tmp.write(pdf_file)
|
446 |
+
pdf_path = tmp.name
|
447 |
+
|
448 |
+
# Extract text from PDF
|
449 |
+
pdf_text = extractor.extract_text_from_pdf(pdf_path)
|
450 |
+
|
451 |
+
if not pdf_text:
|
452 |
+
return None, "Failed to extract text from PDF", "", "No data generated"
|
453 |
+
|
454 |
+
# Clean and chunk the text - reduce chunk size to use less memory
|
455 |
+
cleaned_text = extractor.clean_text(pdf_text)
|
456 |
+
chunks = extractor.chunk_text(cleaned_text, max_chunk_size=400, overlap=30)
|
457 |
+
|
458 |
+
# Check RAM after PDF processing
|
459 |
+
ram_after_pdf = get_process_memory_usage()
|
460 |
+
print(f"RAM usage after PDF processing: {ram_after_pdf:.2f}GB, found {len(chunks)} chunks")
|
461 |
+
|
462 |
+
# If we're approaching the RAM limit already, reduce batch size
|
463 |
+
batch_size = 3 # Default
|
464 |
+
if ram_after_pdf > MAX_RAM_GB * 0.7: # If already using 70% of our limit
|
465 |
+
batch_size = 1 # Process one chunk at a time
|
466 |
+
print(f"High RAM usage detected ({ram_after_pdf:.2f}GB), reducing batch size to 1")
|
467 |
+
elif ram_after_pdf > MAX_RAM_GB * 0.5: # If using 50% of our limit
|
468 |
+
batch_size = 2 # Process two chunks at a time
|
469 |
+
print(f"Moderate RAM usage detected ({ram_after_pdf:.2f}GB), reducing batch size to 2")
|
470 |
+
|
471 |
+
# Generate Q&A pairs for each chunk
|
472 |
+
all_qa_pairs = []
|
473 |
+
all_raw_outputs = []
|
474 |
+
|
475 |
+
total_chunks = len(chunks)
|
476 |
+
|
477 |
+
# Process chunks in smaller batches to avoid memory buildup
|
478 |
+
for i in range(0, total_chunks, batch_size):
|
479 |
+
# Get the current batch of chunks
|
480 |
+
batch_chunks = chunks[i:min(i+batch_size, total_chunks)]
|
481 |
+
|
482 |
+
# Process each chunk in the batch
|
483 |
+
for j, chunk in enumerate(batch_chunks):
|
484 |
+
chunk_index = i + j
|
485 |
+
|
486 |
+
if progress is not None:
|
487 |
+
progress(chunk_index / total_chunks, f"Processing chunk {chunk_index+1}/{total_chunks}")
|
488 |
+
|
489 |
+
# Check if we're approaching RAM limit
|
490 |
+
current_ram = get_process_memory_usage()
|
491 |
+
if current_ram > MAX_RAM_GB * 0.9: # Over 90% of our limit
|
492 |
+
print(f"WARNING: High RAM usage detected: {current_ram:.2f}GB - force releasing memory")
|
493 |
+
import gc
|
494 |
+
gc.collect() # Force garbage collection
|
495 |
+
if torch.cuda.is_available():
|
496 |
+
torch.cuda.empty_cache()
|
497 |
+
|
498 |
+
# If still too high after garbage collection, abort batch processing
|
499 |
+
current_ram = get_process_memory_usage()
|
500 |
+
if current_ram > MAX_RAM_GB * 0.95: # Still dangerously high
|
501 |
+
print(f"CRITICAL: RAM usage too high ({current_ram:.2f}GB), stopping processing")
|
502 |
+
break
|
503 |
+
|
504 |
+
# Clear CUDA cache between chunks
|
505 |
+
if torch.cuda.is_available():
|
506 |
+
torch.cuda.empty_cache()
|
507 |
+
|
508 |
+
try:
|
509 |
+
qa_pairs, raw_output = generator.generate_qa_from_pdf_chunk(
|
510 |
+
chunk,
|
511 |
+
num_questions=num_questions_per_chunk,
|
512 |
+
include_tags=include_tags,
|
513 |
+
difficulty_levels=include_difficulty
|
514 |
+
)
|
515 |
+
except Exception as e:
|
516 |
+
error_type = str(e)
|
517 |
+
if "CUDA" in error_type or "GPU" in error_type or "ZeroGPU" in error_type:
|
518 |
+
print(f"GPU error during generation for chunk {chunk_index+1}: {e}")
|
519 |
+
# Fall back to CPU for this specific generation
|
520 |
+
raw_output = f"Error in chunk {chunk_index+1}: {str(e)}. Skipping..."
|
521 |
+
qa_pairs = None
|
522 |
+
elif "memory" in error_type.lower() or "ram" in error_type.lower():
|
523 |
+
print(f"Memory error processing chunk {chunk_index+1}: {e}")
|
524 |
+
# Force garbage collection and skip chunk
|
525 |
+
import gc
|
526 |
+
gc.collect()
|
527 |
+
if torch.cuda.is_available():
|
528 |
+
torch.cuda.empty_cache()
|
529 |
+
raw_output = f"Memory error in chunk {chunk_index+1}: {str(e)}. Skipping..."
|
530 |
+
qa_pairs = None
|
531 |
+
else:
|
532 |
+
# For other errors, just log and continue
|
533 |
+
print(f"Error processing chunk {chunk_index+1}: {e}")
|
534 |
+
raw_output = f"Error in chunk {chunk_index+1}: {str(e)}"
|
535 |
+
qa_pairs = None
|
536 |
+
|
537 |
+
if qa_pairs:
|
538 |
+
all_qa_pairs.extend(qa_pairs)
|
539 |
+
all_raw_outputs.append(raw_output)
|
540 |
+
|
541 |
+
# Check RAM usage after processing this chunk
|
542 |
+
current_ram = get_process_memory_usage()
|
543 |
+
print(f"RAM after chunk {chunk_index+1}: {current_ram:.2f}GB")
|
544 |
+
|
545 |
+
# Do a thorough cleanup after each batch
|
546 |
+
if torch.cuda.is_available():
|
547 |
+
torch.cuda.empty_cache()
|
548 |
+
|
549 |
+
# Force garbage collection between batches
|
550 |
+
import gc
|
551 |
+
gc.collect()
|
552 |
+
|
553 |
+
# Check if we need to abort due to memory constraints
|
554 |
+
current_ram = get_process_memory_usage()
|
555 |
+
if current_ram > MAX_RAM_GB:
|
556 |
+
print(f"WARNING: Exceeding RAM limit ({current_ram:.2f}GB). Stopping further processing.")
|
557 |
+
if progress is not None:
|
558 |
+
progress(1.0, f"Stopped early due to high memory usage ({current_ram:.2f}GB)")
|
559 |
+
break
|
560 |
+
|
561 |
+
if progress is not None:
|
562 |
+
progress(1.0, "Finished processing")
|
563 |
+
|
564 |
+
# Final cache clear and garbage collection
|
565 |
+
if torch.cuda.is_available():
|
566 |
+
torch.cuda.empty_cache()
|
567 |
+
import gc
|
568 |
+
gc.collect()
|
569 |
+
|
570 |
+
if not all_qa_pairs:
|
571 |
+
return None, "Failed to generate Q&A pairs", "\n\n".join(all_raw_outputs), "No data generated"
|
572 |
+
|
573 |
+
# Save data to file
|
574 |
+
filename = save_data(
|
575 |
+
all_qa_pairs,
|
576 |
+
output_file_format,
|
577 |
+
"qa_dataset"
|
578 |
+
)
|
579 |
+
|
580 |
+
# Format for display
|
581 |
+
formatted_data = format_data_preview(all_qa_pairs)
|
582 |
+
|
583 |
+
# Final memory report
|
584 |
+
final_ram = get_process_memory_usage()
|
585 |
+
print(f"Final RAM usage: {final_ram:.2f}GB")
|
586 |
+
|
587 |
+
return all_qa_pairs, formatted_data, "\n\n".join(all_raw_outputs), f"Data saved to {filename}"
|
588 |
+
except Exception as e:
|
589 |
+
error_msg = f"Error processing PDF: {str(e)}"
|
590 |
+
print(error_msg)
|
591 |
+
import traceback
|
592 |
+
print(traceback.format_exc())
|
593 |
+
return None, error_msg, "", "Processing failed"
|
594 |
+
|
595 |
+
# Set up the Gradio interface
|
596 |
+
def create_interface():
|
597 |
+
with gr.Blocks(title="PDF Q&A Dataset Generator") as app:
|
598 |
+
gr.Markdown("# 📚 PDF Q&A Dataset Generator")
|
599 |
+
gr.Markdown("""
|
600 |
+
Generate question & answer datasets from PDF documents using instruction-tuned language models.
|
601 |
+
Perfect for creating educational resources, quiz materials, or training data for Q&A systems.
|
602 |
+
""")
|
603 |
+
|
604 |
+
with gr.Tabs() as tabs:
|
605 |
+
with gr.TabItem("Generate Q&A Dataset"):
|
606 |
+
with gr.Row():
|
607 |
+
with gr.Column(scale=1):
|
608 |
+
pdf_file = gr.File(
|
609 |
+
label="Upload PDF",
|
610 |
+
file_types=[".pdf"],
|
611 |
+
type="binary"
|
612 |
+
)
|
613 |
+
|
614 |
+
model_dropdown = gr.Dropdown(
|
615 |
+
choices=load_models(),
|
616 |
+
value=DEFAULT_MODEL,
|
617 |
+
label="Model"
|
618 |
+
)
|
619 |
+
|
620 |
+
num_questions = gr.Slider(
|
621 |
+
minimum=1,
|
622 |
+
maximum=5,
|
623 |
+
value=3,
|
624 |
+
step=1,
|
625 |
+
label="Questions per Section"
|
626 |
+
)
|
627 |
+
|
628 |
+
include_tags = gr.Checkbox(
|
629 |
+
value=True,
|
630 |
+
label="Include Tags"
|
631 |
+
)
|
632 |
+
|
633 |
+
include_difficulty = gr.Checkbox(
|
634 |
+
value=True,
|
635 |
+
label="Include Difficulty Levels"
|
636 |
+
)
|
637 |
+
|
638 |
+
output_file_format = gr.Radio(
|
639 |
+
choices=["json", "csv", "excel"],
|
640 |
+
value="json",
|
641 |
+
label="Save File Format"
|
642 |
+
)
|
643 |
+
|
644 |
+
generate_btn = gr.Button("Generate Q&A Dataset", variant="primary")
|
645 |
+
|
646 |
+
progress_bar = gr.Progress()
|
647 |
+
|
648 |
+
with gr.Column(scale=2):
|
649 |
+
with gr.Tab("Parsed Data"):
|
650 |
+
parsed_data_output = gr.JSON(label="Generated Q&A Pairs")
|
651 |
+
formatted_data_output = gr.Textbox(
|
652 |
+
label="Formatted Preview",
|
653 |
+
lines=15
|
654 |
+
)
|
655 |
+
|
656 |
+
with gr.Tab("Raw Output"):
|
657 |
+
raw_output = gr.Textbox(
|
658 |
+
label="Raw Model Output",
|
659 |
+
lines=15
|
660 |
+
)
|
661 |
+
|
662 |
+
file_output = gr.Textbox(label="File Output")
|
663 |
+
|
664 |
+
with gr.TabItem("Documentation"):
|
665 |
+
gr.Markdown("""
|
666 |
+
## How to Use
|
667 |
+
|
668 |
+
1. **Upload a PDF**: Select a PDF document containing the content you want to generate questions from.
|
669 |
+
2. **Select a model**: Choose an instruction-tuned language model from the dropdown.
|
670 |
+
3. **Configure settings**:
|
671 |
+
- Set the number of questions to generate per text section
|
672 |
+
- Choose whether to include tags and difficulty levels
|
673 |
+
- Select your preferred output file format
|
674 |
+
4. **Generate dataset**: Click the "Generate Q&A Dataset" button to create your dataset.
|
675 |
+
|
676 |
+
## About This App
|
677 |
+
|
678 |
+
This app uses instruction-tuned language models to generate question and answer pairs from PDF documents. It:
|
679 |
+
|
680 |
+
1. Extracts text from the uploaded PDF
|
681 |
+
2. Splits the text into manageable chunks
|
682 |
+
3. Generates questions, answers, tags, and difficulty levels for each chunk
|
683 |
+
4. Combines all Q&A pairs into a comprehensive dataset
|
684 |
+
|
685 |
+
### Features:
|
686 |
+
- Automatic text extraction from PDFs
|
687 |
+
- Smart text chunking to maintain context
|
688 |
+
- Customizable number of questions per chunk
|
689 |
+
- Optional tagging and difficulty classification
|
690 |
+
- Multiple output formats (JSON, CSV, Excel)
|
691 |
+
|
692 |
+
### Use Cases:
|
693 |
+
- Create educational resources and quiz materials
|
694 |
+
- Generate training data for Q&A systems
|
695 |
+
- Build flashcard datasets for studying
|
696 |
+
- Develop content for educational applications
|
697 |
+
""")
|
698 |
+
|
699 |
+
with gr.TabItem("Status"):
|
700 |
+
gr.Markdown("""
|
701 |
+
## System Status
|
702 |
+
|
703 |
+
This app runs on CPU mode. Some larger models might be slower to load and generate content.
|
704 |
+
If you encounter any issues with a specific model, try switching to a smaller model like `tiiuae/falcon-7b-instruct`.
|
705 |
+
|
706 |
+
### Troubleshooting
|
707 |
+
|
708 |
+
- If the app seems unresponsive after clicking "Generate", please be patient - model loading may take time.
|
709 |
+
- If you get an error about model loading, try refreshing the page and selecting a different model.
|
710 |
+
- Not all PDFs can be properly processed - if text extraction fails, try with a different PDF.
|
711 |
+
""")
|
712 |
+
|
713 |
+
# Event handler for generate button
|
714 |
+
generate_btn.click(
|
715 |
+
process_pdf_generate_qa,
|
716 |
+
inputs=[
|
717 |
+
pdf_file,
|
718 |
+
model_dropdown,
|
719 |
+
num_questions,
|
720 |
+
include_tags,
|
721 |
+
include_difficulty,
|
722 |
+
output_file_format
|
723 |
+
],
|
724 |
+
outputs=[parsed_data_output, formatted_data_output, raw_output, file_output],
|
725 |
+
show_progress=True
|
726 |
+
)
|
727 |
+
|
728 |
+
return app
|
729 |
+
|
730 |
+
# Export the app for Hugging Face Spaces
|
731 |
+
app = create_interface()
|
732 |
+
|
733 |
+
# Launch the app depending on the environment
|
734 |
+
if __name__ == "__main__":
|
735 |
+
app.launch()
|
736 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|