Spaces:
Runtime error
Runtime error
Update app.py
Browse files1123413 unmodified lines1819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364272829303132333435363738394041424344454647484950515253545556575859606162636465666768696566676869707172737475767778798081828373848586878889from fastapi import FastAPI, HTTPExceptionfrom fastapi import FastAPIfrom pydantic import BaseModelimport tensorflow as tfimport sentencepiece as spm13 unmodified linesoutput_details = interpreter.get_output_details()max_len = input_details[0]['shape'][1]
def run_inference(text: str) -> bool: """Run the model on a single text and return True if toxic.""" tokens = [0] + sp.encode_as_ids(text) + [2]
if len(tokens) > max_len: tokens = tokens[:max_len] tokens[-1] = 2 else: tokens = tokens + [1] * (max_len - len(tokens))
for i, detail in enumerate(input_details): shape = detail['shape'] dtype = detail['dtype'] input_data = np.zeros(shape, dtype=dtype)
if shape[1] == max_len: if 'mask' in detail['name'].lower(): mask = [1] * min(len(sp.encode_as_ids(text)) + 2, max_len) mask += [0] * (max_len - len(mask)) input_data[0] = np.array(mask, dtype=dtype) elif 'type' in detail['name'].lower(): pass else: input_data[0] = np.array(tokens, dtype=dtype)
interpreter.set_tensor(detail['index'], input_data)
interpreter.invoke() output_data = interpreter.get_tensor(output_details[0]['index'])
if output_data.shape[-1] == 2: return bool(output_data[0][1] > 0.5) else: return bool(output_data[0][0] > 0.5)
class TextRequest(BaseModel): text: str
@app.post("/predict")def predict(request: TextRequest): try: # Tokenize text tokens = [0] + sp.encode_as_ids(request.text) + [2] if len(tokens) > max_len: tokens = tokens[:max_len] tokens[-1] = 2 else: tokens = tokens + [1] * (max_len - len(tokens)) # Initialize inputs safely matching the model's expected dtype and shape for i, detail in enumerate(input_details): shape = detail['shape'] dtype = detail['dtype'] # Create a zero array matching the shape input_data = np.zeros(shape, dtype=dtype) # If it expects an input of sequence length, fill it with our tokens/masks if shape[1] == max_len: if 'mask' in detail['name'].lower(): # Attention mask: 1 for tokens, 0 for padding mask = [1] * min(len(sp.encode_as_ids(request.text)) + 2, max_len) mask += [0] * (max_len - len(mask)) input_data[0] = np.array(mask, dtype=dtype) elif 'type' in detail['name'].lower(): # Token type ids (all 0s) pass else: # Assume it's input_ids input_data[0] = np.array(tokens, dtype=dtype) interpreter.set_tensor(detail['index'], input_data) interpreter.invoke() output_data = interpreter.get_tensor(output_details[0]['index']) if output_data.shape[-1] == 2: is_toxic = bool(output_data[0][1] > 0.5) else: is_toxic = bool(output_data[0][0] > 0.5) return {"is_toxic": is_toxic} text = request.text
# Test multiple casing variations against the model. # If ANY variation is toxic, we flag the whole text. variations = set() variations.add(text) # Original: "Fuck you" variations.add(text.lower()) # Lowercase: "fuck you" variations.add(text.upper()) # Uppercase: "FUCK YOU" variations.add(text.capitalize()) # Capitalize: "Fuck you" variations.add(text.title()) # Title: "Fuck You"
for variant in variations: if run_inference(variant): return {"is_toxic": True}
return {"is_toxic": False} except Exception as e: error_msg = traceback.format_exc() print(error_msg) # We return the exact error to Flutter so we can see what went wrong if it fails again return {"is_toxic": False, "error": error_msg}
@app.get("/")def read_root(): return {"status": "Toxic API is running!"}app.py+56-45