Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  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 openai.lib.azure import AzureOpenAI
  17. from zhipuai import ZhipuAI
  18. import io
  19. from abc import ABC
  20. from ollama import Client
  21. from PIL import Image
  22. from openai import OpenAI
  23. import os
  24. import base64
  25. from io import BytesIO
  26. from api.utils import get_uuid
  27. from api.utils.file_utils import get_project_base_directory
  28. class Base(ABC):
  29. def __init__(self, key, model_name):
  30. pass
  31. def describe(self, image, max_tokens=300):
  32. raise NotImplementedError("Please implement encode method!")
  33. def image2base64(self, image):
  34. if isinstance(image, bytes):
  35. return base64.b64encode(image).decode("utf-8")
  36. if isinstance(image, BytesIO):
  37. return base64.b64encode(image.getvalue()).decode("utf-8")
  38. buffered = BytesIO()
  39. try:
  40. image.save(buffered, format="JPEG")
  41. except Exception as e:
  42. image.save(buffered, format="PNG")
  43. return base64.b64encode(buffered.getvalue()).decode("utf-8")
  44. def prompt(self, b64):
  45. return [
  46. {
  47. "role": "user",
  48. "content": [
  49. {
  50. "type": "image_url",
  51. "image_url": {
  52. "url": f"data:image/jpeg;base64,{b64}"
  53. },
  54. },
  55. {
  56. "text": "请用中文详细描述一下图中的内容,比如时间,地点,人物,事情,人物心情等,如果有数据请提取出数据。" if self.lang.lower() == "chinese" else
  57. "Please describe the content of this picture, like where, when, who, what happen. If it has number data, please extract them out.",
  58. },
  59. ],
  60. }
  61. ]
  62. class GptV4(Base):
  63. def __init__(self, key, model_name="gpt-4-vision-preview", lang="Chinese", base_url="https://api.openai.com/v1"):
  64. if not base_url: base_url="https://api.openai.com/v1"
  65. self.client = OpenAI(api_key=key, base_url=base_url)
  66. self.model_name = model_name
  67. self.lang = lang
  68. def describe(self, image, max_tokens=300):
  69. b64 = self.image2base64(image)
  70. prompt = self.prompt(b64)
  71. for i in range(len(prompt)):
  72. for c in prompt[i]["content"]:
  73. if "text" in c: c["type"] = "text"
  74. res = self.client.chat.completions.create(
  75. model=self.model_name,
  76. messages=prompt,
  77. max_tokens=max_tokens,
  78. )
  79. return res.choices[0].message.content.strip(), res.usage.total_tokens
  80. class AzureGptV4(Base):
  81. def __init__(self, key, model_name, lang="Chinese", **kwargs):
  82. self.client = AzureOpenAI(api_key=key, azure_endpoint=kwargs["base_url"], api_version="2024-02-01")
  83. self.model_name = model_name
  84. self.lang = lang
  85. def describe(self, image, max_tokens=300):
  86. b64 = self.image2base64(image)
  87. prompt = self.prompt(b64)
  88. for i in range(len(prompt)):
  89. for c in prompt[i]["content"]:
  90. if "text" in c: c["type"] = "text"
  91. res = self.client.chat.completions.create(
  92. model=self.model_name,
  93. messages=prompt,
  94. max_tokens=max_tokens,
  95. )
  96. return res.choices[0].message.content.strip(), res.usage.total_tokens
  97. class QWenCV(Base):
  98. def __init__(self, key, model_name="qwen-vl-chat-v1", lang="Chinese", **kwargs):
  99. import dashscope
  100. dashscope.api_key = key
  101. self.model_name = model_name
  102. self.lang = lang
  103. def prompt(self, binary):
  104. # stupid as hell
  105. tmp_dir = get_project_base_directory("tmp")
  106. if not os.path.exists(tmp_dir):
  107. os.mkdir(tmp_dir)
  108. path = os.path.join(tmp_dir, "%s.jpg" % get_uuid())
  109. Image.open(io.BytesIO(binary)).save(path)
  110. return [
  111. {
  112. "role": "user",
  113. "content": [
  114. {
  115. "image": f"file://{path}"
  116. },
  117. {
  118. "text": "请用中文详细描述一下图中的内容,比如时间,地点,人物,事情,人物心情等,如果有数据请提取出数据。" if self.lang.lower() == "chinese" else
  119. "Please describe the content of this picture, like where, when, who, what happen. If it has number data, please extract them out.",
  120. },
  121. ],
  122. }
  123. ]
  124. def describe(self, image, max_tokens=300):
  125. from http import HTTPStatus
  126. from dashscope import MultiModalConversation
  127. response = MultiModalConversation.call(model=self.model_name,
  128. messages=self.prompt(image))
  129. if response.status_code == HTTPStatus.OK:
  130. return response.output.choices[0]['message']['content'][0]["text"], response.usage.output_tokens
  131. return response.message, 0
  132. class Zhipu4V(Base):
  133. def __init__(self, key, model_name="glm-4v", lang="Chinese", **kwargs):
  134. self.client = ZhipuAI(api_key=key)
  135. self.model_name = model_name
  136. self.lang = lang
  137. def describe(self, image, max_tokens=1024):
  138. b64 = self.image2base64(image)
  139. res = self.client.chat.completions.create(
  140. model=self.model_name,
  141. messages=self.prompt(b64),
  142. max_tokens=max_tokens,
  143. )
  144. return res.choices[0].message.content.strip(), res.usage.total_tokens
  145. class OllamaCV(Base):
  146. def __init__(self, key, model_name, lang="Chinese", **kwargs):
  147. self.client = Client(host=kwargs["base_url"])
  148. self.model_name = model_name
  149. self.lang = lang
  150. def describe(self, image, max_tokens=1024):
  151. prompt = self.prompt("")
  152. try:
  153. options = {"num_predict": max_tokens}
  154. response = self.client.generate(
  155. model=self.model_name,
  156. prompt=prompt[0]["content"][1]["text"],
  157. images=[image],
  158. options=options
  159. )
  160. ans = response["response"].strip()
  161. return ans, 128
  162. except Exception as e:
  163. return "**ERROR**: " + str(e), 0
  164. class XinferenceCV(Base):
  165. def __init__(self, key, model_name="", lang="Chinese", base_url=""):
  166. self.client = OpenAI(api_key="xxx", base_url=base_url)
  167. self.model_name = model_name
  168. self.lang = lang
  169. def describe(self, image, max_tokens=300):
  170. b64 = self.image2base64(image)
  171. res = self.client.chat.completions.create(
  172. model=self.model_name,
  173. messages=self.prompt(b64),
  174. max_tokens=max_tokens,
  175. )
  176. return res.choices[0].message.content.strip(), res.usage.total_tokens
  177. class LocalCV(Base):
  178. def __init__(self, key, model_name="glm-4v", lang="Chinese", **kwargs):
  179. pass
  180. def describe(self, image, max_tokens=1024):
  181. return "", 0