File size: 6,982 Bytes
4d75b37
 
 
 
 
 
 
 
 
 
8bd3eb9
4d75b37
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73ccce1
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
from __future__ import annotations
from typing import Iterable
import gradio as gr
from gradio.themes.base import Base
from gradio.themes.utils import colors, fonts, sizes
import time
import torch
from transformers import pipeline
import pandas as pd

instruct_pipeline = pipeline(model="databricks/dolly-v2-7b", torch_dtype=torch.bfloat16, trust_remote_code=True, device_map="auto")


def run_pipeline(prompt):
    response = instruct_pipeline(prompt)
    return response

def get_user_input(input_question, history):
    return "", history + [[input_question, None]]

def get_qa_user_input(input_question, history):
    return "", history + [[input_question, None]]

def dolly_chat(history):
    prompt = history[-1][0]
    bot_message = run_pipeline(prompt)
    history[-1][1] = bot_message
    return history

def qa_bot(context, history):
    query = history[-1][0]
    prompt = f'instruction: {query} \ncontext: {context}'
    bot_message = run_pipeline(prompt)
    history[-1][1] = bot_message
    return history

def reset_chatbot():
    return gr.update(value="")

def load_customer_support_example():
    df = pd.read_csv("examples.csv")
    return df['doc'].iloc[0], df['question'].iloc[0]

def load_databricks_doc_example():
    df = pd.read_csv("examples.csv")
    return df['doc'].iloc[1], df['question'].iloc[1]

# Referred & modified from https://gradio.app/theming-guide/
class SeafoamCustom(Base):
    def __init__(
        self,
        *,
        primary_hue: colors.Color | str = colors.emerald,
        secondary_hue: colors.Color | str = colors.blue,
        neutral_hue: colors.Color | str = colors.blue,
        spacing_size: sizes.Size | str = sizes.spacing_md,
        radius_size: sizes.Size | str = sizes.radius_md,
        font: fonts.Font
        | str
        | Iterable[fonts.Font | str] = (
            fonts.GoogleFont("Quicksand"),
            "ui-sans-serif",
            "sans-serif",
        ),
        font_mono: fonts.Font
        | str
        | Iterable[fonts.Font | str] = (
            fonts.GoogleFont("IBM Plex Mono"),
            "ui-monospace",
            "monospace",
        ),
    ):
        super().__init__(
            primary_hue=primary_hue,
            secondary_hue=secondary_hue,
            neutral_hue=neutral_hue,
            spacing_size=spacing_size,
            radius_size=radius_size,
            font=font,
            font_mono=font_mono,
        )
        super().set(
            button_primary_background_fill="linear-gradient(90deg, *primary_300, *secondary_400)",
            button_primary_background_fill_hover="linear-gradient(90deg, *primary_200, *secondary_300)",
            button_primary_text_color="white",
            button_primary_background_fill_dark="linear-gradient(90deg, *primary_600, *secondary_800)",
            block_shadow="*shadow_drop_lg",
            button_shadow="*shadow_drop_lg",
            input_background_fill="zinc",
            input_border_color="*secondary_300",
            input_shadow="*shadow_drop",
            input_shadow_focus="*shadow_drop_lg",
        )


seafoam = SeafoamCustom()

with gr.Blocks(theme=seafoam) as demo:

    with gr.Row(variant='panel'):
      with gr.Column():
          gr.HTML(
              """<html><img src='file/dolly.jpg', alt='dolly logo', width=150, height=150 /><br></html>"""
          )
      with gr.Column():
          gr.Markdown("# **<p align='center'>Dolly 2.0: World's First Truly Open Instruction-Tuned LLM</p>**")
          gr.Markdown("Dolly 2.0, the first open source, instruction-following LLM, fine-tuned on a human-generated instruction dataset licensed for research and commercial use. It's a 12B parameter language model based on the EleutherAI pythia model family and fine-tuned exclusively on a new, high-quality human generated instruction following dataset, crowdsourced among Databricks employees.")

      

    qa_bot_state = gr.State(value=[])

    with gr.Tabs():
        with gr.TabItem("Dolly Chat"):
            
            with gr.Row():

                with gr.Column():
                    chatbot = gr.Chatbot(label="Chat History")
                    input_question = gr.Text(
                        label="Instruction",
                        placeholder="Type prompt and hit enter.",
                    )
                    clear = gr.Button("Clear", variant="primary")

            with gr.Row():
                with gr.Accordion("Show example inputs I can load:", open=False):
                    gr.Examples(
                        [
                            ["Explain to me the difference between nuclear fission and fusion."],
                            ["Give me a list of 5 science fiction books I should read next."],
                            ["I'm selling my Nikon D-750, write a short blurb for my ad."],
                            ["Write a song about sour donuts"],
                            ["Write a tweet about a new book launch by J.K. Rowling."],
                          
                        ],
                        [input_question],
                        [],
                        None,
                        cache_examples=False,
                    )

        with gr.TabItem("Q&A with Context"):
            
            with gr.Row():

                with gr.Column():
                    input_context = gr.Text(label="Add context here", lines=10)

                with gr.Column():
                    qa_chatbot = gr.Chatbot(label="Q&A History")
                    qa_input_question = gr.Text(
                        label="Input Question",
                        placeholder="Type question here and hit enter.",
                    )
                    qa_clear = gr.Button("Clear", variant="primary")

            with gr.Row():
                with gr.Accordion("Show example inputs I can load:", open=False):
                    example_1 = gr.Button("Load Customer support example")
                    example_2 = gr.Button("Load Databricks documentation example")


    input_question.submit(
        get_user_input,
        [input_question, chatbot],
        [input_question, chatbot],
    ).then(dolly_chat, [chatbot], chatbot)


    clear.click(lambda: None, None, chatbot)


    qa_input_question.submit(
        get_qa_user_input,
        [qa_input_question, qa_chatbot],
        [qa_input_question, qa_chatbot],
    ).then(qa_bot, [input_context, qa_chatbot], qa_chatbot)

    qa_clear.click(lambda: None, None, qa_chatbot)

    # reset the chatbot Q&A history when input context changes
    input_context.change(fn=reset_chatbot, inputs=[], outputs=qa_chatbot)

    example_1.click(
        load_customer_support_example,
        [],
        [input_context, qa_input_question],
    )

    example_2.click(
        load_databricks_doc_example,
        [],
        [input_context, qa_input_question],
    )

if __name__ == "__main__":

    demo.queue(concurrency_count=1,max_size=100).launch(max_threads=5,debug=True)