File size: 9,144 Bytes
f56cbc6
3a145aa
f56cbc6
 
 
 
 
3a145aa
972e5ee
3a145aa
f56cbc6
8becaf9
f56cbc6
f6a64dd
f56cbc6
 
f6a64dd
f56cbc6
 
 
f6a64dd
 
f56cbc6
f6a64dd
f56cbc6
 
 
 
 
 
 
 
 
f6a64dd
f56cbc6
3a145aa
f56cbc6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f6a64dd
f56cbc6
f6a64dd
f56cbc6
3a145aa
f56cbc6
 
 
 
 
f6a64dd
 
f56cbc6
e58c8bb
f56cbc6
f6a64dd
 
 
 
 
 
 
 
 
f56cbc6
f6a64dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b88653d
f6a64dd
f56cbc6
 
 
f6a64dd
 
 
 
 
 
 
f56cbc6
f6a64dd
 
972e5ee
f6a64dd
 
 
 
 
540ad6f
3a145aa
f6a64dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e58c8bb
f56cbc6
 
 
 
f6a64dd
 
f56cbc6
3a145aa
 
42861e8
f6a64dd
3a145aa
 
 
972e5ee
f6a64dd
3a145aa
f6a64dd
 
3a145aa
 
 
f6a64dd
3a145aa
 
f6a64dd
3a145aa
f6a64dd
 
3a145aa
f6a64dd
3a145aa
f6a64dd
 
3a145aa
f6a64dd
3a145aa
f6a64dd
 
3a145aa
f6a64dd
972e5ee
3a145aa
972e5ee
f56cbc6
f6a64dd
3a145aa
972e5ee
f56cbc6
f6a64dd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
import requests
import boto3
from dotenv import load_dotenv
import os
import uvicorn
from transformers import pipeline, AutoModelForCausalLM, AutoTokenizer
import torch
import safetensors.torch
from fastapi.responses import StreamingResponse
from tqdm import tqdm

# Cargar las variables de entorno desde el archivo .env
load_dotenv()

# Cargar las credenciales de AWS y el token de Hugging Face desde las variables de entorno
AWS_ACCESS_KEY_ID = os.getenv("AWS_ACCESS_KEY_ID")
AWS_SECRET_ACCESS_KEY = os.getenv("AWS_SECRET_ACCESS_KEY")
AWS_REGION = os.getenv("AWS_REGION")
S3_BUCKET_NAME = os.getenv("S3_BUCKET_NAME")  # Nombre del bucket de S3
HUGGINGFACE_TOKEN = os.getenv("HUGGINGFACE_TOKEN")  # Token de Hugging Face

# Cliente S3 de Amazon
s3_client = boto3.client(
    's3',
    aws_access_key_id=AWS_ACCESS_KEY_ID,
    aws_secret_access_key=AWS_SECRET_ACCESS_KEY,
    region_name=AWS_REGION
)

app = FastAPI()

# Pydantic Model para el cuerpo de la solicitud del endpoint /download_model/
class DownloadModelRequest(BaseModel):
    model_name: str
    pipeline_task: str
    input_text: str

