File size: 30,367 Bytes
148979f
 
 
 
 
f289b70
 
148979f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a9ac22
 
 
 
148979f
 
 
 
2a9ac22
 
 
 
 
 
148979f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f289b70
148979f
 
 
 
 
 
 
 
f289b70
148979f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a9ac22
148979f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a9ac22
148979f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a9ac22
148979f
2a9ac22
148979f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f289b70
 
 
148979f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
import spaces
import argparse
from ast import parse
import datetime
import json
import os
import time
import hashlib
import re

import gradio as gr
import requests
import random
from filelock import FileLock
from io import BytesIO
from PIL import Image, ImageDraw, ImageFont

from constants import LOGDIR
from utils import (
    build_logger,
    server_error_msg,
    violates_moderation,
    moderation_msg,
    load_image_from_base64,
    get_log_filename,
)
from conversation import Conversation

logger = build_logger("gradio_web_server", "gradio_web_server.log")

headers = {"User-Agent": "InternVL-Chat Client"}

no_change_btn = gr.Button()
enable_btn = gr.Button(interactive=True)
disable_btn = gr.Button(interactive=False)


@spaces.GPU(duration=10)
def make_zerogpu_happy():
    pass


def write2file(path, content):
    lock = FileLock(f"{path}.lock")
    with lock:
        with open(path, "a") as fout:
            fout.write(content)


def sort_models(models):
    def custom_sort_key(model_name):
        # InternVL-Chat-V1-5 should be the first item
        if model_name == "InternVL2-Pro":
            return (2, model_name)  # 2 indicates highest precedence
        elif model_name.startswith("InternVL2-8B"):
            return (1, model_name)  # 0 indicates highest precedence
        else:
            return (0, model_name)  # 0 indicates normal order

    models.sort(key=custom_sort_key, reverse=True)
    # try:  # We have five InternVL-Chat-V1-5 models, randomly choose one to be the first
    #     first_three = models[:4]
    #     random.shuffle(first_three)
    #     models[:4] = first_three
    # except:
    #     pass
    return models


def get_model_list():
    logger.info(f"Call `get_model_list`")
    ret = requests.post(args.controller_url + "/refresh_all_workers")
    logger.info(f"status_code from `get_model_list`: {ret.status_code}")
    assert ret.status_code == 200
    ret = requests.post(args.controller_url + "/list_models")
    logger.info(f"status_code from `list_models`: {ret.status_code}")
    models = ret.json()["models"]
    models = sort_models(models)

    logger.info(f"Models (from {args.controller_url}): {models}")
    return models


get_window_url_params = """
function() {
    const params = new URLSearchParams(window.location.search);
    url_params = Object.fromEntries(params);
    console.log(url_params);
    return url_params;
    }
"""


def init_state(state=None):
    if state is not None:
        del state
    return Conversation()


def find_bounding_boxes(state, response):
    pattern = re.compile(r"<ref>\s*(.*?)\s*</ref>\s*<box>\s*(\[\[.*?\]\])\s*</box>")
    matches = pattern.findall(response)
    results = []
    for match in matches:
        results.append((match[0], eval(match[1])))
    returned_image = None
    latest_image = state.get_images(source=state.USER)[-1]
    returned_image = latest_image.copy()
    width, height = returned_image.size
    draw = ImageDraw.Draw(returned_image)
    for result in results:
        line_width = max(1, int(min(width, height) / 200))
        random_color = (
            random.randint(0, 128),
            random.randint(0, 128),
            random.randint(0, 128),
        )
        category_name, coordinates = result
        coordinates = [
            (
                float(x[0]) / 1000,
                float(x[1]) / 1000,
                float(x[2]) / 1000,
                float(x[3]) / 1000,
            )
            for x in coordinates
        ]
        coordinates = [
            (
                int(x[0] * width),
                int(x[1] * height),
                int(x[2] * width),
                int(x[3] * height),
            )
            for x in coordinates
        ]
        for box in coordinates:
            draw.rectangle(box, outline=random_color, width=line_width)
            font = ImageFont.truetype("assets/SimHei.ttf", int(20 * line_width / 2))
            text_size = font.getbbox(category_name)
            text_width, text_height = (
                text_size[2] - text_size[0],
                text_size[3] - text_size[1],
            )
            text_position = (box[0], max(0, box[1] - text_height))
            draw.rectangle(
                [
                    text_position,
                    (text_position[0] + text_width, text_position[1] + text_height),
                ],
                fill=random_color,
            )
            draw.text(text_position, category_name, fill="white", font=font)
    return returned_image if len(matches) > 0 else None


