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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  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 PIL import Image
  20. from openai import OpenAI
  21. import os
  22. import base64
  23. from io import BytesIO
  24. from api.utils import get_uuid
  25. from api.utils.file_utils import get_project_base_directory
  26. class Base(ABC):
  27. def __init__(self, key, model_name):
  28. pass
  29. def describe(self, image, max_tokens=300):
  30. raise NotImplementedError("Please implement encode method!")
  31. def image2base64(self, image):
  32. if isinstance(image, bytes):
  33. return base64.b64encode(image).decode("utf-8")
  34. if isinstance(image, BytesIO):
  35. return base64.b64encode(image.getvalue()).decode("utf-8")
  36. buffered = BytesIO()
  37. try:
  38. image.save(buffered, format="JPEG")
  39. except Exception as e:
  40. image.save(buffered, format="PNG")
  41. return base64.b64encode(buffered.getvalue()).decode("utf-8")
  42. def prompt(self, b64):
  43. return [
  44. {
  45. "role": "user",
  46. "content": [
  47. {
  48. "type": "image_url",
  49. "image_url": {
  50. "url": f"data:image/jpeg;base64,{b64}"
  51. },
  52. },
  53. {
  54. "text": "请用中文详细描述一下图中的内容,比如时间,地点,人物,事情,人物心情等,如果有数据请提取出数据。" if self.lang.lower() == "chinese" else
  55. "Please describe the content of this picture, like where, when, who, what happen. If it has number data, please extract them out.",
  56. },
  57. ],
  58. }
  59. ]
  60. class GptV4(Base):
  61. def __init__(self, key, model_name="gpt-4-vision-preview", lang="Chinese", base_url="https://api.openai.com/v1"):
  62. if not base_url: base_url="https://api.openai.com/v1"
  63. self.client = OpenAI(api_key=key, base_url=base_url)
  64. self.model_name = model_name
  65. self.lang = lang
  66. def describe(self, image, max_tokens=300):
  67. b64 = self.image2base64(image)
  68. res = self.client.chat.completions.create(
  69. model=self.model_name,
  70. messages=self.prompt(b64),
  71. max_tokens=max_tokens,
  72. )
  73. return res.choices[0].message.content.strip(), res.usage.total_tokens
  74. class QWenCV(Base):
  75. def __init__(self, key, model_name="qwen-vl-chat-v1", lang="Chinese", **kwargs):
  76. import dashscope
  77. dashscope.api_key = key
  78. self.model_name = model_name
  79. self.lang = lang
  80. def prompt(self, binary):
  81. # stupid as hell
  82. tmp_dir = get_project_base_directory("tmp")
  83. if not os.path.exists(tmp_dir):
  84. os.mkdir(tmp_dir)
  85. path = os.path.join(tmp_dir, "%s.jpg" % get_uuid())
  86. Image.open(io.BytesIO(binary)).save(path)
  87. return [
  88. {
  89. "role": "user",
  90. "content": [
  91. {
  92. "image": f"file://{path}"
  93. },
  94. {
  95. "text": "请用中文详细描述一下图中的内容,比如时间,地点,人物,事情,人物心情等,如果有数据请提取出数据。" if self.lang.lower() == "chinese" else
  96. "Please describe the content of this picture, like where, when, who, what happen. If it has number data, please extract them out.",
  97. },
  98. ],
  99. }
  100. ]
  101. def describe(self, image, max_tokens=300):
  102. from http import HTTPStatus
  103. from dashscope import MultiModalConversation
  104. response = MultiModalConversation.call(model=self.model_name,
  105. messages=self.prompt(image))
  106. if response.status_code == HTTPStatus.OK:
  107. return response.output.choices[0]['message']['content'][0]["text"], response.usage.output_tokens
  108. return response.message, 0
  109. class Zhipu4V(Base):
  110. def __init__(self, key, model_name="glm-4v", lang="Chinese", **kwargs):
  111. self.client = ZhipuAI(api_key=key)
  112. self.model_name = model_name
  113. self.lang = lang
  114. def describe(self, image, max_tokens=1024):
  115. b64 = self.image2base64(image)
  116. res = self.client.chat.completions.create(
  117. model=self.model_name,
  118. messages=self.prompt(b64),
  119. max_tokens=max_tokens,
  120. )
  121. return res.choices[0].message.content.strip(), res.usage.total_tokens
  122. class LocalCV(Base):
  123. def __init__(self, key, model_name="glm-4v", lang="Chinese", **kwargs):
  124. pass
  125. def describe(self, image, max_tokens=1024):
  126. return "", 0