Módulo de audio y avance imágenes (schemas y openAI)
This commit is contained in:
Binary file not shown.
BIN
app/services/image/__pycache__/prompt_builder.cpython-312.pyc
Normal file
BIN
app/services/image/__pycache__/prompt_builder.cpython-312.pyc
Normal file
Binary file not shown.
@@ -8,14 +8,19 @@ Propósito:
|
||||
|
||||
"""
|
||||
|
||||
import json
|
||||
import tempfile
|
||||
import os
|
||||
from fastapi import HTTPException
|
||||
from matplotlib import image
|
||||
from openai import OpenAI, AsyncOpenAI
|
||||
import assemblyai as aai
|
||||
from pyparsing.common import Any
|
||||
from app.core.config import settings
|
||||
from app.schemas.image_standard import ImageRequestFile, StandardImageAnalysisResult
|
||||
from app.schemas.image_standard import ImageRequestFile, StandardImageAnalysisResult, ImageEvaluationRubric
|
||||
from app.core import config
|
||||
from app.utilities.image_utilities import json_to_rubric, encode_image_from_bytes
|
||||
from app.services.image.prompt_builder import build_image_evaluation_prompt
|
||||
|
||||
# Función de adaptador principal que infiere el proveedor y llama al adaptador específico
|
||||
async def evaluate_image_with_provider(image_request: ImageRequestFile) -> StandardImageAnalysisResult:
|
||||
@@ -24,25 +29,58 @@ async def evaluate_image_with_provider(image_request: ImageRequestFile) -> Stand
|
||||
"""
|
||||
provider = image_request.provider.lower()
|
||||
|
||||
content = await image_request.rubric.read()
|
||||
rubric_dict = json.loads(content)
|
||||
rubric = json_to_rubric(rubric_dict)
|
||||
prompt = build_image_evaluation_prompt(rubric)
|
||||
|
||||
match provider:
|
||||
case "openai":
|
||||
return await evaluate_with_openai(image_request)
|
||||
case "inserte nombre de otra ia aqui":
|
||||
return await evaluate_with_ai_model2(image_request)
|
||||
|
||||
# AGREGAR OTROS CASOS PARA DIFERENTES PROVEEDORES DE IA AQUÍ
|
||||
|
||||
return await evaluate_with_openai(image_request, prompt)
|
||||
case "clarifai":
|
||||
return await evaluate_with_clarifai(image_request, prompt)
|
||||
case "claude":
|
||||
return await evaluate_with_claude(image_request, prompt)
|
||||
case _:
|
||||
raise ValueError(f"Proveedor de IA no soportado: {image_request.provider}")
|
||||
|
||||
# Función de adaptador para evaluar imágenes usando OpenAI
|
||||
async def evaluate_with_openai(image_request: ImageRequestFile) -> StandardImageAnalysisResult:
|
||||
async def evaluate_with_openai(image_request: ImageRequestFile, prompt: str) -> StandardImageAnalysisResult:
|
||||
"""
|
||||
Función de adaptador para evaluar imágenes usando OpenAI.
|
||||
(Plantilla para futuras implementaciones)
|
||||
"""
|
||||
|
||||
client = AsyncOpenAI(api_key=settings.OPENAI_API_KEY)
|
||||
|
||||
image_bytes = await image_request.file.read()
|
||||
base64_image = encode_image_from_bytes(image_bytes)
|
||||
|
||||
try:
|
||||
response = await client.chat.completions.create(
|
||||
model=image_request.model,
|
||||
messages=[
|
||||
{"role": "user", "content": [
|
||||
{"type": "text", "text": prompt},
|
||||
{
|
||||
"type": "image_url",
|
||||
"image_url": {
|
||||
"url": f"data:image/jpeg;base64,{base64_image}"
|
||||
}
|
||||
}
|
||||
]}
|
||||
],
|
||||
response_format={"type": "json_object"}
|
||||
)
|
||||
|
||||
resultado = json.loads(response.choices[0].message.content)
|
||||
return StandardImageAnalysisResult(**resultado)
|
||||
except Exception as e:
|
||||
# Capturamos cualquier error de OpenAI o de lectura de archivos
|
||||
raise HTTPException(
|
||||
status_code=500,
|
||||
detail=f"Error evaluando la imagen: {str(e)}"
|
||||
)
|
||||
# PASOS A SEGUIR PARA IMPLEMENTAR LA LÓGICA DE EVALUACIÓN CON OPENAI:
|
||||
# 1. Validar la imagen de entrada (tamaño, formato, etc.)
|
||||
# 2. Configurar el cliente de OpenAI con la clave API
|
||||
@@ -51,18 +89,74 @@ async def evaluate_with_openai(image_request: ImageRequestFile) -> StandardImage
|
||||
# 5. Manejar errores y excepciones adecuadamente
|
||||
raise NotImplementedError("La función evaluate_with_openai aún no está implementada.")
|
||||
|
||||
async def evaluate_with_ai_model2(image_request: ImageRequestFile) -> StandardImageAnalysisResult:
|
||||
async def evaluate_with_clarifai(image_request: ImageRequestFile, rubric: ImageEvaluationRubric, prompt: str) -> StandardImageAnalysisResult:
|
||||
"""
|
||||
Función de adaptador para transcribir video usando otra AI.
|
||||
Función de adaptador para evaluar imágenes usando Clarifai con un modelo Multimodal.
|
||||
"""
|
||||
try:
|
||||
# 1. Obtener el token de configuración (PAT)
|
||||
pat = settings.CLARIFAI_API_KEY
|
||||
if not pat:
|
||||
raise ValueError("La clave CLARIFAI_API_KEY no está configurada en el entorno.")
|
||||
|
||||
# 2. Obtener la URL del modelo enviada en la petición
|
||||
model_url = image_request.model
|
||||
|
||||
# Inicializar el modelo de Clarifai
|
||||
model = Model(url=model_url, pat=pat)
|
||||
|
||||
# 3. Leer los bytes de la imagen subida
|
||||
image_bytes = await image_request.file.read()
|
||||
|
||||
if not image_bytes:
|
||||
raise ValueError("El archivo de imagen recibido está vacío.")
|
||||
|
||||
# 4. Preparar el input multimodal para Clarifai combinando la imagen y el prompt de evaluación
|
||||
multimodal_input = Inputs.get_multimodal_input(
|
||||
input_id="image_evaluation",
|
||||
image_bytes=image_bytes,
|
||||
raw_text=prompt
|
||||
)
|
||||
|
||||
# 5. Llamar a la API de Clarifai para evaluar la imagen
|
||||
predict_response = model.predict([multimodal_input])
|
||||
|
||||
# Extraer el texto crudo de la respuesta del modelo
|
||||
raw_output = predict_response.outputs[0].data.text.raw
|
||||
|
||||
# 6. Limpiar la respuesta y convertirla a JSON
|
||||
# Los LLMs suelen devolver el JSON envuelto en bloques de markdown (```json ... ```)
|
||||
clean_json = raw_output.replace("```json", "").replace("```", "").strip()
|
||||
|
||||
# Convertir el string limpio a un diccionario de Python
|
||||
parsed_data = json.loads(clean_json)
|
||||
|
||||
# 7. Retornar el resultado validado contra tu esquema estándar de Pydantic
|
||||
return StandardImageAnalysisResult(**parsed_data)
|
||||
|
||||
except json.JSONDecodeError as e:
|
||||
# Error específico si el modelo alucinó texto extra y no devolvió un JSON válido
|
||||
raise HTTPException(
|
||||
status_code=500,
|
||||
detail=f"El modelo de Clarifai no devolvió un JSON válido. Error: {str(e)} | Respuesta cruda: {raw_output if 'raw_output' in locals() else 'N/A'}"
|
||||
)
|
||||
except Exception as e:
|
||||
# Captura cualquier otro error (problemas de red, token inválido, URL incorrecta, etc.)
|
||||
raise HTTPException(
|
||||
status_code=500,
|
||||
detail=f"Error interno al evaluar con Clarifai: {str(e)}"
|
||||
)
|
||||
|
||||
async def evaluate_with_claude(image_request: ImageRequestFile, prompt: str) -> StandardImageAnalysisResult:
|
||||
"""
|
||||
Función de adaptador para evaluar imágenes usando Claude.
|
||||
(Plantilla para futuras implementaciones)
|
||||
"""
|
||||
|
||||
# PASOS A SEGUIR PARA IMPLEMENTAR LA LÓGICA DE TRANSCRIPCIÓN CON IA (ELEGIR MODELO):
|
||||
# 1. Validar el video de entrada (tamaño, formato, etc.)
|
||||
# 2. Configurar el cliente de OpenAI con la clave API
|
||||
# 3. Llamar a la API de OpenAI para transcribir el video
|
||||
# 4. Convertir la respuesta de OpenAI al formato estándar de resumen de texto de Qualidot
|
||||
# PASOS A SEGUIR PARA IMPLEMENTAR LA LÓGICA DE EVALUACIÓN CON CLAUDE:
|
||||
# 1. Validar la imagen de entrada (tamaño, formato, etc.)
|
||||
# 2. Configurar el cliente de Claude con la clave API
|
||||
# 3. Llamar a la API de Claude para evaluar la imagen
|
||||
# 4. Convertir la respuesta de Claude al formato estándar de evaluación de imágenes de Qualidot
|
||||
# 5. Manejar errores y excepciones adecuadamente
|
||||
raise NotImplementedError("La función transcribe_with_ai_model2 aún no está implementada.")
|
||||
|
||||
# Otros modelos de IA
|
||||
raise NotImplementedError("La función evaluate_with_claude aún no está implementada.")
|
||||
|
||||
57
app/services/image/prompt_builder.py
Normal file
57
app/services/image/prompt_builder.py
Normal file
@@ -0,0 +1,57 @@
|
||||
"""
|
||||
Módulo encargado de construir el prompt estandarizado para la evaluación de imágenes,
|
||||
inyectando la rúbrica, el contexto de especialidad y el esquema JSON esperado.
|
||||
Este módulo es crucial para asegurar que los evaluadores expertos reciban instrucciones
|
||||
claras y consistentes, y que sus respuestas se ajusten al formato requerido para su posterior
|
||||
procesamiento y análisis.
|
||||
"""
|
||||
|
||||
|
||||
import json
|
||||
from app.schemas.image_standard import StandardImageAnalysisResult, ImageEvaluationRubric
|
||||
|
||||
def build_image_evaluation_prompt(rubric: ImageEvaluationRubric) -> str:
|
||||
"""
|
||||
Construye el prompt estandarizado inyectando la rúbrica,
|
||||
el contexto de especialidad y el esquema JSON esperado.
|
||||
"""
|
||||
|
||||
# 1. Extraemos el JSON de la rúbrica de forma limpia (ignorando nulos)
|
||||
rubric_json = rubric.model_dump_json(exclude_none=True, indent=2)
|
||||
|
||||
# 2. Extraemos el esquema dinámico de salida basado en Pydantic
|
||||
expected_output_schema = json.dumps(StandardImageAnalysisResult.model_json_schema(), indent=2)
|
||||
|
||||
# 3. Obtenemos el path de especialización
|
||||
# Si por alguna razón viene vacío, le damos un rol genérico por defecto
|
||||
specialization_path = rubric.category if rubric.category else "General Image Analysis"
|
||||
|
||||
# 4. Ensamblamos el prompt con f-strings
|
||||
prompt = f"""
|
||||
# ROLE
|
||||
You are a highly specialized Expert Evaluator with deep domain expertise in the following area: **{specialization_path}**. Your objective is to perform a highly accurate, objective, and domain-calibrated analysis of the provided input based STRICTLY on your specialization and the provided evaluation rubric.
|
||||
|
||||
# TASK
|
||||
I will provide you with an input and a JSON object representing an `EvaluationRubric`.
|
||||
Your task is to analyze the input and score it against every criterion and subcriterion defined in the rubric. You must justify your scores with objective feedback based on evidence.
|
||||
|
||||
# DOMAIN CONTEXT
|
||||
Specialization Path: {specialization_path}
|
||||
|
||||
# RUBRIC
|
||||
{rubric_json}
|
||||
|
||||
# EVALUATION RULES
|
||||
1. **Domain Calibration (CRITICAL):** Calibrate your expectations, strictness, and feedback entirely according to the **{specialization_path}** context. Do not evaluate using generalized standards; apply the specific standards expected at this exact level and category.
|
||||
2. **Strict Adherence:** Evaluate ONLY the criteria and subcriteria listed in the rubric. Do not invent new metrics.
|
||||
3. **Scoring:** Assign a numeric `score` to each criterion and subcriterion. The score must reflect how well the input meets the description of that specific metric.
|
||||
4. **Objective Feedback:** Generate constructive, evidence-grounded `feedback` for the overall evaluation. Mention specific elements or patterns observed in the input that justify the scores within the context of the specialization.
|
||||
5. **Subcriteria Handling:** If a criterion has `subcriteria`, evaluate each subcriterion individually. The parent criterion's score should be a logical aggregate (e.g., average) of its subcriteria scores.
|
||||
|
||||
# OUTPUT FORMAT
|
||||
You MUST return your response EXCLUSIVELY as a raw, valid JSON object that strictly adheres to the following JSON Schema definition. Do NOT include markdown blocks (```json), explanations, or any text outside the JSON object.
|
||||
|
||||
# EXPECTED JSON SCHEMA
|
||||
{expected_output_schema}
|
||||
"""
|
||||
return prompt
|
||||
Reference in New Issue
Block a user