def query_image_generation(response, sd_worker_url, timeout=15):
    if not sd_worker_url:
        return None
    sd_worker_url = f"{sd_worker_url}/generate_image/"
    pattern = r"```drawing-instruction\n(.*?)\n```"
    match = re.search(pattern, response, re.DOTALL)
    if match:
        payload = {"caption": match.group(1)}
        print("drawing-instruction:", payload)
        response = requests.post(sd_worker_url, json=payload, timeout=timeout)
        response.raise_for_status()  # 检查HTTP请求是否成功
        image = Image.open(BytesIO(response.content))
        return image
    else:
        return None


def load_demo(url_params, request: gr.Request = None):
    if not request:
        logger.info(f"load_demo. ip: {request.client.host}. params: {url_params}")

    dropdown_update = gr.Dropdown(visible=True)
    if "model" in url_params:
        model = url_params["model"]
        if model in models:
            dropdown_update = gr.Dropdown(value=model, visible=True)

    state = init_state()
    return state, dropdown_update


def load_demo_refresh_model_list(request: gr.Request = None):
    if not request:
        logger.info(f"load_demo. ip: {request.client.host}")
    models = get_model_list()
    state = init_state()
    dropdown_update = gr.Dropdown(
        choices=models, value=models[0] if len(models) > 0 else ""
    )
    return state, dropdown_update


def vote_last_response(state, liked, model_selector, request: gr.Request):
    conv_data = {
        "tstamp": round(time.time(), 4),
        "like": liked,
        "model": model_selector,
        "state": state.dict(),
        "ip": request.client.host,
    }
    write2file(get_log_filename(), json.dumps(conv_data) + "\n")


def upvote_last_response(state, model_selector, request: gr.Request):
    logger.info(f"upvote. ip: {request.client.host}")
    vote_last_response(state, True, model_selector, request)
    textbox = gr.MultimodalTextbox(value=None, interactive=True)
    return (textbox,) + (disable_btn,) * 3


def downvote_last_response(state, model_selector, request: gr.Request):
    logger.info(f"downvote. ip: {request.client.host}")
    vote_last_response(state, False, model_selector, request)
    textbox = gr.MultimodalTextbox(value=None, interactive=True)
    return (textbox,) + (disable_btn,) * 3


def vote_selected_response(
    state, model_selector, request: gr.Request, data: gr.LikeData
):
    logger.info(
        f"Vote: {data.liked}, index: {data.index}, value: {data.value} , ip: {request.client.host}"
    )
    conv_data = {
        "tstamp": round(time.time(), 4),
        "like": data.liked,
        "index": data.index,
        "model": model_selector,
        "state": state.dict(),
        "ip": request.client.host,
    }
    write2file(get_log_filename(), json.dumps(conv_data) + "\n")
    return


def flag_last_response(state, model_selector, request: gr.Request):
    logger.info(f"flag. ip: {request.client.host}")
    vote_last_response(state, "flag", model_selector, request)
    textbox = gr.MultimodalTextbox(value=None, interactive=True)
    return (textbox,) + (disable_btn,) * 3


