You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

cv_model.py 6.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  1. #
  2. # Copyright 2024 The InfiniFlow Authors. All Rights Reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. from zhipuai import ZhipuAI
  17. import io
  18. from abc import ABC
  19. from ollama import Client
  20. from PIL import Image
  21. from openai import OpenAI
  22. import os
  23. import base64
  24. from io import BytesIO
  25. from api.utils import get_uuid
  26. from api.utils.file_utils import get_project_base_directory
  27. class Base(ABC):
  28. def __init__(self, key, model_name):
  29. pass
  30. def describe(self, image, max_tokens=300):
  31. raise NotImplementedError("Please implement encode method!")
  32. def image2base64(self, image):
  33. if isinstance(image, bytes):
  34. return base64.b64encode(image).decode("utf-8")
  35. if isinstance(image, BytesIO):
  36. return base64.b64encode(image.getvalue()).decode("utf-8")
  37. buffered = BytesIO()
  38. try:
  39. image.save(buffered, format="JPEG")
  40. except Exception as e:
  41. image.save(buffered, format="PNG")
  42. return base64.b64encode(buffered.getvalue()).decode("utf-8")
  43. def prompt(self, b64):
  44. return [
  45. {
  46. "role": "user",
  47. "content": [
  48. {
  49. "type": "image_url",
  50. "image_url": {
  51. "url": f"data:image/jpeg;base64,{b64}"
  52. },
  53. },
  54. {
  55. "text": "请用中文详细描述一下图中的内容,比如时间,地点,人物,事情,人物心情等,如果有数据请提取出数据。" if self.lang.lower() == "chinese" else
  56. "Please describe the content of this picture, like where, when, who, what happen. If it has number data, please extract them out.",
  57. },
  58. ],
  59. }
  60. ]
  61. class GptV4(Base):
  62. def __init__(self, key, model_name="gpt-4-vision-preview", lang="Chinese", base_url="https://api.openai.com/v1"):
  63. if not base_url: base_url="https://api.openai.com/v1"
  64. self.client = OpenAI(api_key=key, base_url=base_url)
  65. self.model_name = model_name
  66. self.lang = lang
  67. def describe(self, image, max_tokens=300):
  68. b64 = self.image2base64(image)
  69. res = self.client.chat.completions.create(
  70. model=self.model_name,
  71. messages=self.prompt(b64),
  72. max_tokens=max_tokens,
  73. )
  74. return res.choices[0].message.content.strip(), res.usage.total_tokens
  75. class QWenCV(Base):
  76. def __init__(self, key, model_name="qwen-vl-chat-v1", lang="Chinese", **kwargs):
  77. import dashscope
  78. dashscope.api_key = key
  79. self.model_name = model_name
  80. self.lang = lang
  81. def prompt(self, binary):
  82. # stupid as hell
  83. tmp_dir = get_project_base_directory("tmp")
  84. if not os.path.exists(tmp_dir):
  85. os.mkdir(tmp_dir)
  86. path = os.path.join(tmp_dir, "%s.jpg" % get_uuid())
  87. Image.open(io.BytesIO(binary)).save(path)
  88. return [
  89. {
  90. "role": "user",
  91. "content": [
  92. {
  93. "image": f"file://{path}"
  94. },
  95. {
  96. "text": "请用中文详细描述一下图中的内容,比如时间,地点,人物,事情,人物心情等,如果有数据请提取出数据。" if self.lang.lower() == "chinese" else
  97. "Please describe the content of this picture, like where, when, who, what happen. If it has number data, please extract them out.",
  98. },
  99. ],
  100. }
  101. ]
  102. def describe(self, image, max_tokens=300):
  103. from http import HTTPStatus
  104. from dashscope import MultiModalConversation
  105. response = MultiModalConversation.call(model=self.model_name,
  106. messages=self.prompt(image))
  107. if response.status_code == HTTPStatus.OK:
  108. return response.output.choices[0]['message']['content'][0]["text"], response.usage.output_tokens
  109. return response.message, 0
  110. class Zhipu4V(Base):
  111. def __init__(self, key, model_name="glm-4v", lang="Chinese", **kwargs):
  112. self.client = ZhipuAI(api_key=key)
  113. self.model_name = model_name
  114. self.lang = lang
  115. def describe(self, image, max_tokens=1024):
  116. b64 = self.image2base64(image)
  117. res = self.client.chat.completions.create(
  118. model=self.model_name,
  119. messages=self.prompt(b64),
  120. max_tokens=max_tokens,
  121. )
  122. return res.choices[0].message.content.strip(), res.usage.total_tokens
  123. class OllamaCV(Base):
  124. def __init__(self, key, model_name, lang="Chinese", **kwargs):
  125. self.client = Client(host=kwargs["base_url"])
  126. self.model_name = model_name
  127. self.lang = lang
  128. def describe(self, image, max_tokens=1024):
  129. prompt = self.prompt("")
  130. try:
  131. options = {"num_predict": max_tokens}
  132. response = self.client.generate(
  133. model=self.model_name,
  134. prompt=prompt[0]["content"][1]["text"],
  135. images=[image],
  136. options=options
  137. )
  138. ans = response["response"].strip()
  139. return ans, 128
  140. except Exception as e:
  141. return "**ERROR**: " + str(e), 0
  142. class XinferenceCV(Base):
  143. def __init__(self, key, model_name="", lang="Chinese", base_url=""):
  144. self.client = OpenAI(api_key="xxx", base_url=base_url)
  145. self.model_name = model_name
  146. self.lang = lang
  147. def describe(self, image, max_tokens=300):
  148. b64 = self.image2base64(image)
  149. res = self.client.chat.completions.create(
  150. model=self.model_name,
  151. messages=self.prompt(b64),
  152. max_tokens=max_tokens,
  153. )
  154. return res.choices[0].message.content.strip(), res.usage.total_tokens
  155. class LocalCV(Base):
  156. def __init__(self, key, model_name="glm-4v", lang="Chinese", **kwargs):
  157. pass
  158. def describe(self, image, max_tokens=1024):
  159. return "", 0