Hjgugugjhuhjggg commited on
Commit
6e677d2
verified
1 Parent(s): 014edf2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +15 -40
app.py CHANGED
@@ -5,24 +5,18 @@ import boto3
5
  from fastapi import FastAPI, HTTPException
6
  from fastapi.responses import JSONResponse
7
  from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
8
- from huggingface_hub import hf_hub_download
9
  import asyncio
 
10
 
11
- # Configuraci贸n del logger
12
  logger = logging.getLogger(__name__)
13
- logger.setLevel(logging.INFO)
14
- console_handler = logging.StreamHandler()
15
- formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
16
- console_handler.setFormatter(formatter)
17
- logger.addHandler(console_handler)
18
 
19
  AWS_ACCESS_KEY_ID = os.getenv("AWS_ACCESS_KEY_ID")
20
  AWS_SECRET_ACCESS_KEY = os.getenv("AWS_SECRET_ACCESS_KEY")
21
  AWS_REGION = os.getenv("AWS_REGION")
22
  S3_BUCKET_NAME = os.getenv("S3_BUCKET_NAME")
23
- HUGGINGFACE_HUB_TOKEN = os.getenv("HUGGINGFACE_HUB_TOKEN")
24
 
25
- MAX_TOKENS = 1024
26
 
27
  s3_client = boto3.client(
28
  's3',
@@ -88,8 +82,9 @@ class S3DirectStream:
88
  model_files = await self.get_model_file_parts(model_prefix)
89
 
90
  if not model_files:
91
- await self.download_and_upload_to_s3(model_prefix, model)
92
 
 
93
  config_stream = await self.stream_from_s3(f"{model_prefix}/config.json")
94
  config_data = config_stream.read()
95
 
@@ -114,7 +109,7 @@ class S3DirectStream:
114
  tokenizer_stream = await self.stream_from_s3(f"{profile}/{model}/tokenizer.json")
115
  tokenizer_data = tokenizer_stream.read().decode("utf-8")
116
 
117
- tokenizer = AutoTokenizer.from_pretrained(f"s3://{self.bucket_name}/{profile}/{model}")
118
  return tokenizer
119
  except Exception as e:
120
  raise HTTPException(status_code=500, detail=f"Error al cargar el tokenizer desde S3: {e}")
@@ -138,22 +133,6 @@ class S3DirectStream:
138
  except self.s3_client.exceptions.ClientError:
139
  return False
140
 
141
- async def download_and_upload_to_s3(self, model_prefix, model_name):
142
- try:
143
- config_file = hf_hub_download(repo_id=model_name, filename="config.json", token=HUGGINGFACE_HUB_TOKEN)
144
- tokenizer_file = hf_hub_download(repo_id=model_name, filename="tokenizer.json", token=HUGGINGFACE_HUB_TOKEN)
145
-
146
- if not await self.file_exists_in_s3(f"{model_prefix}/config.json"):
147
- with open(config_file, "rb") as file:
148
- self.s3_client.put_object(Bucket=self.bucket_name, Key=f"{model_prefix}/config.json", Body=file)
149
-
150
- if not await self.file_exists_in_s3(f"{model_prefix}/tokenizer.json"):
151
- with open(tokenizer_file, "rb") as file:
152
- self.s3_client.put_object(Bucket=self.bucket_name, Key=f"{model_prefix}/tokenizer.json", Body=file)
153
-
154
- except Exception as e:
155
- raise HTTPException(status_code=500, detail=f"Error al descargar o cargar archivos desde Hugging Face a S3: {e}")
156
-
157
  def split_text_by_tokens(text, tokenizer, max_tokens=MAX_TOKENS):
158
  tokens = tokenizer.encode(text)
159
  chunks = []
@@ -169,7 +148,7 @@ def continue_generation(input_text, model, tokenizer, max_tokens=MAX_TOKENS):
169
  input_text = tokenizer.decode(tokens[:max_tokens])
170
  output = model.generate(input_ids=tokenizer.encode(input_text, return_tensors="pt").input_ids)
171
  generated_text += tokenizer.decode(output[0], skip_special_tokens=True)
172
- input_text = input_text[len(input_text):]
173
  return generated_text
174
 
175
  @app.post("/predict/")
@@ -184,7 +163,7 @@ async def predict(model_request: dict):
184
 
185
  streamer = S3DirectStream(S3_BUCKET_NAME)
186
 
187
- await streamer.create_s3_folders(model_name)
188
 
189
  model = await streamer.load_model_from_s3(model_name)
190
  tokenizer = await streamer.load_tokenizer_from_s3(model_name)
@@ -196,22 +175,18 @@ async def predict(model_request: dict):
196
 
197
  result = await asyncio.to_thread(nlp_pipeline, input_text)
198
 
199
- if len(result) > MAX_TOKENS:
200
- chunks = split_text_by_tokens(result, tokenizer)
 
201
  full_result = ""
202
  for chunk in chunks:
203
  full_result += continue_generation(chunk, model, tokenizer)
204
- return {"result": full_result}
205
-
206
- return {"result": result}
207
-
208
- except HTTPException as e:
209
- logger.error(f"Error al realizar la predicci贸n: {str(e.detail)}")
210
- return JSONResponse(status_code=e.status_code, content={"detail": str(e.detail)})
211
 
212
  except Exception as e:
213
- logger.error(f"Error inesperado: {str(e)}")
214
- return JSONResponse(status_code=500, content={"detail": "Error inesperado. Intenta m谩s tarde."})
215
 
216
  if __name__ == "__main__":
217
  import uvicorn
 
5
  from fastapi import FastAPI, HTTPException
6
  from fastapi.responses import JSONResponse
7
  from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
 
8
  import asyncio
9
+ import concurrent.futures
10
 
11
+ logging.basicConfig(level=logging.INFO)
12
  logger = logging.getLogger(__name__)
 
 
 
 
 
13
 
14
  AWS_ACCESS_KEY_ID = os.getenv("AWS_ACCESS_KEY_ID")
15
  AWS_SECRET_ACCESS_KEY = os.getenv("AWS_SECRET_ACCESS_KEY")
16
  AWS_REGION = os.getenv("AWS_REGION")
17
  S3_BUCKET_NAME = os.getenv("S3_BUCKET_NAME")
 
18
 
19
+ MAX_TOKENS = 1024 # Limite de tokens por fragmento
20
 
21
  s3_client = boto3.client(
22
  's3',
 
82
  model_files = await self.get_model_file_parts(model_prefix)
83
 
84
  if not model_files:
85
+ raise HTTPException(status_code=404, detail=f"Archivos del modelo {model_name} no encontrados en S3.")
86
 
87
+ # Verificar que existe el archivo config.json
88
  config_stream = await self.stream_from_s3(f"{model_prefix}/config.json")
89
  config_data = config_stream.read()
90
 
 
109
  tokenizer_stream = await self.stream_from_s3(f"{profile}/{model}/tokenizer.json")
110
  tokenizer_data = tokenizer_stream.read().decode("utf-8")
111
 
112
+ tokenizer = AutoTokenizer.from_pretrained(f"{profile}/{model}")
113
  return tokenizer
114
  except Exception as e:
115
  raise HTTPException(status_code=500, detail=f"Error al cargar el tokenizer desde S3: {e}")
 
133
  except self.s3_client.exceptions.ClientError:
134
  return False
135
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
136
  def split_text_by_tokens(text, tokenizer, max_tokens=MAX_TOKENS):
137
  tokens = tokenizer.encode(text)
138
  chunks = []
 
148
  input_text = tokenizer.decode(tokens[:max_tokens])
149
  output = model.generate(input_ids=tokenizer.encode(input_text, return_tensors="pt").input_ids)
150
  generated_text += tokenizer.decode(output[0], skip_special_tokens=True)
151
+ input_text = input_text[len(input_text):] # Si la entrada se agot贸, ya no hay m谩s que procesar
152
  return generated_text
153
 
154
  @app.post("/predict/")
 
163
 
164
  streamer = S3DirectStream(S3_BUCKET_NAME)
165
 
166
+ await streamer.create_s3_folders(model_name) # Crear las carpetas si no existen
167
 
168
  model = await streamer.load_model_from_s3(model_name)
169
  tokenizer = await streamer.load_tokenizer_from_s3(model_name)
 
175
 
176
  result = await asyncio.to_thread(nlp_pipeline, input_text)
177
 
178
+ chunks = split_text_by_tokens(result, tokenizer)
179
+
180
+ if len(chunks) > 1:
181
  full_result = ""
182
  for chunk in chunks:
183
  full_result += continue_generation(chunk, model, tokenizer)
184
+ return JSONResponse(content={"result": full_result})
185
+ else:
186
+ return JSONResponse(content={"result": result})
 
 
 
 
187
 
188
  except Exception as e:
189
+ raise HTTPException(status_code=500, detail=f"Error al realizar la predicci贸n: {e}")
 
190
 
191
  if __name__ == "__main__":
192
  import uvicorn