def regenerate(state, image_process_mode, request: gr.Request):
    logger.info(f"regenerate. ip: {request.client.host}")
    # state.messages[-1][-1] = None
    state.update_message(Conversation.ASSISTANT, None, -1)
    prev_human_msg = state.messages[-2]
    if type(prev_human_msg[1]) in (tuple, list):
        prev_human_msg[1] = (*prev_human_msg[1][:2], image_process_mode)
    state.skip_next = False
    textbox = gr.MultimodalTextbox(value=None, interactive=True)
    return (state, state.to_gradio_chatbot(), textbox) + (disable_btn,) * 5


def clear_history(request: gr.Request):
    logger.info(f"clear_history. ip: {request.client.host}")
    state = init_state()
    textbox = gr.MultimodalTextbox(value=None, interactive=True)
    return (state, state.to_gradio_chatbot(), textbox) + (disable_btn,) * 5


def change_system_prompt(state, system_prompt, request: gr.Request):
    logger.info(f"Change system prompt. ip: {request.client.host}")
    state.set_system_message(system_prompt)
    return state


def add_text(state, message, system_prompt, model_selector, request: gr.Request):
    print(f"state: {state}")
    if not state:
        state = init_state()
    images = message.get("files", [])
    text = message.get("text", "").strip()
    logger.info(f"add_text. ip: {request.client.host}. len: {len(text)}")
    # import pdb; pdb.set_trace()
    textbox = gr.MultimodalTextbox(value=None, interactive=False)
    if len(text) <= 0 and len(images) == 0:
        state.skip_next = True
        return (state, state.to_gradio_chatbot(), textbox) + (no_change_btn,) * 5
    if args.moderate:
        flagged = violates_moderation(text)
        if flagged:
            state.skip_next = True
            textbox = gr.MultimodalTextbox(
                value={"text": moderation_msg}, interactive=True
            )
            return (state, state.to_gradio_chatbot(), textbox) + (no_change_btn,) * 5
    images = [Image.open(path).convert("RGB") for path in images]

    if len(images) > 0 and len(state.get_images(source=state.USER)) > 0:
        state = init_state(state)
    state.set_system_message(system_prompt)
    state.append_message(Conversation.USER, text, images)
    state.skip_next = False
    return (state, state.to_gradio_chatbot(), textbox, model_selector) + (
        disable_btn,
    ) * 5


