predatortoabuse commited on
Commit
6b60649
1 Parent(s): 96f0dd1

Upload 4 files

Browse files
Files changed (4) hide show
  1. README.md +12 -0
  2. app.py +267 -0
  3. gitignore.txt +2 -0
  4. requirements.txt +2 -0
README.md ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: ReffidGPT Playground
3
+ emoji: 🤖💻
4
+ colorFrom: pink
5
+ colorTo: purple
6
+ sdk: gradio
7
+ sdk_version: 4.9.0
8
+ app_file: app.py
9
+ pinned: false
10
+ ---
11
+
12
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app.py ADDED
@@ -0,0 +1,267 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import time
3
+ import uuid
4
+ from typing import List, Tuple, Optional, Dict, Union
5
+
6
+ import google.generativeai as genai
7
+ import gradio as gr
8
+ from PIL import Image
9
+
10
+ print("google-generativeai:", genai.__version__)
11
+
12
+ GOOGLE_API_KEY = os.environ.get("GOOGLE_API_KEY")
13
+
14
+ TITLE = """<h1 align="center">ReffidGPT Playground 💬</h1>"""
15
+
16
+ AVATAR_IMAGES = (
17
+ None,
18
+ "https://i.postimg.cc/T1hC17DL/20240603-211345.png"
19
+ )
20
+
21
+ IMAGE_CACHE_DIRECTORY = "/tmp"
22
+ IMAGE_WIDTH = 512
23
+ CHAT_HISTORY = List[Tuple[Optional[Union[Tuple[str], str]], Optional[str]]]
24
+
25
+
26
+ def preprocess_stop_sequences(stop_sequences: str) -> Optional[List[str]]:
27
+ if not stop_sequences:
28
+ return None
29
+ return [sequence.strip() for sequence in stop_sequences.split(",")]
30
+
31
+
32
+ def preprocess_image(image: Image.Image) -> Optional[Image.Image]:
33
+ image_height = int(image.height * IMAGE_WIDTH / image.width)
34
+ return image.resize((IMAGE_WIDTH, image_height))
35
+
36
+
37
+ def cache_pil_image(image: Image.Image) -> str:
38
+ image_filename = f"{uuid.uuid4()}.jpeg"
39
+ os.makedirs(IMAGE_CACHE_DIRECTORY, exist_ok=True)
40
+ image_path = os.path.join(IMAGE_CACHE_DIRECTORY, image_filename)
41
+ image.save(image_path, "JPEG")
42
+ return image_path
43
+
44
+
45
+ def preprocess_chat_history(
46
+ history: CHAT_HISTORY
47
+ ) -> List[Dict[str, Union[str, List[str]]]]:
48
+ messages = []
49
+ for user_message, model_message in history:
50
+ if isinstance(user_message, tuple):
51
+ pass
52
+ elif user_message is not None:
53
+ messages.append({'role': 'user', 'parts': [user_message]})
54
+ if model_message is not None:
55
+ messages.append({'role': 'model', 'parts': [model_message]})
56
+ return messages
57
+
58
+
59
+ def upload(files: Optional[List[str]], chatbot: CHAT_HISTORY) -> CHAT_HISTORY:
60
+ for file in files:
61
+ image = Image.open(file).convert('RGB')
62
+ image = preprocess_image(image)
63
+ image_path = cache_pil_image(image)
64
+ chatbot.append(((image_path,), None))
65
+ return chatbot
66
+
67
+
68
+ def user(text_prompt: str, chatbot: CHAT_HISTORY):
69
+ if text_prompt:
70
+ chatbot.append((text_prompt, None))
71
+ return "", chatbot
72
+
73
+
74
+ def bot(
75
+ google_key: str,
76
+ files: Optional[List[str]],
77
+ temperature: float,
78
+ max_output_tokens: int,
79
+ stop_sequences: str,
80
+ top_k: int,
81
+ top_p: float,
82
+ chatbot: CHAT_HISTORY
83
+ ):
84
+ if len(chatbot) == 0:
85
+ return chatbot
86
+
87
+ google_key = google_key if google_key else GOOGLE_API_KEY
88
+ if not google_key:
89
+ raise ValueError(
90
+ "GOOGLE_API_KEY is not set. "
91
+ "Please follow the instructions in the README to set it up.")
92
+
93
+ genai.configure(api_key=google_key)
94
+ generation_config = genai.types.GenerationConfig(
95
+ temperature=temperature,
96
+ max_output_tokens=max_output_tokens,
97
+ stop_sequences=preprocess_stop_sequences(stop_sequences=stop_sequences),
98
+ top_k=top_k,
99
+ top_p=top_p)
100
+
101
+ if files:
102
+ text_prompt = [chatbot[-1][0]] \
103
+ if chatbot[-1][0] and isinstance(chatbot[-1][0], str) \
104
+ else []
105
+ image_prompt = [Image.open(file).convert('RGB') for file in files]
106
+ model = genai.GenerativeModel('gemini-pro-vision')
107
+ response = model.generate_content(
108
+ text_prompt + image_prompt,
109
+ stream=True,
110
+ generation_config=generation_config)
111
+ else:
112
+ messages = preprocess_chat_history(chatbot)
113
+ model = genai.GenerativeModel('gemini-pro')
114
+ response = model.generate_content(
115
+ messages,
116
+ stream=True,
117
+ generation_config=generation_config)
118
+
119
+ # streaming effect
120
+ chatbot[-1][1] = ""
121
+ for chunk in response:
122
+ for i in range(0, len(chunk.text), 10):
123
+ section = chunk.text[i:i + 10]
124
+ chatbot[-1][1] += section
125
+ time.sleep(0.01)
126
+ yield chatbot
127
+
128
+
129
+ google_key_component = gr.Textbox(
130
+ label="GOOGLE API KEY",
131
+ value="",
132
+ type="password",
133
+ placeholder="...",
134
+ info="You have to provide your own GOOGLE_API_KEY for this app to function properly",
135
+ visible=GOOGLE_API_KEY is None
136
+ )
137
+ chatbot_component = gr.Chatbot(
138
+ label='ReffidGPT',
139
+ bubble_full_width=False,
140
+ avatar_images=AVATAR_IMAGES,
141
+ scale=2,
142
+ height=400
143
+ )
144
+ text_prompt_component = gr.Textbox(
145
+ placeholder="Hey ReffidGPT! [press Enter]", show_label=False, autofocus=True, scale=8
146
+ )
147
+ upload_button_component = gr.UploadButton(
148
+ label="Upload Images", file_count="multiple", file_types=["image"], scale=1
149
+ )
150
+ run_button_component = gr.Button(value="Send", variant="primary", scale=1)
151
+ temperature_component = gr.Slider(
152
+ minimum=0,
153
+ maximum=1.0,
154
+ value=0.4,
155
+ step=0.05,
156
+ label="Temperature",
157
+ info=(
158
+ "Temperature controls the degree of randomness in token selection. Lower "
159
+ "temperatures are good for prompts that expect a true or correct response, "
160
+ "while higher temperatures can lead to more diverse or unexpected results. "
161
+ ))
162
+ max_output_tokens_component = gr.Slider(
163
+ minimum=1,
164
+ maximum=2048,
165
+ value=1024,
166
+ step=1,
167
+ label="Token limit",
168
+ info=(
169
+ "Token limit determines the maximum amount of text output from one prompt. A "
170
+ "token is approximately four characters. The default value is 2048."
171
+ ))
172
+ stop_sequences_component = gr.Textbox(
173
+ label="Add stop sequence",
174
+ value="",
175
+ type="text",
176
+ placeholder="STOP, END",
177
+ info=(
178
+ "A stop sequence is a series of characters (including spaces) that stops "
179
+ "response generation if the model encounters it. The sequence is not included "
180
+ "as part of the response. You can add up to five stop sequences."
181
+ ))
182
+ top_k_component = gr.Slider(
183
+ minimum=1,
184
+ maximum=40,
185
+ value=32,
186
+ step=1,
187
+ label="Top-K",
188
+ info=(
189
+ "Top-k changes how the model selects tokens for output. A top-k of 1 means the "
190
+ "selected token is the most probable among all tokens in the model’s "
191
+ "vocabulary (also called greedy decoding), while a top-k of 3 means that the "
192
+ "next token is selected from among the 3 most probable tokens (using "
193
+ "temperature)."
194
+ ))
195
+ top_p_component = gr.Slider(
196
+ minimum=0,
197
+ maximum=1,
198
+ value=1,
199
+ step=0.01,
200
+ label="Top-P",
201
+ info=(
202
+ "Top-p changes how the model selects tokens for output. Tokens are selected "
203
+ "from most probable to least until the sum of their probabilities equals the "
204
+ "top-p value. For example, if tokens A, B, and C have a probability of .3, .2, "
205
+ "and .1 and the top-p value is .5, then the model will select either A or B as "
206
+ "the next token (using temperature). "
207
+ ))
208
+
209
+ user_inputs = [
210
+ text_prompt_component,
211
+ chatbot_component
212
+ ]
213
+
214
+ bot_inputs = [
215
+ google_key_component,
216
+ upload_button_component,
217
+ temperature_component,
218
+ max_output_tokens_component,
219
+ stop_sequences_component,
220
+ top_k_component,
221
+ top_p_component,
222
+ chatbot_component
223
+ ]
224
+
225
+ with gr.Blocks() as demo:
226
+ gr.HTML(TITLE)
227
+ with gr.Column():
228
+ google_key_component.render()
229
+ chatbot_component.render()
230
+ with gr.Row():
231
+ text_prompt_component.render()
232
+ upload_button_component.render()
233
+ run_button_component.render()
234
+ with gr.Accordion("Parameters", open=False):
235
+ temperature_component.render()
236
+ max_output_tokens_component.render()
237
+ stop_sequences_component.render()
238
+ with gr.Accordion("Advanced", open=False):
239
+ top_k_component.render()
240
+ top_p_component.render()
241
+
242
+ run_button_component.click(
243
+ fn=user,
244
+ inputs=user_inputs,
245
+ outputs=[text_prompt_component, chatbot_component],
246
+ queue=False
247
+ ).then(
248
+ fn=bot, inputs=bot_inputs, outputs=[chatbot_component],
249
+ )
250
+
251
+ text_prompt_component.submit(
252
+ fn=user,
253
+ inputs=user_inputs,
254
+ outputs=[text_prompt_component, chatbot_component],
255
+ queue=False
256
+ ).then(
257
+ fn=bot, inputs=bot_inputs, outputs=[chatbot_component],
258
+ )
259
+
260
+ upload_button_component.upload(
261
+ fn=upload,
262
+ inputs=[upload_button_component, chatbot_component],
263
+ outputs=[chatbot_component],
264
+ queue=False
265
+ )
266
+
267
+ demo.queue(max_size=99).launch(debug=False, show_error=True)
gitignore.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ .idea/
2
+ venv/
requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ google-generativeai==0.3.1
2
+ gradio