Xilixmeaty40 commited on
Commit
db3b038
verified
1 Parent(s): 80af556

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +49 -70
app.py CHANGED
@@ -3,40 +3,34 @@ from gradio_client import Client
3
  from huggingface_hub import InferenceClient
4
  import random
5
 
6
- # Configuraci贸n del cliente
7
  ss_client = Client("https://xilixmeaty40-testing.hf.space/")
8
 
9
- # Carga de modelos desde un archivo
10
  with open("models.txt", "r") as file:
11
  models = file.read().splitlines()
12
 
13
- # Creaci贸n de clientes de inferencia para cada modelo
14
- clients = [InferenceClient(model) for model in models]
 
 
 
 
 
15
 
16
- # Variable para controlar la verbosidad del programa
17
- VERBOSE = False
18
 
19
- # Funci贸n para cargar modelos
20
  def load_models(inp):
21
- if VERBOSE:
22
- print(type(inp))
23
- print(inp)
24
- print(models[inp])
25
  return gr.update(label=models[inp])
26
 
27
- # Funci贸n para dar formato al prompt de entrada
28
  def format_prompt(message, history, cust_p):
29
  prompt = ""
30
  if history:
31
  for user_prompt, bot_response in history:
32
  prompt += f"<start_of_turn>user{user_prompt}<end_of_turn>"
33
  prompt += f"<start_of_turn>model{bot_response}<end_of_turn>"
34
- if VERBOSE:
35
- print(prompt)
36
  prompt += cust_p.replace("USER_INPUT", message)
37
  return prompt
38
 
39
- # Funci贸n para la interacci贸n de chat
40
  def chat_inf(system_prompt, prompt, history, memory, client_choice, seed, temp, tokens, top_p, rep_p, chat_mem, cust_p):
41
  hist_len = 0
42
  client = clients[int(client_choice) - 1]