def http_bot(
    state,
    model_selector,
    temperature,
    top_p,
    repetition_penalty,
    max_new_tokens,
    max_input_tiles,
    # bbox_threshold,
    # mask_threshold,
    request: gr.Request,
):
    logger.info(f"http_bot. ip: {request.client.host}")
    start_tstamp = time.time()
    model_name = model_selector
    if hasattr(state, "skip_next") and state.skip_next:
        # This generate call is skipped due to invalid inputs
        yield (
            state,
            state.to_gradio_chatbot(),
            gr.MultimodalTextbox(interactive=False),
        ) + (no_change_btn,) * 5
        return

    # Query worker address
    controller_url = args.controller_url
    ret = requests.post(
        controller_url + "/get_worker_address", json={"model": model_name}
    )
    worker_addr = ret.json()["address"]
    if worker_addr.startswith("http://0.0.0.0") and args.worker_ip:
        worker_addr = worker_addr.replace("0.0.0.0", args.worker_ip)
    logger.info(f"model_name: {model_name}, worker_addr: {worker_addr}")

    # No available worker
    if worker_addr == "":
        # state.messages[-1][-1] = server_error_msg
        state.update_message(Conversation.ASSISTANT, server_error_msg)
        yield (
            state,
            state.to_gradio_chatbot(),
            gr.MultimodalTextbox(interactive=False),
            disable_btn,
            disable_btn,
            disable_btn,
            enable_btn,
            enable_btn,
        )
        return

    all_images = state.get_images(source=state.USER)
    all_image_paths = [state.save_image(image) for image in all_images]

    # Make requests
    pload = {
        "model": model_name,
        "prompt": state.get_prompt(),
        "temperature": float(temperature),
        "top_p": float(top_p),
        "max_new_tokens": max_new_tokens,
        "max_input_tiles": max_input_tiles,
        # "bbox_threshold": bbox_threshold,
        # "mask_threshold": mask_threshold,
        "repetition_penalty": repetition_penalty,
        "images": f"List of {len(all_images)} images: {all_image_paths}",
    }
    logger.info(f"==== request ====\n{pload}")
    pload.pop("images")
    pload["prompt"] = state.get_prompt(inlude_image=True)
    state.append_message(Conversation.ASSISTANT, state.streaming_placeholder)
    yield (
        state,
        state.to_gradio_chatbot(),
        gr.MultimodalTextbox(interactive=False),
    ) + (disable_btn,) * 5

    try:
        # Stream output
        response = requests.post(
            worker_addr + "/worker_generate_stream",
            headers=headers,
            json=pload,
            stream=True,
            timeout=20,
        )
        for chunk in response.iter_lines(decode_unicode=False, delimiter=b"\0"):
            if chunk:
                data = json.loads(chunk.decode())
                if data["error_code"] == 0:
                    if "text" in data:
                        output = data["text"].strip()
                        output += state.streaming_placeholder

                    image = None
                    if "image" in data:
                        image = load_image_from_base64(data["image"])
                        _ = state.save_image(image)

                    state.update_message(Conversation.ASSISTANT, output, image)
                    yield (
                        state,
                        state.to_gradio_chatbot(),
                        gr.MultimodalTextbox(interactive=False),
                    ) + (disable_btn,) * 5
                else:
                    output = (
                        f"**{data['text']}**" + f" (error_code: {data['error_code']})"
                    )

                    state.update_message(Conversation.ASSISTANT, output, None)
                    yield (
                        state,
                        state.to_gradio_chatbot(),
                        gr.MultimodalTextbox(interactive=True),
                    ) + (
                        disable_btn,
                        disable_btn,
                        disable_btn,
                        enable_btn,
                        enable_btn,
                    )
                    return
    except requests.exceptions.RequestException as e:
        state.update_message(Conversation.ASSISTANT, server_error_msg, None)
        yield (
            state,
            state.to_gradio_chatbot(),
            gr.MultimodalTextbox(interactive=True),
        ) + (
            disable_btn,
            disable_btn,
            disable_btn,
            enable_btn,
            enable_btn,
        )
        return

    ai_response = state.return_last_message()
    if "<ref>" in ai_response:
        returned_image = find_bounding_boxes(state, ai_response)
        returned_image = [returned_image] if returned_image else []
        state.update_message(Conversation.ASSISTANT, ai_response, returned_image)
    if "```drawing-instruction" in ai_response:
        returned_image = query_image_generation(
            ai_response, sd_worker_url=sd_worker_url
        )
        returned_image = [returned_image] if returned_image else []
        state.update_message(Conversation.ASSISTANT, ai_response, returned_image)

    state.end_of_current_turn()

    yield (
        state,
        state.to_gradio_chatbot(),
        gr.MultimodalTextbox(interactive=True),
    ) + (enable_btn,) * 5

    finish_tstamp = time.time()
    logger.info(f"{output}")
    data = {
        "tstamp": round(finish_tstamp, 4),
        "like": None,
        "model": model_name,
        "start": round(start_tstamp, 4),
        "finish": round(start_tstamp, 4),
        "state": state.dict(),
        "images": all_image_paths,
        "ip": request.client.host,
    }
    write2file(get_log_filename(), json.dumps(data) + "\n")


