Xilixmeaty40 commited on
Commit
3edcab0
·
verified ·
1 Parent(s): 837a8df

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +167 -0
app.py ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from gradio_client import Client
3
+ from huggingface_hub import InferenceClient, HFRepository
4
+
5
+ import random
6
+
7
+ # Cargar modelos desde un archivo de texto
8
+ def load_models_from_file(filename):
9
+ with open(filename, 'r') as file:
10
+ models = [line.strip() for line in file.readlines() if line.strip()]
11
+ return models
12
+
13
+ # Cargar modelos desde un archivo de texto (models.txt)
14
+ models = load_models_from_file("models.txt")
15
+
16
+ # Crear clientes de inferencia para cada modelo
17
+ clients = []
18
+ for model in models:
19
+ try:
20
+ clients.append(InferenceClient(model))
21
+ except Exception as e:
22
+ print(f"Error loading model {model}: {str(e)}")
23
+
24
+ # Cargar conjuntos de datos desde un archivo de texto
25
+ def load_datasets_from_file(filename):
26
+ with open(filename, 'r') as file:
27
+ datasets = [line.strip() for line in file.readlines() if line.strip()]
28
+ return datasets
29
+
30
+ # Cargar conjuntos de datos desde un archivo de texto (datasets.txt)
31
+ datasets = load_datasets_from_file("datasets.txt")
32
+
33
+ # Crear clientes de repositorio para cada conjunto de datos
34
+ repository_clients = []
35
+ for dataset in datasets:
36
+ try:
37
+ repository_clients.append(HFRepository(dataset))
38
+ except Exception as e:
39
+ print(f"Error loading dataset {dataset}: {str(e)}")
40
+
41
+ VERBOSE = False
42
+
43
+ def format_prompt(message, history, cust_p):
44
+ prompt = ""
45
+ if history:
46
+ for user_prompt, bot_response in history:
47
+ prompt += f"<start_of_turn>user{user_prompt}<end_of_turn>"
48
+ prompt += f"<start_of_turn>model{bot_response}<end_of_turn>"
49
+ if VERBOSE:
50
+ print(prompt)
51
+ prompt += cust_p.replace("USER_INPUT", message)
52
+ return prompt
53
+
54
+ def chat_inf(system_prompt, prompt, history, memory, client_choice, seed, temp, tokens, top_p, rep_p, chat_mem, cust_p):
55
+ if not clients or not repository_clients:
56
+ yield [("Error", "No models or datasets available")], memory
57
+ else:
58
+ try:
59
+ client = clients[int(client_choice) - 1]
60
+ hist_len = 0
61
+ if not history:
62
+ history = []
63
+ if not memory:
64
+ memory = []
65
+ if memory:
66
+ for ea in memory[0 - chat_mem:]:
67
+ hist_len += len(str(ea))
68
+ in_len = len(system_prompt + prompt) + hist_len
69
+
70
+ if (in_len + tokens) > 500000:
71
+ history.append((prompt, "Wait, that's too many tokens, please reduce the 'Chat Memory' value, or reduce the 'Max new tokens' value"))
72
+ yield history, memory
73
+ else:
74
+ generate_kwargs = dict(
75
+ temperature=temp,
76
+ max_new_tokens=tokens,
77
+ top_p=top_p,
78
+ repetition_penalty=rep_p,
79
+ do_sample=True,
80
+ seed=seed,
81
+ )
82
+ if system_prompt:
83
+ formatted_prompt = format_prompt(f"{system_prompt}, {prompt}", memory[0 - chat_mem:], cust_p)
84
+ else:
85
+ formatted_prompt = format_prompt(prompt, memory[0 - chat_mem:], cust_p)
86
+ stream = client.text_generation(formatted_prompt, **generate_kwargs, stream=True, details=True, return_full_text=True)
87
+ output = ""
88
+ for response in stream:
89
+ output += response.token.text
90
+ yield [(prompt, output)], memory
91
+ history.append((prompt, output))
92
+ memory.append((prompt, output))
93
+ except Exception as e:
94
+ yield [(prompt, f"Error: {str(e)}")], memory
95
+
96
+ def get_screenshot(chat: list, height=5000, width=600, chatblock=[], theme="light", wait=3000, header=True):
97
+ tog = 0
98
+ if chatblock:
99
+ tog = 3
100
+ result = ss_client.predict(str(chat), height, width, chatblock, header, theme, wait, api_name="/run_script")
101
+ out = f'https://xilixmeaty40-testing.hf.space/file={result[tog]}'
102
+ return out
103
+
104
+ def clear_fn():
105
+ return None, None, None, None
106
+
107
+ rand_val = random.randint(1, 1111111111111111)
108
+
109
+ def check_rand(inp, val):
110
+ if inp:
111
+ return gr.Slider(label="Seed", minimum=1, maximum=1111111111111111, value=random.randint(1, 1111111111111111))
112
+ else:
113
+ return gr.Slider(label="Seed", minimum=1, maximum=1111111111111111, value=int(val))
114
+
115
+ with gr.Blocks() as app:
116
+ memory = gr.State()
117
+ gr.HTML("""<center><h1 style='font-size:xx-large;'>Google Gemma Models</h1><br><h3>running on Huggingface Inference Client</h3><br><h7>EXPERIMENTAL""")
118
+ chat_b = gr.Chatbot(height=500)
119
+ with gr.Group():
120
+ with gr.Row():
121
+ with gr.Column(scale=3):
122
+ inp = gr.Textbox(label="Prompt")
123
+ sys_inp = gr.Textbox(label="System Prompt (optional)")
124
+ with gr.Accordion("Prompt Format", open=False):
125
+ custom_prompt = gr.Textbox(label="Modify Prompt Format", info="For testing purposes. 'USER_INPUT' is where 'SYSTEM_PROMPT, PROMPT' will be placed", lines=3, value="<start_of_turn>userUSER_INPUT<end_of_turn><start_of_turn>model")
126
+ with gr.Row():
127
+ with gr.Column(scale=2):
128
+ btn = gr.Button("Chat")
129
+ with gr.Column(scale=1):
130
+ with gr.Group():
131
+ stop_btn = gr.Button("Stop")
132
+ clear_btn = gr.Button("Clear")
133
+ client_choice = gr.Dropdown(label="Models", type='index', choices=[c for c in models], value=models[0], interactive=True)
134
+ with gr.Column(scale=1):
135
+ with gr.Group():
136
+ rand = gr.Checkbox(label="Random Seed", value=True)
137
+ seed = gr.Slider(label="Seed", minimum=1, maximum=1111111111111111, step=1, value=rand_val)
138
+ tokens = gr.Slider(label="Max new tokens", value=1600, minimum=0, maximum=500000, step=64, interactive=True, visible=True, info="The maximum number of tokens")
139
+ temp = gr.Slider(label="Temperature", step=0.01, minimum=0.01, maximum=1.0, value=0.49)
140
+ top_p = gr.Slider(label="Top-P", step=0.01, minimum=0.01, maximum=1.0, value=0.49)
141
+ rep_p = gr.Slider(label="Repetition Penalty", step=0.01, minimum=0.1, maximum=2.0, value=0.99)
142
+ chat_mem = gr.Number(label="Chat Memory", info="Number of previous chats to retain", value=4)
143
+ with gr.Accordion(label="Screenshot", open=False):
144
+ with gr.Row():
145
+ with gr.Column(scale=3):
146
+ im_btn = gr.Button("Screenshot")
147
+ img = gr.Image(type='filepath')
148
+ with gr.Column(scale=1):
149
+ with gr.Row():
150
+ im_height = gr.Number(label="Height", value=5000)
151
+ im_width = gr.Number(label="Width", value=500)
152
+ wait_time = gr.Number(label="Wait Time", value=3000)
153
+ theme = gr.Radio(label="Theme", choices=["light", "dark"], value="light")
154
+ chatblock = gr.Dropdown(label="Chatblocks", info="Choose specific blocks of chat", choices=[c for c in range(1, 40)], multiselect=True)
155
+
156
+ client_choice.change(load_models, client_choice, [chat_b])
157
+ app.load(load_models, client_choice, [chat_b])
158
+
159
+ im_go = im_btn.click(get_screenshot, [chat_b, im_height, im_width, chatblock, theme, wait_time], img)
160
+
161
+ chat_sub = inp.submit(check_rand, [rand, seed], seed).then(chat_inf, [sys_inp, inp, chat_b, memory, client_choice, seed, temp, tokens, top_p, rep_p, chat_mem, custom_prompt], [chat_b, memory])
162
+ go = btn.click(check_rand, [rand, seed], seed).then(chat_inf, [sys_inp, inp, chat_b, memory, client_choice, seed, temp, tokens, top_p, rep_p, chat_mem, custom_prompt], [chat_b, memory])
163
+
164
+ stop_btn.click(None, None, None, cancels=[go, im_go, chat_sub])
165
+ clear_btn.click(clear_fn, None, [inp, sys_inp, chat_b, memory])
166
+
167
+ app.queue(default_concurrency_limit=10).launch()