Yahir commited on
Commit
8e07109
1 Parent(s): 8acc27a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +32 -152
app.py CHANGED
@@ -1,160 +1,40 @@
1
  import gradio as gr
2
- from gradio_client import Client
3
- from huggingface_hub import InferenceClient
4
  import random
5
- ss_client = Client("https://omnibus-html-image-current-tab.hf.space/")
6
 
7
- models=[
8
- "google/gemma-7b",
9
- "google/gemma-7b-it",
10
- "google/gemma-2b",
11
- "google/gemma-2b-it"
12
- ]
13
- clients=[
14
- InferenceClient(models[0]),
15
- InferenceClient(models[1]),
16
- InferenceClient(models[2]),
17
- InferenceClient(models[3]),
18
- ]
19
-
20
- VERBOSE=False
21
-
22
- def load_models(inp):
23
- if VERBOSE==True:
24
- print(type(inp))
25
- print(inp)
26
- print(models[inp])
27
- #client_z.clear()
28
- #client_z.append(InferenceClient(models[inp]))
29
- return gr.update(label=models[inp])
30
-
31
- def format_prompt(message, history, cust_p):
32
- prompt = ""
33
- if history:
34
- for user_prompt, bot_response in history:
35
- prompt += f"<start_of_turn>user{user_prompt}<end_of_turn>"
36
- prompt += f"<start_of_turn>model{bot_response}<end_of_turn>"
37
- if VERBOSE==True:
38
- print(prompt)
39
- #prompt += f"<start_of_turn>user\n{message}<end_of_turn>\n<start_of_turn>model\n"
40
- prompt+=cust_p.replace("USER_INPUT",message)
41
- return prompt
42
-
43
- def chat_inf(system_prompt,prompt,history,memory,client_choice,seed,temp,tokens,top_p,rep_p,chat_mem,cust_p):
44
- #token max=8192
45
- print(client_choice)
46
- hist_len=0
47
- client=clients[int(client_choice)-1]
48
- if not history:
49
- history = []
50
- hist_len=0
51
- if not memory:
52
- memory = []
53
- mem_len=0
54
- if memory:
55
- for ea in memory[0-chat_mem:]:
56
- hist_len+=len(str(ea))
57
- in_len=len(system_prompt+prompt)+hist_len
58
-
59
- if (in_len+tokens) > 8000:
60
- history.append((prompt,"Wait, that's too many tokens, please reduce the 'Chat Memory' value, or reduce the 'Max new tokens' value"))
61
- yield history,memory
62
- else:
63
- generate_kwargs = dict(
64
- temperature=temp,
65
- max_new_tokens=tokens,
66
- top_p=top_p,
67
- repetition_penalty=rep_p,
68
- do_sample=True,
69
- seed=seed,
70
- )
71
- if system_prompt:
72
- formatted_prompt = format_prompt(f"{system_prompt}, {prompt}", memory[0-chat_mem:],cust_p)
73
- else:
74
- formatted_prompt = format_prompt(prompt, memory[0-chat_mem:],cust_p)
75
- stream = client.text_generation(formatted_prompt, **generate_kwargs, stream=True, details=True, return_full_text=True)
76
- output = ""
77
- for response in stream:
78
- output += response.token.text
79
- yield [(prompt,output)],memory
80
- history.append((prompt,output))
81
- memory.append((prompt,output))
82
- yield history,memory
83
-
84
- if VERBOSE==True:
85
- print("\n######### HIST "+str(in_len))
86
- print("\n######### TOKENS "+str(tokens))
87
 
88
- def get_screenshot(chat: list,height=5000,width=600,chatblock=[],theme="light",wait=3000,header=True):
89
- print(chatblock)
90
- tog = 0
91
- if chatblock:
92
- tog = 3
93
- result = ss_client.predict(str(chat),height,width,chatblock,header,theme,wait,api_name="/run_script")
94
- out = f'https://omnibus-html-image-current-tab.hf.space/file={result[tog]}'
95
- print(out)
96
- return out
97
 
98
  def clear_fn():
