mrtngrsbch ffahmed commited on
Commit
c37fb0d
·
0 Parent(s):

Duplicate from microsoft-cognitive-service/mm-react

Browse files

Co-authored-by: fai ah <[email protected]>

.gitattributes ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tflite filter=lfs diff=lfs merge=lfs -text
29
+ *.tgz filter=lfs diff=lfs merge=lfs -text
30
+ *.wasm filter=lfs diff=lfs merge=lfs -text
31
+ *.xz filter=lfs diff=lfs merge=lfs -text
32
+ *.zip filter=lfs diff=lfs merge=lfs -text
33
+ *.zst filter=lfs diff=lfs merge=lfs -text
34
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
35
+ *.png filter=lfs diff=lfs merge=lfs -text
Dockerfile ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.10.9
2
+
3
+ WORKDIR /src
4
+
5
+ COPY ./MM-REACT /src/MM-REACT
6
+
7
+ COPY ./requirements.txt /src/requirements.txt
8
+
9
+ COPY ./langchain-0.0.94-py3-none-any.whl /src/langchain-0.0.94-py3-none-any.whl
10
+
11
+ RUN pip install --no-cache-dir /src/langchain-0.0.94-py3-none-any.whl
12
+
13
+ RUN pip install --no-cache-dir --upgrade -r /src/requirements.txt
14
+
15
+ WORKDIR /src/MM-REACT
16
+
17
+
18
+ CMD ["python", "app.py", "--port", "7860", "--openAIModel", "azureGPT4", "--noIntermediateConv"]
MM-REACT/app.py ADDED
@@ -0,0 +1,528 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ import io
3
+ import os
4
+ from typing import Optional, Tuple
5
+ import datetime
6
+ import sys
7
+ import gradio as gr
8
+ import requests
9
+ import json
10
+ from threading import Lock
11
+ from langchain import ConversationChain, LLMChain
12
+ from langchain.agents import load_tools, initialize_agent, Tool
13
+ from langchain.tools.bing_search.tool import BingSearchRun, BingSearchAPIWrapper
14
+ from langchain.chains.conversation.memory import ConversationBufferMemory
15
+ from langchain.llms import OpenAI
16
+ from langchain.chains import PALChain
17
+ from langchain.llms import AzureOpenAI
18
+ from langchain.utilities import ImunAPIWrapper, ImunMultiAPIWrapper
19
+ from langchain.utils import get_url_path
20
+ from openai.error import AuthenticationError, InvalidRequestError, RateLimitError
21
+ import argparse
22
+ import logging
23
+ from opencensus.ext.azure.log_exporter import AzureLogHandler
24
+ import uuid
25
+
26
+ logger = None
27
+
28
+
29
+ OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY")
30
+ BUG_FOUND_MSG = "Some Functionalities not supported yet. Please refresh and hit 'Click to wake up MM-REACT'"
31
+ AUTH_ERR_MSG = "OpenAI key needed"
32
+ REFRESH_MSG = "Please refresh and hit 'Click to wake up MM-REACT'"
33
+ MAX_TOKENS = 512
34
+
35
+
36
+ def get_logger():
37
+ global logger
38
+ if logger is None:
39
+ logger = logging.getLogger(__name__)
40
+ logger.addHandler(AzureLogHandler())
41
+ return logger
42
+
43
+
44
+ # load chain
45
+ def load_chain(history, log_state):
46
+ global ARGS
47
+
48
+ if ARGS.openAIModel == 'openAIGPT35':
49
+ # openAI GPT 3.5
50
+ llm = OpenAI(temperature=0, max_tokens=MAX_TOKENS)
51
+ elif ARGS.openAIModel == 'azureChatGPT':
52
+ # for Azure OpenAI ChatGPT
53
+ llm = AzureOpenAI(deployment_name="text-chat-davinci-002", model_name="text-chat-davinci-002", temperature=0, max_tokens=MAX_TOKENS)
54
+ elif ARGS.openAIModel == 'azureGPT35turbo':
55
+ # for Azure OpenAI gpt3.5 turbo
56
+ llm = AzureOpenAI(deployment_name="gpt-35-turbo-version-0301", model_name="gpt-35-turbo (version 0301)", temperature=0, max_tokens=MAX_TOKENS)
57
+ elif ARGS.openAIModel == 'azureTextDavinci003':
58
+ # for Azure OpenAI text davinci
59
+ llm = AzureOpenAI(deployment_name="text-davinci-003", model_name="text-davinci-003", temperature=0, max_tokens=MAX_TOKENS)
60
+ elif ARGS.openAIModel == 'azureGPT4':
61
+ # for Azure GPT4 private preview
62
+ llm = AzureOpenAI(deployment_name="gpt-4-32k-0314", temperature=0, chat_completion=True, max_tokens=MAX_TOKENS, openai_api_version="2023-03-15-preview")
63
+
64
+ memory = ConversationBufferMemory(memory_key="chat_history")
65
+
66
+
67
+ #############################
68
+ # loading all tools
69
+
70
+ imun_dense = ImunAPIWrapper(
71
+ imun_url=os.environ.get("IMUN_URL2"),
72
+ params=os.environ.get("IMUN_PARAMS2"),
73
+ imun_subscription_key=os.environ.get("IMUN_SUBSCRIPTION_KEY2"))
74
+
75
+ imun = ImunAPIWrapper()
76
+ imun = ImunMultiAPIWrapper(imuns=[imun, imun_dense])
77
+
78
+ imun_celeb = ImunAPIWrapper(
79
+ imun_url=os.environ.get("IMUN_CELEB_URL"),
80
+ params="")
81
+
82
+ imun_read = ImunAPIWrapper(
83
+ imun_url=os.environ.get("IMUN_OCR_READ_URL"),
84
+ params=os.environ.get("IMUN_OCR_PARAMS"),
85
+ imun_subscription_key=os.environ.get("IMUN_OCR_SUBSCRIPTION_KEY"))
86
+
87
+ imun_receipt = ImunAPIWrapper(
88
+ imun_url=os.environ.get("IMUN_OCR_RECEIPT_URL"),
89
+ params=os.environ.get("IMUN_OCR_PARAMS"),
90
+ imun_subscription_key=os.environ.get("IMUN_OCR_SUBSCRIPTION_KEY"))
91
+
92
+ imun_businesscard = ImunAPIWrapper(
93
+ imun_url=os.environ.get("IMUN_OCR_BC_URL"),
94
+ params=os.environ.get("IMUN_OCR_PARAMS"),
95
+ imun_subscription_key=os.environ.get("IMUN_OCR_SUBSCRIPTION_KEY"))
96
+
97
+ imun_layout = ImunAPIWrapper(
98
+ imun_url=os.environ.get("IMUN_OCR_LAYOUT_URL"),
99
+ params=os.environ.get("IMUN_OCR_PARAMS"),
100
+ imun_subscription_key=os.environ.get("IMUN_OCR_SUBSCRIPTION_KEY"))
101
+
102
+ imun_invoice = ImunAPIWrapper(
103
+ imun_url=os.environ.get("IMUN_OCR_INVOICE_URL"),
104
+ params=os.environ.get("IMUN_OCR_PARAMS"),
105
+ imun_subscription_key=os.environ.get("IMUN_OCR_SUBSCRIPTION_KEY"))
106
+
107
+ bing = BingSearchAPIWrapper(k=2)
108
+
109
+ def edit_photo(query: str) -> str:
110
+ endpoint = os.environ.get("PHOTO_EDIT_ENDPOINT_URL")
111
+ query = query.strip()
112
+ url_idx, img_url = get_url_path(query)
113
+ if not img_url.startswith(("http://", "https://")):
114
+ return "Invalid image URL"
115
+ img_url = img_url.replace("0.0.0.0", os.environ.get("PHOTO_EDIT_ENDPOINT_URL_SHORT"))
116
+ instruction = query[:url_idx]
117
+ # This should be some internal IP to wherever the server runs
118
+ job = {"image_path": img_url, "instruction": instruction}
119
+ response = requests.post(endpoint, json=job)
120
+ if response.status_code != 200:
121
+ return "Could not finish the task try again later!"
122
+ return "Here is the edited image " + endpoint + response.json()["edited_image"]
123
+
124
+ # these tools should not step on each other's toes
125
+ tools = [
126
+ Tool(
127
+ name="PAL-MATH",
128
+ func=PALChain.from_math_prompt(llm).run,
129
+ description=(
130
+ "A wrapper around calculator. "
131
+ "A language model that is really good at solving complex word math problems."
132
+ "Input should be a fully worded hard word math problem."
133
+ )
134
+ ),
135
+ Tool(
136
+ name = "Image Understanding",
137
+ func=imun.run,
138
+ description=(
139
+ "A wrapper around Image Understanding. "
140
+ "Useful for when you need to understand what is inside an image (objects, texts, people)."
141
+ "Input should be an image url, or path to an image file (e.g. .jpg, .png)."
142
+ )
143
+ ),
144
+ Tool(
145
+ name = "OCR Understanding",
146
+ func=imun_read.run,
147
+ description=(
148
+ "A wrapper around OCR Understanding (Optical Character Recognition). "
149
+ "Useful after Image Understanding tool has found text or handwriting is present in the image tags."
150
+ "This tool can find the actual text, written name, or product name in the image."
151
+ "Input should be an image url, or path to an image file (e.g. .jpg, .png)."
152
+ )
153
+ ),
154
+ Tool(
155
+ name = "Receipt Understanding",
156
+ func=imun_receipt.run,
157
+ description=(
158
+ "A wrapper receipt understanding. "
159
+ "Useful after Image Understanding tool has recognized a receipt in the image tags."
160
+ "This tool can find the actual receipt text, prices and detailed items."
161
+ "Input should be an image url, or path to an image file (e.g. .jpg, .png)."
162
+ )
163
+ ),
164
+ Tool(
165
+ name = "Business Card Understanding",
166
+ func=imun_businesscard.run,
167
+ description=(
168
+ "A wrapper around business card understanding. "
169
+ "Useful after Image Understanding tool has recognized businesscard in the image tags."
170
+ "This tool can find the actual business card text, name, address, email, website on the card."
171
+ "Input should be an image url, or path to an image file (e.g. .jpg, .png)."
172
+ )
173
+ ),
174
+ Tool(
175
+ name = "Layout Understanding",
176
+ func=imun_layout.run,
177
+ description=(
178
+ "A wrapper around layout and table understanding. "
179
+ "Useful after Image Understanding tool has recognized businesscard in the image tags."
180
+ "This tool can find the actual business card text, name, address, email, website on the card."
181
+ "Input should be an image url, or path to an image file (e.g. .jpg, .png)."
182
+ )
183
+ ),
184
+ Tool(
185
+ name = "Invoice Understanding",
186
+ func=imun_invoice.run,
187
+ description=(
188
+ "A wrapper around invoice understanding. "
189
+ "Useful after Image Understanding tool has recognized businesscard in the image tags."
190
+ "This tool can find the actual business card text, name, address, email, website on the card."
191
+ "Input should be an image url, or path to an image file (e.g. .jpg, .png)."
192
+ )
193
+ ),
194
+ Tool(
195
+ name = "Celebrity Understanding",
196
+ func=imun_celeb.run,
197
+ description=(
198
+ "A wrapper around celebrity understanding. "
199
+ "Useful after Image Understanding tool has recognized people in the image tags that could be celebrities."
200
+ "This tool can find the name of celebrities in the image."
201
+ "Input should be an image url, or path to an image file (e.g. .jpg, .png)."
202
+ )
203
+ ),
204
+ BingSearchRun(api_wrapper=bing),
205
+ Tool(
206
+ name = "Photo Editing",
207
+ func=edit_photo,
208
+ description=(
209
+ "A wrapper around photo editing. "
210
+ "Useful to edit an image with a given instruction."
211
+ "Input should be an image url, or path to an image file (e.g. .jpg, .png)."
212
+ )
213
+ ),
214
+ ]
215
+
216
+ chain = initialize_agent(tools, llm, agent="conversational-assistant", verbose=True, memory=memory, return_intermediate_steps=True, max_iterations=4)
217
+ log_state = log_state or ""
218
+ print ("log_state {}".format(log_state))
219
+ log_state = str(uuid.uuid1())
220
+ print("langchain reloaded")
221
+ # eproperties = {'custom_dimensions': {'key_1': 'value_1', 'key_2': 'value_2'}}
222
+ properties = {'custom_dimensions': {'session': log_state}}
223
+ get_logger().warning("langchain reloaded", extra=properties)
224
+ history = []
225
+ history.append(("Show me what you got!", "Hi Human, Please upload an image to get started!"))
226
+
227
+ return history, history, chain, log_state, \
228
+ gr.Textbox.update(visible=True), \
229
+ gr.Button.update(visible=True), \
230
+ gr.UploadButton.update(visible=True), \
231
+ gr.Row.update(visible=True), \
232
+ gr.HTML.update(visible=True), \
233
+ gr.Button.update(variant="secondary")
234
+
235
+
236
+ # executes input typed by human
237
+ def run_chain(chain, inp):
238
+ # global chain
239
+
240
+ output = ""
241
+ try:
242
+ output = chain.conversation(input=inp, keep_short=ARGS.noIntermediateConv)
243
+ # output = chain.run(input=inp)
244
+ except AuthenticationError as ae:
245
+ output = AUTH_ERR_MSG + str(datetime.datetime.now()) + ". " + str(ae)
246
+ print("output", output)
247
+ except RateLimitError as rle:
248
+ output = "\n\nRateLimitError: " + str(rle)
249
+ except ValueError as ve:
250
+ output = "\n\nValueError: " + str(ve)
251
+ except InvalidRequestError as ire:
252
+ output = "\n\nInvalidRequestError: " + str(ire)
253
+ except Exception as e:
254
+ output = "\n\n" + BUG_FOUND_MSG + ":\n\n" + str(e)
255
+
256
+ return output
257
+
258
+ # simple chat function wrapper
259
+ class ChatWrapper:
260
+
261
+ def __init__(self):
262
+ self.lock = Lock()
263
+
264
+ def __call__(
265
+ self, inp: str, history: Optional[Tuple[str, str]], chain: Optional[ConversationChain], log_state
266
+ ):
267
+
268
+ """Execute the chat functionality."""
269
+ self.lock.acquire()
270
+ try:
271
+ print("\n==== date/time: " + str(datetime.datetime.now()) + " ====")
272
+ print("inp: " + inp)
273
+
274
+ properties = {'custom_dimensions': {'session': log_state}}
275
+ get_logger().warning("inp: " + inp, extra=properties)
276
+
277
+
278
+ history = history or []
279
+ # If chain is None, that is because no API key was provided.
280
+ output = "Please paste your OpenAI key from openai.com to use this app. " + str(datetime.datetime.now())
281
+
282
+ ########################
283
+ # multi line
284
+ outputs = run_chain(chain, inp)
285
+
286
+ outputs = process_chain_output(outputs)
287
+
288
+ print (" len(outputs) {}".format(len(outputs)))
289
+ for i, output in enumerate(outputs):
290
+ if i==0:
291
+ history.append((inp, output))
292
+ else:
293
+ history.append((None, output))
294
+
295
+
296
+ except Exception as e:
297
+ raise e
298
+ finally:
299
+ self.lock.release()
300
+
301
+ print (history)
302
+ properties = {'custom_dimensions': {'session': log_state}}
303
+ if outputs is None:
304
+ outputs = ""
305
+ get_logger().warning(str(json.dumps(outputs)), extra=properties)
306
+
307
+ return history, history, ""
308
+
309
+ def add_image_with_path(state, chain, imagepath, log_state):
310
+ global ARGS
311
+ state = state or []
312
+
313
+ url_input_for_chain = "http://0.0.0.0:{}/file={}".format(ARGS.port, imagepath)
314
+
315
+ outputs = run_chain(chain, url_input_for_chain)
316
+
317
+ ########################
318
+ # multi line response handling
319
+ outputs = process_chain_output(outputs)
320
+
321
+ for i, output in enumerate(outputs):
322
+ if i==0:
323
+ # state.append((f"![](/file={imagepath})", output))
324
+ state.append(((imagepath,), output))
325
+ else:
326
+ state.append((None, output))
327
+
328
+
329
+ print (state)
330
+ properties = {'custom_dimensions': {'session': log_state}}
331
+ get_logger().warning("url_input_for_chain: " + url_input_for_chain, extra=properties)
332
+ if outputs is None:
333
+ outputs = ""
334
+ get_logger().warning(str(json.dumps(outputs)), extra=properties)
335
+ return state, state
336
+
337
+
338
+ # upload image
339
+ def add_image(state, chain, image, log_state):
340
+ global ARGS
341
+ state = state or []
342
+
343
+ # handling spaces in image path
344
+ imagepath = image.name.replace(" ", "%20")
345
+
346
+ url_input_for_chain = "http://0.0.0.0:{}/file={}".format(ARGS.port, imagepath)
347
+
348
+ outputs = run_chain(chain, url_input_for_chain)
349
+
350
+ ########################
351
+ # multi line response handling
352
+ outputs = process_chain_output(outputs)
353
+
354
+ for i, output in enumerate(outputs):
355
+ if i==0:
356
+ state.append(((imagepath,), output))
357
+ else:
358
+ state.append((None, output))
359
+
360
+
361
+ print (state)
362
+ properties = {'custom_dimensions': {'session': log_state}}
363
+ get_logger().warning("url_input_for_chain: " + url_input_for_chain, extra=properties)
364
+ if outputs is None:
365
+ outputs = ""
366
+ get_logger().warning(str(json.dumps(outputs)), extra=properties)
367
+ return state, state
368
+
369
+ # extract image url from response and process differently
370
+ def replace_with_image_markup(text):
371
+ img_url = None
372
+ text= text.strip()
373
+ url_idx = text.rfind(" ")
374
+ img_url = text[url_idx + 1:].strip()
375
+ if img_url.endswith((".", "?")):
376
+ img_url = img_url[:-1]
377
+
378
+ # if img_url is not None:
379
+ # img_url = f"![](/file={img_url})"
380
+ return img_url
381
+
382
+ # multi line response handling
383
+ def process_chain_output(outputs):
384
+ global ARGS
385
+ EMPTY_AI_REPLY = "AI:"
386
+ # print("outputs {}".format(outputs))
387
+ if isinstance(outputs, str): # single line output
388
+ if outputs.strip() == EMPTY_AI_REPLY:
389
+ outputs = REFRESH_MSG
390
+ outputs = [outputs]
391
+ elif isinstance(outputs, list): # multi line output
392
+ if ARGS.noIntermediateConv: # remove the items with assistant in it.
393
+ cleanOutputs = []
394
+ for output in outputs:
395
+ if output.strip() == EMPTY_AI_REPLY:
396
+ output = REFRESH_MSG
397
+ # found an edited image url to embed
398
+ img_url = None
399
+ # print ("type list: {}".format(output))
400
+ if "assistant: here is the edited image " in output.lower():
401
+ img_url = replace_with_image_markup(output)
402
+ cleanOutputs.append("Assistant: Here is the edited image")
403
+ if img_url is not None:
404
+ cleanOutputs.append((img_url,))
405
+ else:
406
+ cleanOutputs.append(output)
407
+ # cleanOutputs = cleanOutputs + output+ "."
408
+ outputs = cleanOutputs
409
+
410
+ return outputs
411
+
412
+
413
+ def init_and_kick_off():
414
+ global ARGS
415
+ # initalize chatWrapper
416
+ chat = ChatWrapper()
417
+
418
+ exampleTitle = """<h3>Examples to start conversation..</h3>"""
419
+ comingSoon = """<center><b><p style="color:Red;">MM-REACT: April 20th version with GPT4 and image understanding capabilities</p></b></center>"""
420
+ detailLinks = """
421
+ <center>
422
+ <a href="https://multimodal-react.github.io/"> MM-ReAct Website</a>
423
+ ·
424
+ <a href="https://arxiv.org/abs/2303.11381">MM-ReAct Paper</a>
425
+ ·
426
+ <a href="https://github.com/microsoft/MM-REACT">MM-ReAct Code</a>
427
+ </center>
428
+ """
429
+
430
+ with gr.Blocks(css="#tryButton {width: 120px;}") as block:
431
+ llm_state = gr.State()
432
+ history_state = gr.State()
433
+ chain_state = gr.State()
434
+ log_state = gr.State()
435
+
436
+ reset_btn = gr.Button(value="!!!CLICK to wake up MM-REACT!!!", variant="primary", elem_id="resetbtn").style(full_width=True)
437
+ gr.HTML(detailLinks)
438
+ gr.HTML(comingSoon)
439
+
440
+ example_image_size = 90
441
+ col_min_width = 80
442
+ button_variant = "primary"
443
+ with gr.Row():
444
+ with gr.Column(scale=1.0, min_width=100):
445
+ chatbot = gr.Chatbot(elem_id="chatbot", label="MM-REACT Bot").style(height=620)
446
+ with gr.Column(scale=0.20, min_width=200, visible=False) as exampleCol:
447
+ with gr.Row():
448
+ grExampleTitle = gr.HTML(exampleTitle, visible=False)
449
+ with gr.Row():
450
+ with gr.Column(scale=0.50, min_width=col_min_width):
451
+ example3Image = gr.Image("images/receipt.png", interactive=False).style(height=example_image_size, width=example_image_size)
452
+ with gr.Column(scale=0.50, min_width=col_min_width):
453
+ example3ImageButton = gr.Button(elem_id="tryButton", value="Try it!", variant=button_variant).style(full_width=True)
454
+ # dummy text field to hold the path
455
+ example3ImagePath = gr.Text("images/receipt.png", interactive=False, visible=False)
456
+ with gr.Row():
457
+ with gr.Column(scale=0.50, min_width=col_min_width):
458
+ example1Image = gr.Image("images/money.png", interactive=False).style(height=example_image_size, width=example_image_size)
459
+ with gr.Column(scale=0.50, min_width=col_min_width):
460
+ example1ImageButton = gr.Button(elem_id="tryButton", value="Try it!", variant=button_variant).style(full_width=True)
461
+ # dummy text field to hold the path
462
+ example1ImagePath = gr.Text("images/money.png", interactive=False, visible=False)
463
+ with gr.Row():
464
+ with gr.Column(scale=0.50, min_width=col_min_width):
465
+ example2Image = gr.Image("images/cartoon.png", interactive=False).style(height=example_image_size, width=example_image_size)
466
+ with gr.Column(scale=0.50, min_width=col_min_width):
467
+ example2ImageButton = gr.Button(elem_id="tryButton", value="Try it!", variant=button_variant).style(full_width=True)
468
+ # dummy text field to hold the path
469
+ example2ImagePath = gr.Text("images/cartoon.png", interactive=False, visible=False)
470
+ with gr.Row():
471
+ with gr.Column(scale=0.50, min_width=col_min_width):
472
+ example4Image = gr.Image("images/product.png", interactive=False).style(height=example_image_size, width=example_image_size)
473
+ with gr.Column(scale=0.50, min_width=col_min_width):
474
+ example4ImageButton = gr.Button(elem_id="tryButton", value="Try it!", variant=button_variant).style(full_width=True)
475
+ # dummy text field to hold the path
476
+ example4ImagePath = gr.Text("images/product.png", interactive=False, visible=False)
477
+ with gr.Row():
478
+ with gr.Column(scale=0.50, min_width=col_min_width):
479
+ example5Image = gr.Image("images/celebrity.png", interactive=False).style(height=example_image_size, width=example_image_size)
480
+ with gr.Column(scale=0.50, min_width=col_min_width):
481
+ example5ImageButton = gr.Button(elem_id="tryButton", value="Try it!", variant=button_variant).style(full_width=True)
482
+ # dummy text field to hold the path
483
+ example5ImagePath = gr.Text("images/celebrity.png", interactive=False, visible=False)
484
+
485
+
486
+
487
+ with gr.Row():
488
+ with gr.Column(scale=0.75):
489
+ message = gr.Textbox(label="Upload a pic and ask!",
490
+ placeholder="Type your question about the uploaded image",
491
+ lines=1, visible=False)
492
+ with gr.Column(scale=0.15):
493
+ submit = gr.Button(value="Send", variant="secondary", visible=False).style(full_width=True)
494
+ with gr.Column(scale=0.10, min_width=0):
495
+ btn = gr.UploadButton("🖼️", file_types=["image"], visible=False).style(full_width=True)
496
+
497
+
498
+ message.submit(chat, inputs=[message, history_state, chain_state, log_state], outputs=[chatbot, history_state, message])
499
+
500
+ submit.click(chat, inputs=[message, history_state, chain_state, log_state], outputs=[chatbot, history_state, message])
501
+
502
+ btn.upload(add_image, inputs=[history_state, chain_state, btn, log_state], outputs=[history_state, chatbot])
503
+
504
+ # load the chain
505
+ reset_btn.click(load_chain, inputs=[history_state, log_state], outputs=[chatbot, history_state, chain_state, log_state, message, submit, btn, exampleCol, grExampleTitle, reset_btn])
506
+
507
+ # setup listener click for the examples
508
+ example1ImageButton.click(add_image_with_path, inputs=[history_state, chain_state, example1ImagePath, log_state], outputs=[history_state, chatbot])
509
+ example2ImageButton.click(add_image_with_path, inputs=[history_state, chain_state, example2ImagePath, log_state], outputs=[history_state, chatbot])
510
+ example3ImageButton.click(add_image_with_path, inputs=[history_state, chain_state, example3ImagePath, log_state], outputs=[history_state, chatbot])
511
+ example4ImageButton.click(add_image_with_path, inputs=[history_state, chain_state, example4ImagePath, log_state], outputs=[history_state, chatbot])
512
+ example5ImageButton.click(add_image_with_path, inputs=[history_state, chain_state, example5ImagePath, log_state], outputs=[history_state, chatbot])
513
+
514
+
515
+ # launch the app
516
+ block.launch(server_name="0.0.0.0", server_port = ARGS.port)
517
+
518
+ if __name__ == '__main__':
519
+ parser = argparse.ArgumentParser()
520
+
521
+ parser.add_argument('--port', type=int, required=False, default=7860)
522
+ parser.add_argument('--openAIModel', type=str, required=False, default='azureGPT4')
523
+ parser.add_argument('--noIntermediateConv', default=True, action='store_true', help='if this flag is turned on no intermediate conversation should be shown')
524
+
525
+ global ARGS
526
+ ARGS = parser.parse_args()
527
+
528
+ init_and_kick_off()
MM-REACT/images/cartoon.png ADDED

