Spaces:
Sleeping
Sleeping
Hjgugugjhuhjggg
commited on
Update app.py
Browse files
app.py
CHANGED
@@ -5,15 +5,22 @@ import boto3
|
|
5 |
from fastapi import FastAPI, HTTPException
|
6 |
from fastapi.responses import JSONResponse
|
7 |
from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
|
|
|
8 |
import asyncio
|
9 |
|
10 |
-
|
11 |
logger = logging.getLogger(__name__)
|
|
|
|
|
|
|
|
|
|
|
12 |
|
13 |
AWS_ACCESS_KEY_ID = os.getenv("AWS_ACCESS_KEY_ID")
|
14 |
AWS_SECRET_ACCESS_KEY = os.getenv("AWS_SECRET_ACCESS_KEY")
|
15 |
AWS_REGION = os.getenv("AWS_REGION")
|
16 |
S3_BUCKET_NAME = os.getenv("S3_BUCKET_NAME")
|
|
|
17 |
|
18 |
MAX_TOKENS = 1024
|
19 |
|
@@ -81,7 +88,7 @@ class S3DirectStream:
|
|
81 |
model_files = await self.get_model_file_parts(model_prefix)
|
82 |
|
83 |
if not model_files:
|
84 |
-
|
85 |
|
86 |
config_stream = await self.stream_from_s3(f"{model_prefix}/config.json")
|
87 |
config_data = config_stream.read()
|
@@ -107,7 +114,7 @@ class S3DirectStream:
|
|
107 |
tokenizer_stream = await self.stream_from_s3(f"{profile}/{model}/tokenizer.json")
|
108 |
tokenizer_data = tokenizer_stream.read().decode("utf-8")
|
109 |
|
110 |
-
tokenizer = AutoTokenizer.from_pretrained(f"{profile}/{model}")
|
111 |
return tokenizer
|
112 |
except Exception as e:
|
113 |
raise HTTPException(status_code=500, detail=f"Error al cargar el tokenizer desde S3: {e}")
|
@@ -131,6 +138,22 @@ class S3DirectStream:
|
|
131 |
except self.s3_client.exceptions.ClientError:
|
132 |
return False
|
133 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
134 |
def split_text_by_tokens(text, tokenizer, max_tokens=MAX_TOKENS):
|
135 |
tokens = tokenizer.encode(text)
|
136 |
chunks = []
|
@@ -173,18 +196,22 @@ async def predict(model_request: dict):
|
|
173 |
|
174 |
result = await asyncio.to_thread(nlp_pipeline, input_text)
|
175 |
|
176 |
-
|
177 |
-
|
178 |
-
if len(chunks) > 1:
|
179 |
full_result = ""
|
180 |
for chunk in chunks:
|
181 |
full_result += continue_generation(chunk, model, tokenizer)
|
182 |
-
return
|
183 |
-
|
184 |
-
|
|
|
|
|
|
|
|
|
185 |
|
186 |
except Exception as e:
|
187 |
-
|
|
|
188 |
|
189 |
if __name__ == "__main__":
|
190 |
import uvicorn
|
|
|
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 |
|
|
|
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()
|
|
|
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 |
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 = []
|
|
|
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
|