99
- return None,None,None,None
100
- rand_val=random.randint(1,1111111111111111)
101
-
102
- def check_rand(inp,val):
103
- if inp==True:
104
- return gr.Slider(label="Seed", minimum=1, maximum=1111111111111111, value=random.randint(1,1111111111111111))
105
- else:
106
- return gr.Slider(label="Seed", minimum=1, maximum=1111111111111111, value=int(val))
107
-
108
- with gr.Blocks() as app:
109
- memory=gr.State()
110
- gr.HTML("""<center><h1 style='font-size:xx-large;'>Google Gemma Models</h1><br><h3>running on Huggingface Inference Client</h3><br><h7>EXPERIMENTAL""")
111
- chat_b = gr.Chatbot(height=500)
112
- with gr.Group():
113
- with gr.Row():
114
- with gr.Column(scale=3):
115
- inp = gr.Textbox(label="Prompt")
116
- sys_inp = gr.Textbox(label="System Prompt (optional)")
117
- with gr.Accordion("Prompt Format",open=False):
118
- 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")
119
- with gr.Row():
120
- with gr.Column(scale=2):
121
- btn = gr.Button("Chat")
122
- with gr.Column(scale=1):
123
- with gr.Group():
124
- stop_btn=gr.Button("Stop")
125
- clear_btn=gr.Button("Clear")
126
- client_choice=gr.Dropdown(label="Models",type='index',choices=[c for c in models],value=models[0],interactive=True)
127
- with gr.Column(scale=1):
128
- with gr.Group():
129
- rand = gr.Checkbox(label="Random Seed", value=True)
130
- seed=gr.Slider(label="Seed", minimum=1, maximum=1111111111111111,step=1, value=rand_val)
131
- tokens = gr.Slider(label="Max new tokens",value=1600,minimum=0,maximum=8000,step=64,interactive=True, visible=True,info="The maximum number of tokens")
132
- temp=gr.Slider(label="Temperature",step=0.01, minimum=0.01, maximum=1.0, value=0.49)
133
- top_p=gr.Slider(label="Top-P",step=0.01, minimum=0.01, maximum=1.0, value=0.49)
134
- rep_p=gr.Slider(label="Repetition Penalty",step=0.01, minimum=0.1, maximum=2.0, value=0.99)
135
- chat_mem=gr.Number(label="Chat Memory", info="Number of previous chats to retain",value=4)
136
- with gr.Accordion(label="Screenshot",open=False):
137
- with gr.Row():
138
- with gr.Column(scale=3):
139
- im_btn=gr.Button("Screenshot")
140
- img=gr.Image(type='filepath')
141
- with gr.Column(scale=1):
142
- with gr.Row():
143
- im_height=gr.Number(label="Height",value=5000)
144
- im_width=gr.Number(label="Width",value=500)
145
- wait_time=gr.Number(label="Wait Time",value=3000)
146
- theme=gr.Radio(label="Theme", choices=["light","dark"],value="light")
147
- chatblock=gr.Dropdown(label="Chatblocks",info="Choose specific blocks of chat",choices=[c for c in range(1,40)],multiselect=True)
148
-
149
-
150
- client_choice.change(load_models,client_choice,[chat_b])
151
- app.load(load_models,client_choice,[chat_b])
152
-
153
- im_go=im_btn.click(get_screenshot,[chat_b,im_height,im_width,chatblock,theme,wait_time],img)
154
-
155
- 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])
156
- 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])
157
 
158
- stop_btn.click(None,None,None,cancels=[go,im_go,chat_sub])
159
- clear_btn.click(clear_fn,None,[inp,sys_inp,chat_b,memory])
160
  app.queue(default_concurrency_limit=10).launch()
 
1
  import gradio as gr
2
+ from transformers import AutoTokenizer, AutoModelForCausalLM
3
+ import torch
4
  import random
 
5
 
6
+ models = ["microsoft/DialoGPT-medium", "facebook/opt-125m"]
7
+ tokenizers = {name: AutoTokenizer.from_pretrained(name) for name in models}
8
+ clients = {name: AutoModelForCausalLM.from_pretrained(name).to('cpu') for name in models}
9
+ ss_client=AutoModelForCausalLM.from_pretrained("nchlt/omnibus-image-current-tab").to('cuda')
10
+
11
+ def load_models(choice):
12
+ return clients[choice],tokenizers[choice]
13
+
14
+ def chat_inf(sys, inp, chat, mem, cli, seed, temp, tokens, top_p, rep_p, chat_mem, custom_prompt):
15
+ torch.manual_seed(int(seed))
16
+ if not sys:
17
+ sys = "<|startoftext|>"
18
+ if inp is None:
19
+ return [],[]
20
+ history=[(inp,chat)]
21
+ chat+=[inp]
22
+ response = cli.generate(torch.tensor([tokenizers[cli].encode(f'{sys}: {inp}\n') for inp in chat]), max_length=int(tokens), temperature=float(temp), top_p=float(top_p), do_sample=True, repetition_penalty=float(rep_p))
23
+ res = tokenizers[cli].decode(response[:, -1])
24
+ chat+=[res]
25
+
26
+ custom_prompt.text = "\n".join([f"{i}: {inp} <--> {res}" for i,(inp,res) in enumerate(history[::-1][:chat_mem])])
27
+ return res, chat
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
 
29
+ def get_screenshot(cli, im_height, im_width, chatblock, theme, wait_time):
30
+ chat = cli.generate(torch.tensor([tokenizers[cli].encode('<|startoftext|>: '+'\n'.join([inp for i,(inp,res) in enumerate(history[::-1][:chatblock]) if not i%2])) for _ in range(5)]), max_length=int(tokens), temperature=float(temp), top_p=float(top_p), do_sample=True, repetition_penalty=float(rep_p))
31
+ return tokenizers[cli].decode(response[:, -1])
 
 
 
 
 
 
32
 
33
  def clear_fn():
34
+ inp.value = ""
35
+ sys_inp.value = ""
36
+ chat_b.value = []
37
+ memory.value = None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
 
39
+ im_go=im_btn.click(get_screenshot,[chat_b,im_height,im_width,chatblock,theme,wait_time],img)
 
40
  app.queue(default_concurrency_limit=10).launch()