@@ -65,17 +59,20 @@ def chat_inf(system_prompt, prompt, history, memory, client_choice, seed, temp,
65
  formatted_prompt = format_prompt(f"{system_prompt}, {prompt}", memory[0 - chat_mem:], cust_p)
66
  else:
67
  formatted_prompt = format_prompt(prompt, memory[0 - chat_mem:], cust_p)
68
- stream = client.text_generation(formatted_prompt, **generate_kwargs, stream=True, details=True, return_full_text=True)
69
- output = ""
70
- for response in stream:
71
- output += response.token.text
72
- yield [(prompt, output)], memory
73
- history.append((prompt, output))
74
- memory.append((prompt, output))
75
- yield history, memory
76
-
77
- # Funci贸n para obtener capturas de pantalla
78
- def get_screenshot(chat: list, height=5000, width=600, chatblock=[], theme="light", wait=3000, header=True):
 
 
 
79
  tog = 0
80
  if chatblock:
81
  tog = 3
@@ -83,21 +80,17 @@ def get_screenshot(chat: list, height=5000, width=600, chatblock=[], theme="ligh
83
  out = f'https://xilixmeaty40-testing.hf.space/file={result[tog]}'
84
  return out
85
 
86
- # Funci贸n para limpiar los campos
87
  def clear_fn():
88
  return None, None, None, None
89
 
90
- # Generaci贸n de un valor aleatorio para la semilla
91
  rand_val = random.randint(1, 1111111111111111)
92
 
93
- # Funci贸n para verificar y establecer la semilla aleatoria
94
  def check_rand(inp, val):
95
  if inp:
96
  return gr.Slider(label="Seed", minimum=1, maximum=1111111111111111, value=random.randint(1, 1111111111111111))
97
  else:
98
  return gr.Slider(label="Seed", minimum=1, maximum=1111111111111111, value=int(val))
99
 
100
- # Creaci贸n de la aplicaci贸n con Gradio
101
  with gr.Blocks() as app:
102
  memory = gr.State()
103
  gr.HTML("""<center><h1 style='font-size:xx-large;'>Google Gemma Models</h1><br><h3>running on Huggingface Inference Client</h3><br><h7>EXPERIMENTAL""")
@@ -107,49 +100,35 @@ with gr.Blocks() as app:
107
  with gr.Column(scale=3):
108
  inp = gr.Textbox(label="Prompt")
109
  sys_inp = gr.Textbox(label="System Prompt (optional)")
110
- with gr.Accordion("Prompt Format", open=False):
111
- 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")
112
  with gr.Row():
113
  with gr.Column(scale=2):
114
  btn = gr.Button("Chat")
115
  with gr.Column(scale=1):
116
- with gr.Group():
117
- stop_btn = gr.Button("Stop")
118
- clear_btn = gr.Button("Clear")
119
- client_choice = gr.Dropdown(label="Models", type='index', choices=[c for c in models], value=models[0], interactive=True)
120
  with gr.Column(scale=1):
121
- with gr.Group():
122
- rand = gr.Checkbox(label="Random Seed", value=True)
123
- seed = gr.Slider(label="Seed", minimum=1, maximum=1111111111111111, step=1, value=rand_val)
124
- tokens = gr.Slider(label="Max new tokens", value=300000, minimum=0, maximum=800000, step=64, interactive=True, visible=True, info="The maximum number of tokens")
125
- temp = gr.Slider(label="Temperature", step=0.01, minimum=0.01, maximum=1.0, value=0.49)
126
- top_p = gr.Slider(label="Top-P", step=0.01, minimum=0.01, maximum=1.0, value=0.49)
127
- rep_p = gr.Slider(label="Repetition Penalty", step=0.01, minimum=0.1, maximum=2.0, value=0.99)
128
- chat_mem = gr.Number(label="Chat Memory", info="Number of previous chats to retain", value=4)
129
  with gr.Accordion(label="Screenshot", open=False):
130
- with gr.Row():
131
- with gr.Column(scale=3):
132
- im_btn = gr.Button("Screenshot")
133
- img = gr.Image(type='filepath')
134
- with gr.Column(scale=1):
135
- with gr.Row():
136
- im_height = gr.Number(label="Height", value=5000)
137
- im_width = gr.Number(label="Width", value=500)
138
- wait_time = gr.Number(label="Wait Time", value=3000)
139
- theme = gr.Radio(label="Theme", choices=["light", "dark"], value="light")
140
- chatblock = gr.Dropdown(label="Chatblocks", info="Choose specific blocks of chat", choices=[c for c in range(1, 40)], multiselect=True)
141
-
142
- # Eventos de la aplicaci贸n
143
- client_choice.change(load_models, client_choice, [chat_b])
144
- app.load(load_models, client_choice, [chat_b])
145
-
146
- im_go = im_btn.click(get_screenshot, [chat_b, im_height, im_width, chatblock, theme, wait_time], img)
147
-
148
- 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])
149
- 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])
150
-
151
- stop_btn.click(None, None, None, cancels=[go, im_go, chat_sub])
152
- clear_btn.click(clear_fn, None, [inp, sys_inp, chat_b, memory])
153
-
154
- # Lanzamiento de la aplicaci贸n
155
- app.queue(default_concurrency_limit=10).launch()
 
3
  from huggingface_hub import InferenceClient
4
  import random
5
 
 
6
  ss_client = Client("https://xilixmeaty40-testing.hf.space/")
7
 
 
8
  with open("models.txt", "r") as file:
9
  models = file.read().splitlines()
10
 
11
+ clients = []
12
+ for model in models:
13
+ try:
14
+ client = InferenceClient(model)
15
+ clients.append(client)
16
+ except Exception as e:
17
+ print(f"Failed to load model {model}: {e}")
18
 
19
+ if not clients:
20
+ raise Exception("All models failed to load or no models provided.")
21
 
 
22
  def load_models(inp):
 
 
 
 
23
  return gr.update(label=models[inp])
24
 
 
25
  def format_prompt(message, history, cust_p):
26
  prompt = ""
27
  if history:
28
  for user_prompt, bot_response in history:
29
  prompt += f"<start_of_turn>user{user_prompt}<end_of_turn>"
30
  prompt += f"<start_of_turn>model{bot_response}<end_of_turn>"
 
 
31
  prompt += cust_p.replace("USER_INPUT", message)
32
  return prompt
33
 
 
34
  def chat_inf(system_prompt, prompt, history, memory, client_choice, seed, temp, tokens, top_p, rep_p, chat_mem, cust_p):
35
  hist_len = 0
36
  client = clients[int(client_choice) - 1]
 
59
  formatted_prompt = format_prompt(f"{system_prompt}, {prompt}", memory[0 - chat_mem:], cust_p)
60
  else:
61
  formatted_prompt = format_prompt(prompt, memory[0 - chat_mem:], cust_p)