Git LFS Details

  • SHA256: 21802525f0fa269131e78c5ac55d150bdd6cb728a473b09a871e28a02c5dd123
  • Pointer size: 132 Bytes
  • Size of remote file: 1.06 MB
MM-REACT/images/celebrity.png ADDED

Git LFS Details

  • SHA256: 9c60f49627655d70c76ff0106f61412db1735cad1820ed1b87f9ca7e287d9763
  • Pointer size: 132 Bytes
  • Size of remote file: 2.24 MB
MM-REACT/images/money.png ADDED

Git LFS Details

  • SHA256: 0c7f6155049624573c2852538c86ffaab41c258f04462d0f9dc1b73b86949030
  • Pointer size: 131 Bytes
  • Size of remote file: 763 kB
MM-REACT/images/product.png ADDED

Git LFS Details

  • SHA256: b6bd4efae45dadf27cd9b960a56aded711d0c8ec3e41ae0012eb8dd0c8c92ceb
  • Pointer size: 131 Bytes
  • Size of remote file: 655 kB
MM-REACT/images/receipt.png ADDED

Git LFS Details

  • SHA256: 86a1c65f0e82c855cbd766178fe9080fe9c084678da79f2e695680c0ee97b9eb
  • Pointer size: 131 Bytes
  • Size of remote file: 656 kB
