Spaces:
Sleeping
Sleeping
Update app.py
Browse files17 unmodified lines181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071724 unmodified lines77787980818217 unmodified linesmodel.half() # Use half-precision for faster computationtry:model = torch.compile(model) # PyTorch 2.0+ optimizationexcept:pass # Ignore if torch.compile is not availabledef sanitize_amount(output):"""Sanitizes the amount field to ensure it is correctly formatted."""# Fix malformed amounts like "46307.0" -> "4630.07" or "4630327.0" -> "463032.07"def fix_malformed_amount(match):full_match = match.group(0)integer_part = match.group(1)decimal_part = match.group(2)return f"{integer_part}.{decimal_part}" # Reconstruct the correct format# Match numbers with misplaced decimal pointsoutput = re.sub(r'(\d+)(\d{2})\.0', fix_malformed_amount, output)return outputdef generate_command(input_command):"""Generates the command and ensures the exact amount is displayed without changes."""prompt = "extract: " + input_commandinput_ids = tokenizer(prompt, return_tensors="pt").input_ids.to(device)# Generate output from the modeloutput_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)# Sanitize the output to fix malformed amountssanitized_result = sanitize_amount(result)try:# Attempt to parse the sanitized result as JSONdata = json.loads(sanitized_result)# Convert numeric amounts to strings to preserve exact formattingif isinstance(data.get("amount"), (int, float)):data["amount"] = str(data["amount"])return json.dumps(data, ensure_ascii=False) # Return as JSON stringexcept json.JSONDecodeError:# If not valid JSON, return the raw sanitized outputreturn sanitized_result# Create a Gradio interfaceiface = gr.Interface(4 unmodified linesdescription="Enter a command, and the fine-tuned T5 model will extract relevant details in JSON format.",)# Launch the appif __name__ == "__main__":iface.launch()17 unmodified lines18192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172734 unmodified lines787980818217 unmodified linesmodel.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(4 unmodified linesdescription="Enter a command, and the fine-tuned T5 model will extract relevant details in JSON format.",)if __name__ == "__main__":iface.launch()
app.py+36-36