Update app.py
Browse files1 unmodified line2345678910111213141516171819202122232425262728293031323340 unmodified lines7475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117187 unmodified lines3053063073083093103113123133143153161 unmodified lineimport PyPDF2import reimport jsonfrom typing import List, Dict, Tuplefrom transformers import pipelineimport tempfileimport os# Initialize the question generation pipeline using a small CPU-friendly modelprint("Loading models... This may take a minute on first run.")qa_generator = pipeline("text2text-generation",model="valhalla/t5-small-qg-hl",tokenizer="valhalla/t5-small-qg-hl",device=-1 # Force CPU)def extract_text_from_pdf(pdf_file) -> str:"""Extract text from uploaded PDF file."""text = ""try:# Handle both file path and file objectif isinstance(pdf_file, str):pdf_reader = PyPDF2.PdfReader(pdf_file)else:pdf_reader = PyPDF2.PdfReader(pdf_file)for page in pdf_reader.pages:text += page.extract_text() + "\n"except Exception as e:return f"Error reading PDF: {str(e)}"40 unmodified linesflashcards = []# Skip chunks that are too shortif len(chunk.split()) < 20:return []try:# Generate highlight format for T5 question generation# We'll create simple highlight by taking key sentencessentences = chunk.split('. ')if len(sentences) < 2:return []# Generate questions for different parts of the chunkfor i in range(min(num_questions, len(sentences))):# Create highlight contexthighlight = sentences[i]context = chunk# Format for T5: "generate question: <hl> highlight <hl> context"input_text = f"generate question: <hl> {highlight} <hl> {context}"# Generate questionoutputs = qa_generator(input_text,max_length=128,num_return_sequences=1,do_sample=True,temperature=0.7)question = outputs[0]['generated_text'].strip()# Clean up questionquestion = re.sub(r'^(question:|q:)', '', question, flags=re.IGNORECASE).strip()if question and len(question) > 10:flashcards.append({"question": question,"answer": highlight.strip(),"context": context[:200] + "..." if len(context) > 200 else context})except Exception as e:187 unmodified linesgr.Markdown("*Raw JSON data for custom applications*")# Event handlersprocess_btn.click(fn=process_pdf,inputs=[pdf_input, questions_per_chunk, max_chunks],outputs=[status_text, csv_output, json_output]).then(fn=lambda x: x if not isinstance(x, str) or not x.startswith("π") else gr.update(),inputs=status_text,outputs=output_display)1 unmodified line234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757640 unmodified lines117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148187 unmodified lines3363373383393403413423433443453463473483493503513523531 unmodified lineimport PyPDF2import reimport jsonfrom typing import List, Dictfrom transformers import AutoTokenizer, AutoModelForSeq2SeqLMimport torchimport tempfileimport os# Initialize the model and tokenizer directlyprint("Loading models... This may take a minute on first run.")model_name = "valhalla/t5-small-qg-hl"tokenizer = AutoTokenizer.from_pretrained(model_name)model = AutoModelForSeq2SeqLM.from_pretrained(model_name)# Set to evaluation mode and CPUmodel.eval()device = torch.device("cpu")model.to(device)def generate_questions(context: str, answer: str, max_length: int = 128) -> str:"""Generate a question using T5 model."""try:# Format: "generate question: <hl> answer <hl> context"input_text = f"generate question: <hl> {answer} <hl> {context}"# Tokenizeinputs = tokenizer(input_text,return_tensors="pt",max_length=512,truncation=True,padding=True).to(device)# Generatewith torch.no_grad():outputs = model.generate(**inputs,max_length=max_length,num_beams=4,early_stopping=True,do_sample=True,temperature=0.7)# Decodequestion = tokenizer.decode(outputs[0], skip_special_tokens=True)# Clean upquestion = re.sub(r'^(question:|q:)', '', question, flags=re.IGNORECASE).strip()return question if len(question) > 10 else ""except Exception as e:print(f"Error generating question: {e}")return ""def extract_text_from_pdf(pdf_file) -> str:"""Extract text from uploaded PDF file."""text = ""try:if isinstance(pdf_file, str):pdf_reader = PyPDF2.PdfReader(pdf_file)else:pdf_reader = PyPDF2.PdfReader(pdf_file)for page in pdf_reader.pages:page_text = page.extract_text()if page_text:text += page_text + "\n"except Exception as e:return f"Error reading PDF: {str(e)}"40 unmodified linesflashcards = []# Skip chunks that are too shortwords = chunk.split()if len(words) < 20:return []try:# Split into sentences to use as answerssentences = [s.strip() for s in chunk.split('. ') if len(s.strip()) > 20]if len(sentences) < 1:return []# Generate questions for different sentencesfor i in range(min(num_questions, len(sentences))):answer = sentences[i]# Skip very short answersif len(answer.split()) < 3:continuequestion = generate_questions(chunk, answer)if question and question != answer: # Make sure they're differentflashcards.append({"question": question,"answer": answer,"context": chunk[:200] + "..." if len(chunk) > 200 else chunk})except Exception as e:187 unmodified linesgr.Markdown("*Raw JSON data for custom applications*")# Event handlersdef update_display(status):"""Update display when processing is done."""if status and not status.startswith(("π", "π§Ή", "βοΈ", "π΄", "β ")):return statusreturn gr.update()process_btn.click(fn=process_pdf,inputs=[pdf_input, questions_per_chunk, max_chunks],outputs=[status_text, csv_output, json_output]).then(fn=update_display,inputs=status_text,outputs=output_display)
app.py+76-39