GenAI-Arena / serve /log_server.py
tianleliphoebe's picture
add video model
944dd2b
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_SUBDOMAIN, APPEND_JSON, SAVE_IMAGE, SAVE_VIDEO, SAVE_LOG
logger = build_logger("log_server", "log_server.log", add_remote_handler=False)
app = APIRouter(prefix=LOG_SERVER_SUBDOMAIN)
@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
if os.path.dirname(file_name):
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.
if os.path.dirname(image_path):
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}"}
@app.post(f"/{SAVE_VIDEO}")
async def save_video(video: UploadFile = File(...), video_path: str = Form(...)):
"""
Saves an uploaded video to the specified path.
"""
# Note: 'video_path' should include the file name and extension for the video to be saved.
if os.path.dirname(video_path):
os.makedirs(os.path.dirname(video_path), exist_ok=True)
async with aiofiles.open(video_path, mode='wb') as f:
content = await video.read() # Read the content of the uploaded video
await f.write(content) # Write the video content to a file
logger.info(f"Video saved successfully at {video_path}")
return {"message": f"Image saved successfully at {video_path}"}
@app.post(f"/{SAVE_LOG}")
async def save_log(message: str = Form(...), log_path: str = Form(...)):
"""
Save a log message to a specified log file on the server.
"""
# Ensure the directory for the log file exists
if os.path.dirname(log_path):
os.makedirs(os.path.dirname(log_path), exist_ok=True)
# Append the log message to the specified log file
async with aiofiles.open(log_path, mode='a') as f:
await f.write(f"{message}\n")
logger.info(f"Romote log message saved to {log_path}")
return {"message": f"Log message saved successfully to {log_path}"}