title_html = """
<h2> <span class="gradient-text" id="text">InternVL2</span><span class="plain-text">: Better than the Best—Expanding Performance Boundaries of Open-Source Multimodal Models with the Progressive Scaling Strategy</span></h2>
<a href="https://internvl.github.io/blog/2024-07-02-InternVL-2.0/">[📜 InternVL2 Blog]</a> 
<a href="https://huggingface.co/spaces/OpenGVLab/InternVL">[🤗 HF Demo]</a> 
<a href="https://github.com/OpenGVLab/InternVL?tab=readme-ov-file#quick-start-with-huggingface">[🚀 Quick Start]</a> 
<a href="https://github.com/OpenGVLab/InternVL/blob/main/document/How_to_use_InternVL_API.md">[🌐 API]</a> 
"""

tos_markdown = """
### Terms of use
By using this service, users are required to agree to the following terms:
The service is a research preview intended for non-commercial use only. It only provides limited safety measures and may generate offensive content. It must not be used for any illegal, harmful, violent, racist, or sexual purposes. The service may collect user dialogue data for future research.
Please click the "Flag" button if you get any inappropriate answer! We will collect those to keep improving our moderator.
For an optimal experience, please use desktop computers for this demo, as mobile devices may compromise its quality.
"""


learn_more_markdown = """
### License
The service is a research preview intended for non-commercial use only, subject to the model [License](https://github.com/facebookresearch/llama/blob/main/MODEL_CARD.md) of LLaMA, [Terms of Use](https://openai.com/policies/terms-of-use) of the data generated by OpenAI, and [Privacy Practices](https://chrome.google.com/webstore/detail/sharegpt-share-your-chatg/daiacboceoaocpibfodeljbdfacokfjb) of ShareGPT. Please contact us if you find any potential violation.

### Acknowledgement
This demo is modified from LLaVA's demo. Thanks for their awesome work!
"""
# .gradio-container {margin: 5px 10px 0 10px !important};
block_css = """
.gradio-container {margin: 0.1% 1% 0 1% !important; max-width: 98% !important;};
#buttons button {
    min-width: min(120px,100%);
}

.gradient-text {
    font-size: 28px;
    width: auto;
    font-weight: bold;
    background: linear-gradient(45deg, red, orange, yellow, green, blue, indigo, violet);
    background-clip: text;
    -webkit-background-clip: text;
    color: transparent;
}

.plain-text {
    font-size: 22px;
    width: auto;
    font-weight: bold;
}
"""

js = """
function createWaveAnimation() {
    const text = document.getElementById('text');
    var i = 0;
    setInterval(function() {
        const colors = [
            'red, orange, yellow, green, blue, indigo, violet, purple',
            'orange, yellow, green, blue, indigo, violet, purple, red',
            'yellow, green, blue, indigo, violet, purple, red, orange',
            'green, blue, indigo, violet, purple, red, orange, yellow',
            'blue, indigo, violet, purple, red, orange, yellow, green',
            'indigo, violet, purple, red, orange, yellow, green, blue',
            'violet, purple, red, orange, yellow, green, blue, indigo',
            'purple, red, orange, yellow, green, blue, indigo, violet',
        ];
        const angle = 45;
        const colorIndex = i % colors.length;
        text.style.background = `linear-gradient(${angle}deg, ${colors[colorIndex]})`;
        text.style.webkitBackgroundClip = 'text';
        text.style.backgroundClip = 'text';
        text.style.color = 'transparent';
        text.style.fontSize = '28px';
        text.style.width = 'auto';
        text.textContent = 'InternVL2';
        text.style.fontWeight = 'bold';
        i += 1;
    }, 200);
    const params = new URLSearchParams(window.location.search);
    url_params = Object.fromEntries(params);
    // console.log(url_params);
    // console.log('hello world...');
    // console.log(window.location.search);
    // console.log('hello world...');
    // alert(window.location.search)
    // alert(url_params);
    return url_params;
}

"""


