Spaces:
Sleeping
Sleeping
File size: 14,228 Bytes
7c21718 9de7b93 2e9ad50 7c21718 718116c 7c21718 4bb04f8 2e9ad50 7c21718 a0b48c5 7c21718 277e316 e6982de 6e229a7 e77c20c 7c21718 e77c20c e6982de e77c20c e6982de e77c20c 7c21718 2e9ad50 31c0598 7c21718 2e9ad50 7c21718 e6982de 7c21718 b7a38a6 7c21718 e77c20c e6982de 7c21718 a0b48c5 b7a38a6 31c0598 e6982de 564b6ea e6982de e77c20c 718116c 564b6ea e6982de 31c0598 e6982de 2e9ad50 e6982de 2e9ad50 b7a38a6 7c21718 3ed39a1 e6982de 2e9ad50 e6982de e77c20c 718116c 5d4a408 e6982de 2e9ad50 e77c20c 7c21718 e77c20c 2e9ad50 e77c20c 2e9ad50 7c21718 e6982de 7c21718 a0b48c5 7c21718 c8741b0 2e9ad50 7c21718 a0b48c5 7c21718 2e9ad50 c17efbf c8741b0 c17efbf 2e9ad50 c17efbf 2e9ad50 a0b48c5 2e9ad50 c17efbf e77c20c e6982de 7c21718 e6982de b5fcdec 2e9ad50 6e7eb77 2e9ad50 f7e7ec1 2e9ad50 a0b48c5 2e9ad50 eeba3ac 2e9ad50 eeba3ac 2e9ad50 6de156a eeba3ac 6de156a a0b48c5 2e9ad50 6de156a 2e9ad50 6de156a b7a38a6 a0b48c5 2e9ad50 a0b48c5 2e9ad50 f7e7ec1 a0b48c5 7c21718 a0b48c5 7c21718 b7a38a6 e77c20c e6982de 7c21718 e6982de e77c20c e6982de 7c21718 a0b48c5 7c21718 e6982de b7a38a6 6e229a7 78f7e86 e77c20c 7c21718 e6982de e77c20c e6982de 7c21718 a0b48c5 7c21718 b7a38a6 e77c20c e6982de b7a38a6 6e229a7 e77c20c e6982de 7c21718 e6982de e77c20c e6982de 7c21718 |
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 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 |
import os
import torch
from fastapi import FastAPI, HTTPException
from fastapi.responses import StreamingResponse, JSONResponse
from pydantic import BaseModel, field_validator
from transformers import (
AutoConfig,
pipeline,
AutoModelForCausalLM,
AutoTokenizer,
GenerationConfig,
StoppingCriteria,
StoppingCriteriaList,
)
import boto3
import uvicorn
import asyncio
from transformers import pipeline
import json
from huggingface_hub import login
import base64
from botocore.exceptions import NoCredentialsError
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")
HUGGINGFACE_HUB_TOKEN = os.getenv("HUGGINGFACE_HUB_TOKEN")
if HUGGINGFACE_HUB_TOKEN:
login(token=HUGGINGFACE_HUB_TOKEN,
add_to_git_credential=False)
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()
class GenerateRequest(BaseModel):
model_name: str
input_text: str = ""
task_type: str
temperature: float = 1.0
max_new_tokens: int = 3
stream: bool = True
top_p: float = 1.0
top_k: int = 50
repetition_penalty: float = 1.0
num_return_sequences: int = 1
do_sample: bool = True
stop_sequences: list[str] = []
@field_validator("model_name")
def model_name_cannot_be_empty(cls, v):
if not v:
raise ValueError("model_name cannot be empty.")
return v
@field_validator("task_type")
def task_type_must_be_valid(cls, v):
valid_types = ["text-to-text", "text-to-image",
"text-to-speech", "text-to-video"]
if v not in valid_types:
raise ValueError(f"task_type must be one of: {valid_types}")
return v
model_cache = {}
class S3ModelLoader:
def __init__(self, bucket_name, s3_client):
self.bucket_name = bucket_name
self.s3_client = s3_client
def _get_s3_uri(self, model_name):
return f"s3://{self.bucket_name}/" \
f"{model_name.replace('/', '-')}"
async def load_model_and_tokenizer(self, model_name):
if model_name in model_cache:
return model_cache[model_name]
s3_uri = self._get_s3_uri(model_name)
try:
config = AutoConfig.from_pretrained(
s3_uri, local_files_only=False
)
model = AutoModelForCausalLM.from_pretrained(
s3_uri, config=config, local_files_only=False
)
tokenizer = AutoTokenizer.from_pretrained(
s3_uri, config=config, local_files_only=False
)
if tokenizer.eos_token_id is not None and \
tokenizer.pad_token_id is None:
tokenizer.pad_token_id = config.pad_token_id \
or tokenizer.eos_token_id
model_cache[model_name] = (model, tokenizer)
return model, tokenizer
except (EnvironmentError, NoCredentialsError):
try:
config = AutoConfig.from_pretrained(
model_name, token=HUGGINGFACE_HUB_TOKEN
)
tokenizer = AutoTokenizer.from_pretrained(
model_name, config=config, token=HUGGINGFACE_HUB_TOKEN
)
model = AutoModelForCausalLM.from_pretrained(
model_name, config=config, token=HUGGINGFACE_HUB_TOKEN
)
if tokenizer.eos_token_id is not None and \
tokenizer.pad_token_id is None:
tokenizer.pad_token_id = config.pad_token_id \
or tokenizer.eos_token_id
model.save_pretrained(s3_uri)
tokenizer.save_pretrained(s3_uri)
config = AutoConfig.from_pretrained(
s3_uri, local_files_only=False
)
model = AutoModelForCausalLM.from_pretrained(
s3_uri, config=config, local_files_only=False
)
tokenizer = AutoTokenizer.from_pretrained(
s3_uri, config=config, local_files_only=False
)
model_cache[model_name] = (model, tokenizer)
return model, tokenizer
except Exception as e:
raise HTTPException(
status_code=500, detail=f"Error loading model: {e}"
)
model_loader = S3ModelLoader(S3_BUCKET_NAME, s3_client)
@app.post("/generate")
async def generate(request: GenerateRequest):
try:
model_name = request.model_name
input_text = request.input_text
task_type = request.task_type
temperature = request.temperature
max_new_tokens = request.max_new_tokens
stream = request.stream
top_p = request.top_p
top_k = request.top_k
repetition_penalty = request.repetition_penalty
num_return_sequences = request.num_return_sequences
do_sample = request.do_sample
stop_sequences = request.stop_sequences
model, tokenizer = await model_loader.load_model_and_tokenizer(model_name)
device = "cuda" if torch.cuda.is_available() else "cpu"
model.to(device)
if "text-to-text" == task_type:
generation_config = GenerationConfig(
temperature=temperature,
max_new_tokens=max_new_tokens,
top_p=top_p,
top_k=top_k,
repetition_penalty=repetition_penalty,
do_sample=do_sample,
num_return_sequences=num_return_sequences,
eos_token_id = tokenizer.eos_token_id
)
if stream:
return StreamingResponse(
stream_text(model, tokenizer, input_text,
generation_config, stop_sequences,
device),
media_type="text/plain"
)
else:
result = await generate_text(model, tokenizer, input_text,
generation_config, stop_sequences,
device)
return JSONResponse({"text": result, "is_end": True})
else:
return HTTPException(status_code=400, detail="Task type not text-to-text")
except Exception as e:
raise HTTPException(
status_code=500, detail=f"Internal server error: {str(e)}"
)
class StopOnSequences(StoppingCriteria):
def __init__(self, stop_sequences, tokenizer):
self.stop_sequences = stop_sequences
self.tokenizer = tokenizer
self.stop_ids = [tokenizer.encode(seq, add_special_tokens=False) for seq in stop_sequences]
def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> bool:
decoded_text = self.tokenizer.decode(input_ids[0], skip_special_tokens=True)
for stop_sequence in self.stop_sequences:
if stop_sequence in decoded_text:
return True
return False
async def stream_text(model, tokenizer, input_text,
generation_config, stop_sequences,
device):
encoded_input = tokenizer(
input_text, return_tensors="pt",
truncation=True
).to(device)
stop_criteria = StopOnSequences(stop_sequences, tokenizer)
stopping_criteria = StoppingCriteriaList([stop_criteria])
output_text = ""
while True:
outputs = await asyncio.to_thread(model.generate,
**encoded_input,
do_sample=generation_config.do_sample,
max_new_tokens=generation_config.max_new_tokens,
temperature=generation_config.temperature,
top_p=generation_config.top_p,
top_k=generation_config.top_k,
repetition_penalty=generation_config.repetition_penalty,
num_return_sequences=generation_config.num_return_sequences,
output_scores=True,
return_dict_in_generate=True,
stopping_criteria=stopping_criteria
)
new_text = tokenizer.decode(
outputs.sequences[0][len(encoded_input["input_ids"][0]):],
skip_special_tokens=True
)
if len(new_text) == 0:
if not stop_criteria(outputs.sequences, None):
for text in output_text.split():
yield json.dumps({"text": text, "is_end": False}) + "\n"
yield json.dumps({"text": "", "is_end": True}) + "\n"
break
output_text += new_text
for text in new_text.split():
yield json.dumps({"text": text, "is_end": False}) + "\n"
if stop_criteria(outputs.sequences, None):
yield json.dumps({"text": "", "is_end": True}) + "\n"
break
encoded_input = tokenizer(
output_text, return_tensors="pt",
truncation=True
).to(device)
output_text = ""
async def generate_text(model, tokenizer, input_text,
generation_config, stop_sequences,
device):
encoded_input = tokenizer(
input_text, return_tensors="pt",
truncation=True
).to(device)
stop_criteria = StopOnSequences(stop_sequences, tokenizer)
stopping_criteria = StoppingCriteriaList([stop_criteria])
outputs = await asyncio.to_thread(model.generate,
**encoded_input,
do_sample=generation_config.do_sample,
max_new_tokens=generation_config.max_new_tokens,
temperature=generation_config.temperature,
top_p=generation_config.top_p,
top_k=generation_config.top_k,
repetition_penalty=generation_config.repetition_penalty,
num_return_sequences=generation_config.num_return_sequences,
output_scores=True,
return_dict_in_generate=True,
stopping_criteria=stopping_criteria
)
generated_text = tokenizer.decode(
outputs.sequences[0], skip_special_tokens=True
)
return generated_text
@app.post("/generate-image")
async def generate_image(request: GenerateRequest):
try:
validated_body = request
device = "cuda" if torch.cuda.is_available() else "cpu"
if validated_body.model_name not in model_cache:
model = pipeline(
"text-to-image", model=validated_body.model_name,
device=device
)
model_cache[validated_body.model_name] = model
else:
model = model_cache[validated_body.model_name]
image = model(validated_body.input_text)[0]
image_data = list(image.getdata())
return json.dumps({"image_data": image_data, "is_end": True})
except Exception as e:
raise HTTPException(
status_code=500,
detail=f"Internal server error: {str(e)}"
)
@app.post("/generate-text-to-speech")
async def generate_text_to_speech(request: GenerateRequest):
try:
validated_body = request
device = "cuda" if torch.cuda.is_available() else "cpu"
if validated_body.model_name not in model_cache:
audio_generator = pipeline(
"text-to-speech", model=validated_body.model_name,
device=device
)
model_cache[validated_body.model_name] = audio_generator
else:
audio_generator = model_cache[validated_body.model_name]
audio = audio_generator(validated_body.input_text)
audio_bytes = audio["audio"]
audio_base64 = base64.b64encode(audio_bytes).decode('utf-8')
return json.dumps({"audio": audio_base64, "is_end": True})
except Exception as e:
raise HTTPException(
status_code=500,
detail=f"Internal server error: {str(e)}"
)
@app.post("/generate-video")
async def generate_video(request: GenerateRequest):
try:
validated_body = request
device = "cuda" if torch.cuda.is_available() else "cpu"
if validated_body.model_name not in model_cache:
video_generator = pipeline(
"text-to-video", model=validated_body.model_name,
device=device
)
model_cache[validated_body.model_name] = video_generator
else:
video_generator = model_cache[validated_body.model_name]
video = video_generator(validated_body.input_text)
video_base64 = base64.b64encode(video).decode('utf-8')
return json.dumps({"video": video_base64, "is_end": True})
except Exception as e:
raise HTTPException(
status_code=500,
detail=f"Internal server error: {str(e)}"
)
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=7860) |