File size: 11,950 Bytes
ebcc7d1 9a88738 ebcc7d1 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 | from fastapi import FastAPI, File, UploadFile, Form, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from typing import Optional, Any, Dict, Union
import shutil
import os
import json
from loguru import logger
from pathlib import Path
import tempfile
import numpy as np
from datetime import datetime
import base64
from io import BytesIO
from PIL import Image
from main import RenAITranscription
app = FastAPI(title="RenAI Transcription API", version="1.0.0")
# Add CORS middleware
# app.add_middleware(
# CORSMiddleware,
# allow_origins=["*"],
# allow_credentials=True,
# allow_methods=["*"],
# allow_headers=["*"],
# )
ALLOWED_EXTENSIONS = {".jpg", ".jpeg", ".png", ".bmp", ".tiff", ".webp"}
MAX_FILE_SIZE = 10 * 1024 * 1024 # 10MB
def numpy_to_base64(array: np.ndarray, format: str = 'PNG', quality: int = 85) -> str:
"""
Convert numpy array (image) to base64 encoded string for web display.
Args:
array: Numpy array representing the image
format: Image format ('PNG' or 'JPEG')
quality: JPEG quality (1-100), only used if format is JPEG
Returns:
Data URI string that can be directly used in HTML <img> src attribute
"""
try:
# Convert numpy array to PIL Image
img = Image.fromarray(array)
# Save to bytes buffer
buffer = BytesIO()
if format.upper() == 'JPEG':
# Convert to RGB if needed (JPEG doesn't support transparency)
if img.mode in ('RGBA', 'LA', 'P'):
background = Image.new('RGB', img.size, (255, 255, 255))
if img.mode == 'P':
img = img.convert('RGBA')
background.paste(img, mask=img.split()[-1] if img.mode in ('RGBA', 'LA') else None)
img = background
img.save(buffer, format='JPEG', quality=quality, optimize=True)
mime_type = 'image/jpeg'
else:
img.save(buffer, format='PNG', optimize=True)
mime_type = 'image/png'
# Encode to base64
img_str = base64.b64encode(buffer.getvalue()).decode('utf-8')
return f"data:{mime_type};base64,{img_str}"
except Exception as e:
logger.error(f"Error converting numpy array to base64: {e}")
return None
def format_transcription_result(result: Dict, include_images: bool = False, image_format: str = 'PNG') -> Dict[str, Any]:
"""
Format transcription result into a structured response.
Args:
result: Dictionary with line IDs as keys, each containing 'image' and 'transcription'
include_images: Whether to include base64 encoded images in response
image_format: Image format for base64 encoding ('PNG' or 'JPEG')
Returns:
Formatted dictionary with transcription data
"""
formatted_lines = {}
transcription_text = []
for line_id, line_data in result.items():
formatted_line = {
'line_id': line_id,
'transcription': line_data.get('transcription', '')
}
# Optionally include image as base64 (web-ready format)
if include_images and 'image' in line_data:
image_array = line_data['image']
if isinstance(image_array, np.ndarray):
image_base64 = numpy_to_base64(image_array, format=image_format)
if image_base64:
formatted_line['image'] = image_base64
formatted_lines[line_id] = formatted_line
transcription_text.append(f"{line_id}: {line_data.get('transcription', '')}")
return {
'lines': formatted_lines,
'full_text': '\n'.join(transcription_text),
'total_lines': len(result)
}
@app.get("/")
def home():
return {
"message": "Hello, RenAI!",
"version": "1.0.0",
"endpoints": {
"transcribe": "/renai-transcribe (POST)",
"transcribe_base64": "/renai-transcribe-base64 (POST)",
"health": "/health (GET)"
}
}
@app.post("/renai-transcribe")
async def transcription_endpoint(
image: UploadFile = File(..., description="Image file to transcribe"),
userToken: Optional[str] = Form(None, description="User authentication token"),
post_processing_enabled: bool = Form(False, description="Enable post-processing"),
unet_enabled: bool = Form(False, description="Enable UNet processing"),
include_images: bool = Form(True, description="Include base64 encoded line images in response"),
image_format: str = Form("JPEG", description="Image format for line images: PNG or JPEG")
):
"""
Upload an image file and get transcription results.
- **image**: Image file (JPG, PNG, BMP, TIFF, WebP)
- **userToken**: Optional user authentication token
- **post_processing_enabled**: Enable/disable post-processing
- **unet_enabled**: Enable/disable UNet processing
- **include_images**: Include base64 encoded images of each line (web-ready format)
- **image_format**: Format for line images: 'PNG' (higher quality, larger) or 'JPEG' (smaller, faster)
"""
start_time = datetime.now()
logger.info(f"Transcription request received for file: {image.filename} by userToken: {userToken if userToken else 'Anonymous'}")
# Validate file type
if not image.filename:
raise HTTPException(status_code=400, detail="No file provided")
file_extension = Path(image.filename).suffix.lower()
if file_extension not in ALLOWED_EXTENSIONS:
raise HTTPException(
status_code=400,
detail=f"Invalid file type. Allowed types: {', '.join(ALLOWED_EXTENSIONS)}"
)
# Check file size
if image.size and image.size > MAX_FILE_SIZE:
raise HTTPException(
status_code=400,
detail=f"File too large. Maximum size: {MAX_FILE_SIZE // (1024*1024)}MB"
)
temp_file_path = None
try:
# Create temporary file
with tempfile.NamedTemporaryFile(delete=False, suffix=file_extension) as temp_file:
shutil.copyfileobj(image.file, temp_file)
temp_file_path = temp_file.name
logger.info(f"Processing image: {temp_file_path}")
# Call transcription function
result = RenAITranscription(
image=temp_file_path,
post_processing_enabled=post_processing_enabled,
unet_enabled=unet_enabled
)
logger.info(f"Transcription completed. Result type: {type(result)}, Lines: {len(result)}")
# Format the result
formatted_result = format_transcription_result(result, include_images=include_images, image_format=image_format)
# Clean up
os.unlink(temp_file_path)
processing_time = (datetime.now() - start_time).total_seconds()
logger.info(f"Request completed in {processing_time:.2f}s")
response_data = {
"success": True,
"filename": image.filename,
"transcription": formatted_result,
"metadata": {
"processing_time_seconds": round(processing_time, 2),
"timestamp": datetime.now().isoformat(),
"total_lines": formatted_result['total_lines'],
"parameters": {
"post_processing_enabled": post_processing_enabled,
"unet_enabled": unet_enabled,
"include_images": include_images,
"userToken": userToken if userToken else "Anonymous"
}
}
}
return JSONResponse(content=response_data)
except Exception as e:
# Clean up
if temp_file_path and os.path.exists(temp_file_path):
try:
os.unlink(temp_file_path)
except:
pass
logger.error(f"Transcription failed: {e}")
raise HTTPException(
status_code=500,
detail={
"error": str(e),
"type": type(e).__name__
}
)
@app.post("/renai-transcribe-base64")
async def transcription_base64_endpoint(
image_data: str = Form(..., description="Base64 encoded image data"),
userToken: Optional[str] = Form(None, description="User authentication token"),
post_processing_enabled: bool = Form(False, description="Enable post-processing"),
unet_enabled: bool = Form(False, description="Enable UNet processing"),
include_images: bool = Form(False, description="Include base64 encoded line images in response"),
image_format: str = Form("JPEG", description="Image format for line images: PNG or JPEG")
):
"""
Alternative endpoint that accepts base64 encoded image data.
"""
import base64
import io
from PIL import Image
start_time = datetime.now()
logger.info(f"Base64 transcription request received by userToken: {userToken if userToken else 'Anonymous'}")
temp_file_path = None
try:
# Remove data URL prefix if present
if "," in image_data:
image_data = image_data.split(",", 1)[1]
# Decode base64 image
image_bytes = base64.b64decode(image_data)
image_pil = Image.open(io.BytesIO(image_bytes))
# Create temporary file
with tempfile.NamedTemporaryFile(delete=False, suffix=".png") as temp_file:
image_pil.save(temp_file.name)
temp_file_path = temp_file.name
logger.info(f"Processing base64 image: {temp_file_path}")
# Call transcription function
result = RenAITranscription(
image=temp_file_path,
post_processing_enabled=post_processing_enabled,
unet_enabled=unet_enabled
)
# Format the result
formatted_result = format_transcription_result(result, include_images=include_images, image_format=image_format)
# Clean up
os.unlink(temp_file_path)
processing_time = (datetime.now() - start_time).total_seconds()
logger.info(f"Base64 request completed in {processing_time:.2f}s")
response_data = {
"success": True,
"transcription": formatted_result,
"metadata": {
"processing_time_seconds": round(processing_time, 2),
"timestamp": datetime.now().isoformat(),
"total_lines": formatted_result['total_lines'],
"parameters": {
"post_processing_enabled": post_processing_enabled,
"unet_enabled": unet_enabled,
"include_images": include_images,
"image_format": image_format if include_images else None,
"userToken": userToken if userToken else "Anonymous"
}
}
}
return JSONResponse(content=response_data)
except Exception as e:
if temp_file_path and os.path.exists(temp_file_path):
try:
os.unlink(temp_file_path)
except:
pass
logger.error(f"Base64 transcription failed: {e}")
raise HTTPException(
status_code=500,
detail={
"error": str(e),
"type": type(e).__name__
}
)
@app.get("/health")
def health_check():
try:
return {
"status": "healthy",
"service": "RenAI Transcription API",
"timestamp": datetime.now().isoformat()
}
except Exception as e:
logger.error(f"Health check failed: {e}")
raise HTTPException(status_code=500, detail="Service unhealthy") |