README.md ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: mm-react
3
+ emoji: 💻
4
+ colorFrom: indigo
5
+ colorTo: pink
6
+ sdk: docker
7
+ pinned: false
8
+ license: other
9
+ duplicated_from: microsoft-cognitive-service/mm-react
10
+ ---
11
+
12
+ <h1 style=font-size:30px align="center">Additional Details</h1>
13
+ <p align="center">
14
+ <a style=font-size:25px href="https://multimodal-react.github.io/"> MM-ReAct Website</a>
15
+ ·
16
+ <a style=font-size:25px href="https://arxiv.org/abs/2303.11381">MM-ReAct Paper</a>
17
+ ·
18
+ <a style=font-size:25px href="https://github.com/microsoft/MM-REACT">MM-ReAct Code</a>
19
+ </p>
20
+
21
+ * If you modify the code you can build "langchain-0.0.94-py3-none-any.whl" from [this folder](https://github.com/microsoft/MM-REACT/tree/main/langchain) using "poetry build"
22
+ * [List of environment Variables](https://github.com/microsoft/MM-REACT#here-are-the-list-of-resources-you-need-to-set-up-in-azure-and-their-environment-variables) you need to set as SECRET in huggingface space.
langchain-0.0.94-py3-none-any.whl ADDED
Binary file (321 kB). View file
 
requirements.txt ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ opencensus==0.11.0
2
+ opencensus-context==0.1.3
3
+ opencensus-ext-azure==1.1.6
4
+ opencensus-ext-logging==0.1.1
5
+ imagesize==1.4.1
6
+ gradio==3.25.0
7
+ gradio_client==0.1.0
8
+ openai==0.27.4
9
+ requests==2.28.2