def build_demo(embed_mode):
    textbox = gr.MultimodalTextbox(
        interactive=True,
        file_types=["image", "video"],
        placeholder="Enter message or upload file...",
        show_label=False,
    )

    with gr.Blocks(
        title="InternVL-Chat",
        theme=gr.themes.Default(),
        css=block_css,
    ) as demo:
        models = get_model_list()
        state = gr.State()

        if not embed_mode:
            # gr.Markdown(title_markdown)
            gr.HTML(title_html)

        with gr.Row():
            with gr.Column(scale=2):

                with gr.Row(elem_id="model_selector_row"):
                    model_selector = gr.Dropdown(
                        choices=models,
                        value=models[0] if len(models) > 0 else "",
                        # value="InternVL-Chat-V1-5",
                        interactive=True,
                        show_label=False,
                        container=False,
                    )

                with gr.Accordion("System Prompt", open=False) as system_prompt_row:
                    system_prompt = gr.Textbox(
                        value="请尽可能详细地回答用户的问题。",
                        label="System Prompt",
                        interactive=True,
                    )
                with gr.Accordion("Parameters", open=False) as parameter_row:
                    temperature = gr.Slider(
                        minimum=0.0,
                        maximum=1.0,
                        value=0.2,
                        step=0.1,
                        interactive=True,
                        label="Temperature",
                    )
                    top_p = gr.Slider(
                        minimum=0.0,
                        maximum=1.0,
                        value=0.7,
                        step=0.1,
                        interactive=True,
                        label="Top P",
                    )
                    repetition_penalty = gr.Slider(
                        minimum=1.0,
                        maximum=1.5,
                        value=1.1,
                        step=0.02,
                        interactive=True,
                        label="Repetition penalty",
                    )
                    max_output_tokens = gr.Slider(
                        minimum=0,
                        maximum=4096,
                        value=1024,
                        step=64,
                        interactive=True,
                        label="Max output tokens",
                    )
                    max_input_tiles = gr.Slider(
                        minimum=1,
                        maximum=32,
                        value=12,
                        step=1,
                        interactive=True,
                        label="Max input tiles (control the image size)",
                    )
                examples = gr.Examples(
                    examples=[
                        [
                            {
                                "files": [
                                    "gallery/prod_9.jpg",
                                ],
                                "text": "What's at the far end of the image?",
                            }
                        ],
                        [
                            {
                                "files": [
                                    "gallery/astro_on_unicorn.png",
                                ],
                                "text": "What does this image mean?",
                            }
                        ],
                        [
                            {
                                "files": [
                                    "gallery/prod_12.png",
                                ],
                                "text": "What are the consequences of the easy decisions shown in this image?",
                            }
                        ],
                        [
                            {
                                "files": [
                                    "gallery/water.jpg",
                                ],
                                "text": "Please describe this image.",
                            }
                        ],
                    ],
                    inputs=[textbox],
                )

            with gr.Column(scale=8):
                chatbot = gr.Chatbot(
                    elem_id="chatbot",
                    label="InternVL2",
                    height=580,
                    show_copy_button=True,
                    show_share_button=True,
                    avatar_images=[
                        "assets/human.png",
                        "assets/assistant.png",
                    ],
                    bubble_full_width=False,
                )
                with gr.Row():
                    with gr.Column(scale=8):
                        textbox.render()
                    with gr.Column(scale=1, min_width=50):
                        submit_btn = gr.Button(value="Send", variant="primary")
                with gr.Row(elem_id="buttons") as button_row:
                    upvote_btn = gr.Button(value="👍  Upvote", interactive=False)
                    downvote_btn = gr.Button(value="👎  Downvote", interactive=False)
                    flag_btn = gr.Button(value="⚠️  Flag", interactive=False)
                    # stop_btn = gr.Button(value="⏹️  Stop Generation", interactive=False)
                    regenerate_btn = gr.Button(
                        value="🔄  Regenerate", interactive=False
                    )
                    clear_btn = gr.Button(value="🗑️  Clear", interactive=False)

        if not embed_mode:
            gr.Markdown(tos_markdown)
            gr.Markdown(learn_more_markdown)
        url_params = gr.JSON(visible=False)

        # Register listeners
        btn_list = [upvote_btn, downvote_btn, flag_btn, regenerate_btn, clear_btn]
        upvote_btn.click(
            upvote_last_response,
            [state, model_selector],
            [textbox, upvote_btn, downvote_btn, flag_btn],
        )
        downvote_btn.click(
            downvote_last_response,
            [state, model_selector],
            [textbox, upvote_btn, downvote_btn, flag_btn],
        )
        chatbot.like(
            vote_selected_response,
            [state, model_selector],
            [],
        )
        flag_btn.click(
            flag_last_response,
            [state, model_selector],
            [textbox, upvote_btn, downvote_btn, flag_btn],
        )
        regenerate_btn.click(
            regenerate,
            [state, system_prompt],
            [state, chatbot, textbox] + btn_list,
        ).then(
            http_bot,
            [
                state,
                model_selector,
                temperature,
                top_p,
                repetition_penalty,
                max_output_tokens,
                max_input_tiles,
                # bbox_threshold,
                # mask_threshold,
            ],
            [state, chatbot, textbox] + btn_list,
        )
        clear_btn.click(clear_history, None, [state, chatbot, textbox] + btn_list)

        textbox.submit(
            add_text,
            [state, textbox, system_prompt, model_selector],
            [state, chatbot, textbox, model_selector] + btn_list,
        ).then(
            http_bot,
            [
                state,
                model_selector,
                temperature,
                top_p,
                repetition_penalty,
                max_output_tokens,
                max_input_tiles,
                # bbox_threshold,
                # mask_threshold,
            ],
            [state, chatbot, textbox] + btn_list,
        )
        submit_btn.click(
            add_text,
            [state, textbox, system_prompt, model_selector],
            [state, chatbot, textbox, model_selector] + btn_list,
        ).then(
            http_bot,
            [
                state,
                model_selector,
                temperature,
                top_p,
                repetition_penalty,
                max_output_tokens,
                max_input_tiles,
                # bbox_threshold,
                # mask_threshold,
            ],
            [state, chatbot, textbox] + btn_list,
        )

        # NOTE: The following code will be not triggered when deployed on HF space.
        # It's very strange. I don't know why.
        """
        if args.model_list_mode == "once":
            demo.load(
                load_demo,
                [url_params],
                [state, model_selector],
                js=js,
            )
        elif args.model_list_mode == "reload":
            demo.load(
                load_demo_refresh_model_list,
                None,
                [state, model_selector],
                js=js,
            )
        else:
            raise ValueError(f"Unknown model list mode: {args.model_list_mode}")
        """

    return demo


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--host", type=str, default="0.0.0.0")
    parser.add_argument("--port", type=int, default=7860)
    parser.add_argument("--controller-url", type=str, default=None)
    parser.add_argument("--worker-ip", type=str, default=None)
    parser.add_argument("--concurrency-count", type=int, default=10)
    parser.add_argument(
        "--model-list-mode", type=str, default="reload", choices=["once", "reload"]
    )
    parser.add_argument("--sd-worker-url", type=str, default=None)
    parser.add_argument("--share", action="store_true")
    parser.add_argument("--moderate", action="store_true")
    parser.add_argument("--embed", action="store_true")
    args = parser.parse_args()
    logger.info(f"args: {args}")
    if not args.controller_url:
        args.controller_url = os.environ.get("CONTROLLER_URL", None)

    if not args.controller_url:
        raise ValueError("controller-url is required.")

    if not args.worker_ip:
        args.worker_ip = os.environ.get("WORKER_IP", None)

    sd_worker_url = args.sd_worker_url
    logger.info(args)
    demo = build_demo(args.embed)
    demo.queue(api_open=False).launch(
        server_name=args.host,
        server_port=args.port,
        share=args.share,
        max_threads=args.concurrency_count,
    )