Spaces:
Sleeping
Sleeping
Update helper.py
Browse files
helper.py
CHANGED
@@ -4,31 +4,39 @@ from typing import Callable
|
|
4 |
import base64
|
5 |
from openai import OpenAI
|
6 |
|
7 |
-
def get_fn(model_name: str, **model_kwargs):
|
8 |
-
"""Create a chat function that uses the OpenAI-compatible endpoint."""
|
9 |
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
15 |
|
16 |
def predict(
|
17 |
message: str,
|
18 |
history,
|
19 |
system_prompt: str,
|
20 |
temperature: float,
|
21 |
-
|
22 |
-
|
|
|
|
|
23 |
):
|
24 |
try:
|
25 |
-
|
26 |
-
|
27 |
-
messages.append({"role": "system", "content": system_prompt})
|
28 |
for user_msg, assistant_msg in history:
|
29 |
-
|
30 |
-
|
31 |
-
messages.append({"role": "user", "content": message})
|
32 |
|
33 |
response = client.chat.completions.create(
|
34 |
model=model_name,
|
@@ -43,58 +51,95 @@ def get_fn(model_name: str, **model_kwargs):
|
|
43 |
|
44 |
response_text = ""
|
45 |
for chunk in response:
|
46 |
-
|
47 |
-
|
48 |
-
|
|
|
|
|
49 |
yield response_text.strip()
|
|
|
|
|
|
|
|
|
50 |
except Exception as e:
|
51 |
print(f"Error during generation: {str(e)}")
|
52 |
yield f"An error occurred: {str(e)}"
|
53 |
|
54 |
return predict
|
55 |
|
|
|
56 |
def get_image_base64(url: str, ext: str):
|
57 |
with open(url, "rb") as image_file:
|
58 |
encoded_string = base64.b64encode(image_file.read()).decode('utf-8')
|
59 |
return "data:image/" + ext + ";base64," + encoded_string
|
60 |
|
|
|
61 |
def handle_user_msg(message: str):
|
62 |
-
if
|
63 |
return message
|
64 |
-
elif
|
65 |
-
if message
|
66 |
ext = os.path.splitext(message["files"][-1])[1].strip(".")
|
67 |
if ext.lower() in ["png", "jpg", "jpeg", "gif", "pdf"]:
|
68 |
encoded_str = get_image_base64(message["files"][-1], ext)
|
69 |
else:
|
70 |
raise NotImplementedError(f"Not supported file type {ext}")
|
71 |
content = [
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
else:
|
81 |
-
content = message
|
82 |
return content
|
83 |
else:
|
84 |
raise NotImplementedError
|
85 |
|
86 |
-
def get_model_path(name: str = None, model_path: str = None) -> str:
|
87 |
-
"""Get the model name to use with the endpoint."""
|
88 |
-
if model_path:
|
89 |
-
return model_path
|
90 |
-
if name:
|
91 |
-
return name
|
92 |
-
raise ValueError("Either name or model_path must be provided")
|
93 |
|
94 |
-
def
|
95 |
-
|
96 |
-
|
97 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
98 |
|
99 |
interface = gr.ChatInterface(
|
100 |
fn=fn,
|
@@ -105,9 +150,11 @@ def registry(name: str = None, model_path: str = None, **kwargs):
|
|
105 |
label="System prompt"
|
106 |
),
|
107 |
gr.Slider(0, 1, 0.7, label="Temperature"),
|
108 |
-
gr.Slider(128, 4096, 1024, label="Max tokens"),
|
|
|
|
|
109 |
gr.Slider(0, 1, 0.95, label="Top P sampling"),
|
110 |
],
|
111 |
)
|
112 |
-
|
113 |
-
return interface
|
|
|
4 |
import base64
|
5 |
from openai import OpenAI
|
6 |
|
|
|
|
|
7 |
|
8 |
+
|
9 |
+
def get_fn(model_path: str, **model_kwargs):
|
10 |
+
"""Create a chat function with the specified model."""
|
11 |
+
|
12 |
+
# instatiate a OpenAI client for a custom endpoint
|
13 |
+
try:
|
14 |
+
OPENAI_API_KEY = "-"
|
15 |
+
client = OpenAI(
|
16 |
+
base_url=" http://192.222.58.60:8000/v1",
|
17 |
+
api_key="tela",
|
18 |
+
)
|
19 |
+
|
20 |
+
except Exception as e:
|
21 |
+
print(f"The api or base url were not definied: {str(e)}")
|
22 |
+
|
23 |
|
24 |
def predict(
|
25 |
message: str,
|
26 |
history,
|
27 |
system_prompt: str,
|
28 |
temperature: float,
|
29 |
+
max_new_tokens: int,
|
30 |
+
top_k: int,
|
31 |
+
repetition_penalty: float,
|
32 |
+
top_p: float
|
33 |
):
|
34 |
try:
|
35 |
+
# Format conversation with ChatML format
|
36 |
+
instruction = '<|im_start|>system\n' + system_prompt + '\n<|im_end|>\n'
|
|
|
37 |
for user_msg, assistant_msg in history:
|
38 |
+
instruction += f'<|im_start|>user\n{user_msg}\n<|im_end|>\n<|im_start|>assistant\n{assistant_msg}\n<|im_end|>\n'
|
39 |
+
instruction += f'<|im_start|>user\n{message}\n<|im_end|>\n<|im_start|>assistant\n'
|
|
|
40 |
|
41 |
response = client.chat.completions.create(
|
42 |
model=model_name,
|
|
|
51 |
|
52 |
response_text = ""
|
53 |
for chunk in response:
|
54 |
+
streamer = chunk.choices[0].delta.content
|
55 |
+
for new_token in streamer:
|
56 |
+
if new_token in ["<|endoftext|>", "<|im_end|>"]:
|
57 |
+
break
|
58 |
+
response_text += new_token
|
59 |
yield response_text.strip()
|
60 |
+
|
61 |
+
if not response_text.strip():
|
62 |
+
yield "I apologize, but I was unable to generate a response. Please try again."
|
63 |
+
|
64 |
except Exception as e:
|
65 |
print(f"Error during generation: {str(e)}")
|
66 |
yield f"An error occurred: {str(e)}"
|
67 |
|
68 |
return predict
|
69 |
|
70 |
+
|
71 |
def get_image_base64(url: str, ext: str):
|
72 |
with open(url, "rb") as image_file:
|
73 |
encoded_string = base64.b64encode(image_file.read()).decode('utf-8')
|
74 |
return "data:image/" + ext + ";base64," + encoded_string
|
75 |
|
76 |
+
|
77 |
def handle_user_msg(message: str):
|
78 |
+
if type(message) is str:
|
79 |
return message
|
80 |
+
elif type(message) is dict:
|
81 |
+
if message["files"] is not None and len(message["files"]) > 0:
|
82 |
ext = os.path.splitext(message["files"][-1])[1].strip(".")
|
83 |
if ext.lower() in ["png", "jpg", "jpeg", "gif", "pdf"]:
|
84 |
encoded_str = get_image_base64(message["files"][-1], ext)
|
85 |
else:
|
86 |
raise NotImplementedError(f"Not supported file type {ext}")
|
87 |
content = [
|
88 |
+
{"type": "text", "text": message["text"]},
|
89 |
+
{
|
90 |
+
"type": "image_url",
|
91 |
+
"image_url": {
|
92 |
+
"url": encoded_str,
|
93 |
+
}
|
94 |
+
},
|
95 |
+
]
|
96 |
else:
|
97 |
+
content = message["text"]
|
98 |
return content
|
99 |
else:
|
100 |
raise NotImplementedError
|
101 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
102 |
|
103 |
+
def get_interface_args(pipeline):
|
104 |
+
if pipeline == "chat":
|
105 |
+
inputs = None
|
106 |
+
outputs = None
|
107 |
+
|
108 |
+
def preprocess(message, history):
|
109 |
+
messages = []
|
110 |
+
files = None
|
111 |
+
for user_msg, assistant_msg in history:
|
112 |
+
if assistant_msg is not None:
|
113 |
+
messages.append({"role": "user", "content": handle_user_msg(user_msg)})
|
114 |
+
messages.append({"role": "assistant", "content": assistant_msg})
|
115 |
+
else:
|
116 |
+
files = user_msg
|
117 |
+
if type(message) is str and files is not None:
|
118 |
+
message = {"text":message, "files":files}
|
119 |
+
elif type(message) is dict and files is not None:
|
120 |
+
if message["files"] is None or len(message["files"]) == 0:
|
121 |
+
message["files"] = files
|
122 |
+
messages.append({"role": "user", "content": handle_user_msg(message)})
|
123 |
+
return {"messages": messages}
|
124 |
+
|
125 |
+
postprocess = lambda x: x
|
126 |
+
else:
|
127 |
+
# Add other pipeline types when they will be needed
|
128 |
+
raise ValueError(f"Unsupported pipeline type: {pipeline}")
|
129 |
+
return inputs, outputs, preprocess, postprocess
|
130 |
+
|
131 |
+
|
132 |
+
def get_pipeline(model_name):
|
133 |
+
# Determine the pipeline type based on the model name
|
134 |
+
# For simplicity, assuming all models are chat models at the moment
|
135 |
+
return "chat"
|
136 |
+
|
137 |
+
|
138 |
+
|
139 |
+
def registry(name: str = None, **kwargs):
|
140 |
+
"""Create a Gradio Interface with similar styling and parameters."""
|
141 |
+
|
142 |
+
fn = get_fn(name, **kwargs)
|
143 |
|
144 |
interface = gr.ChatInterface(
|
145 |
fn=fn,
|
|
|
150 |
label="System prompt"
|
151 |
),
|
152 |
gr.Slider(0, 1, 0.7, label="Temperature"),
|
153 |
+
gr.Slider(128, 4096, 1024, label="Max new tokens"),
|
154 |
+
gr.Slider(1, 80, 40, label="Top K sampling"),
|
155 |
+
gr.Slider(0, 2, 1.1, label="Repetition penalty"),
|
156 |
gr.Slider(0, 1, 0.95, label="Top P sampling"),
|
157 |
],
|
158 |
)
|
159 |
+
|
160 |
+
return interface
|