File size: 13,456 Bytes
7c21718
 
9de7b93
2e9ad50
7c21718
d05ede6
 
 
 
 
 
 
66c68f4
d05ede6
7c21718
a0b48c5
277e316
66c68f4
e6982de
e77c20c
66c68f4
b7effa9
d05ede6
7c21718
 
 
e6982de
d05ede6
 
 
7c21718
 
 
 
 
 
 
d05ede6
 
31c0598
7c21718
d05ede6
7c21718
 
d05ede6
7c21718
d05ede6
7c21718
 
 
 
 
d05ede6
7c21718
 
d05ede6
 
7c21718
 
 
d05ede6
 
 
66c68f4
d05ede6
66c68f4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d05ede6
66c68f4
 
 
 
 
 
 
 
d05ede6
7c21718
 
a0b48c5
7c21718
 
 
 
 
c8741b0
2e9ad50
7c21718
 
 
 
 
 
d05ede6
66c68f4
 
d05ede6
 
c17efbf
d05ede6
 
 
 
 
 
 
 
 
 
2e9ad50
d05ede6
b7effa9
d05ede6
b7effa9
d05ede6
 
2e9ad50
d05ede6
 
 
2e9ad50
c17efbf
e77c20c
d05ede6
7c21718
d05ede6
 
 
 
2e9ad50
 
 
 
 
d05ede6
2e9ad50
d05ede6
2e9ad50
d05ede6
2e9ad50
 
 
 
d05ede6
b7effa9
d05ede6
 
b7effa9
d05ede6
 
 
 
 
 
2e9ad50
 
d05ede6
6de156a
d05ede6
6de156a
d05ede6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b7effa9
d05ede6
b7effa9
 
d05ede6
 
 
 
66c68f4
d05ede6
 
66c68f4
d05ede6
 
 
 
 
 
 
 
66c68f4
b7effa9
66c68f4
 
b7effa9
 
d05ede6
 
 
 
 
 
 
 
2e9ad50
 
d05ede6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2e9ad50
d05ede6
7c21718
a0b48c5
7c21718
 
66c68f4
d05ede6
 
 
 
 
 
 
 
 
 
 
 
 
b7a38a6
d05ede6
e77c20c
d05ede6
66c68f4
d05ede6
7c21718
d05ede6
 
 
 
 
 
7c21718
a0b48c5
7c21718
 
66c68f4
d05ede6
 
 
 
 
 
 
 
 
 
 
 
 
 
6e229a7
d05ede6
 
e77c20c
d05ede6
e77c20c
d05ede6
66c68f4
d05ede6
7c21718
d05ede6
 
 
 
 
 
7c21718
a0b48c5
7c21718
 
66c68f4
d05ede6
 
 
 
 
 
 
 
 
 
 
 
 
6e229a7
d05ede6
 
e77c20c
d05ede6
66c68f4
d05ede6
7c21718
d05ede6
 
 
 
 
66c68f4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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,
    AutoModelForCausalLM,
    AutoTokenizer,
    GenerationConfig,
    StoppingCriteria,
    StoppingCriteriaList,
    pipeline
)
import uvicorn
import asyncio
import json
import base64
from huggingface_hub import login
from botocore.exceptions import NoCredentialsError
from functools import lru_cache
from typing import AsyncGenerator


HUGGINGFACE_HUB_TOKEN = os.getenv("HUGGINGFACE_HUB_TOKEN")

if HUGGINGFACE_HUB_TOKEN:
    login(token=HUGGINGFACE_HUB_TOKEN,
          add_to_git_credential=False)


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_data = {}  # Global dictionary to store model data

model_load_lock = asyncio.Lock() # Lock to avoid race conditions

@lru_cache(maxsize=None)
async def _load_model_and_tokenizer(model_name):
    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
          
          return {"model":model, "tokenizer":tokenizer}
    except Exception as e:
        raise HTTPException(
            status_code=500, detail=f"Error loading model: {e}"
        )

async def load_model_and_tokenizer(model_name):
    async with model_load_lock:
      if model_name in model_data:
          return model_data[model_name].get("model"), model_data[model_name].get("tokenizer")
      
      model_bundle = await _load_model_and_tokenizer(model_name)
      model_data[model_name] = model_bundle
      return model_bundle.get("model"), model_bundle.get("tokenizer")


@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 load_model_and_tokenizer(model_name)
        device = "cpu" # Force 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_json_responses(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) -> AsyncGenerator[dict, None]:
    
    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 not new_text:
            if not stop_criteria(outputs.sequences, None):
                yield {"text": output_text, "is_end": False}
                yield {"text": "", "is_end": True}
            break
        
        output_text += new_text
        
        yield {"text": new_text, "is_end": False}
              
        if stop_criteria(outputs.sequences, None):
            yield {"text": "", "is_end": True}
            break
        
        encoded_input = tokenizer(
            output_text, return_tensors="pt",
            truncation=True
        ).to(device)
        output_text = ""


async def stream_json_responses(generator: AsyncGenerator[dict, None]) -> AsyncGenerator[str, None]:
    async for data in generator:
        yield json.dumps(data) + "\n"


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 = "cpu" # Force CPU
        
        if validated_body.model_name not in model_data:
            config = AutoConfig.from_pretrained(
                    validated_body.model_name, token=HUGGINGFACE_HUB_TOKEN
                )
            model = pipeline(
                "text-to-image", model=validated_body.model_name,
                device=device, config=config
            )
            model_data[validated_body.model_name] = {"model":model}
        else:
            model = model_data[validated_body.model_name]["model"]
        
        image = model(validated_body.input_text)[0]
        
        image_data = list(image.getdata())
        
        return JSONResponse({"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 = "cpu"  # Force CPU

        if validated_body.model_name not in model_data:
             config = AutoConfig.from_pretrained(
                    validated_body.model_name, token=HUGGINGFACE_HUB_TOKEN
                )
            
             audio_generator = pipeline(
                "text-to-speech", model=validated_body.model_name,
                device=device, config=config
            )
             model_data[validated_body.model_name] = {"model":audio_generator}
        else:
            audio_generator = model_data[validated_body.model_name]["model"]

        audio = audio_generator(validated_body.input_text)

        
        audio_bytes = audio["audio"]
        
        audio_base64 = base64.b64encode(audio_bytes).decode('utf-8')
        
        return JSONResponse({"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 = "cpu"  # Force CPU
        if validated_body.model_name not in model_data:
            config = AutoConfig.from_pretrained(
                    validated_body.model_name, token=HUGGINGFACE_HUB_TOKEN
                )
            
            video_generator = pipeline(
                "text-to-video", model=validated_body.model_name,
                device=device, config=config
            )
            model_data[validated_body.model_name] = {"model":video_generator}
        else:
            video_generator = model_data[validated_body.model_name]["model"]

        video = video_generator(validated_body.input_text)
        
        
        video_base64 = base64.b64encode(video).decode('utf-8')
        
        return JSONResponse({"video": video_base64, "is_end": True})

    except Exception as e:
        raise HTTPException(
            status_code=500,
            detail=f"Internal server error: {str(e)}"
        )

@app.on_event("startup")
async def startup_event():
    # Load models here
    print("Loading models...")
    
    models_to_load = set()
    
    for env_var_key, env_var_value in os.environ.items():
        if env_var_key.startswith("MODEL_NAME_"):
            models_to_load.add(env_var_value)
            
    
    for model_name in models_to_load:
        try:
            await load_model_and_tokenizer(model_name)
            print(f"Model {model_name} loaded")
        except Exception as e:
             print(f"Error loading model {model_name}: {e}")
            

    print("Models loaded.")

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