| from fastapi import FastAPI, HTTPException |
| from fastapi.middleware.cors import CORSMiddleware |
| from pydantic import BaseModel |
| import base64 |
| import cv2 |
| import numpy as np |
| import random |
| import uvicorn |
|
|
| app = FastAPI() |
|
|
| |
| app.add_middleware( |
| CORSMiddleware, |
| allow_origins=["*"], |
| allow_credentials=True, |
| allow_methods=["*"], |
| allow_headers=["*"], |
| ) |
|
|
| |
| class ClientRequest(BaseModel): |
| message: str |
|
|
| |
| def generate_random_image_base64(): |
| |
| width, height = 400, 400 |
| img = np.zeros((height, width, 3), dtype=np.uint8) |
| |
| |
| bg_color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)) |
| img[:] = bg_color |
| |
| |
| for _ in range(5): |
| color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)) |
| thickness = random.choice([-1, 2, 4]) |
| |
| shape_type = random.choice(["circle", "rectangle"]) |
| if shape_type == "circle": |
| center = (random.randint(0, width), random.randint(0, height)) |
| radius = random.randint(20, 80) |
| cv2.circle(img, center, radius, color, thickness) |
| else: |
| pt1 = (random.randint(0, width), random.randint(0, height)) |
| pt2 = (random.randint(0, width), random.randint(0, height)) |
| cv2.rectangle(img, pt1, pt2, color, thickness) |
|
|
| |
| _, buffer = cv2.imencode('.jpg', img) |
| |
| |
| img_base64 = base64.b64encode(buffer).decode('utf-8') |
| return img_base64 |
|
|
| @app.post("/get_image_and_text") |
| def handle_unity_request(request: ClientRequest): |
| |
| if request.message.strip().lower() != "ok": |
| raise HTTPException(status_code=400, detail="Invalid message. Please send 'ok'.") |
| |
| |
| base64_image = generate_random_image_base64() |
| |
| |
| random_responses = [ |
| "Server received OK! Here is your lucky image.", |
| "System Status: Perfect. Image generated successfully.", |
| "Hello from Hugging Face! Processing done.", |
| "OK received. Sending custom 2D matrix back to Unity." |
| ] |
| selected_text = random.choice(random_responses) |
| |
| |
| return { |
| "status": "success", |
| "reply_text": selected_text, |
| "image_base64": base64_image |
| } |
|
|
| if __name__ == "__main__": |
| uvicorn.run(app, host="0.0.0.0", port=7860) |