GenAI-Arena / serve /log_server.py
tianleliphoebe's picture
Reinitialize
e368cec
raw
history blame
1.59 kB
from fastapi import FastAPI, File, UploadFile, Form, APIRouter
from typing import Optional
import json
import os
import aiofiles
from .log_utils import build_logger
from .constants import LOG_SERVER_SUBDOAMIN, APPEND_JSON, SAVE_IMAGE
logger = build_logger("log_server", "log_server.log")
app = APIRouter(prefix=f"/{LOG_SERVER_SUBDOAMIN}")
@app.post(f"/{APPEND_JSON}")
async def append_json(json_str: str = Form(...), file_name: str = Form(...)):
"""
Appends a JSON string to a specified file.
"""
# Convert the string back to a JSON object (dict)
data = json.loads(json_str)
# Append the data to the specified file
os.makedirs(os.path.dirname(file_name), exist_ok=True)
async with aiofiles.open(file_name, mode='a') as f:
await f.write(json.dumps(data) + "\n")
logger.info(f"Appended 1 JSON object to {file_name}")
return {"message": "JSON data appended successfully"}
@app.post(f"/{SAVE_IMAGE}")
async def save_image(image: UploadFile = File(...), image_path: str = Form(...)):
"""
Saves an uploaded image to the specified path.
"""
# Note: 'image_path' should include the file name and extension for the image to be saved.
os.makedirs(os.path.dirname(image_path), exist_ok=True)
async with aiofiles.open(image_path, mode='wb') as f:
content = await image.read() # Read the content of the uploaded image
await f.write(content) # Write the image content to a file
logger.info(f"Image saved successfully at {image_path}")
return {"message": f"Image saved successfully at {image_path}"}