Spaces:
Sleeping
Sleeping
Update app.py
Browse files1234562 unmodified lines910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182import jsonimport torchimport reimport gradio as grfrom transformers import T5Tokenizer, T5ForConditionalGeneration2 unmodified linestokenizer = T5Tokenizer.from_pretrained(model_name)model = T5ForConditionalGeneration.from_pretrained(model_name)# Move model to GPU if availabledevice = torch.device("cuda" if torch.cuda.is_available() else "cpu")model.to(device)# Enable optimizations for GPUif torch.cuda.is_available():model.half() # Use half-precision for faster computationtry:model = torch.compile(model) # PyTorch 2.0+ optimizationexcept Exception:pass # Ignore if torch.compile is not availabledef correct_amount_format(output):"""This function attempts to fix the numeric formatting issues in the generated output:1. It replaces a comma used as a decimal separator (i.e. followed by exactly two digits) with a period.2. It converts the number to a float and rounds it to two decimal places.If the output is valid JSON, it will update the "amount" field accordingly.Otherwise, it falls back to a regex-based fix."""try:# Try to parse the output as JSONdata = json.loads(output)if "amount" in data and isinstance(data["amount"], str):# Replace a comma that is likely a decimal separator (e.g., "10,50" -> "10.50")amount_str = re.sub(r'(\d+),(\d{2})\b', r'\1.\2', data["amount"])try:# Convert to float, round to two decimals, then reformatnum = float(amount_str)rounded = round(num, 2)data["amount"] = "{:.2f}".format(rounded)except ValueError:# If conversion fails, leave the original valuepassreturn json.dumps(data, ensure_ascii=False)except json.JSONDecodeError:# Fallback if output is not valid JSON:# Replace commas used as decimal separators (only if followed by exactly 2 digits)output = re.sub(r'(\d+),(\d{2})\b', r'\1.\2', output)# Fallback: truncate any extra digits (note: this does not round)output = re.sub(r'(\d+\.\d{2})\d+', r'\1', output)return outputdef generate_command(input_command):prompt = "extract: " + input_commandinput_ids = tokenizer(prompt, return_tensors="pt").input_ids.to(device)output_ids = model.generate(input_ids,max_length=64, # Reduced for speednum_beams=3, # Lowered from 5 to 3 for faster outputearly_stopping=True)result = tokenizer.decode(output_ids[0], skip_special_tokens=True)# Apply the updated post-processing to correct the amount formattingresult = correct_amount_format(result)return result# Create a Gradio interfaceiface = gr.Interface(fn=generate_command,inputs=gr.Textbox(lines=2, placeholder="Enter a command..."),outputs=gr.Textbox(label="Extracted JSON Output"),title="T5 Fine-Tuned Command Extractor",description="Enter a command, and the fine-tuned T5 model will extract relevant details in JSON format.",)if __name__ == "__main__":iface.launch()1234562 unmodified lines910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273import jsonimport reimport torchimport gradio as grfrom transformers import T5Tokenizer, T5ForConditionalGeneration2 unmodified linestokenizer = T5Tokenizer.from_pretrained(model_name)model = T5ForConditionalGeneration.from_pretrained(model_name)device = torch.device("cuda" if torch.cuda.is_available() else "cpu")model.to(device)if torch.cuda.is_available():model.half()try:model = torch.compile(model)except:passdef correct_amount_format(output):# Attempt to parse as JSON and correct amountstry:data = json.loads(output)def correct_value(value):if isinstance(value, str):# Remove commas used as thousand separatorsvalue = re.sub(r',(?=\d{3})', '', value)# Replace the first comma with a period (decimal)value = value.replace(',', '.', 1)return value# Correct each value in the JSON dataif isinstance(data, dict):for key in data:data[key] = correct_value(data[key])elif isinstance(data, list):for i in range(len(data)):data[i] = correct_value(data[i])return json.dumps(data, ensure_ascii=False)except json.JSONDecodeError:# Fallback for invalid JSON: basic correctionsoutput = re.sub(r'(\d+),(\d+)\b', r'\1.\2', output)return outputdef generate_command(input_command):prompt = "extract: " + input_commandinput_ids = tokenizer(prompt, return_tensors="pt").input_ids.to(device)output_ids = model.generate(input_ids,max_length=64,num_beams=3,early_stopping=True)result = tokenizer.decode(output_ids[0], skip_special_tokens=True)result = correct_amount_format(result)return resultiface = gr.Interface(fn=generate_command,inputs=gr.Textbox(lines=2, placeholder="Enter a command..."),outputs=gr.Textbox(label="Extracted JSON Output"),title="T5 Fine-Tuned Command Extractor",description="Extracts details in JSON format with exact amount preservation.",)if __name__ == "__main__":iface.launch()
app.py+31-40