class S3DirectStream:
    def __init__(self, bucket_name):
        self.s3_client = boto3.client(
            's3',
            aws_access_key_id=AWS_ACCESS_KEY_ID,
            aws_secret_access_key=AWS_SECRET_ACCESS_KEY,
            region_name=AWS_REGION
        )
        self.bucket_name = bucket_name

    def stream_from_s3(self, key):
        try:
            print(f"Descargando archivo {key} desde S3...")
            response = self.s3_client.get_object(Bucket=self.bucket_name, Key=key)
            return response['Body']  # Devolver el cuerpo directamente para el StreamingResponse
        except self.s3_client.exceptions.NoSuchKey:
            raise HTTPException(status_code=404, detail=f"El archivo {key} no existe en el bucket S3.")

    def file_exists_in_s3(self, key):
        try:
            self.s3_client.head_object(Bucket=self.bucket_name, Key=key)
            return True
        except self.s3_client.exceptions.ClientError:
            return False

    def load_model_from_stream(self, model_prefix):
        try:
            print(f"Cargando el modelo {model_prefix} desde S3...")
            if self.file_exists_in_s3(f"{model_prefix}/config.json") and \
               (self.file_exists_in_s3(f"{model_prefix}/pytorch_model.bin") or self.file_exists_in_s3(f"{model_prefix}/model.safetensors")):
                print(f"Modelo {model_prefix} ya existe en S3. No es necesario descargarlo.")
                return self.load_model_from_existing_s3(model_prefix)
            
            print(f"Modelo {model_prefix} no encontrado. Procediendo a descargar...")
            self.download_and_upload_to_s3(model_prefix)
            return self.load_model_from_stream(model_prefix)
        except HTTPException as e:
            print(f"Error al cargar el modelo: {e}")
            return None

    def load_model_from_existing_s3(self, model_prefix):
        # Cargar el modelo y los archivos necesarios desde S3
        print(f"Cargando los archivos {model_prefix} desde S3...")
        config_stream = self.stream_from_s3(f"{model_prefix}/config.json")
        config_data = config_stream.read().decode("utf-8")
        
        print(f"Cargando el modelo de lenguaje {model_prefix}...")

        # Verificar si el archivo es un safetensor o un archivo binario
        if self.file_exists_in_s3(f"{model_prefix}/model.safetensors"):
            # Usar safetensors si el archivo es de tipo safetensors
            model_stream = self.stream_from_s3(f"{model_prefix}/model.safetensors")
            model = AutoModelForCausalLM.from_config(config_data)
            model.load_state_dict(safetensors.torch.load_stream(model_stream))  # Cargar el modelo utilizando safetensors
        else:
            # Cargar el modelo utilizando pytorch si el archivo es .bin
            model_stream = self.stream_from_s3(f"{model_prefix}/pytorch_model.bin")
            model = AutoModelForCausalLM.from_config(config_data)
            model.load_state_dict(torch.load(model_stream, map_location="cpu"))

        return model

    def load_tokenizer_from_stream(self, model_prefix):
        try:
            if self.file_exists_in_s3(f"{model_prefix}/tokenizer.json"):
                print(f"Tokenizer para {model_prefix} ya existe en S3. No es necesario descargarlo.")
                return self.load_tokenizer_from_existing_s3(model_prefix)
            
            print(f"Tokenizer para {model_prefix} no encontrado. Procediendo a descargar...")
            self.download_and_upload_to_s3(model_prefix)
            return self.load_tokenizer_from_stream(model_prefix)
        except HTTPException as e:
            print(f"Error al cargar el tokenizer: {e}")
            return None

    def load_tokenizer_from_existing_s3(self, model_prefix):
        print(f"Cargando el tokenizer para {model_prefix} desde S3...")
        tokenizer_stream = self.stream_from_s3(f"{model_prefix}/tokenizer.json")
        tokenizer = AutoTokenizer.from_pretrained(tokenizer_stream)
        return tokenizer

    def download_and_upload_to_s3(self, model_prefix):
        # URLs de los archivos de Hugging Face
        model_url = f"https://huggingface.co/{model_prefix}/resolve/main/pytorch_model.bin"
        safetensors_url = f"https://huggingface.co/{model_prefix}/resolve/main/model.safetensors"
        tokenizer_url = f"https://huggingface.co/{model_prefix}/resolve/main/tokenizer.json"
        config_url = f"https://huggingface.co/{model_prefix}/resolve/main/config.json"

        print(f"Descargando y subiendo archivos para el modelo {model_prefix} a S3...")
        self.download_and_upload_to_s3_url(model_url, f"{model_prefix}/pytorch_model.bin")
        self.download_and_upload_to_s3_url(safetensors_url, f"{model_prefix}/model.safetensors")
        self.download_and_upload_to_s3_url(tokenizer_url, f"{model_prefix}/tokenizer.json")
        self.download_and_upload_to_s3_url(config_url, f"{model_prefix}/config.json")

    def download_and_upload_to_s3_url(self, url: str, s3_key: str):
        print(f"Descargando archivo desde {url}...")
        response = requests.get(url)
        if response.status_code == 200:
            # Subir archivo a S3
            print(f"Subiendo archivo a S3 con key {s3_key}...")
            self.s3_client.put_object(Bucket=self.bucket_name, Key=s3_key, Body=response.content)
        else:
            raise HTTPException(status_code=500, detail=f"Error al descargar el archivo desde {url}")


@app.post("/predict/")
async def predict(model_request: DownloadModelRequest):
    try:
        print(f"Recibiendo solicitud para predecir con el modelo {model_request.model_name}...")
        # Cargar el modelo y tokenizer desde S3
        streamer = S3DirectStream(S3_BUCKET_NAME)
        model = streamer.load_model_from_stream(model_request.model_name)
        tokenizer = streamer.load_tokenizer_from_stream(model_request.model_name)

        # Obtener el pipeline adecuado según la solicitud
        task = model_request.pipeline_task
        if task not in ["text-generation", "sentiment-analysis", "translation", "fill-mask", "question-answering", "text-to-speech", "text-to-image", "text-to-audio", "text-to-video"]:
            raise HTTPException(status_code=400, detail="Pipeline task no soportado")

        # Crear el pipeline dinámicamente basado en el tipo de tarea
        nlp_pipeline = pipeline(task, model=model, tokenizer=tokenizer)

        # Ejecutar el pipeline con el input_text
        input_text = model_request.input_text
        outputs = nlp_pipeline(input_text)

        # Procesar los diferentes tipos de respuestas según el pipeline
        if task in ["text-generation", "translation", "fill-mask", "sentiment-analysis", "question-answering"]:
            return {"response": outputs}

        elif task == "text-to-image":
            # Asumir que outputs es la imagen generada
            s3_key = f"{model_request.model_name}/generated_image.png"  # Definir el key del archivo de imagen
            return StreamingResponse(streamer.stream_from_s3(s3_key), media_type="image/png")

        elif task == "text-to-audio":
            # Asumir que outputs es el audio generado
            s3_key = f"{model_request.model_name}/generated_audio.wav"  # Definir el key del archivo de audio
            return StreamingResponse(streamer.stream_from_s3(s3_key), media_type="audio/wav")

        elif task == "text-to-video":
            # Asumir que outputs es el video generado
            s3_key = f"{model_request.model_name}/generated_video.mp4"  # Definir el key del archivo de video
            return StreamingResponse(streamer.stream_from_s3(s3_key), media_type="video/mp4")

        else:
            raise HTTPException(status_code=400, detail="Tipo de tarea desconocido")

    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Error al procesar la solicitud: {str(e)}")


if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8000)