您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147
  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"):
  62. self.client = OpenAI(api_key=key)
  63. self.model_name = model_name
  64. self.lang = lang
  65. def describe(self, image, max_tokens=300):
  66. b64 = self.image2base64(image)
  67. res = self.client.chat.completions.create(
  68. model=self.model_name,
  69. messages=self.prompt(b64),
  70. max_tokens=max_tokens,
  71. )
  72. return res.choices[0].message.content.strip(), res.usage.total_tokens
  73. class QWenCV(Base):
  74. def __init__(self, key, model_name="qwen-vl-chat-v1", lang="Chinese"):
  75. import dashscope
  76. dashscope.api_key = key
  77. self.model_name = model_name
  78. self.lang = lang
  79. def prompt(self, binary):
  80. # stupid as hell
  81. tmp_dir = get_project_base_directory("tmp")
  82. if not os.path.exists(tmp_dir):
  83. os.mkdir(tmp_dir)
  84. path = os.path.join(tmp_dir, "%s.jpg" % get_uuid())
  85. Image.open(io.BytesIO(binary)).save(path)
  86. return [
  87. {
  88. "role": "user",
  89. "content": [
  90. {
  91. "image": f"file://{path}"
  92. },
  93. {
  94. "text": "请用中文详细描述一下图中的内容,比如时间,地点,人物,事情,人物心情等,如果有数据请提取出数据。" if self.lang.lower() == "chinese" else
  95. "Please describe the content of this picture, like where, when, who, what happen. If it has number data, please extract them out.",
  96. },
  97. ],
  98. }
  99. ]
  100. def describe(self, image, max_tokens=300):
  101. from http import HTTPStatus
  102. from dashscope import MultiModalConversation
  103. response = MultiModalConversation.call(model=self.model_name,
  104. messages=self.prompt(image))
  105. if response.status_code == HTTPStatus.OK:
  106. return response.output.choices[0]['message']['content'][0]["text"], response.usage.output_tokens
  107. return response.message, 0
  108. class Zhipu4V(Base):
  109. def __init__(self, key, model_name="glm-4v", lang="Chinese"):
  110. self.client = ZhipuAI(api_key=key)
  111. self.model_name = model_name
  112. self.lang = lang
  113. def describe(self, image, max_tokens=1024):
  114. b64 = self.image2base64(image)
  115. res = self.client.chat.completions.create(
  116. model=self.model_name,
  117. messages=self.prompt(b64),
  118. max_tokens=max_tokens,
  119. )
  120. return res.choices[0].message.content.strip(), res.usage.total_tokens
  121. class LocalCV(Base):
  122. def __init__(self, key, model_name="glm-4v", lang="Chinese"):
  123. pass
  124. def describe(self, image, max_tokens=1024):
  125. return "", 0