tuyendragon commited on
Commit
ee366bf
β€’
1 Parent(s): 6bb8996

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -223
app.py DELETED
@@ -1,223 +0,0 @@
1
- import json
2
- import gradio as gr
3
- import os
4
- import requests
5
-
6
- hf_token = os.getenv('HF_TOKEN')
7
- api_url = os.getenv('API_URL')
8
- api_url_nostream = os.getenv('API_URL_NOSTREAM')
9
- headers = {
10
- 'Content-Type': 'application/json',
11
- }
12
-
13
- system_message = "\nYou are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure that your responses are socially unbiased and positive in nature.\n\nIf a question does not make any sense, or is not factually coherent, explain why instead of answering something not correct. If you don't know the answer to a question, please don't share false information."
14
- title = "Llama2 70B Chatbot"
15
- description = """
16
- This Space demonstrates model [Llama-2-70b-chat-hf](https://huggingface.co/meta-llama/Llama-2-70b-chat-hf) by Meta, a Llama 2 model with 70B parameters fine-tuned for chat instructions. This space is running on Inference Endpoints using text-generation-inference library. If you want to run your own service, you can also [deploy the model on Inference Endpoints](https://ui.endpoints.huggingface.co/).
17
- πŸ”Ž For more details about the Llama 2 family of models and how to use them with `transformers`, take a look [at our blog post](https://huggingface.co/blog/llama2).
18
- πŸ”¨ Looking for lighter chat model versions of Llama-v2?
19
- - πŸ‡ Check out the [7B Chat model demo](https://huggingface.co/spaces/huggingface-projects/llama-2-7b-chat).
20
- - 🦊 Check out the [13B Chat model demo](https://huggingface.co/spaces/huggingface-projects/llama-2-13b-chat).
21
- Note: As a derivate work of [Llama-2-70b-chat](https://huggingface.co/meta-llama/Llama-2-70b-chat-hf) by Meta,
22
- this demo is governed by the original [license](https://huggingface.co/spaces/ysharma/Explore_llamav2_with_TGI/blob/main/LICENSE.txt) and [acceptable use policy](https://huggingface.co/spaces/ysharma/Explore_llamav2_with_TGI/blob/main/USE_POLICY.md).
23
- """
24
- css = """.toast-wrap { display: none !important } """
25
- examples=[
26
- ['Hello there! How are you doing?'],
27
- ['Can you explain to me briefly what is Python programming language?'],
28
- ['Explain the plot of Cinderella in a sentence.'],
29
- ['How many hours does it take a man to eat a Helicopter?'],
30
- ["Write a 100-word article on 'Benefits of Open-Source in AI research'"],
31
- ]
32
-
33
-
34
- # Stream text
35
- def predict(message, chatbot, system_prompt="", temperature=0.9, max_new_tokens=256, top_p=0.6, repetition_penalty=1.0,):
36
-
37
- if system_prompt != "":
38
- system_message = system_prompt
39
- else:
40
- system_message = "\nYou are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure that your responses are socially unbiased and positive in nature.\n\nIf a question does not make any sense, or is not factually coherent, explain why instead of answering something not correct. If you don't know the answer to a question, please don't share false information."
41
-
42
- temperature = float(temperature)
43
- if temperature < 1e-2:
44
- temperature = 1e-2
45
- top_p = float(top_p)
46
-
47
- input_prompt = f"[INST] <<SYS>>\n{system_message}\n<</SYS>>\n\n "
48
- for interaction in chatbot:
49
- input_prompt = input_prompt + str(interaction[0]) + " [/INST] " + str(interaction[1]) + " </s><s> [INST] "
50
-
51
- input_prompt = input_prompt + str(message) + " [/INST] "
52
-
53
- data = {
54
- "inputs": input_prompt,
55
- "parameters": {
56
- "max_new_tokens":max_new_tokens,
57
- "temperature":temperature,
58
- "top_p":top_p,
59
- "repetition_penalty":repetition_penalty,
60
- "do_sample":True,
61
- },
62
- }
63
- response = requests.post(api_url, headers=headers, data=json.dumps(data), auth=('hf', hf_token), stream=True)
64
-
65
- partial_message = ""
66
- for line in response.iter_lines():
67
- if line: # filter out keep-alive new lines
68
- # Decode from bytes to string
69
- decoded_line = line.decode('utf-8')
70
-
71
- # Remove 'data:' prefix
72
- if decoded_line.startswith('data:'):
73
- json_line = decoded_line[5:] # Exclude the first 5 characters ('data:')
74
- else:
75
- gr.Warning(f"This line does not start with 'data:': {decoded_line}")
76
- continue
77
-
78
- # Load as JSON
79
- try:
80
- json_obj = json.loads(json_line)
81
- if 'token' in json_obj:
82
- partial_message = partial_message + json_obj['token']['text']
83
- yield partial_message
84
- elif 'error' in json_obj:
85
- yield json_obj['error'] + '. Please refresh and try again with an appropriate smaller input prompt.'
86
- else:
87
- gr.Warning(f"The key 'token' does not exist in this JSON object: {json_obj}")
88
-
89
- except json.JSONDecodeError:
90
- gr.Warning(f"This line is not valid JSON: {json_line}")
91
- continue
92
- except KeyError as e:
93
- gr.Warning(f"KeyError: {e} occurred for JSON object: {json_obj}")
94
- continue
95
-
96
-
97
- # No Stream
98
- def predict_batch(message, chatbot, system_prompt="", temperature=0.9, max_new_tokens=256, top_p=0.6, repetition_penalty=1.0,):
99
-
100
- if system_prompt != "":
101
- system_message = system_prompt
102
- else:
103
- system_message = "\nYou are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure that your responses are socially unbiased and positive in nature.\n\nIf a question does not make any sense, or is not factually coherent, explain why instead of answering something not correct. If you don't know the answer to a question, please don't share false information."
104
-
105
- temperature = float(temperature)
106
- if temperature < 1e-2:
107
- temperature = 1e-2
108
- top_p = float(top_p)
109
-
110
- input_prompt = f"[INST]<<SYS>>\n{system_message}\n<</SYS>>\n\n "
111
- for interaction in chatbot:
112
- input_prompt = input_prompt + str(interaction[0]) + " [/INST] " + str(interaction[1]) + " </s><s> [INST] "
113
-
114
- input_prompt = input_prompt + str(message) + " [/INST] "
115
-
116
- data = {
117
- "inputs": input_prompt,
118
- "parameters": {
119
- "max_new_tokens":max_new_tokens,
120
- "temperature":temperature,
121
- "top_p":top_p,
122
- "repetition_penalty":repetition_penalty,
123
- "do_sample":True,
124
- },
125
- }
126
-
127
- response = requests.post(api_url_nostream, headers=headers, data=json.dumps(data), auth=('hf', hf_token))
128
-
129
- if response.status_code == 200: # check if the request was successful
130
- try:
131
- json_obj = response.json()
132
- if 'generated_text' in json_obj and len(json_obj['generated_text']) > 0:
133
- return json_obj['generated_text']
134
- elif 'error' in json_obj:
135
- return json_obj['error'] + ' Please refresh and try again with smaller input prompt'
136
- else:
137
- print(f"Unexpected response: {json_obj}")
138
- except json.JSONDecodeError:
139
- print(f"Failed to decode response as JSON: {response.text}")
140
- else:
141
- print(f"Request failed with status code {response.status_code}")
142
-
143
-
144
- def vote(data: gr.LikeData):
145
- if data.liked:
146
- print("You upvoted this response: " + data.value)
147
- else:
148
- print("You downvoted this response: " + data.value)
149
-
150
-
151
- additional_inputs=[
152
- gr.Textbox("", label="Optional system prompt"),
153
- gr.Slider(
154
- label="Temperature",
155
- value=0.9,
156
- minimum=0.0,
157
- maximum=1.0,
158
- step=0.05,
159
- interactive=True,
160
- info="Higher values produce more diverse outputs",
161
- ),
162
- gr.Slider(
163
- label="Max new tokens",
164
- value=256,
165
- minimum=0,
166
- maximum=4096,
167
- step=64,
168
- interactive=True,
169
- info="The maximum numbers of new tokens",
170
- ),
171
- gr.Slider(
172
- label="Top-p (nucleus sampling)",
173
- value=0.6,
174
- minimum=0.0,
175
- maximum=1,
176
- step=0.05,
177
- interactive=True,
178
- info="Higher values sample more low-probability tokens",
179
- ),
180
- gr.Slider(
181
- label="Repetition penalty",
182
- value=1.2,
183
- minimum=1.0,
184
- maximum=2.0,
185
- step=0.05,
186
- interactive=True,
187
- info="Penalize repeated tokens",
188
- )
189
- ]
190
-
191
- chatbot_stream = gr.Chatbot(avatar_images=('user.png', 'bot2.png'),bubble_full_width = False)
192
- chatbot_batch = gr.Chatbot(avatar_images=('user1.png', 'bot1.png'),bubble_full_width = False)
193
- chat_interface_stream = gr.ChatInterface(predict,
194
- title=title,
195
- description=description,
196
- chatbot=chatbot_stream,
197
- css=css,
198
- examples=examples,
199
- cache_examples=True,
200
- additional_inputs=additional_inputs,)
201
- chat_interface_batch = gr.ChatInterface(predict_batch,
202
- title=title,
203
- description=description,
204
- chatbot=chatbot_batch,
205
- css=css,
206
- examples=examples,
207
- cache_examples=True,
208
- additional_inputs=additional_inputs,)
209
-
210
- # Gradio Demo
211
- with gr.Blocks() as demo:
212
-
213
- with gr.Tab("Streaming"):
214
- #gr.ChatInterface(predict, title=title, description=description, css=css, examples=examples, cache_examples=True, additional_inputs=additional_inputs,)
215
- chatbot_stream.like(vote, None, None)
216
- chat_interface_stream.render()
217
-
218
- with gr.Tab("Batch"):
219
- #gr.ChatInterface(predict_batch, title=title, description=description, css=css, examples=examples, cache_examples=True, additional_inputs=additional_inputs,)
220
- chatbot_batch.like(vote, None, None)
221
- chat_interface_batch.render()
222
-
223
- demo.queue(concurrency_count=75, max_size=100).launch(debug=True)