Spaces:
Runtime error
Runtime error
update
Browse files- models/search_agent/mindsearch_agent.py +12 -6
- models/search_agent/utils.py +173 -0
- models/vsa_model.py +60 -21
models/search_agent/mindsearch_agent.py
CHANGED
|
@@ -194,7 +194,7 @@ class MindSearchAgent(BaseAgent):
|
|
| 194 |
WebSearchGraph.searcher_cfg = searcher_cfg
|
| 195 |
super().__init__(llm=llm, action_executor=None, protocol=protocol)
|
| 196 |
|
| 197 |
-
def
|
| 198 |
if isinstance(message, str):
|
| 199 |
message = [{'role': 'user', 'content': message}]
|
| 200 |
elif isinstance(message, dict):
|
|
@@ -211,26 +211,32 @@ class MindSearchAgent(BaseAgent):
|
|
| 211 |
agent_return.inner_steps = deepcopy(inner_history)
|
| 212 |
for _ in range(self.max_turn):
|
| 213 |
prompt = self._protocol.format(inner_step=inner_history)
|
|
|
|
|
|
|
|
|
|
| 214 |
code = None
|
| 215 |
-
response = self.llm.
|
| 216 |
-
|
|
|
|
|
|
|
| 217 |
response = response.replace('<|plugin|>', '<|interpreter|>')
|
| 218 |
_, language, action = self._protocol.parse(response)
|
| 219 |
if not language and not action:
|
| 220 |
continue
|
| 221 |
code = action['parameters']['command'] if action else ''
|
| 222 |
-
agent_return.state = self._determine_agent_state(model_state, code, agent_return)
|
| 223 |
agent_return.response = language if not code else code
|
|
|
|
| 224 |
inner_history.append({'role': 'language', 'content': language})
|
| 225 |
print(colored(response, 'blue'))
|
|
|
|
| 226 |
if code:
|
| 227 |
-
|
| 228 |
-
code, as_dict, return_early)
|
| 229 |
else:
|
| 230 |
agent_return.state = AgentStatusCode.END
|
| 231 |
return agent_return
|
| 232 |
agent_return.state = AgentStatusCode.END
|
| 233 |
return agent_return
|
|
|
|
| 234 |
|
| 235 |
def stream_chat(self, message, **kwargs):
|
| 236 |
if isinstance(message, str):
|
|
|
|
| 194 |
WebSearchGraph.searcher_cfg = searcher_cfg
|
| 195 |
super().__init__(llm=llm, action_executor=None, protocol=protocol)
|
| 196 |
|
| 197 |
+
def generate(self, message, **kwargs):
|
| 198 |
if isinstance(message, str):
|
| 199 |
message = [{'role': 'user', 'content': message}]
|
| 200 |
elif isinstance(message, dict):
|
|
|
|
| 211 |
agent_return.inner_steps = deepcopy(inner_history)
|
| 212 |
for _ in range(self.max_turn):
|
| 213 |
prompt = self._protocol.format(inner_step=inner_history)
|
| 214 |
+
prompt = [
|
| 215 |
+
''.join([p['role'] + ': ' + p['content'] for p in prompt])
|
| 216 |
+
]
|
| 217 |
code = None
|
| 218 |
+
response = self.llm.generate(
|
| 219 |
+
prompt,
|
| 220 |
+
**kwargs,
|
| 221 |
+
)[0]
|
| 222 |
response = response.replace('<|plugin|>', '<|interpreter|>')
|
| 223 |
_, language, action = self._protocol.parse(response)
|
| 224 |
if not language and not action:
|
| 225 |
continue
|
| 226 |
code = action['parameters']['command'] if action else ''
|
|
|
|
| 227 |
agent_return.response = language if not code else code
|
| 228 |
+
|
| 229 |
inner_history.append({'role': 'language', 'content': language})
|
| 230 |
print(colored(response, 'blue'))
|
| 231 |
+
|
| 232 |
if code:
|
| 233 |
+
self._process_code(agent_return, inner_history, code, as_dict, return_early)
|
|
|
|
| 234 |
else:
|
| 235 |
agent_return.state = AgentStatusCode.END
|
| 236 |
return agent_return
|
| 237 |
agent_return.state = AgentStatusCode.END
|
| 238 |
return agent_return
|
| 239 |
+
|
| 240 |
|
| 241 |
def stream_chat(self, message, **kwargs):
|
| 242 |
if isinstance(message, str):
|
models/search_agent/utils.py
ADDED
|
@@ -0,0 +1,173 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import copy
|
| 2 |
+
import logging
|
| 3 |
+
from typing import List, Optional, Union
|
| 4 |
+
|
| 5 |
+
from lagent.llms.base_llm import BaseModel
|
| 6 |
+
from lagent.schema import ModelStatusCode
|
| 7 |
+
from lagent.utils.util import filter_suffix
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class LMDeployServer(BaseModel):
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
Args:
|
| 14 |
+
path (str): The path to the model.
|
| 15 |
+
It could be one of the following options:
|
| 16 |
+
- i) A local directory path of a turbomind model which is
|
| 17 |
+
converted by `lmdeploy convert` command or download from
|
| 18 |
+
ii) and iii).
|
| 19 |
+
- ii) The model_id of a lmdeploy-quantized model hosted
|
| 20 |
+
inside a model repo on huggingface.co, such as
|
| 21 |
+
"InternLM/internlm-chat-20b-4bit",
|
| 22 |
+
"lmdeploy/llama2-chat-70b-4bit", etc.
|
| 23 |
+
- iii) The model_id of a model hosted inside a model repo
|
| 24 |
+
on huggingface.co, such as "internlm/internlm-chat-7b",
|
| 25 |
+
"Qwen/Qwen-7B-Chat ", "baichuan-inc/Baichuan2-7B-Chat"
|
| 26 |
+
and so on.
|
| 27 |
+
model_name (str): needed when model_path is a pytorch model on
|
| 28 |
+
huggingface.co, such as "internlm-chat-7b",
|
| 29 |
+
"Qwen-7B-Chat ", "Baichuan2-7B-Chat" and so on.
|
| 30 |
+
server_name (str): host ip for serving
|
| 31 |
+
server_port (int): server port
|
| 32 |
+
tp (int): tensor parallel
|
| 33 |
+
log_level (str): set log level whose value among
|
| 34 |
+
[CRITICAL, ERROR, WARNING, INFO, DEBUG]
|
| 35 |
+
"""
|
| 36 |
+
|
| 37 |
+
def __init__(self,
|
| 38 |
+
path: str,
|
| 39 |
+
model_name: Optional[str] = None,
|
| 40 |
+
server_name: str = '0.0.0.0',
|
| 41 |
+
server_port: int = 23333,
|
| 42 |
+
tp: int = 1,
|
| 43 |
+
log_level: str = 'WARNING',
|
| 44 |
+
serve_cfg=dict(),
|
| 45 |
+
**kwargs):
|
| 46 |
+
super().__init__(path=path, **kwargs)
|
| 47 |
+
self.model_name = model_name
|
| 48 |
+
# TODO get_logger issue in multi processing
|
| 49 |
+
import lmdeploy
|
| 50 |
+
self.client = lmdeploy.serve(
|
| 51 |
+
model_path=self.path,
|
| 52 |
+
model_name=model_name,
|
| 53 |
+
server_name=server_name,
|
| 54 |
+
server_port=server_port,
|
| 55 |
+
tp=tp,
|
| 56 |
+
log_level=log_level,
|
| 57 |
+
**serve_cfg)
|
| 58 |
+
|
| 59 |
+
def generate(self,
|
| 60 |
+
inputs: Union[str, List[str]],
|
| 61 |
+
session_id: int = 2967,
|
| 62 |
+
sequence_start: bool = True,
|
| 63 |
+
sequence_end: bool = True,
|
| 64 |
+
ignore_eos: bool = False,
|
| 65 |
+
skip_special_tokens: Optional[bool] = False,
|
| 66 |
+
timeout: int = 30,
|
| 67 |
+
**kwargs) -> List[str]:
|
| 68 |
+
"""Start a new round conversation of a session. Return the chat
|
| 69 |
+
completions in non-stream mode.
|
| 70 |
+
|
| 71 |
+
Args:
|
| 72 |
+
inputs (str, List[str]): user's prompt(s) in this round
|
| 73 |
+
session_id (int): the identical id of a session
|
| 74 |
+
sequence_start (bool): start flag of a session
|
| 75 |
+
sequence_end (bool): end flag of a session
|
| 76 |
+
ignore_eos (bool): indicator for ignoring eos
|
| 77 |
+
skip_special_tokens (bool): Whether or not to remove special tokens
|
| 78 |
+
in the decoding. Default to be False.
|
| 79 |
+
timeout (int): max time to wait for response
|
| 80 |
+
Returns:
|
| 81 |
+
(a list of/batched) text/chat completion
|
| 82 |
+
"""
|
| 83 |
+
|
| 84 |
+
batched = True
|
| 85 |
+
if isinstance(inputs, str):
|
| 86 |
+
inputs = [inputs]
|
| 87 |
+
batched = False
|
| 88 |
+
|
| 89 |
+
gen_params = self.update_gen_params(**kwargs)
|
| 90 |
+
max_new_tokens = gen_params.pop('max_new_tokens')
|
| 91 |
+
gen_params.update(max_tokens=max_new_tokens)
|
| 92 |
+
|
| 93 |
+
resp = [''] * len(inputs)
|
| 94 |
+
for text in self.client.completions_v1(
|
| 95 |
+
self.model_name,
|
| 96 |
+
inputs,
|
| 97 |
+
session_id=session_id,
|
| 98 |
+
sequence_start=sequence_start,
|
| 99 |
+
sequence_end=sequence_end,
|
| 100 |
+
stream=False,
|
| 101 |
+
ignore_eos=ignore_eos,
|
| 102 |
+
skip_special_tokens=skip_special_tokens,
|
| 103 |
+
timeout=timeout,
|
| 104 |
+
**gen_params):
|
| 105 |
+
resp = [
|
| 106 |
+
resp[i] + item['text']
|
| 107 |
+
for i, item in enumerate(text['choices'])
|
| 108 |
+
]
|
| 109 |
+
# remove stop_words
|
| 110 |
+
resp = filter_suffix(resp, self.gen_params.get('stop_words'))
|
| 111 |
+
if not batched:
|
| 112 |
+
return resp[0]
|
| 113 |
+
return resp
|
| 114 |
+
|
| 115 |
+
def stream_chat(self,
|
| 116 |
+
inputs: List[dict],
|
| 117 |
+
session_id=0,
|
| 118 |
+
sequence_start: bool = True,
|
| 119 |
+
sequence_end: bool = True,
|
| 120 |
+
stream: bool = True,
|
| 121 |
+
ignore_eos: bool = False,
|
| 122 |
+
skip_special_tokens: Optional[bool] = False,
|
| 123 |
+
timeout: int = 30,
|
| 124 |
+
**kwargs):
|
| 125 |
+
"""Start a new round conversation of a session. Return the chat
|
| 126 |
+
completions in stream mode.
|
| 127 |
+
|
| 128 |
+
Args:
|
| 129 |
+
session_id (int): the identical id of a session
|
| 130 |
+
inputs (List[dict]): user's inputs in this round conversation
|
| 131 |
+
sequence_start (bool): start flag of a session
|
| 132 |
+
sequence_end (bool): end flag of a session
|
| 133 |
+
stream (bool): return in a streaming format if enabled
|
| 134 |
+
ignore_eos (bool): indicator for ignoring eos
|
| 135 |
+
skip_special_tokens (bool): Whether or not to remove special tokens
|
| 136 |
+
in the decoding. Default to be False.
|
| 137 |
+
timeout (int): max time to wait for response
|
| 138 |
+
Returns:
|
| 139 |
+
tuple(Status, str, int): status, text/chat completion,
|
| 140 |
+
generated token number
|
| 141 |
+
"""
|
| 142 |
+
gen_params = self.update_gen_params(**kwargs)
|
| 143 |
+
max_new_tokens = gen_params.pop('max_new_tokens')
|
| 144 |
+
gen_params.update(max_tokens=max_new_tokens)
|
| 145 |
+
prompt = self.template_parser(inputs)
|
| 146 |
+
|
| 147 |
+
resp = ''
|
| 148 |
+
finished = False
|
| 149 |
+
stop_words = self.gen_params.get('stop_words')
|
| 150 |
+
for text in self.client.completions_v1(
|
| 151 |
+
self.model_name,
|
| 152 |
+
prompt,
|
| 153 |
+
session_id=session_id,
|
| 154 |
+
sequence_start=sequence_start,
|
| 155 |
+
sequence_end=sequence_end,
|
| 156 |
+
stream=stream,
|
| 157 |
+
ignore_eos=ignore_eos,
|
| 158 |
+
skip_special_tokens=skip_special_tokens,
|
| 159 |
+
timeout=timeout,
|
| 160 |
+
**gen_params):
|
| 161 |
+
resp += text['choices'][0]['text']
|
| 162 |
+
if not resp:
|
| 163 |
+
continue
|
| 164 |
+
# remove stop_words
|
| 165 |
+
for sw in stop_words:
|
| 166 |
+
if sw in resp:
|
| 167 |
+
resp = filter_suffix(resp, stop_words)
|
| 168 |
+
finished = True
|
| 169 |
+
break
|
| 170 |
+
yield ModelStatusCode.STREAM_ING, resp, None
|
| 171 |
+
if finished:
|
| 172 |
+
break
|
| 173 |
+
yield ModelStatusCode.END, resp, None
|
models/vsa_model.py
CHANGED
|
@@ -6,7 +6,6 @@
|
|
| 6 |
# https://github.com/IDEA-Research/GroundingDINO
|
| 7 |
# https://github.com/InternLM/MindSearch
|
| 8 |
# --------------------------------------------------------
|
| 9 |
-
import spaces
|
| 10 |
import os
|
| 11 |
import copy
|
| 12 |
|
|
@@ -25,7 +24,7 @@ from llava.mm_utils import process_images, tokenizer_image_token, get_model_name
|
|
| 25 |
|
| 26 |
from datetime import datetime
|
| 27 |
from lagent.actions import ActionExecutor, BingBrowser
|
| 28 |
-
from lagent.llms import INTERNLM2_META, LMDeployServer
|
| 29 |
from lagent.schema import AgentReturn, AgentStatusCode
|
| 30 |
from lagent.schema import AgentStatusCode
|
| 31 |
from .search_agent.mindsearch_agent import (
|
|
@@ -37,6 +36,7 @@ from .search_agent.mindsearch_prompt import (
|
|
| 37 |
searcher_input_template_cn, searcher_input_template_en,
|
| 38 |
searcher_system_prompt_cn, searcher_system_prompt_en
|
| 39 |
)
|
|
|
|
| 40 |
|
| 41 |
from typing import List, Union
|
| 42 |
|
|
@@ -210,7 +210,24 @@ class WebSearcher:
|
|
| 210 |
raise Exception('Unsupported model for web searcher.')
|
| 211 |
|
| 212 |
self.lang = lang
|
| 213 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 214 |
path = model_path,
|
| 215 |
model_name = model_name,
|
| 216 |
meta_template = INTERNLM2_META,
|
|
@@ -219,7 +236,7 @@ class WebSearcher:
|
|
| 219 |
temperature = temperature,
|
| 220 |
max_new_tokens = max_new_tokens,
|
| 221 |
repetition_penalty = repetition_penalty,
|
| 222 |
-
stop_words = ['<|im_end|>']
|
| 223 |
)
|
| 224 |
self.agent = MindSearchAgent(
|
| 225 |
llm = llm,
|
|
@@ -259,6 +276,14 @@ class WebSearcher:
|
|
| 259 |
with open('temp/search_result_{}.txt'.format(qid), 'w', encoding='utf-8') as wf:
|
| 260 |
wf.write(result)
|
| 261 |
results.append(result)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 262 |
return results
|
| 263 |
|
| 264 |
|
|
@@ -296,28 +321,17 @@ class VisionSearchAssistant:
|
|
| 296 |
self.vlm_load_4bit = vlm_load_4bit
|
| 297 |
self.vlm_load_8bit = vlm_load_8bit
|
| 298 |
self.use_correlate = True
|
|
|
|
|
|
|
|
|
|
|
|
|
| 299 |
|
| 300 |
-
@spaces.GPU
|
| 301 |
def app_run(
|
| 302 |
self,
|
| 303 |
image: Union[str, Image.Image, np.ndarray],
|
| 304 |
text: str,
|
| 305 |
ground_classes: List[str] = COCO_CLASSES
|
| 306 |
-
):
|
| 307 |
-
self.searcher = WebSearcher(
|
| 308 |
-
model_path = self.search_model
|
| 309 |
-
)
|
| 310 |
-
self.grounder = VisualGrounder(
|
| 311 |
-
model_path = self.ground_model,
|
| 312 |
-
device = self.ground_device,
|
| 313 |
-
)
|
| 314 |
-
self.vlm = VLM(
|
| 315 |
-
model_path = self.vlm_model,
|
| 316 |
-
device = self.vlm_device,
|
| 317 |
-
load_4bit = self.vlm_load_4bit,
|
| 318 |
-
load_8bit = self.vlm_load_8bit
|
| 319 |
-
)
|
| 320 |
-
|
| 321 |
# Create and clear the temporary directory.
|
| 322 |
if not os.access('temp', os.F_OK):
|
| 323 |
os.makedirs('temp')
|
|
@@ -338,6 +352,10 @@ class VisionSearchAssistant:
|
|
| 338 |
raise Exception('Unsupported input image format.')
|
| 339 |
|
| 340 |
# Visual Grounding
|
|
|
|
|
|
|
|
|
|
|
|
|
| 341 |
bboxes, labels, out_image = self.grounder(in_image, classes = ground_classes)
|
| 342 |
yield out_image, 'ground'
|
| 343 |
|
|
@@ -352,7 +370,16 @@ class VisionSearchAssistant:
|
|
| 352 |
det_images.append(in_image)
|
| 353 |
labels.append('image')
|
| 354 |
|
|
|
|
|
|
|
|
|
|
| 355 |
# Visual Captioning
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 356 |
captions = []
|
| 357 |
for det_image, label in zip(det_images, labels):
|
| 358 |
inp = get_caption_prompt(label, text)
|
|
@@ -386,11 +413,20 @@ class VisionSearchAssistant:
|
|
| 386 |
|
| 387 |
queries = [text + " " + query for query in queries]
|
| 388 |
|
|
|
|
|
|
|
|
|
|
| 389 |
# Web Searching
|
| 390 |
contexts = self.searcher(queries)
|
| 391 |
yield contexts, 'search'
|
| 392 |
|
| 393 |
# QA
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 394 |
TOKEN_LIMIT = 3500
|
| 395 |
max_length_per_context = TOKEN_LIMIT // len(contexts)
|
| 396 |
for cid, context in enumerate(contexts):
|
|
@@ -403,4 +439,7 @@ class VisionSearchAssistant:
|
|
| 403 |
wf.write(answer)
|
| 404 |
print(answer)
|
| 405 |
|
| 406 |
-
yield answer, 'answer'
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
# https://github.com/IDEA-Research/GroundingDINO
|
| 7 |
# https://github.com/InternLM/MindSearch
|
| 8 |
# --------------------------------------------------------
|
|
|
|
| 9 |
import os
|
| 10 |
import copy
|
| 11 |
|
|
|
|
| 24 |
|
| 25 |
from datetime import datetime
|
| 26 |
from lagent.actions import ActionExecutor, BingBrowser
|
| 27 |
+
from lagent.llms import INTERNLM2_META, LMDeployServer, LMDeployPipeline
|
| 28 |
from lagent.schema import AgentReturn, AgentStatusCode
|
| 29 |
from lagent.schema import AgentStatusCode
|
| 30 |
from .search_agent.mindsearch_agent import (
|
|
|
|
| 36 |
searcher_input_template_cn, searcher_input_template_en,
|
| 37 |
searcher_system_prompt_cn, searcher_system_prompt_en
|
| 38 |
)
|
| 39 |
+
from lmdeploy.messages import PytorchEngineConfig
|
| 40 |
|
| 41 |
from typing import List, Union
|
| 42 |
|
|
|
|
| 210 |
raise Exception('Unsupported model for web searcher.')
|
| 211 |
|
| 212 |
self.lang = lang
|
| 213 |
+
backend_config = PytorchEngineConfig(
|
| 214 |
+
max_batch_size = 1,
|
| 215 |
+
)
|
| 216 |
+
# llm = LMDeployServer(
|
| 217 |
+
# path = model_path,
|
| 218 |
+
# model_name = model_name,
|
| 219 |
+
# meta_template = INTERNLM2_META,
|
| 220 |
+
# top_p = top_p,
|
| 221 |
+
# top_k = top_k,
|
| 222 |
+
# temperature = temperature,
|
| 223 |
+
# max_new_tokens = max_new_tokens,
|
| 224 |
+
# repetition_penalty = repetition_penalty,
|
| 225 |
+
# stop_words = ['<|im_end|>'],
|
| 226 |
+
# serve_cfg = dict(
|
| 227 |
+
# backend_config = backend_config
|
| 228 |
+
# )
|
| 229 |
+
# )
|
| 230 |
+
llm = LMDeployPipeline(
|
| 231 |
path = model_path,
|
| 232 |
model_name = model_name,
|
| 233 |
meta_template = INTERNLM2_META,
|
|
|
|
| 236 |
temperature = temperature,
|
| 237 |
max_new_tokens = max_new_tokens,
|
| 238 |
repetition_penalty = repetition_penalty,
|
| 239 |
+
stop_words = ['<|im_end|>'],
|
| 240 |
)
|
| 241 |
self.agent = MindSearchAgent(
|
| 242 |
llm = llm,
|
|
|
|
| 276 |
with open('temp/search_result_{}.txt'.format(qid), 'w', encoding='utf-8') as wf:
|
| 277 |
wf.write(result)
|
| 278 |
results.append(result)
|
| 279 |
+
# for qid, query in enumerate(queries):
|
| 280 |
+
# result = None
|
| 281 |
+
# agent_return = self.agent.generate(query)
|
| 282 |
+
# result = agent_return.response
|
| 283 |
+
# assert result is not None
|
| 284 |
+
# with open('temp/search_result_{}.txt'.format(qid), 'w', encoding='utf-8') as wf:
|
| 285 |
+
# wf.write(result)
|
| 286 |
+
# results.append(result)
|
| 287 |
return results
|
| 288 |
|
| 289 |
|
|
|
|
| 321 |
self.vlm_load_4bit = vlm_load_4bit
|
| 322 |
self.vlm_load_8bit = vlm_load_8bit
|
| 323 |
self.use_correlate = True
|
| 324 |
+
|
| 325 |
+
self.searcher = WebSearcher(
|
| 326 |
+
model_path = self.search_model
|
| 327 |
+
)
|
| 328 |
|
|
|
|
| 329 |
def app_run(
|
| 330 |
self,
|
| 331 |
image: Union[str, Image.Image, np.ndarray],
|
| 332 |
text: str,
|
| 333 |
ground_classes: List[str] = COCO_CLASSES
|
| 334 |
+
):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 335 |
# Create and clear the temporary directory.
|
| 336 |
if not os.access('temp', os.F_OK):
|
| 337 |
os.makedirs('temp')
|
|
|
|
| 352 |
raise Exception('Unsupported input image format.')
|
| 353 |
|
| 354 |
# Visual Grounding
|
| 355 |
+
self.grounder = VisualGrounder(
|
| 356 |
+
model_path = self.ground_model,
|
| 357 |
+
device = self.ground_device,
|
| 358 |
+
)
|
| 359 |
bboxes, labels, out_image = self.grounder(in_image, classes = ground_classes)
|
| 360 |
yield out_image, 'ground'
|
| 361 |
|
|
|
|
| 370 |
det_images.append(in_image)
|
| 371 |
labels.append('image')
|
| 372 |
|
| 373 |
+
del self.grounder
|
| 374 |
+
torch.cuda.empty_cache()
|
| 375 |
+
|
| 376 |
# Visual Captioning
|
| 377 |
+
self.vlm = VLM(
|
| 378 |
+
model_path = self.vlm_model,
|
| 379 |
+
device = self.vlm_device,
|
| 380 |
+
load_4bit = self.vlm_load_4bit,
|
| 381 |
+
load_8bit = self.vlm_load_8bit
|
| 382 |
+
)
|
| 383 |
captions = []
|
| 384 |
for det_image, label in zip(det_images, labels):
|
| 385 |
inp = get_caption_prompt(label, text)
|
|
|
|
| 413 |
|
| 414 |
queries = [text + " " + query for query in queries]
|
| 415 |
|
| 416 |
+
del self.vlm
|
| 417 |
+
torch.cuda.empty_cache()
|
| 418 |
+
|
| 419 |
# Web Searching
|
| 420 |
contexts = self.searcher(queries)
|
| 421 |
yield contexts, 'search'
|
| 422 |
|
| 423 |
# QA
|
| 424 |
+
self.vlm = VLM(
|
| 425 |
+
model_path = self.vlm_model,
|
| 426 |
+
device = self.vlm_device,
|
| 427 |
+
load_4bit = self.vlm_load_4bit,
|
| 428 |
+
load_8bit = self.vlm_load_8bit
|
| 429 |
+
)
|
| 430 |
TOKEN_LIMIT = 3500
|
| 431 |
max_length_per_context = TOKEN_LIMIT // len(contexts)
|
| 432 |
for cid, context in enumerate(contexts):
|
|
|
|
| 439 |
wf.write(answer)
|
| 440 |
print(answer)
|
| 441 |
|
| 442 |
+
yield answer, 'answer'
|
| 443 |
+
|
| 444 |
+
del self.vlm
|
| 445 |
+
torch.cuda.empty_cache()
|