Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  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. import json
  27. import requests
  28. from api.utils import get_uuid
  29. from api.utils.file_utils import get_project_base_directory
  30. class Base(ABC):
  31. def __init__(self, key, model_name):
  32. pass
  33. def describe(self, image, max_tokens=300):
  34. raise NotImplementedError("Please implement encode method!")
  35. def image2base64(self, image):
  36. if isinstance(image, bytes):
  37. return base64.b64encode(image).decode("utf-8")
  38. if isinstance(image, BytesIO):
  39. return base64.b64encode(image.getvalue()).decode("utf-8")
  40. buffered = BytesIO()
  41. try:
  42. image.save(buffered, format="JPEG")
  43. except Exception as e:
  44. image.save(buffered, format="PNG")
  45. return base64.b64encode(buffered.getvalue()).decode("utf-8")
  46. def prompt(self, b64):
  47. return [
  48. {
  49. "role": "user",
  50. "content": [
  51. {
  52. "type": "image_url",
  53. "image_url": {
  54. "url": f"data:image/jpeg;base64,{b64}"
  55. },
  56. },
  57. {
  58. "text": "请用中文详细描述一下图中的内容,比如时间,地点,人物,事情,人物心情等,如果有数据请提取出数据。" if self.lang.lower() == "chinese" else
  59. "Please describe the content of this picture, like where, when, who, what happen. If it has number data, please extract them out.",
  60. },
  61. ],
  62. }
  63. ]
  64. class GptV4(Base):
  65. def __init__(self, key, model_name="gpt-4-vision-preview", lang="Chinese", base_url="https://api.openai.com/v1"):
  66. if not base_url: base_url="https://api.openai.com/v1"
  67. self.client = OpenAI(api_key=key, base_url=base_url)
  68. self.model_name = model_name
  69. self.lang = lang
  70. def describe(self, image, max_tokens=300):
  71. b64 = self.image2base64(image)
  72. prompt = self.prompt(b64)
  73. for i in range(len(prompt)):
  74. for c in prompt[i]["content"]:
  75. if "text" in c: c["type"] = "text"
  76. res = self.client.chat.completions.create(
  77. model=self.model_name,
  78. messages=prompt,
  79. max_tokens=max_tokens,
  80. )
  81. return res.choices[0].message.content.strip(), res.usage.total_tokens
  82. class AzureGptV4(Base):
  83. def __init__(self, key, model_name, lang="Chinese", **kwargs):
  84. self.client = AzureOpenAI(api_key=key, azure_endpoint=kwargs["base_url"], api_version="2024-02-01")
  85. self.model_name = model_name
  86. self.lang = lang
  87. def describe(self, image, max_tokens=300):
  88. b64 = self.image2base64(image)
  89. prompt = self.prompt(b64)
  90. for i in range(len(prompt)):
  91. for c in prompt[i]["content"]:
  92. if "text" in c: c["type"] = "text"
  93. res = self.client.chat.completions.create(
  94. model=self.model_name,
  95. messages=prompt,
  96. max_tokens=max_tokens,
  97. )
  98. return res.choices[0].message.content.strip(), res.usage.total_tokens
  99. class QWenCV(Base):
  100. def __init__(self, key, model_name="qwen-vl-chat-v1", lang="Chinese", **kwargs):
  101. import dashscope
  102. dashscope.api_key = key
  103. self.model_name = model_name
  104. self.lang = lang
  105. def prompt(self, binary):
  106. # stupid as hell
  107. tmp_dir = get_project_base_directory("tmp")
  108. if not os.path.exists(tmp_dir):
  109. os.mkdir(tmp_dir)
  110. path = os.path.join(tmp_dir, "%s.jpg" % get_uuid())
  111. Image.open(io.BytesIO(binary)).save(path)
  112. return [
  113. {
  114. "role": "user",
  115. "content": [
  116. {
  117. "image": f"file://{path}"
  118. },
  119. {
  120. "text": "请用中文详细描述一下图中的内容,比如时间,地点,人物,事情,人物心情等,如果有数据请提取出数据。" if self.lang.lower() == "chinese" else
  121. "Please describe the content of this picture, like where, when, who, what happen. If it has number data, please extract them out.",
  122. },
  123. ],
  124. }
  125. ]
  126. def describe(self, image, max_tokens=300):
  127. from http import HTTPStatus
  128. from dashscope import MultiModalConversation
  129. response = MultiModalConversation.call(model=self.model_name,
  130. messages=self.prompt(image))
  131. if response.status_code == HTTPStatus.OK:
  132. return response.output.choices[0]['message']['content'][0]["text"], response.usage.output_tokens
  133. return response.message, 0
  134. class Zhipu4V(Base):
  135. def __init__(self, key, model_name="glm-4v", lang="Chinese", **kwargs):
  136. self.client = ZhipuAI(api_key=key)
  137. self.model_name = model_name
  138. self.lang = lang
  139. def describe(self, image, max_tokens=1024):
  140. b64 = self.image2base64(image)
  141. res = self.client.chat.completions.create(
  142. model=self.model_name,
  143. messages=self.prompt(b64),
  144. max_tokens=max_tokens,
  145. )
  146. return res.choices[0].message.content.strip(), res.usage.total_tokens
  147. class OllamaCV(Base):
  148. def __init__(self, key, model_name, lang="Chinese", **kwargs):
  149. self.client = Client(host=kwargs["base_url"])
  150. self.model_name = model_name
  151. self.lang = lang
  152. def describe(self, image, max_tokens=1024):
  153. prompt = self.prompt("")
  154. try:
  155. options = {"num_predict": max_tokens}
  156. response = self.client.generate(
  157. model=self.model_name,
  158. prompt=prompt[0]["content"][1]["text"],
  159. images=[image],
  160. options=options
  161. )
  162. ans = response["response"].strip()
  163. return ans, 128
  164. except Exception as e:
  165. return "**ERROR**: " + str(e), 0
  166. class XinferenceCV(Base):
  167. def __init__(self, key, model_name="", lang="Chinese", base_url=""):
  168. self.client = OpenAI(api_key="xxx", base_url=base_url)
  169. self.model_name = model_name
  170. self.lang = lang
  171. def describe(self, image, max_tokens=300):
  172. b64 = self.image2base64(image)
  173. res = self.client.chat.completions.create(
  174. model=self.model_name,
  175. messages=self.prompt(b64),
  176. max_tokens=max_tokens,
  177. )
  178. return res.choices[0].message.content.strip(), res.usage.total_tokens
  179. class GeminiCV(Base):
  180. def __init__(self, key, model_name="gemini-1.0-pro-vision-latest", lang="Chinese", **kwargs):
  181. from google.generativeai import client,GenerativeModel
  182. client.configure(api_key=key)
  183. _client = client.get_default_generative_client()
  184. self.model_name = model_name
  185. self.model = GenerativeModel(model_name=self.model_name)
  186. self.model._client = _client
  187. self.lang = lang
  188. def describe(self, image, max_tokens=2048):
  189. from PIL.Image import open
  190. gen_config = {'max_output_tokens':max_tokens}
  191. prompt = "请用中文详细描述一下图中的内容,比如时间,地点,人物,事情,人物心情等,如果有数据请提取出数据。" if self.lang.lower() == "chinese" else \
  192. "Please describe the content of this picture, like where, when, who, what happen. If it has number data, please extract them out."
  193. b64 = self.image2base64(image)
  194. img = open(BytesIO(base64.b64decode(b64)))
  195. input = [prompt,img]
  196. res = self.model.generate_content(
  197. input,
  198. generation_config=gen_config,
  199. )
  200. return res.text,res.usage_metadata.total_token_count
  201. class OpenRouterCV(Base):
  202. def __init__(
  203. self,
  204. key,
  205. model_name,
  206. lang="Chinese",
  207. base_url="https://openrouter.ai/api/v1/chat/completions",
  208. ):
  209. self.model_name = model_name
  210. self.lang = lang
  211. self.base_url = "https://openrouter.ai/api/v1/chat/completions"
  212. self.key = key
  213. def describe(self, image, max_tokens=300):
  214. b64 = self.image2base64(image)
  215. response = requests.post(
  216. url=self.base_url,
  217. headers={
  218. "Authorization": f"Bearer {self.key}",
  219. },
  220. data=json.dumps(
  221. {
  222. "model": self.model_name,
  223. "messages": self.prompt(b64),
  224. "max_tokens": max_tokens,
  225. }
  226. ),
  227. )
  228. response = response.json()
  229. return (
  230. response["choices"][0]["message"]["content"].strip(),
  231. response["usage"]["total_tokens"],
  232. )
  233. def prompt(self, b64):
  234. return [
  235. {
  236. "role": "user",
  237. "content": [
  238. {
  239. "type": "image_url",
  240. "image_url": {"url": f"data:image/jpeg;base64,{b64}"},
  241. },
  242. {
  243. "type": "text",
  244. "text": (
  245. "请用中文详细描述一下图中的内容,比如时间,地点,人物,事情,人物心情等,如果有数据请提取出数据。"
  246. if self.lang.lower() == "chinese"
  247. else "Please describe the content of this picture, like where, when, who, what happen. If it has number data, please extract them out."
  248. ),
  249. },
  250. ],
  251. }
  252. ]
  253. class LocalCV(Base):
  254. def __init__(self, key, model_name="glm-4v", lang="Chinese", **kwargs):
  255. pass
  256. def describe(self, image, max_tokens=1024):
  257. return "", 0