Handwriting_Model_Inf / handwriting_api.py
3morrrrr's picture
Upload 14 files
569596a verified
from fastapi import FastAPI as FastAPIApp, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
import uvicorn
import os
from hand import Hand
from typing import List, Optional
app = FastAPIApp()
hand = Hand()
class InputData(BaseModel):
text: str
bias: Optional[float] = 0.75
style: Optional[int] = 9
stroke_colors: Optional[List[str]] = ['black']
stroke_widths: Optional[List[float]] = [2]
def validate_input(data: InputData):
if len(data.text) > 75:
raise ValueError("Text must be 75 characters or less")
if not (0.5 <= data.bias <= 1.0):
raise ValueError("Bias must be between 0.5 and 1.0")
if not (0 <= data.style <= 12):
raise ValueError("Style must be between 0 and 12")
if len(data.stroke_colors) != len(data.text.split('\n')):
raise ValueError("Number of stroke colors must match number of lines")
if len(data.stroke_widths) != len(data.text.split('\n')):
raise ValueError("Number of stroke widths must match number of lines")
@app.post("/synthesize")
def synthesize(data: InputData):
try:
validate_input(data)
lines = data.text.split('\n')
biases = [data.bias] * len(lines)
styles = [data.style] * len(lines)
hand.write(
filename='img/output.svg',
lines=lines,
biases=biases,
styles=styles,
stroke_colors=data.stroke_colors,
stroke_widths=data.stroke_widths
)
return {"result": "Handwriting synthesized successfully", "output_file": "img/output.svg"}
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e))
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=8000)