xinference 1.4.0__py3-none-any.whl → 1.4.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of xinference might be problematic. Click here for more details.

Files changed (59) hide show
  1. xinference/_compat.py +1 -0
  2. xinference/_version.py +3 -3
  3. xinference/api/restful_api.py +4 -0
  4. xinference/core/model.py +23 -3
  5. xinference/core/supervisor.py +6 -0
  6. xinference/core/worker.py +54 -11
  7. xinference/model/llm/__init__.py +4 -2
  8. xinference/model/llm/core.py +1 -0
  9. xinference/model/llm/llama_cpp/core.py +6 -1
  10. xinference/model/llm/llm_family.json +117 -1
  11. xinference/model/llm/llm_family_modelscope.json +125 -1
  12. xinference/model/llm/reasoning_parser.py +3 -3
  13. xinference/model/llm/sglang/core.py +111 -13
  14. xinference/model/llm/transformers/core.py +1 -0
  15. xinference/model/llm/transformers/deepseek_vl.py +1 -1
  16. xinference/model/llm/transformers/deepseek_vl2.py +287 -0
  17. xinference/model/llm/utils.py +26 -14
  18. xinference/model/llm/vllm/core.py +149 -8
  19. xinference/model/llm/vllm/distributed_executor.py +314 -0
  20. xinference/model/rerank/core.py +16 -11
  21. xinference/thirdparty/deepseek_vl2/__init__.py +31 -0
  22. xinference/thirdparty/deepseek_vl2/models/__init__.py +26 -0
  23. xinference/thirdparty/deepseek_vl2/models/configuration_deepseek.py +210 -0
  24. xinference/thirdparty/deepseek_vl2/models/conversation.py +310 -0
  25. xinference/thirdparty/deepseek_vl2/models/modeling_deepseek.py +1975 -0
  26. xinference/thirdparty/deepseek_vl2/models/modeling_deepseek_vl_v2.py +697 -0
  27. xinference/thirdparty/deepseek_vl2/models/processing_deepseek_vl_v2.py +675 -0
  28. xinference/thirdparty/deepseek_vl2/models/siglip_vit.py +661 -0
  29. xinference/thirdparty/deepseek_vl2/serve/__init__.py +0 -0
  30. xinference/thirdparty/deepseek_vl2/serve/app_modules/__init__.py +0 -0
  31. xinference/thirdparty/deepseek_vl2/serve/app_modules/gradio_utils.py +83 -0
  32. xinference/thirdparty/deepseek_vl2/serve/app_modules/overwrites.py +81 -0
  33. xinference/thirdparty/deepseek_vl2/serve/app_modules/presets.py +115 -0
  34. xinference/thirdparty/deepseek_vl2/serve/app_modules/utils.py +333 -0
  35. xinference/thirdparty/deepseek_vl2/serve/assets/Kelpy-Codos.js +100 -0
  36. xinference/thirdparty/deepseek_vl2/serve/assets/avatar.png +0 -0
  37. xinference/thirdparty/deepseek_vl2/serve/assets/custom.css +355 -0
  38. xinference/thirdparty/deepseek_vl2/serve/assets/custom.js +22 -0
  39. xinference/thirdparty/deepseek_vl2/serve/assets/favicon.ico +0 -0
  40. xinference/thirdparty/deepseek_vl2/serve/assets/simsun.ttc +0 -0
  41. xinference/thirdparty/deepseek_vl2/serve/inference.py +197 -0
  42. xinference/thirdparty/deepseek_vl2/utils/__init__.py +18 -0
  43. xinference/thirdparty/deepseek_vl2/utils/io.py +80 -0
  44. xinference/web/ui/build/asset-manifest.json +3 -3
  45. xinference/web/ui/build/index.html +1 -1
  46. xinference/web/ui/build/static/js/{main.3cea968e.js → main.5ca4eea1.js} +3 -3
  47. xinference/web/ui/build/static/js/main.5ca4eea1.js.map +1 -0
  48. xinference/web/ui/node_modules/.cache/babel-loader/0f0967acaec5df1d45b80010949c258d64297ebbb0f44b8bb3afcbd45c6f0ec4.json +1 -0
  49. xinference/web/ui/node_modules/.cache/babel-loader/68249645124f37d01eef83b1d897e751f895bea919b6fb466f907c1f87cebc84.json +1 -0
  50. {xinference-1.4.0.dist-info → xinference-1.4.1.dist-info}/METADATA +4 -4
  51. {xinference-1.4.0.dist-info → xinference-1.4.1.dist-info}/RECORD +56 -31
  52. xinference/web/ui/build/static/js/main.3cea968e.js.map +0 -1
  53. xinference/web/ui/node_modules/.cache/babel-loader/7f59e45e3f268ab8a4788b6fb024cf8dab088736dff22f5a3a39c122a83ab930.json +0 -1
  54. xinference/web/ui/node_modules/.cache/babel-loader/dcd60488509450bfff37bfff56de2c096d51de17dd00ec60d4db49c8b483ada1.json +0 -1
  55. /xinference/web/ui/build/static/js/{main.3cea968e.js.LICENSE.txt → main.5ca4eea1.js.LICENSE.txt} +0 -0
  56. {xinference-1.4.0.dist-info → xinference-1.4.1.dist-info}/LICENSE +0 -0
  57. {xinference-1.4.0.dist-info → xinference-1.4.1.dist-info}/WHEEL +0 -0
  58. {xinference-1.4.0.dist-info → xinference-1.4.1.dist-info}/entry_points.txt +0 -0
  59. {xinference-1.4.0.dist-info → xinference-1.4.1.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,83 @@
1
+ # Copyright (c) 2023-2024 DeepSeek.
2
+ #
3
+ # Permission is hereby granted, free of charge, to any person obtaining a copy of
4
+ # this software and associated documentation files (the "Software"), to deal in
5
+ # the Software without restriction, including without limitation the rights to
6
+ # use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
7
+ # the Software, and to permit persons to whom the Software is furnished to do so,
8
+ # subject to the following conditions:
9
+ #
10
+ # The above copyright notice and this permission notice shall be included in all
11
+ # copies or substantial portions of the Software.
12
+ #
13
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
15
+ # FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
16
+ # COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
17
+ # IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
18
+ # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
19
+
20
+ from functools import wraps
21
+
22
+ import gradio as gr
23
+
24
+
25
+ def wrap_gen_fn(gen_fn):
26
+ @wraps(gen_fn)
27
+ def wrapped_gen_fn(prompt, *args, **kwargs):
28
+ try:
29
+ yield from gen_fn(prompt, *args, **kwargs)
30
+ except gr.Error as g_err:
31
+ raise g_err
32
+ except Exception as e:
33
+ raise gr.Error(f"Failed to generate text: {e}") from e
34
+
35
+ return wrapped_gen_fn
36
+
37
+
38
+ def delete_last_conversation(chatbot, history):
39
+ if len(history) % 2 != 0:
40
+ gr.Error("history length is not even")
41
+ return (
42
+ chatbot,
43
+ history,
44
+ "Delete Done",
45
+ )
46
+
47
+ if len(chatbot) > 0:
48
+ chatbot.pop()
49
+
50
+ if len(history) > 0 and len(history) % 2 == 0:
51
+ history.pop()
52
+ history.pop()
53
+
54
+ return (
55
+ chatbot,
56
+ history,
57
+ "Delete Done",
58
+ )
59
+
60
+
61
+ def reset_state():
62
+ return [], [], None, "Reset Done"
63
+
64
+
65
+ def reset_textbox():
66
+ return gr.update(value=""), ""
67
+
68
+
69
+ def cancel_outputing():
70
+ return "Stop Done"
71
+
72
+
73
+ class State:
74
+ interrupted = False
75
+
76
+ def interrupt(self):
77
+ self.interrupted = True
78
+
79
+ def recover(self):
80
+ self.interrupted = False
81
+
82
+
83
+ shared_state = State()
@@ -0,0 +1,81 @@
1
+ # Copyright (c) 2023-2024 DeepSeek.
2
+ #
3
+ # Permission is hereby granted, free of charge, to any person obtaining a copy of
4
+ # this software and associated documentation files (the "Software"), to deal in
5
+ # the Software without restriction, including without limitation the rights to
6
+ # use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
7
+ # the Software, and to permit persons to whom the Software is furnished to do so,
8
+ # subject to the following conditions:
9
+ #
10
+ # The above copyright notice and this permission notice shall be included in all
11
+ # copies or substantial portions of the Software.
12
+ #
13
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
15
+ # FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
16
+ # COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
17
+ # IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
18
+ # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
19
+
20
+ from __future__ import annotations
21
+
22
+ import logging
23
+ from typing import List, Tuple
24
+
25
+ from deepseek_vl2.serve.app_modules.presets import gr
26
+ from deepseek_vl2.serve.app_modules.utils import convert_asis, convert_mdtext, detect_converted_mark
27
+
28
+
29
+ def compact_text_chunks(self, prompt, text_chunks: List[str]) -> List[str]:
30
+ logging.debug("Compacting text chunks...🚀🚀🚀")
31
+ combined_str = [c.strip() for c in text_chunks if c.strip()]
32
+ combined_str = [f"[{index+1}] {c}" for index, c in enumerate(combined_str)]
33
+ combined_str = "\n\n".join(combined_str)
34
+ # resplit based on self.max_chunk_overlap
35
+ text_splitter = self.get_text_splitter_given_prompt(prompt, 1, padding=1)
36
+ return text_splitter.split_text(combined_str)
37
+
38
+
39
+ def postprocess(
40
+ self, y: List[Tuple[str | None, str | None]]
41
+ ) -> List[Tuple[str | None, str | None]]:
42
+ """
43
+ Parameters:
44
+ y: List of tuples representing the message and response pairs. Each message and response should be a string, which may be in Markdown format.
45
+ Returns:
46
+ List of tuples representing the message and response. Each message and response will be a string of HTML.
47
+ """
48
+ if y is None or y == []:
49
+ return []
50
+ temp = []
51
+ for x in y:
52
+ user, bot = x
53
+ if not detect_converted_mark(user):
54
+ user = convert_asis(user)
55
+ if not detect_converted_mark(bot):
56
+ bot = convert_mdtext(bot)
57
+ temp.append((user, bot))
58
+ return temp
59
+
60
+
61
+ with open("deepseek_vl2/serve/assets/custom.js", "r", encoding="utf-8") as f, open(
62
+ "deepseek_vl2/serve/assets/Kelpy-Codos.js", "r", encoding="utf-8"
63
+ ) as f2:
64
+ customJS = f.read()
65
+ kelpyCodos = f2.read()
66
+
67
+
68
+ def reload_javascript():
69
+ print("Reloading javascript...")
70
+ js = f"<script>{customJS}</script><script>{kelpyCodos}</script>"
71
+
72
+ def template_response(*args, **kwargs):
73
+ res = GradioTemplateResponseOriginal(*args, **kwargs)
74
+ res.body = res.body.replace(b"</html>", f"{js}</html>".encode("utf8"))
75
+ res.init_headers()
76
+ return res
77
+
78
+ gr.routes.templates.TemplateResponse = template_response
79
+
80
+
81
+ GradioTemplateResponseOriginal = gr.routes.templates.TemplateResponse
@@ -0,0 +1,115 @@
1
+ # Copyright (c) 2023-2024 DeepSeek.
2
+ #
3
+ # Permission is hereby granted, free of charge, to any person obtaining a copy of
4
+ # this software and associated documentation files (the "Software"), to deal in
5
+ # the Software without restriction, including without limitation the rights to
6
+ # use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
7
+ # the Software, and to permit persons to whom the Software is furnished to do so,
8
+ # subject to the following conditions:
9
+ #
10
+ # The above copyright notice and this permission notice shall be included in all
11
+ # copies or substantial portions of the Software.
12
+ #
13
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
15
+ # FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
16
+ # COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
17
+ # IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
18
+ # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
19
+
20
+ # -*- coding:utf-8 -*-
21
+ import gradio as gr
22
+
23
+ title = """<h1 align="left" style="min-width:200px; margin-top:0;">Chat with DeepSeek-VL2 </h1>"""
24
+ description_top = """Special Tokens: `<image>`, Visual Grounding: `<|ref|>{query}<|/ref|>`, Grounding Conversation: `<|grounding|>{question}`"""
25
+ description = """"""
26
+ CONCURRENT_COUNT = 1
27
+ MAX_EVENTS = 10
28
+ MAX_IMAGE_SIZE = 800
29
+ MIN_IMAGE_SIZE = 400
30
+
31
+ BOX2COLOR = {
32
+ 0: (255, 0, 0),
33
+ 1: (0, 255, 0),
34
+ 2: (0, 0, 255),
35
+ 3: (0, 255, 255),
36
+ 4: (255, 255, 0),
37
+ 5: (255, 0, 255),
38
+ 6: (127, 127, 127),
39
+ 7: (255, 255, 127),
40
+ 8: (255, 127, 255),
41
+ 9: (127, 255, 255),
42
+ 10: (127, 127, 255),
43
+ 11: (127, 255, 127),
44
+ 12: (255, 127, 127),
45
+ }
46
+
47
+
48
+ ALREADY_CONVERTED_MARK = "<!-- ALREADY CONVERTED BY PARSER. -->"
49
+
50
+ small_and_beautiful_theme = gr.themes.Soft(
51
+ primary_hue=gr.themes.Color(
52
+ c50="#EBFAF2",
53
+ c100="#CFF3E1",
54
+ c200="#A8EAC8",
55
+ c300="#77DEA9",
56
+ c400="#3FD086",
57
+ c500="#02C160",
58
+ c600="#06AE56",
59
+ c700="#05974E",
60
+ c800="#057F45",
61
+ c900="#04673D",
62
+ c950="#2E5541",
63
+ name="small_and_beautiful",
64
+ ),
65
+ secondary_hue=gr.themes.Color(
66
+ c50="#576b95",
67
+ c100="#576b95",
68
+ c200="#576b95",
69
+ c300="#576b95",
70
+ c400="#576b95",
71
+ c500="#576b95",
72
+ c600="#576b95",
73
+ c700="#576b95",
74
+ c800="#576b95",
75
+ c900="#576b95",
76
+ c950="#576b95",
77
+ ),
78
+ neutral_hue=gr.themes.Color(
79
+ name="gray",
80
+ c50="#f6f7f8",
81
+ # c100="#f3f4f6",
82
+ c100="#F2F2F2",
83
+ c200="#e5e7eb",
84
+ c300="#d1d5db",
85
+ c400="#B2B2B2",
86
+ c500="#808080",
87
+ c600="#636363",
88
+ c700="#515151",
89
+ c800="#393939",
90
+ # c900="#272727",
91
+ c900="#2B2B2B",
92
+ c950="#171717",
93
+ ),
94
+ radius_size=gr.themes.sizes.radius_sm,
95
+ ).set(
96
+ # button_primary_background_fill="*primary_500",
97
+ button_primary_background_fill_dark="*primary_600",
98
+ # button_primary_background_fill_hover="*primary_400",
99
+ # button_primary_border_color="*primary_500",
100
+ button_primary_border_color_dark="*primary_600",
101
+ button_primary_text_color="white",
102
+ button_primary_text_color_dark="white",
103
+ button_secondary_background_fill="*neutral_100",
104
+ button_secondary_background_fill_hover="*neutral_50",
105
+ button_secondary_background_fill_dark="*neutral_900",
106
+ button_secondary_text_color="*neutral_800",
107
+ button_secondary_text_color_dark="white",
108
+ # background_fill_primary="#F7F7F7",
109
+ # background_fill_primary_dark="#1F1F1F",
110
+ # block_title_text_color="*primary_500",
111
+ block_title_background_fill_dark="*primary_900",
112
+ block_label_background_fill_dark="*primary_900",
113
+ input_background_fill="#F6F6F6",
114
+ # chatbot_code_background_color_dark="*neutral_950",
115
+ )
@@ -0,0 +1,333 @@
1
+ # Copyright (c) 2023-2024 DeepSeek.
2
+ #
3
+ # Permission is hereby granted, free of charge, to any person obtaining a copy of
4
+ # this software and associated documentation files (the "Software"), to deal in
5
+ # the Software without restriction, including without limitation the rights to
6
+ # use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
7
+ # the Software, and to permit persons to whom the Software is furnished to do so,
8
+ # subject to the following conditions:
9
+ #
10
+ # The above copyright notice and this permission notice shall be included in all
11
+ # copies or substantial portions of the Software.
12
+ #
13
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
15
+ # FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
16
+ # COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
17
+ # IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
18
+ # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
19
+
20
+ # -*- coding:utf-8 -*-
21
+ from __future__ import annotations
22
+
23
+ import html
24
+ import logging
25
+ import io
26
+ import os
27
+ import re
28
+ import base64
29
+ import time
30
+ from PIL import Image, ImageDraw, ImageFont
31
+
32
+ import mdtex2html
33
+ from markdown import markdown
34
+ from pygments import highlight
35
+ from pygments.formatters import HtmlFormatter
36
+ from pygments.lexers import ClassNotFound, get_lexer_by_name, guess_lexer
37
+
38
+ from deepseek_vl2.serve.app_modules.presets import (
39
+ ALREADY_CONVERTED_MARK,
40
+ BOX2COLOR,
41
+ MAX_IMAGE_SIZE,
42
+ MIN_IMAGE_SIZE
43
+ )
44
+
45
+ logger = logging.getLogger("gradio_logger")
46
+
47
+
48
+ def configure_logger():
49
+ logger = logging.getLogger("gradio_logger")
50
+ logger.setLevel(logging.DEBUG)
51
+
52
+ timestr = time.strftime("%Y%m%d-%H%M%S")
53
+ os.makedirs("deepseek_vl2/serve/logs", exist_ok=True)
54
+ file_handler = logging.FileHandler(
55
+ f"deepseek_vl2/serve/logs/{timestr}_gradio_log.log"
56
+ )
57
+ console_handler = logging.StreamHandler()
58
+
59
+ formatter = logging.Formatter(
60
+ "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
61
+ )
62
+ console_handler.setFormatter(formatter)
63
+ file_handler.setFormatter(formatter)
64
+
65
+ console_handler.setLevel(logging.INFO)
66
+ file_handler.setLevel(logging.INFO)
67
+
68
+ logger.addHandler(console_handler)
69
+ logger.addHandler(file_handler)
70
+
71
+ return logger
72
+
73
+
74
+ def strip_stop_words(x, stop_words):
75
+ for w in stop_words:
76
+ if w in x:
77
+ return x[: x.index(w)].strip()
78
+ return x.strip()
79
+
80
+
81
+ def format_output(history, text, x):
82
+ updated_history = history + [[text, x]]
83
+ a = [[y[0], convert_to_markdown(y[1])] for y in updated_history]
84
+ return a, updated_history
85
+
86
+
87
+ def markdown_to_html_with_syntax_highlight(md_str): # deprecated
88
+ def replacer(match):
89
+ lang = match.group(1) or "text"
90
+ code = match.group(2)
91
+
92
+ try:
93
+ lexer = get_lexer_by_name(lang, stripall=True)
94
+ except ValueError:
95
+ lexer = get_lexer_by_name("text", stripall=True)
96
+
97
+ formatter = HtmlFormatter()
98
+ highlighted_code = highlight(code, lexer, formatter)
99
+
100
+ return f'<pre><code class="{lang}">{highlighted_code}</code></pre>'
101
+
102
+ code_block_pattern = r"```(\w+)?\n([\s\S]+?)\n```"
103
+ md_str = re.sub(code_block_pattern, replacer, md_str, flags=re.MULTILINE)
104
+
105
+ html_str = markdown(md_str)
106
+ return html_str
107
+
108
+
109
+ def normalize_markdown(md_text: str) -> str: # deprecated
110
+ lines = md_text.split("\n")
111
+ normalized_lines = []
112
+ inside_list = False
113
+
114
+ for i, line in enumerate(lines):
115
+ if re.match(r"^(\d+\.|-|\*|\+)\s", line.strip()):
116
+ if not inside_list and i > 0 and lines[i - 1].strip() != "":
117
+ normalized_lines.append("")
118
+ inside_list = True
119
+ normalized_lines.append(line)
120
+ elif inside_list and line.strip() == "":
121
+ if i < len(lines) - 1 and not re.match(
122
+ r"^(\d+\.|-|\*|\+)\s", lines[i + 1].strip()
123
+ ):
124
+ normalized_lines.append(line)
125
+ continue
126
+ else:
127
+ inside_list = False
128
+ normalized_lines.append(line)
129
+
130
+ return "\n".join(normalized_lines)
131
+
132
+
133
+ def convert_mdtext(md_text):
134
+ code_block_pattern = re.compile(r"```(.*?)(?:```|$)", re.DOTALL)
135
+ inline_code_pattern = re.compile(r"`(.*?)`", re.DOTALL)
136
+ code_blocks = code_block_pattern.findall(md_text)
137
+ non_code_parts = code_block_pattern.split(md_text)[::2]
138
+
139
+ result = []
140
+ for non_code, code in zip(non_code_parts, code_blocks + [""]):
141
+ if non_code.strip():
142
+ non_code = normalize_markdown(non_code)
143
+ if inline_code_pattern.search(non_code):
144
+ result.append(markdown(non_code, extensions=["tables"]))
145
+ else:
146
+ result.append(mdtex2html.convert(non_code, extensions=["tables"]))
147
+ if code.strip():
148
+ code = f"\n```{code}\n\n```"
149
+ code = markdown_to_html_with_syntax_highlight(code)
150
+ result.append(code)
151
+ result = "".join(result)
152
+ result += ALREADY_CONVERTED_MARK
153
+ return result
154
+
155
+
156
+ def convert_asis(userinput):
157
+ return f'<p style="white-space:pre-wrap;">{html.escape(userinput)}</p>{ALREADY_CONVERTED_MARK}'
158
+
159
+
160
+ def is_stop_word_or_prefix(s: str, stop_words: list) -> bool:
161
+ return any(s.endswith(stop_word) for stop_word in stop_words)
162
+
163
+
164
+ def detect_converted_mark(userinput):
165
+ return bool(userinput.endswith(ALREADY_CONVERTED_MARK))
166
+
167
+
168
+ def detect_language(code):
169
+ first_line = "" if code.startswith("\n") else code.strip().split("\n", 1)[0]
170
+ language = first_line.lower() if first_line else ""
171
+ code_without_language = code[len(first_line) :].lstrip() if first_line else code
172
+ return language, code_without_language
173
+
174
+
175
+ def convert_to_markdown(text):
176
+ text = text.replace("$", "&#36;")
177
+ text = text.replace("\r\n", "\n")
178
+
179
+ def replace_leading_tabs_and_spaces(line):
180
+ new_line = []
181
+
182
+ for char in line:
183
+ if char == "\t":
184
+ new_line.append("&#9;")
185
+ elif char == " ":
186
+ new_line.append("&nbsp;")
187
+ else:
188
+ break
189
+ return "".join(new_line) + line[len(new_line) :]
190
+
191
+ markdown_text = ""
192
+ lines = text.split("\n")
193
+ in_code_block = False
194
+
195
+ for line in lines:
196
+ if in_code_block is False and line.startswith("```"):
197
+ in_code_block = True
198
+ markdown_text += f"{line}\n"
199
+ elif in_code_block is True and line.startswith("```"):
200
+ in_code_block = False
201
+ markdown_text += f"{line}\n"
202
+ elif in_code_block:
203
+ markdown_text += f"{line}\n"
204
+ else:
205
+ line = replace_leading_tabs_and_spaces(line)
206
+ line = re.sub(r"^(#)", r"\\\1", line)
207
+ markdown_text += f"{line} \n"
208
+
209
+ return markdown_text
210
+
211
+
212
+ def add_language_tag(text):
213
+ def detect_language(code_block):
214
+ try:
215
+ lexer = guess_lexer(code_block)
216
+ return lexer.name.lower()
217
+ except ClassNotFound:
218
+ return ""
219
+
220
+ code_block_pattern = re.compile(r"(```)(\w*\n[^`]+```)", re.MULTILINE)
221
+
222
+ def replacement(match):
223
+ code_block = match.group(2)
224
+ if match.group(2).startswith("\n"):
225
+ language = detect_language(code_block)
226
+ return (
227
+ f"```{language}{code_block}```" if language else f"```\n{code_block}```"
228
+ )
229
+ else:
230
+ return match.group(1) + code_block + "```"
231
+
232
+ text2 = code_block_pattern.sub(replacement, text)
233
+ return text2
234
+
235
+
236
+ def is_variable_assigned(var_name: str) -> bool:
237
+ return var_name in locals()
238
+
239
+
240
+ def pil_to_base64(
241
+ image: Image.Image,
242
+ alt: str = "user upload image",
243
+ resize: bool = True,
244
+ max_size: int = MAX_IMAGE_SIZE,
245
+ min_size: int = MIN_IMAGE_SIZE,
246
+ format: str = "JPEG",
247
+ quality: int = 95
248
+ ) -> str:
249
+
250
+ if resize:
251
+ max_hw, min_hw = max(image.size), min(image.size)
252
+ aspect_ratio = max_hw / min_hw
253
+ shortest_edge = int(min(max_size / aspect_ratio, min_size, min_hw))
254
+ longest_edge = int(shortest_edge * aspect_ratio)
255
+ W, H = image.size
256
+ if H > W:
257
+ H, W = longest_edge, shortest_edge
258
+ else:
259
+ H, W = shortest_edge, longest_edge
260
+ image = image.resize((W, H))
261
+
262
+ buffered = io.BytesIO()
263
+ image.save(buffered, format=format, quality=quality)
264
+ img_b64_str = base64.b64encode(buffered.getvalue()).decode()
265
+ img_str = f'<img src="data:image/png;base64,{img_b64_str}" alt="{alt}" />'
266
+
267
+ return img_str
268
+
269
+
270
+ def parse_ref_bbox(response, image: Image.Image):
271
+ try:
272
+ image = image.copy()
273
+ image_w, image_h = image.size
274
+ draw = ImageDraw.Draw(image)
275
+
276
+ ref = re.findall(r'<\|ref\|>.*?<\|/ref\|>', response)
277
+ bbox = re.findall(r'<\|det\|>.*?<\|/det\|>', response)
278
+ assert len(ref) == len(bbox)
279
+
280
+ if len(ref) == 0:
281
+ return None
282
+
283
+ boxes, labels = [], []
284
+ for box, label in zip(bbox, ref):
285
+ box = box.replace('<|det|>', '').replace('<|/det|>', '')
286
+ label = label.replace('<|ref|>', '').replace('<|/ref|>', '')
287
+ box = box[1:-1]
288
+ for onebox in re.findall(r'\[.*?\]', box):
289
+ boxes.append(eval(onebox))
290
+ labels.append(label)
291
+
292
+ for indice, (box, label) in enumerate(zip(boxes, labels)):
293
+ box = (
294
+ int(box[0] / 999 * image_w),
295
+ int(box[1] / 999 * image_h),
296
+ int(box[2] / 999 * image_w),
297
+ int(box[3] / 999 * image_h),
298
+ )
299
+
300
+ box_color = BOX2COLOR[indice % len(BOX2COLOR.keys())]
301
+ box_width = 3
302
+ draw.rectangle(box, outline=box_color, width=box_width)
303
+
304
+ text_x = box[0]
305
+ text_y = box[1] - 20
306
+ text_color = box_color
307
+ font = ImageFont.truetype("deepseek_vl2/serve/assets/simsun.ttc", size=20)
308
+ draw.text((text_x, text_y), label, font=font, fill=text_color)
309
+
310
+ # print(f"boxes = {boxes}, labels = {labels}, re-render = {image}")
311
+ return image
312
+ except:
313
+ return None
314
+
315
+
316
+ def display_example(image_list):
317
+ images_html = ""
318
+ for i, img_path in enumerate(image_list):
319
+ image = Image.open(img_path)
320
+ buffered = io.BytesIO()
321
+ image.save(buffered, format="PNG", quality=100)
322
+ img_b64_str = base64.b64encode(buffered.getvalue()).decode()
323
+ img_str = f'<img src="data:image/png;base64,{img_b64_str}" alt="{img_path}" style="height:80px; margin-right: 10px;" />'
324
+ images_html += img_str
325
+
326
+ result_html = f"""
327
+ <div style="display: flex; align-items: center; margin-bottom: 10px;">
328
+ <div style="flex: 1; margin-right: 10px;">{images_html}</div>
329
+ </div>
330
+ """
331
+
332
+ return result_html
333
+