Update app.py
Browse files1 unmodified line2345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576771 unmodified line7980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201 unmodified lineimport loggingimport osimport reimport spacesimport torchfrom cleantext import cleanimport gradio as grfrom tqdm.auto import tqdmfrom transformers import pipelinefrom transformers import AutoModelForSequenceClassification, AutoTokenizerlogging.basicConfig(level=logging.INFO)logging.info(f"torch version:\t{torch.__version__}")device = 0 if torch.cuda.is_available() else -1checker = pipeline("text-classification",model=checker_model_name,device=device, # แก้จาก device_map="cuda" เป็น device)corrector = pipeline("text2text-generation",model=corrector_model_name,device=device, # แก้จาก device_map="cuda" เป็น device)corrector = pipeline("text2text-generation",corrector_model_name,device_map="cuda",)def split_text(text: str) -> list:# Split the text into sentences using regexsentences = re.split(r"(?<=[^A-Z].[.?]) +(?=[A-Z])", text)# Initialize lists for batchingsentence_batches = []temp_batch = []# Create batches of 2-3 sentencesfor sentence in sentences:temp_batch.append(sentence)if len(temp_batch) >= 2 and len(temp_batch) <= 3 or sentence == sentences[-1]:sentence_batches.append(temp_batch)temp_batch = []return sentence_batchesdef correct_text(text: str, separator: str = " ") -> str:# Split the text into sentence batchessentence_batches = split_text(text)# Initialize a list to store the corrected textcorrected_text = []# Process each batchfor batch in tqdm(sentence_batches, total=len(sentence_batches), desc="correcting text.."):raw_text = " ".join(batch)# Check grammar qualityresults = checker(raw_text)# Correct text if neededif results[0]["label"] != "LABEL_1" or (results[0]["label"] == "LABEL_1" and results[0]["score"] < 0.9):1 unmodified linecorrected_text.append(corrected_batch[0]["generated_text"])else:corrected_text.append(raw_text)# Join the corrected textreturn separator.join(corrected_text)def update(text: str):# Clean and truncate input texttext = clean(text[:4000], lower=False)return correct_text(text)# Create the Gradio interfacewith gr.Blocks() as demo:gr.Markdown("# <center>Robust Grammar Correction with FLAN-T5</center>")gr.Markdown("**Instructions:** Enter the text you want to correct in the textbox below (_text will be truncated to 4000 characters_). Click 'Process' to run.")gr.Markdown("""Models:- `textattack/roberta-base-CoLA` for grammar quality detection- `pszemraj/flan-t5-large-grammar-synthesis` for grammar correction""")with gr.Row():inp = gr.Textbox(label="input",placeholder="Enter text to check & correct",value="I wen to the store yesturday to bye some food. I needd milk, bread, and a few otter things. The store was really crowed and I had a hard time finding everyting I needed. I finaly made it to the check out line and payed for my stuff.",)out = gr.Textbox(label="output", interactive=False)btn = gr.Button("Process")btn.click(fn=update, inputs=inp, outputs=out)gr.Markdown("---")gr.Markdown("- See the [model card](https://huggingface.co/pszemraj/flan-t5-large-grammar-synthesis) for more info")# Launch the demodemo.launch(debug=True)1 unmodified line2345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455561 unmodified line585960616263646566676869707172737475761 unmodified lineimport loggingimport osimport reimport torchfrom cleantext import cleanimport gradio as grfrom tqdm.auto import tqdmfrom transformers import pipelinelogging.basicConfig(level=logging.INFO)logging.info(f"torch version:\t{torch.__version__}")# --- 1. ต้องประกาศชื่อ Model ไว้ตรงนี้ก่อน (ห้ามย้ายไปไว้ข้างล่าง) ---checker_model_name = "textattack/roberta-base-CoLA"corrector_model_name = "pszemraj/flan-t5-large-grammar-synthesis"# --- 2. เช็ค Device (ป้องกัน RuntimeError เรื่อง NVIDIA) ---device = 0 if torch.cuda.is_available() else -1logging.info(f"Using device: {'cuda' if device == 0 else 'cpu'}")# --- 3. สร้าง Pipeline (ดึงตัวแปรจากข้อ 1 มาใช้) ---checker = pipeline("text-classification",model=checker_model_name,device=device,)corrector = pipeline("text2text-generation",model=corrector_model_name,device=device,)# --- ฟังก์ชันการทำงานอื่นๆ ---def split_text(text: str) -> list:sentences = re.split(r"(?<=[^A-Z].[.?]) +(?=[A-Z])", text)sentence_batches = []temp_batch = []for sentence in sentences:temp_batch.append(sentence)if (len(temp_batch) >= 2 and len(temp_batch) <= 3) or sentence == sentences[-1]:sentence_batches.append(temp_batch)temp_batch = []return sentence_batchesdef correct_text(text: str, separator: str = " ") -> str:sentence_batches = split_text(text)corrected_text = []for batch in tqdm(sentence_batches, desc="correcting text.."):raw_text = " ".join(batch)results = checker(raw_text)# ตรวจสอบคุณภาพไวยากรณ์if results[0]["label"] != "LABEL_1" or (results[0]["label"] == "LABEL_1" and results[0]["score"] < 0.9):1 unmodified linecorrected_text.append(corrected_batch[0]["generated_text"])else:corrected_text.append(raw_text)return separator.join(corrected_text)def update(text: str):text = clean(text[:4000], lower=False)return correct_text(text)# --- 4. Interface ---with gr.Blocks() as demo:gr.Markdown("# <center>Robust Grammar Correction</center>")with gr.Row():inp = gr.Textbox(label="Input", placeholder="Enter text here...")out = gr.Textbox(label="Output", interactive=False)btn = gr.Button("Process")btn.click(fn=update, inputs=inp, outputs=out)demo.launch()
app.py+19-63