Spaces:
Sleeping
Sleeping
Store generated content metadata in sofia-rivera-gallery dataset automatically
Browse files- api_wrapper.py +54 -155
api_wrapper.py
CHANGED
|
@@ -1,6 +1,6 @@
|
|
| 1 |
"""
|
| 2 |
Sofia AI API Wrapper - FastAPI REST API
|
| 3 |
-
Integración completa para n8n y
|
| 4 |
"""
|
| 5 |
|
| 6 |
from fastapi import FastAPI, HTTPException, Header, Depends
|
|
@@ -8,45 +8,31 @@ from fastapi.middleware.cors import CORSMiddleware
|
|
| 8 |
from pydantic import BaseModel
|
| 9 |
from typing import Optional, List, Dict
|
| 10 |
import os
|
|
|
|
|
|
|
|
|
|
| 11 |
from generation import generate_image_from_prompt
|
| 12 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
# Crear instancia de FastAPI
|
| 14 |
app = FastAPI(
|
| 15 |
title="Sofia AI API",
|
| 16 |
-
description="API REST
|
| 17 |
-
version="1.
|
| 18 |
)
|
| 19 |
|
| 20 |
-
# Configurar CORS para permitir llamadas desde n8n
|
| 21 |
app.add_middleware(
|
| 22 |
CORSMiddleware,
|
| 23 |
-
allow_origins=["*"],
|
| 24 |
allow_credentials=True,
|
| 25 |
allow_methods=["*"],
|
| 26 |
allow_headers=["*"],
|
| 27 |
)
|
| 28 |
|
| 29 |
-
# Modelos
|
| 30 |
-
class ImageGenerationRequest(BaseModel):
|
| 31 |
-
prompt: str
|
| 32 |
-
style: str = "lifestyle"
|
| 33 |
-
model_name: str = "SG161222/RealVisXL_V4.0_Lightning"
|
| 34 |
-
|
| 35 |
-
class ImageGenerationResponse(BaseModel):
|
| 36 |
-
success: bool
|
| 37 |
-
image_path: Optional[str]
|
| 38 |
-
message: str
|
| 39 |
-
|
| 40 |
-
class ContentRequest(BaseModel):
|
| 41 |
-
topic: str
|
| 42 |
-
platform: str
|
| 43 |
-
tone: str = "engaging"
|
| 44 |
-
|
| 45 |
-
class ContentResponse(BaseModel):
|
| 46 |
-
success: bool
|
| 47 |
-
content: str
|
| 48 |
-
platform: str
|
| 49 |
-
|
| 50 |
class WorkflowRequest(BaseModel):
|
| 51 |
topic: str
|
| 52 |
platform: str
|
|
@@ -57,10 +43,9 @@ class WorkflowResponse(BaseModel):
|
|
| 57 |
success: bool
|
| 58 |
content: str
|
| 59 |
image_path: Optional[str]
|
| 60 |
-
|
| 61 |
-
suggestions: List[str]
|
| 62 |
|
| 63 |
-
# Autenticación
|
| 64 |
API_KEY = os.getenv("SOFIA_API_KEY", "sofia_dev_key_2026")
|
| 65 |
|
| 66 |
def verify_api_key(x_api_key: str = Header(None)):
|
|
@@ -68,134 +53,48 @@ def verify_api_key(x_api_key: str = Header(None)):
|
|
| 68 |
raise HTTPException(status_code=401, detail="API Key inválida")
|
| 69 |
return x_api_key
|
| 70 |
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
@app.get("/")
|
| 76 |
-
def root():
|
| 77 |
-
return {
|
| 78 |
-
"message": "Sofia AI API - Sistema Multi-Agente",
|
| 79 |
-
"version": "1.0.0",
|
| 80 |
-
"endpoints": {
|
| 81 |
-
"health": "/health",
|
| 82 |
-
"image_generate": "/api/v1/image/generate",
|
| 83 |
-
"content_create": "/api/v1/content/create",
|
| 84 |
-
"workflow_complete": "/api/v1/workflow/complete"
|
| 85 |
-
},
|
| 86 |
-
"docs": "/docs"
|
| 87 |
-
}
|
| 88 |
-
|
| 89 |
-
@app.get("/health")
|
| 90 |
-
def health_check():
|
| 91 |
-
"""Endpoint de salud para monitoreo"""
|
| 92 |
-
return {
|
| 93 |
-
"status": "healthy",
|
| 94 |
-
"service": "sofia-ai-api",
|
| 95 |
-
"timestamp": "2026-02-09T22:00:00Z"
|
| 96 |
-
}
|
| 97 |
-
|
| 98 |
-
@app.post("/api/v1/image/generate", response_model=ImageGenerationResponse)
|
| 99 |
-
def generate_image(
|
| 100 |
-
request: ImageGenerationRequest,
|
| 101 |
-
api_key: str = Depends(verify_api_key)
|
| 102 |
-
):
|
| 103 |
-
"""
|
| 104 |
-
Genera una imagen de Sofia Rivera usando HuggingFace API
|
| 105 |
-
|
| 106 |
-
- **prompt**: Descripción de la imagen a generar
|
| 107 |
-
- **style**: Estilo (lifestyle, fitness, fashion, beach, Personalizado)
|
| 108 |
-
- **model_name**: Modelo a usar (por defecto RealVisXL)
|
| 109 |
-
"""
|
| 110 |
-
try:
|
| 111 |
-
# Base de Sofia para consistencia
|
| 112 |
-
sofia_base = "Professional portrait of Sofia Rivera, a beautiful 25yo Spanish-Latina woman, hazel eyes, wavy dark chocolate hair, sun-kissed skin, highly detailed, 8k, instagram style, "
|
| 113 |
-
|
| 114 |
-
# Construir prompt completo
|
| 115 |
-
if request.style == "Personalizado":
|
| 116 |
-
full_prompt = sofia_base + request.prompt
|
| 117 |
-
else:
|
| 118 |
-
full_prompt = sofia_base + request.style
|
| 119 |
-
|
| 120 |
-
# Generar imagen
|
| 121 |
-
img_path, status = generate_image_from_prompt(
|
| 122 |
-
prompt=full_prompt,
|
| 123 |
-
model_name=request.model_name
|
| 124 |
-
)
|
| 125 |
-
|
| 126 |
-
if img_path:
|
| 127 |
-
return ImageGenerationResponse(
|
| 128 |
-
success=True,
|
| 129 |
-
image_path=img_path,
|
| 130 |
-
message=status
|
| 131 |
-
)
|
| 132 |
-
else:
|
| 133 |
-
return ImageGenerationResponse(
|
| 134 |
-
success=False,
|
| 135 |
-
image_path=None,
|
| 136 |
-
message=status
|
| 137 |
-
)
|
| 138 |
-
|
| 139 |
-
except Exception as e:
|
| 140 |
-
raise HTTPException(status_code=500, detail=f"Error generando imagen: {str(e)}")
|
| 141 |
-
|
| 142 |
-
@app.post("/api/v1/content/create", response_model=ContentResponse)
|
| 143 |
-
def create_content(
|
| 144 |
-
request: ContentRequest,
|
| 145 |
-
api_key: str = Depends(verify_api_key)
|
| 146 |
-
):
|
| 147 |
-
"""
|
| 148 |
-
Crea contenido para redes sociales
|
| 149 |
|
| 150 |
-
- **topic**: Tema del contenido
|
| 151 |
-
- **platform**: Plataforma (Instagram, Twitter, LinkedIn, TikTok)
|
| 152 |
-
- **tone**: Tono del contenido (engaging, professional, casual, inspirational)
|
| 153 |
-
"""
|
| 154 |
try:
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
"linkedin": f"Professional insight on {request.topic}\n\nIn today's digital landscape, {request.topic} is becoming increasingly important.\n\n#ProfessionalDevelopment #{request.topic.replace(' ', '')}",
|
| 159 |
-
"tiktok": f"🎬 Video idea: {request.topic}\n\nHook: Did you know about {request.topic}?\nContent: [Engaging explanation]\nCTA: Follow for more!\n\n#{request.topic.replace(' ', '')} #Viral"
|
| 160 |
-
}
|
| 161 |
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
f"Content about {request.topic} for {request.platform}"
|
| 165 |
-
)
|
| 166 |
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
|
|
|
|
|
|
|
|
|
| 171 |
)
|
| 172 |
-
|
| 173 |
except Exception as e:
|
| 174 |
-
|
| 175 |
|
| 176 |
@app.post("/api/v1/workflow/complete", response_model=WorkflowResponse)
|
| 177 |
def complete_workflow(
|
| 178 |
request: WorkflowRequest,
|
| 179 |
api_key: str = Depends(verify_api_key)
|
| 180 |
):
|
| 181 |
-
"""
|
| 182 |
-
Workflow completo: Genera contenido + imagen en un solo paso
|
| 183 |
-
Perfecto para integración con n8n
|
| 184 |
-
|
| 185 |
-
- **topic**: Tema
|
| 186 |
-
- **platform**: Plataforma de destino
|
| 187 |
-
- **style**: Estilo de imagen
|
| 188 |
-
- **tone**: Tono del contenido
|
| 189 |
-
"""
|
| 190 |
try:
|
| 191 |
# 1. Crear contenido
|
| 192 |
content_templates = {
|
| 193 |
-
"instagram": f"✨ {request.topic} ✨
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 197 |
}
|
| 198 |
-
|
| 199 |
content = content_templates.get(request.platform.lower(), f"Content: {request.topic}")
|
| 200 |
|
| 201 |
# 2. Generar imagen
|
|
@@ -204,29 +103,29 @@ def complete_workflow(
|
|
| 204 |
|
| 205 |
img_path, status = generate_image_from_prompt(prompt=full_prompt)
|
| 206 |
|
| 207 |
-
# 3.
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
|
|
|
|
|
|
|
|
|
| 214 |
|
| 215 |
-
|
| 216 |
-
suggestions.append("💡 Add relevant hashtags")
|
| 217 |
-
score -= 15
|
| 218 |
|
| 219 |
return WorkflowResponse(
|
| 220 |
success=True,
|
| 221 |
content=content,
|
| 222 |
image_path=img_path,
|
| 223 |
-
|
| 224 |
-
suggestions=suggestions
|
| 225 |
)
|
| 226 |
|
| 227 |
except Exception as e:
|
| 228 |
-
raise HTTPException(status_code=500, detail=
|
| 229 |
|
| 230 |
if __name__ == "__main__":
|
| 231 |
import uvicorn
|
| 232 |
-
uvicorn.run(app, host="0.0.0.0", port=7860)
|
|
|
|
| 1 |
"""
|
| 2 |
Sofia AI API Wrapper - FastAPI REST API
|
| 3 |
+
Integración completa para n8n y almacenamiento en metadatos de HF
|
| 4 |
"""
|
| 5 |
|
| 6 |
from fastapi import FastAPI, HTTPException, Header, Depends
|
|
|
|
| 8 |
from pydantic import BaseModel
|
| 9 |
from typing import Optional, List, Dict
|
| 10 |
import os
|
| 11 |
+
import json
|
| 12 |
+
from datetime import datetime
|
| 13 |
+
from huggingface_hub import HfApi
|
| 14 |
from generation import generate_image_from_prompt
|
| 15 |
|
| 16 |
+
# Configuración de Hugging Face
|
| 17 |
+
HF_TOKEN = os.getenv("HF_TOKEN")
|
| 18 |
+
REPO_ID = "GoGma/sofia-rivera-gallery" # Tu dataset de metadata
|
| 19 |
+
|
| 20 |
# Crear instancia de FastAPI
|
| 21 |
app = FastAPI(
|
| 22 |
title="Sofia AI API",
|
| 23 |
+
description="API REST con almacenamiento automático en metadatos",
|
| 24 |
+
version="1.1.0"
|
| 25 |
)
|
| 26 |
|
|
|
|
| 27 |
app.add_middleware(
|
| 28 |
CORSMiddleware,
|
| 29 |
+
allow_origins=["*"],
|
| 30 |
allow_credentials=True,
|
| 31 |
allow_methods=["*"],
|
| 32 |
allow_headers=["*"],
|
| 33 |
)
|
| 34 |
|
| 35 |
+
# Modelos
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
class WorkflowRequest(BaseModel):
|
| 37 |
topic: str
|
| 38 |
platform: str
|
|
|
|
| 43 |
success: bool
|
| 44 |
content: str
|
| 45 |
image_path: Optional[str]
|
| 46 |
+
metadata_status: str
|
|
|
|
| 47 |
|
| 48 |
+
# Autenticación
|
| 49 |
API_KEY = os.getenv("SOFIA_API_KEY", "sofia_dev_key_2026")
|
| 50 |
|
| 51 |
def verify_api_key(x_api_key: str = Header(None)):
|
|
|
|
| 53 |
raise HTTPException(status_code=401, detail="API Key inválida")
|
| 54 |
return x_api_key
|
| 55 |
|
| 56 |
+
def save_to_metadata(data: dict):
|
| 57 |
+
"""Guarda el contenido generado en el dataset de Hugging Face"""
|
| 58 |
+
if not HF_TOKEN:
|
| 59 |
+
return "⚠️ Metadata no guardada: HF_TOKEN no configurado"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 60 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 61 |
try:
|
| 62 |
+
api = HfApi(token=HF_TOKEN)
|
| 63 |
+
timestamp = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
|
| 64 |
+
filename = f"content_{timestamp}.json"
|
|
|
|
|
|
|
|
|
|
| 65 |
|
| 66 |
+
# Preparar JSON
|
| 67 |
+
json_content = json.dumps(data, indent=4, ensure_ascii=False)
|
|
|
|
|
|
|
| 68 |
|
| 69 |
+
# Subir al repositorio de galería/metadata
|
| 70 |
+
api.upload_file(
|
| 71 |
+
path_or_fileobj=json_content.encode("utf-8"),
|
| 72 |
+
path_in_repo=f"history/{filename}",
|
| 73 |
+
repo_id=REPO_ID,
|
| 74 |
+
repo_type="dataset",
|
| 75 |
+
commit_message=f"Add generated content metadata: {timestamp}"
|
| 76 |
)
|
| 77 |
+
return "✅ Metadata guardada en HF Dataset"
|
| 78 |
except Exception as e:
|
| 79 |
+
return f"❌ Error guardando metadata: {str(e)}"
|
| 80 |
|
| 81 |
@app.post("/api/v1/workflow/complete", response_model=WorkflowResponse)
|
| 82 |
def complete_workflow(
|
| 83 |
request: WorkflowRequest,
|
| 84 |
api_key: str = Depends(verify_api_key)
|
| 85 |
):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 86 |
try:
|
| 87 |
# 1. Crear contenido
|
| 88 |
content_templates = {
|
| 89 |
+
"instagram": f"✨ {request.topic} ✨
|
| 90 |
+
|
| 91 |
+
Caption: Let's talk about {request.topic}! 💫
|
| 92 |
+
|
| 93 |
+
Hashtags: #{request.topic.replace(' ', '')} #SofiaRivera",
|
| 94 |
+
"twitter": f"💭 {request.topic}
|
| 95 |
+
|
| 96 |
+
#{request.topic.replace(' ', '')} #SofiaAI",
|
| 97 |
}
|
|
|
|
| 98 |
content = content_templates.get(request.platform.lower(), f"Content: {request.topic}")
|
| 99 |
|
| 100 |
# 2. Generar imagen
|
|
|
|
| 103 |
|
| 104 |
img_path, status = generate_image_from_prompt(prompt=full_prompt)
|
| 105 |
|
| 106 |
+
# 3. Guardar en Metadata de Hugging Face
|
| 107 |
+
metadata_payload = {
|
| 108 |
+
"timestamp": datetime.now().isoformat(),
|
| 109 |
+
"topic": request.topic,
|
| 110 |
+
"platform": request.platform,
|
| 111 |
+
"style": request.style,
|
| 112 |
+
"content": content,
|
| 113 |
+
"image_url": img_path,
|
| 114 |
+
"server_status": status
|
| 115 |
+
}
|
| 116 |
|
| 117 |
+
meta_status = save_to_metadata(metadata_payload)
|
|
|
|
|
|
|
| 118 |
|
| 119 |
return WorkflowResponse(
|
| 120 |
success=True,
|
| 121 |
content=content,
|
| 122 |
image_path=img_path,
|
| 123 |
+
metadata_status=meta_status
|
|
|
|
| 124 |
)
|
| 125 |
|
| 126 |
except Exception as e:
|
| 127 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 128 |
|
| 129 |
if __name__ == "__main__":
|
| 130 |
import uvicorn
|
| 131 |
+
uvicorn.run(app, host="0.0.0.0", port=7860)
|