62
+ try:
63
+ stream = client.text_generation(formatted_prompt, **generate_kwargs, stream=True, details=True, return_full_text=True)
64
+ output = ""
65
+ for response in stream:
66
+ output += response.token.text
67
+ yield [(prompt, output)], memory
68
+ history.append((prompt, output))
69
+ memory.append((prompt, output))
70
+ yield history, memory
71
+ except Exception as e:
72
+ print(f"Error during model inference: {e}")
73
+ yield [("Error", "The model failed to respond, possibly due to a timeout. Please try again.")], memory
74
+
75
+ def get_screenshot(chat, height=5000, width=600, chatblock=[], theme="light", wait=3000, header=True):
76
  tog = 0
77
  if chatblock:
78
  tog = 3
 
80
  out = f'https://xilixmeaty40-testing.hf.space/file={result[tog]}'
81
  return out
82
 
 
83
  def clear_fn():
84
  return None, None, None, None
85
 
 
86
  rand_val = random.randint(1, 1111111111111111)
87
 
 
88
  def check_rand(inp, val):
89
  if inp:
90
  return gr.Slider(label="Seed", minimum=1, maximum=1111111111111111, value=random.randint(1, 1111111111111111))
91
  else:
92
  return gr.Slider(label="Seed", minimum=1, maximum=1111111111111111, value=int(val))
93
 
 
94
  with gr.Blocks() as app:
95
  memory = gr.State()
96
  gr.HTML("""<center><h1 style='font-size:xx-large;'>Google Gemma Models</h1><br><h3>running on Huggingface Inference Client</h3><br><h7>EXPERIMENTAL""")
 
100
  with gr.Column(scale=3):
101
  inp = gr.Textbox(label="Prompt")
102
  sys_inp = gr.Textbox(label="System Prompt (optional)")
103
+ custom_prompt = gr.Textbox(label="Modify Prompt Format", lines=3, value="<start_of_turn>userUSER_INPUT<end_of_turn><start_of_turn>model")
 
104
  with gr.Row():
105
  with gr.Column(scale=2):
106
  btn = gr.Button("Chat")
107
  with gr.Column(scale=1):
108
+ stop_btn = gr.Button("Stop")
109
+ clear_btn = gr.Button("Clear")
110
+ client_choice = gr.Dropdown(label="Models", type='index', choices=[c for c in models if c in [client.model_id for client in clients]], value=models[0], interactive=True)
 
111
  with gr.Column(scale=1):
112
+ rand = gr.Checkbox(label="Random Seed", value=True)
113
+ seed = gr.Slider(label="Seed", minimum=1, maximum=1111111111111111, step=1, value=rand_val)
114
+ tokens = gr.Slider(label="Max new tokens", value=300000, minimum=0, maximum=800000, step=64)
115
+ temp = gr.Slider(label="Temperature", step=0.01, minimum=0.01, maximum=1.0, value=0.49)
116
+ top_p = gr.Slider(label="Top-P", step=0.01, minimum=0.01, maximum=1.0, value=0.49)
117
+ rep_p = gr.Slider(label="Repetition Penalty", step=0.01, minimum=0.1, maximum=2.0, value=0.99)
118
+ chat_mem = gr.Number(label="Chat Memory", value=4)
 
119
  with gr.Accordion(label="Screenshot", open=False):
120
+ im_btn = gr.Button("Screenshot")
121
+ img = gr.Image(type='filepath')
122
+ im_height = gr.Number(label="Height", value=5000)
123
+ im_width = gr.Number(label="Width", value=500)
124
+ wait_time = gr.Number(label="Wait Time", value=3000)
125
+ theme = gr.Radio(label="Theme", choices=["light", "dark"], value="light")
126
+ chatblock = gr.Dropdown(label="Chatblocks", choices=[c for c in range(0, 21)], value=0, type="index")
127
+ header = gr.Checkbox(label="Include header?", value=True)
128
+ rand.change(check_rand, inputs=[rand, seed], outputs=seed)
129
+ btn.click(chat_inf, inputs=[sys_inp, inp, chat_b, memory, client_choice, seed, temp, tokens, top_p, rep_p, chat_mem, custom_prompt], outputs=[chat_b, memory])
130
+ stop_btn.click(lambda: None, [], chat_b.stop)
131
+ clear_btn.click(clear_fn, [], [inp, sys_inp, chat_b, memory])
132
+ im_btn.click(get_screenshot, inputs=[chat_b, im_height, im_width, chatblock, theme, wait_time, header], outputs=img)
133
+
134
+ app.launch()