Hjgugugjhuhjggg commited on
Commit
c496fe5
1 Parent(s): 5a21f1e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +13 -4
app.py CHANGED
@@ -5,13 +5,16 @@ import logging
5
  from fastapi import FastAPI, HTTPException
6
  from pydantic import BaseModel
7
  from google.cloud import storage
 
8
  from transformers import pipeline, AutoModelForCausalLM, AutoTokenizer
9
  import uvicorn
10
- import torch
11
  import requests
12
  import io
13
  from safetensors import safe_open
 
14
 
 
15
  from dotenv import load_dotenv
16
  load_dotenv()
17
 
@@ -20,9 +23,11 @@ GCS_BUCKET_NAME = os.getenv("GCS_BUCKET_NAME")
20
  GOOGLE_APPLICATION_CREDENTIALS_JSON = os.getenv("GOOGLE_APPLICATION_CREDENTIALS_JSON")
21
  HF_API_TOKEN = os.getenv("HF_API_TOKEN")
22
 
 
23
  logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
24
  logger = logging.getLogger(__name__)
25
 
 
26
  try:
27
  credentials_info = json.loads(GOOGLE_APPLICATION_CREDENTIALS_JSON)
28
  storage_client = storage.Client.from_service_account_info(credentials_info)
@@ -66,12 +71,13 @@ def load_model_from_gcs(model_name: str, model_files: list):
66
  gcs_handler = GCSHandler(GCS_BUCKET_NAME)
67
  model_blobs = {file: gcs_handler.download_file(f"{model_name}/{file}") for file in model_files}
68
 
 
69
  model_stream = model_blobs.get("pytorch_model.bin") or model_blobs.get("model.safetensors")
70
  config_stream = model_blobs.get("config.json")
71
  tokenizer_stream = model_blobs.get("tokenizer.json")
72
 
73
  if "safetensors" in model_stream.name:
74
- model = load_safetensors_model(model_stream)
75
  else:
76
  model = AutoModelForCausalLM.from_pretrained(model_stream, config=config_stream)
77
 
@@ -79,7 +85,7 @@ def load_model_from_gcs(model_name: str, model_files: list):
79
 
80
  return model, tokenizer
81
 
82
- def load_safetensors_model(model_stream):
83
  with safe_open(model_stream, framework="pt") as model_data:
84
  model = torch.load(model_data)
85
  return model
@@ -88,7 +94,7 @@ def get_model_files_from_gcs(model_name: str):
88
  gcs_handler = GCSHandler(GCS_BUCKET_NAME)
89
  blob_list = list(gcs_handler.bucket.list_blobs(prefix=f"{model_name}/"))
90
  model_files = [blob.name for blob in blob_list if "pytorch_model" in blob.name or "model" in blob.name]
91
- model_files = sorted(model_files)
92
  return model_files
93
 
94
  @app.post("/predict/")
@@ -98,14 +104,17 @@ async def predict(request: DownloadModelRequest):
98
  gcs_handler = GCSHandler(GCS_BUCKET_NAME)
99
  model_prefix = request.model_name
100
 
 
101
  model_files = get_model_files_from_gcs(model_prefix)
102
 
103
  if not model_files:
104
  logger.error(f"Modelos no encontrados en GCS para '{model_prefix}'.")
105
  raise HTTPException(status_code=404, detail="Model files not found in GCS.")
106
 
 
107
  model, tokenizer = load_model_from_gcs(model_prefix, model_files)
108
 
 
109
  pipe = pipeline(request.pipeline_task, model=model, tokenizer=tokenizer)
110
 
111
  if request.pipeline_task in ["text-generation", "translation", "summarization"]:
 
5
  from fastapi import FastAPI, HTTPException
6
  from pydantic import BaseModel
7
  from google.cloud import storage
8
+ from google.auth import exceptions
9
  from transformers import pipeline, AutoModelForCausalLM, AutoTokenizer
10
  import uvicorn
11
+ from google.cloud.storage.blob import Blob
12
  import requests
13
  import io
14
  from safetensors import safe_open
15
+ import torch
16
 
17
+ # Cargar las variables de entorno
18
  from dotenv import load_dotenv
19
  load_dotenv()
20
 
 
23
  GOOGLE_APPLICATION_CREDENTIALS_JSON = os.getenv("GOOGLE_APPLICATION_CREDENTIALS_JSON")
24
  HF_API_TOKEN = os.getenv("HF_API_TOKEN")
25
 
26
+ # Configuración del logger
27
  logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
28
  logger = logging.getLogger(__name__)
29
 
30
+ # Inicializar el cliente de Google Cloud Storage
31
  try:
32
  credentials_info = json.loads(GOOGLE_APPLICATION_CREDENTIALS_JSON)
33
  storage_client = storage.Client.from_service_account_info(credentials_info)
 
71
  gcs_handler = GCSHandler(GCS_BUCKET_NAME)
72
  model_blobs = {file: gcs_handler.download_file(f"{model_name}/{file}") for file in model_files}
73
 
74
+ # Verificar si el modelo es de safetensors o torch
75
  model_stream = model_blobs.get("pytorch_model.bin") or model_blobs.get("model.safetensors")
76
  config_stream = model_blobs.get("config.json")
77
  tokenizer_stream = model_blobs.get("tokenizer.json")
78
 
79
  if "safetensors" in model_stream.name:
80
+ model = load_safetensors_model(model_stream, config_stream)
81
  else:
82
  model = AutoModelForCausalLM.from_pretrained(model_stream, config=config_stream)
83
 
 
85
 
86
  return model, tokenizer
87
 
88
+ def load_safetensors_model(model_stream, config_stream):
89
  with safe_open(model_stream, framework="pt") as model_data:
90
  model = torch.load(model_data)
91
  return model
 
94
  gcs_handler = GCSHandler(GCS_BUCKET_NAME)
95
  blob_list = list(gcs_handler.bucket.list_blobs(prefix=f"{model_name}/"))
96
  model_files = [blob.name for blob in blob_list if "pytorch_model" in blob.name or "model" in blob.name]
97
+ model_files = sorted(model_files) # Asegurar que los archivos fragmentados estén en el orden correcto
98
  return model_files
99
 
100
  @app.post("/predict/")
 
104
  gcs_handler = GCSHandler(GCS_BUCKET_NAME)
105
  model_prefix = request.model_name
106
 
107
+ # Obtener los archivos del modelo (incluyendo fragmentados)
108
  model_files = get_model_files_from_gcs(model_prefix)
109
 
110
  if not model_files:
111
  logger.error(f"Modelos no encontrados en GCS para '{model_prefix}'.")
112
  raise HTTPException(status_code=404, detail="Model files not found in GCS.")
113
 
114
+ # Cargar el modelo desde GCS
115
  model, tokenizer = load_model_from_gcs(model_prefix, model_files)
116
 
117
+ # Instanciar el pipeline de Hugging Face
118
  pipe = pipeline(request.pipeline_task, model=model, tokenizer=tokenizer)
119
 
120
  if request.pipeline_task in ["text-generation", "translation", "summarization"]: