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 28KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726
  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 rag.nlp import is_english
  29. from api.utils import get_uuid
  30. from api.utils.file_utils import get_project_base_directory
  31. class Base(ABC):
  32. def __init__(self, key, model_name):
  33. pass
  34. def describe(self, image, max_tokens=300):
  35. raise NotImplementedError("Please implement encode method!")
  36. def chat(self, system, history, gen_conf, image=""):
  37. if system:
  38. history[-1]["content"] = system + history[-1]["content"] + "user query: " + history[-1]["content"]
  39. try:
  40. for his in history:
  41. if his["role"] == "user":
  42. his["content"] = self.chat_prompt(his["content"], image)
  43. response = self.client.chat.completions.create(
  44. model=self.model_name,
  45. messages=history,
  46. max_tokens=gen_conf.get("max_tokens", 1000),
  47. temperature=gen_conf.get("temperature", 0.3),
  48. top_p=gen_conf.get("top_p", 0.7)
  49. )
  50. return response.choices[0].message.content.strip(), response.usage.total_tokens
  51. except Exception as e:
  52. return "**ERROR**: " + str(e), 0
  53. def chat_streamly(self, system, history, gen_conf, image=""):
  54. if system:
  55. history[-1]["content"] = system + history[-1]["content"] + "user query: " + history[-1]["content"]
  56. ans = ""
  57. tk_count = 0
  58. try:
  59. for his in history:
  60. if his["role"] == "user":
  61. his["content"] = self.chat_prompt(his["content"], image)
  62. response = self.client.chat.completions.create(
  63. model=self.model_name,
  64. messages=history,
  65. max_tokens=gen_conf.get("max_tokens", 1000),
  66. temperature=gen_conf.get("temperature", 0.3),
  67. top_p=gen_conf.get("top_p", 0.7),
  68. stream=True
  69. )
  70. for resp in response:
  71. if not resp.choices[0].delta.content: continue
  72. delta = resp.choices[0].delta.content
  73. ans += delta
  74. if resp.choices[0].finish_reason == "length":
  75. ans += "...\nFor the content length reason, it stopped, continue?" if is_english(
  76. [ans]) else "······\n由于长度的原因,回答被截断了,要继续吗?"
  77. tk_count = resp.usage.total_tokens
  78. if resp.choices[0].finish_reason == "stop": tk_count = resp.usage.total_tokens
  79. yield ans
  80. except Exception as e:
  81. yield ans + "\n**ERROR**: " + str(e)
  82. yield tk_count
  83. def image2base64(self, image):
  84. if isinstance(image, bytes):
  85. return base64.b64encode(image).decode("utf-8")
  86. if isinstance(image, BytesIO):
  87. return base64.b64encode(image.getvalue()).decode("utf-8")
  88. buffered = BytesIO()
  89. try:
  90. image.save(buffered, format="JPEG")
  91. except Exception as e:
  92. image.save(buffered, format="PNG")
  93. return base64.b64encode(buffered.getvalue()).decode("utf-8")
  94. def prompt(self, b64):
  95. return [
  96. {
  97. "role": "user",
  98. "content": [
  99. {
  100. "type": "image_url",
  101. "image_url": {
  102. "url": f"data:image/jpeg;base64,{b64}"
  103. },
  104. },
  105. {
  106. "text": "请用中文详细描述一下图中的内容,比如时间,地点,人物,事情,人物心情等,如果有数据请提取出数据。" if self.lang.lower() == "chinese" else
  107. "Please describe the content of this picture, like where, when, who, what happen. If it has number data, please extract them out.",
  108. },
  109. ],
  110. }
  111. ]
  112. def chat_prompt(self, text, b64):
  113. return [
  114. {
  115. "type": "image_url",
  116. "image_url": {
  117. "url": f"data:image/jpeg;base64,{b64}",
  118. },
  119. },
  120. {
  121. "type": "text",
  122. "text": text
  123. },
  124. ]
  125. class GptV4(Base):
  126. def __init__(self, key, model_name="gpt-4-vision-preview", lang="Chinese", base_url="https://api.openai.com/v1"):
  127. if not base_url: base_url="https://api.openai.com/v1"
  128. self.client = OpenAI(api_key=key, base_url=base_url)
  129. self.model_name = model_name
  130. self.lang = lang
  131. def describe(self, image, max_tokens=300):
  132. b64 = self.image2base64(image)
  133. prompt = self.prompt(b64)
  134. for i in range(len(prompt)):
  135. for c in prompt[i]["content"]:
  136. if "text" in c: c["type"] = "text"
  137. res = self.client.chat.completions.create(
  138. model=self.model_name,
  139. messages=prompt,
  140. max_tokens=max_tokens,
  141. )
  142. return res.choices[0].message.content.strip(), res.usage.total_tokens
  143. class AzureGptV4(Base):
  144. def __init__(self, key, model_name, lang="Chinese", **kwargs):
  145. api_key = json.loads(key).get('api_key', '')
  146. api_version = json.loads(key).get('api_version', '2024-02-01')
  147. self.client = AzureOpenAI(api_key=api_key, azure_endpoint=kwargs["base_url"], api_version=api_version)
  148. self.model_name = model_name
  149. self.lang = lang
  150. def describe(self, image, max_tokens=300):
  151. b64 = self.image2base64(image)
  152. prompt = self.prompt(b64)
  153. for i in range(len(prompt)):
  154. for c in prompt[i]["content"]:
  155. if "text" in c: c["type"] = "text"
  156. res = self.client.chat.completions.create(
  157. model=self.model_name,
  158. messages=prompt,
  159. max_tokens=max_tokens,
  160. )
  161. return res.choices[0].message.content.strip(), res.usage.total_tokens
  162. class QWenCV(Base):
  163. def __init__(self, key, model_name="qwen-vl-chat-v1", lang="Chinese", **kwargs):
  164. import dashscope
  165. dashscope.api_key = key
  166. self.model_name = model_name
  167. self.lang = lang
  168. def prompt(self, binary):
  169. # stupid as hell
  170. tmp_dir = get_project_base_directory("tmp")
  171. if not os.path.exists(tmp_dir):
  172. os.mkdir(tmp_dir)
  173. path = os.path.join(tmp_dir, "%s.jpg" % get_uuid())
  174. Image.open(io.BytesIO(binary)).save(path)
  175. return [
  176. {
  177. "role": "user",
  178. "content": [
  179. {
  180. "image": f"file://{path}"
  181. },
  182. {
  183. "text": "请用中文详细描述一下图中的内容,比如时间,地点,人物,事情,人物心情等,如果有数据请提取出数据。" if self.lang.lower() == "chinese" else
  184. "Please describe the content of this picture, like where, when, who, what happen. If it has number data, please extract them out.",
  185. },
  186. ],
  187. }
  188. ]
  189. def chat_prompt(self, text, b64):
  190. return [
  191. {"image": f"{b64}"},
  192. {"text": text},
  193. ]
  194. def describe(self, image, max_tokens=300):
  195. from http import HTTPStatus
  196. from dashscope import MultiModalConversation
  197. response = MultiModalConversation.call(model=self.model_name,
  198. messages=self.prompt(image))
  199. if response.status_code == HTTPStatus.OK:
  200. return response.output.choices[0]['message']['content'][0]["text"], response.usage.output_tokens
  201. return response.message, 0
  202. def chat(self, system, history, gen_conf, image=""):
  203. from http import HTTPStatus
  204. from dashscope import MultiModalConversation
  205. if system:
  206. history[-1]["content"] = system + history[-1]["content"] + "user query: " + history[-1]["content"]
  207. for his in history:
  208. if his["role"] == "user":
  209. his["content"] = self.chat_prompt(his["content"], image)
  210. response = MultiModalConversation.call(model=self.model_name, messages=history,
  211. max_tokens=gen_conf.get("max_tokens", 1000),
  212. temperature=gen_conf.get("temperature", 0.3),
  213. top_p=gen_conf.get("top_p", 0.7))
  214. ans = ""
  215. tk_count = 0
  216. if response.status_code == HTTPStatus.OK:
  217. ans += response.output.choices[0]['message']['content']
  218. tk_count += response.usage.total_tokens
  219. if response.output.choices[0].get("finish_reason", "") == "length":
  220. ans += "...\nFor the content length reason, it stopped, continue?" if is_english(
  221. [ans]) else "······\n由于长度的原因,回答被截断了,要继续吗?"
  222. return ans, tk_count
  223. return "**ERROR**: " + response.message, tk_count
  224. def chat_streamly(self, system, history, gen_conf, image=""):
  225. from http import HTTPStatus
  226. from dashscope import MultiModalConversation
  227. if system:
  228. history[-1]["content"] = system + history[-1]["content"] + "user query: " + history[-1]["content"]
  229. for his in history:
  230. if his["role"] == "user":
  231. his["content"] = self.chat_prompt(his["content"], image)
  232. ans = ""
  233. tk_count = 0
  234. try:
  235. response = MultiModalConversation.call(model=self.model_name, messages=history,
  236. max_tokens=gen_conf.get("max_tokens", 1000),
  237. temperature=gen_conf.get("temperature", 0.3),
  238. top_p=gen_conf.get("top_p", 0.7),
  239. stream=True)
  240. for resp in response:
  241. if resp.status_code == HTTPStatus.OK:
  242. ans = resp.output.choices[0]['message']['content']
  243. tk_count = resp.usage.total_tokens
  244. if resp.output.choices[0].get("finish_reason", "") == "length":
  245. ans += "...\nFor the content length reason, it stopped, continue?" if is_english(
  246. [ans]) else "······\n由于长度的原因,回答被截断了,要继续吗?"
  247. yield ans
  248. else:
  249. yield ans + "\n**ERROR**: " + resp.message if str(resp.message).find(
  250. "Access") < 0 else "Out of credit. Please set the API key in **settings > Model providers.**"
  251. except Exception as e:
  252. yield ans + "\n**ERROR**: " + str(e)
  253. yield tk_count
  254. class Zhipu4V(Base):
  255. def __init__(self, key, model_name="glm-4v", lang="Chinese", **kwargs):
  256. self.client = ZhipuAI(api_key=key)
  257. self.model_name = model_name
  258. self.lang = lang
  259. def describe(self, image, max_tokens=1024):
  260. b64 = self.image2base64(image)
  261. prompt = self.prompt(b64)
  262. prompt[0]["content"][1]["type"] = "text"
  263. res = self.client.chat.completions.create(
  264. model=self.model_name,
  265. messages=prompt,
  266. max_tokens=max_tokens,
  267. )
  268. return res.choices[0].message.content.strip(), res.usage.total_tokens
  269. def chat(self, system, history, gen_conf, image=""):
  270. if system:
  271. history[-1]["content"] = system + history[-1]["content"] + "user query: " + history[-1]["content"]
  272. try:
  273. for his in history:
  274. if his["role"] == "user":
  275. his["content"] = self.chat_prompt(his["content"], image)
  276. response = self.client.chat.completions.create(
  277. model=self.model_name,
  278. messages=history,
  279. max_tokens=gen_conf.get("max_tokens", 1000),
  280. temperature=gen_conf.get("temperature", 0.3),
  281. top_p=gen_conf.get("top_p", 0.7)
  282. )
  283. return response.choices[0].message.content.strip(), response.usage.total_tokens
  284. except Exception as e:
  285. return "**ERROR**: " + str(e), 0
  286. def chat_streamly(self, system, history, gen_conf, image=""):
  287. if system:
  288. history[-1]["content"] = system + history[-1]["content"] + "user query: " + history[-1]["content"]
  289. ans = ""
  290. tk_count = 0
  291. try:
  292. for his in history:
  293. if his["role"] == "user":
  294. his["content"] = self.chat_prompt(his["content"], image)
  295. response = self.client.chat.completions.create(
  296. model=self.model_name,
  297. messages=history,
  298. max_tokens=gen_conf.get("max_tokens", 1000),
  299. temperature=gen_conf.get("temperature", 0.3),
  300. top_p=gen_conf.get("top_p", 0.7),
  301. stream=True
  302. )
  303. for resp in response:
  304. if not resp.choices[0].delta.content: continue
  305. delta = resp.choices[0].delta.content
  306. ans += delta
  307. if resp.choices[0].finish_reason == "length":
  308. ans += "...\nFor the content length reason, it stopped, continue?" if is_english(
  309. [ans]) else "······\n由于长度的原因,回答被截断了,要继续吗?"
  310. tk_count = resp.usage.total_tokens
  311. if resp.choices[0].finish_reason == "stop": tk_count = resp.usage.total_tokens
  312. yield ans
  313. except Exception as e:
  314. yield ans + "\n**ERROR**: " + str(e)
  315. yield tk_count
  316. class OllamaCV(Base):
  317. def __init__(self, key, model_name, lang="Chinese", **kwargs):
  318. self.client = Client(host=kwargs["base_url"])
  319. self.model_name = model_name
  320. self.lang = lang
  321. def describe(self, image, max_tokens=1024):
  322. prompt = self.prompt("")
  323. try:
  324. options = {"num_predict": max_tokens}
  325. response = self.client.generate(
  326. model=self.model_name,
  327. prompt=prompt[0]["content"][1]["text"],
  328. images=[image],
  329. options=options
  330. )
  331. ans = response["response"].strip()
  332. return ans, 128
  333. except Exception as e:
  334. return "**ERROR**: " + str(e), 0
  335. def chat(self, system, history, gen_conf, image=""):
  336. if system:
  337. history[-1]["content"] = system + history[-1]["content"] + "user query: " + history[-1]["content"]
  338. try:
  339. for his in history:
  340. if his["role"] == "user":
  341. his["images"] = [image]
  342. options = {}
  343. if "temperature" in gen_conf: options["temperature"] = gen_conf["temperature"]
  344. if "max_tokens" in gen_conf: options["num_predict"] = gen_conf["max_tokens"]
  345. if "top_p" in gen_conf: options["top_k"] = gen_conf["top_p"]
  346. if "presence_penalty" in gen_conf: options["presence_penalty"] = gen_conf["presence_penalty"]
  347. if "frequency_penalty" in gen_conf: options["frequency_penalty"] = gen_conf["frequency_penalty"]
  348. response = self.client.chat(
  349. model=self.model_name,
  350. messages=history,
  351. options=options,
  352. keep_alive=-1
  353. )
  354. ans = response["message"]["content"].strip()
  355. return ans, response["eval_count"] + response.get("prompt_eval_count", 0)
  356. except Exception as e:
  357. return "**ERROR**: " + str(e), 0
  358. def chat_streamly(self, system, history, gen_conf, image=""):
  359. if system:
  360. history[-1]["content"] = system + history[-1]["content"] + "user query: " + history[-1]["content"]
  361. for his in history:
  362. if his["role"] == "user":
  363. his["images"] = [image]
  364. options = {}
  365. if "temperature" in gen_conf: options["temperature"] = gen_conf["temperature"]
  366. if "max_tokens" in gen_conf: options["num_predict"] = gen_conf["max_tokens"]
  367. if "top_p" in gen_conf: options["top_k"] = gen_conf["top_p"]
  368. if "presence_penalty" in gen_conf: options["presence_penalty"] = gen_conf["presence_penalty"]
  369. if "frequency_penalty" in gen_conf: options["frequency_penalty"] = gen_conf["frequency_penalty"]
  370. ans = ""
  371. try:
  372. response = self.client.chat(
  373. model=self.model_name,
  374. messages=history,
  375. stream=True,
  376. options=options,
  377. keep_alive=-1
  378. )
  379. for resp in response:
  380. if resp["done"]:
  381. yield resp.get("prompt_eval_count", 0) + resp.get("eval_count", 0)
  382. ans += resp["message"]["content"]
  383. yield ans
  384. except Exception as e:
  385. yield ans + "\n**ERROR**: " + str(e)
  386. yield 0
  387. class LocalAICV(GptV4):
  388. def __init__(self, key, model_name, base_url, lang="Chinese"):
  389. if not base_url:
  390. raise ValueError("Local cv model url cannot be None")
  391. if base_url.split("/")[-1] != "v1":
  392. base_url = os.path.join(base_url, "v1")
  393. self.client = OpenAI(api_key="empty", base_url=base_url)
  394. self.model_name = model_name.split("___")[0]
  395. self.lang = lang
  396. class XinferenceCV(Base):
  397. def __init__(self, key, model_name="", lang="Chinese", base_url=""):
  398. if base_url.split("/")[-1] != "v1":
  399. base_url = os.path.join(base_url, "v1")
  400. self.client = OpenAI(api_key=key, base_url=base_url)
  401. self.model_name = model_name
  402. self.lang = lang
  403. def describe(self, image, max_tokens=300):
  404. b64 = self.image2base64(image)
  405. res = self.client.chat.completions.create(
  406. model=self.model_name,
  407. messages=self.prompt(b64),
  408. max_tokens=max_tokens,
  409. )
  410. return res.choices[0].message.content.strip(), res.usage.total_tokens
  411. class GeminiCV(Base):
  412. def __init__(self, key, model_name="gemini-1.0-pro-vision-latest", lang="Chinese", **kwargs):
  413. from google.generativeai import client, GenerativeModel, GenerationConfig
  414. client.configure(api_key=key)
  415. _client = client.get_default_generative_client()
  416. self.model_name = model_name
  417. self.model = GenerativeModel(model_name=self.model_name)
  418. self.model._client = _client
  419. self.lang = lang
  420. def describe(self, image, max_tokens=2048):
  421. from PIL.Image import open
  422. gen_config = {'max_output_tokens':max_tokens}
  423. prompt = "请用中文详细描述一下图中的内容,比如时间,地点,人物,事情,人物心情等,如果有数据请提取出数据。" if self.lang.lower() == "chinese" else \
  424. "Please describe the content of this picture, like where, when, who, what happen. If it has number data, please extract them out."
  425. b64 = self.image2base64(image)
  426. img = open(BytesIO(base64.b64decode(b64)))
  427. input = [prompt,img]
  428. res = self.model.generate_content(
  429. input,
  430. generation_config=gen_config,
  431. )
  432. return res.text,res.usage_metadata.total_token_count
  433. def chat(self, system, history, gen_conf, image=""):
  434. if system:
  435. history[-1]["content"] = system + history[-1]["content"] + "user query: " + history[-1]["content"]
  436. try:
  437. for his in history:
  438. if his["role"] == "assistant":
  439. his["role"] = "model"
  440. his["parts"] = [his["content"]]
  441. his.pop("content")
  442. if his["role"] == "user":
  443. his["parts"] = [his["content"]]
  444. his.pop("content")
  445. history[-1]["parts"].append(f"data:image/jpeg;base64," + image)
  446. response = self.model.generate_content(history, generation_config=GenerationConfig(
  447. max_output_tokens=gen_conf.get("max_tokens", 1000), temperature=gen_conf.get("temperature", 0.3),
  448. top_p=gen_conf.get("top_p", 0.7)))
  449. ans = response.text
  450. return ans, response.usage_metadata.total_token_count
  451. except Exception as e:
  452. return "**ERROR**: " + str(e), 0
  453. def chat_streamly(self, system, history, gen_conf, image=""):
  454. if system:
  455. history[-1]["content"] = system + history[-1]["content"] + "user query: " + history[-1]["content"]
  456. ans = ""
  457. tk_count = 0
  458. try:
  459. for his in history:
  460. if his["role"] == "assistant":
  461. his["role"] = "model"
  462. his["parts"] = [his["content"]]
  463. his.pop("content")
  464. if his["role"] == "user":
  465. his["parts"] = [his["content"]]
  466. his.pop("content")
  467. history[-1]["parts"].append(f"data:image/jpeg;base64," + image)
  468. response = self.model.generate_content(history, generation_config=GenerationConfig(
  469. max_output_tokens=gen_conf.get("max_tokens", 1000), temperature=gen_conf.get("temperature", 0.3),
  470. top_p=gen_conf.get("top_p", 0.7)), stream=True)
  471. for resp in response:
  472. if not resp.text: continue
  473. ans += resp.text
  474. yield ans
  475. except Exception as e:
  476. yield ans + "\n**ERROR**: " + str(e)
  477. yield response._chunks[-1].usage_metadata.total_token_count
  478. class OpenRouterCV(GptV4):
  479. def __init__(
  480. self,
  481. key,
  482. model_name,
  483. lang="Chinese",
  484. base_url="https://openrouter.ai/api/v1",
  485. ):
  486. if not base_url:
  487. base_url = "https://openrouter.ai/api/v1"
  488. self.client = OpenAI(api_key=key, base_url=base_url)
  489. self.model_name = model_name
  490. self.lang = lang
  491. class LocalCV(Base):
  492. def __init__(self, key, model_name="glm-4v", lang="Chinese", **kwargs):
  493. pass
  494. def describe(self, image, max_tokens=1024):
  495. return "", 0
  496. class NvidiaCV(Base):
  497. def __init__(
  498. self,
  499. key,
  500. model_name,
  501. lang="Chinese",
  502. base_url="https://ai.api.nvidia.com/v1/vlm",
  503. ):
  504. if not base_url:
  505. base_url = ("https://ai.api.nvidia.com/v1/vlm",)
  506. self.lang = lang
  507. factory, llm_name = model_name.split("/")
  508. if factory != "liuhaotian":
  509. self.base_url = os.path.join(base_url, factory, llm_name)
  510. else:
  511. self.base_url = os.path.join(
  512. base_url, "community", llm_name.replace("-v1.6", "16")
  513. )
  514. self.key = key
  515. def describe(self, image, max_tokens=1024):
  516. b64 = self.image2base64(image)
  517. response = requests.post(
  518. url=self.base_url,
  519. headers={
  520. "accept": "application/json",
  521. "content-type": "application/json",
  522. "Authorization": f"Bearer {self.key}",
  523. },
  524. json={
  525. "messages": self.prompt(b64),
  526. "max_tokens": max_tokens,
  527. },
  528. )
  529. response = response.json()
  530. return (
  531. response["choices"][0]["message"]["content"].strip(),
  532. response["usage"]["total_tokens"],
  533. )
  534. def prompt(self, b64):
  535. return [
  536. {
  537. "role": "user",
  538. "content": (
  539. "请用中文详细描述一下图中的内容,比如时间,地点,人物,事情,人物心情等,如果有数据请提取出数据。"
  540. if self.lang.lower() == "chinese"
  541. else "Please describe the content of this picture, like where, when, who, what happen. If it has number data, please extract them out."
  542. )
  543. + f' <img src="data:image/jpeg;base64,{b64}"/>',
  544. }
  545. ]
  546. def chat_prompt(self, text, b64):
  547. return [
  548. {
  549. "role": "user",
  550. "content": text + f' <img src="data:image/jpeg;base64,{b64}"/>',
  551. }
  552. ]
  553. class StepFunCV(GptV4):
  554. def __init__(self, key, model_name="step-1v-8k", lang="Chinese", base_url="https://api.stepfun.com/v1"):
  555. if not base_url: base_url="https://api.stepfun.com/v1"
  556. self.client = OpenAI(api_key=key, base_url=base_url)
  557. self.model_name = model_name
  558. self.lang = lang
  559. class LmStudioCV(GptV4):
  560. def __init__(self, key, model_name, lang="Chinese", base_url=""):
  561. if not base_url:
  562. raise ValueError("Local llm url cannot be None")
  563. if base_url.split("/")[-1] != "v1":
  564. base_url = os.path.join(base_url, "v1")
  565. self.client = OpenAI(api_key="lm-studio", base_url=base_url)
  566. self.model_name = model_name
  567. self.lang = lang
  568. class OpenAI_APICV(GptV4):
  569. def __init__(self, key, model_name, lang="Chinese", base_url=""):
  570. if not base_url:
  571. raise ValueError("url cannot be None")
  572. if base_url.split("/")[-1] != "v1":
  573. base_url = os.path.join(base_url, "v1")
  574. self.client = OpenAI(api_key=key, base_url=base_url)
  575. self.model_name = model_name.split("___")[0]
  576. self.lang = lang
  577. class TogetherAICV(GptV4):
  578. def __init__(self, key, model_name, lang="Chinese", base_url="https://api.together.xyz/v1"):
  579. if not base_url:
  580. base_url = "https://api.together.xyz/v1"
  581. super().__init__(key, model_name,lang,base_url)
  582. class YiCV(GptV4):
  583. def __init__(self, key, model_name, lang="Chinese",base_url="https://api.lingyiwanwu.com/v1",):
  584. if not base_url:
  585. base_url = "https://api.lingyiwanwu.com/v1"
  586. super().__init__(key, model_name,lang,base_url)
  587. class HunyuanCV(Base):
  588. def __init__(self, key, model_name, lang="Chinese",base_url=None):
  589. from tencentcloud.common import credential
  590. from tencentcloud.hunyuan.v20230901 import hunyuan_client
  591. key = json.loads(key)
  592. sid = key.get("hunyuan_sid", "")
  593. sk = key.get("hunyuan_sk", "")
  594. cred = credential.Credential(sid, sk)
  595. self.model_name = model_name
  596. self.client = hunyuan_client.HunyuanClient(cred, "")
  597. self.lang = lang
  598. def describe(self, image, max_tokens=4096):
  599. from tencentcloud.hunyuan.v20230901 import models
  600. from tencentcloud.common.exception.tencent_cloud_sdk_exception import (
  601. TencentCloudSDKException,
  602. )
  603. b64 = self.image2base64(image)
  604. req = models.ChatCompletionsRequest()
  605. params = {"Model": self.model_name, "Messages": self.prompt(b64)}
  606. req.from_json_string(json.dumps(params))
  607. ans = ""
  608. try:
  609. response = self.client.ChatCompletions(req)
  610. ans = response.Choices[0].Message.Content
  611. return ans, response.Usage.TotalTokens
  612. except TencentCloudSDKException as e:
  613. return ans + "\n**ERROR**: " + str(e), 0
  614. def prompt(self, b64):
  615. return [
  616. {
  617. "Role": "user",
  618. "Contents": [
  619. {
  620. "Type": "image_url",
  621. "ImageUrl": {
  622. "Url": f"data:image/jpeg;base64,{b64}"
  623. },
  624. },
  625. {
  626. "Type": "text",
  627. "Text": "请用中文详细描述一下图中的内容,比如时间,地点,人物,事情,人物心情等,如果有数据请提取出数据。" if self.lang.lower() == "chinese" else
  628. "Please describe the content of this picture, like where, when, who, what happen. If it has number data, please extract them out.",
  629. },
  630. ],
  631. }
  632. ]