File size: 5,575 Bytes
63a3448
3e60998
12fa10e
40bfc4e
591c7b1
a83c936
9c95830
 
df37b63
12fa10e
5101abe
 
 
 
 
9c95830
288b3a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63a3448
ff71cd5
 
 
 
 
 
 
 
 
 
 
 
12fa10e
 
 
ff71cd5
 
 
 
 
 
 
 
 
 
 
12fa10e
 
ff71cd5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12fa10e
ff71cd5
 
 
 
 
 
12fa10e
ff71cd5
 
c1ccf5a
12fa10e
c1ccf5a
 
 
ff71cd5
 
 
 
 
288b3a4
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
import gradio as gr
from config import howManyModelsToUse,num_models,max_images,inference_timeout,MAX_SEED,thePrompt,preSetPrompt,negPreSetPrompt
from all_models import models
import asyncio
from externalmod import gr_Interface_load, save_image, randomize_seed
import os
from threading import RLock
lock = RLock()
HF_TOKEN = os.getenv("ohgoddamn")
default_models = models[:num_models]
def get_current_time():
    from datetime import datetime
    now = datetime.now()
    current_time = now.strftime("%y-%m-%d %H:%M:%S")
    return current_time








def load_fn(models, HF_TOKEN):
    global models_load
    models_load = {}
    for model in models:
        if model not in models_load:
            try:
                m = gr_Interface_load(f'models/{model}', hf_token=HF_TOKEN)
                models_load[model] = m.fn  # Store the callable
            except Exception as error:
                print(error)
                models_load[model] = lambda **kwargs: None

async def infer(model_str, prompt, nprompt="", height=0, width=0, steps=0, cfg=0, seed=-1, timeout=120, hf_token=None):
    print(f"{prompt}\n{model_str}\n{timeout}\n")
    kwargs = {}
    if height > 0: kwargs["height"] = height
    if width > 0: kwargs["width"] = width
    if steps > 0: kwargs["num_inference_steps"] = steps
    if cfg > 0: kwargs["guidance_scale"] = cfg
    kwargs["negative_prompt"] = nprompt

    theSeed = randomize_seed() if seed == -1 else seed
    kwargs["seed"] = theSeed
    if hf_token:
        kwargs["token"] = hf_token

    try:
        task = asyncio.create_task(asyncio.to_thread(models_load[model_str], prompt=prompt, **kwargs))
        result = await asyncio.wait_for(task, timeout=timeout)
    except asyncio.TimeoutError as e:
        print(f"Timeout: {model_str}")
        if not task.done(): task.cancel()
        raise Exception(f"Timeout: {model_str}") from e
    except Exception as e:
        print(f"Exception: {model_str} -> {e}")
        if not task.done(): task.cancel()
        raise Exception(f"Inference failed: {model_str}") from e

    if result is not None and not isinstance(result, tuple):
        with lock:
            png_path =  model_str.replace("/", "_") + " - " + get_current_time() + "_" + str(theSeed) + ".png"
            image = save_image(result, png_path, model_str, prompt, nprompt, height, width, steps, cfg, theSeed)
        return image
    return None

def gen_fn(model_str, prompt, nprompt="", height=0, width=0, steps=0, cfg=0, seed=-1, inference_timeout2=120):
    try:
        loop = asyncio.new_event_loop()
        result = loop.run_until_complete(infer(model_str, prompt, nprompt,
                                               height, width, steps, cfg, seed, inference_timeout2, HF_TOKEN))
    except Exception as e:
        print(f"gen_fn: Task aborted: {model_str} -> {e}")
        raise gr.Error(f"Task aborted: {model_str}, Error: {e}")
    finally:
        loop.close()
    return result





    
'''
def load_fn(models,HF_TOKEN):
    global models_load
    models_load = {}
    for model in models:
        if model not in models_load.keys():
            try:
                m = gr_Interface_load(f'models/{model}', hf_token=HF_TOKEN)
            except Exception as error:
                print(error)
                m = gr.Interface(lambda: None, ['text'], ['image'])
            models_load.update({model: m})

async def infer(model_str, prompt, nprompt="", height=0, width=0, steps=0, cfg=0, seed=-1, timeout=inference_timeout):
    print(f"{prompt}\n")
    print(f"{model_str}\n")
    print(f"{timeout}\n")
    kwargs = {}
    if height > 0: kwargs["height"] = height
    if width > 0: kwargs["width"] = width
    if steps > 0: kwargs["num_inference_steps"] = steps
    if cfg > 0: cfg = kwargs["guidance_scale"] = cfg
    if seed == -1:
        theSeed = randomize_seed()
    else: 
        theSeed = seed
    kwargs["seed"] = theSeed
    task = asyncio.create_task(asyncio.to_thread(models_load[model_str].fn, prompt=prompt, negative_prompt=nprompt, **kwargs, token=HF_TOKEN))
    print(f"await")
    await asyncio.sleep(20)
    try:
        result = await asyncio.wait_for(task, timeout=timeout)
    except asyncio.TimeoutError as e:
        print(e)
        print(f"infer: Task timed out: {model_str}")
        if not task.done(): task.cancel()
        result = None
        raise Exception(f"Task timed out: {model_str}") from e
    except Exception as e:
        print(e)
        print(f"infer: exception: {model_str}")
        if not task.done(): task.cancel()
        result = None
        raise Exception() from e
    if task.done() and result is not None and not isinstance(result, tuple):
        print(f"{result}")
        with lock:
            png_path =  model_str.replace("/", "_") + " - " + get_current_time() + "_" + str(theSeed) + ".png"
            image = save_image(result, png_path, model_str, prompt, nprompt, height, width, steps, cfg, theSeed)
        return image
    return None

def gen_fn(model_str, prompt, nprompt="", height=0, width=0, steps=0, cfg=0, seed=-1, inference_timeout2=120):
    try:
        loop = asyncio.new_event_loop()
        result = loop.run_until_complete(infer(model_str, prompt, nprompt,
                                         height, width, steps, cfg, seed, inference_timeout2))
    except (Exception, asyncio.CancelledError) as e:
        print(e)
        print(f"gen_fn: Task aborted: {model_str}")
        result = None
        raise gr.Error(f"Task aborted: {model_str}, Error: {e}")
    finally:
        loop.close()
    return result
'''