File size: 8,078 Bytes
0a2a245
a9003db
9c9ed59
05e56df
b62cff3
001008d
a9003db
 
 
e16e805
5a80314
a9003db
9c9ed59
 
 
6ab0133
870d98c
c252f95
49e0a2f
c252f95
49e0a2f
9c9ed59
 
 
 
 
 
 
0dbf789
809cb4d
8a171c1
 
0dbf789
15bac2b
 
5da3af3
15bac2b
 
a1e37d7
f32a12d
cdb1abe
f32a12d
49e0a2f
 
f32a12d
 
 
 
 
 
 
636230c
f32a12d
 
 
 
576644f
f32a12d
 
 
 
 
 
 
 
 
607c97e
49e0a2f
607c97e
576644f
 
3bf0404
 
a1e37d7
49e0a2f
a1e37d7
 
 
 
 
 
 
 
 
 
 
 
 
 
14ee5b6
a1e37d7
a7ddd31
a1e37d7
 
 
 
4d94d53
a3cd820
a1e37d7
88cd932
 
4b9dcb6
88cd932
 
 
 
 
21f63fb
88cd932
 
48d4148
49e0a2f
4b9dcb6
7a15f69
deb06b5
995ee34
deb06b5
 
88cd932
8a171c1
d816c58
9c9ed59
 
 
 
6ac6c80
f714139
50a07a1
 
eb661de
a1e37d7
615f8ac
 
 
 
5da3af3
615f8ac
 
 
 
e3e3154
08600bb
 
a1e37d7
d768eff
dfee1fe
5da3af3
 
 
 
 
 
 
50a07a1
8b77f39
5da3af3
 
 
 
9433083
ab486e4
9433083
5da3af3
 
 
 
50a07a1
 
5da3af3
 
 
 
 
 
 
 
 
 
f4f7ea8
c252f95
e37f76c
 
ceeead3
 
c252f95
a8362fd
f714139
a8362fd
f714139
a8362fd
 
 
 
2af5f1a
a8362fd
 
 
 
 
 
ceeead3
5da3af3
50a07a1
0dbf789
9c9ed59
15bac2b
3bd525e
15bac2b
 
 
 
 
aa188c8
0f2ed31
3bd525e
ff05f4a
09c8a28
1187a52
3bd525e
 
 
f96f7a3
33bab5c
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
from huggingface_hub import InferenceClient, HfApi, upload_file
import datetime
import gradio as gr
import random
import prompts
import json
import uuid
import os
token=os.environ.get("HF_TOKEN")
username="johann22"
dataset_name="chat-roulette-1"
api=HfApi(token="")
client = InferenceClient(
    "mistralai/Mixtral-8x7B-Instruct-v0.1"
)
history = []
hist_out= []
summary =[]
main_point=[]
summary.append("")
main_point.append("")
def format_prompt(message, history):
  prompt = "<s>"
  for user_prompt, bot_response in history:
    prompt += f"[INST] {user_prompt} [/INST]"
    prompt += f" {bot_response}</s> "
  prompt += f"[INST] {message} [/INST]"
  return prompt
agents =[
    "QUESTION_GENERATOR",
    "AI_REPORT_WRITER",

]
temperature=0.9
max_new_tokens=256
max_new_tokens2=1048
top_p=0.95
repetition_penalty=1.0,

def compress_history(formatted_prompt):
    
    seed = random.randint(1,1111111111111111)
    agent=prompts.COMPRESS_HISTORY_PROMPT.format(history=summary[0],focus=main_point[0])
    
    system_prompt=agent
    temperature = 0.9
    if temperature < 1e-2:
        temperature = 1e-2

    generate_kwargs = dict(
        temperature=temperature,
        max_new_tokens=30480,
        top_p=0.95,
        repetition_penalty=1.0,
        do_sample=True,
        seed=seed,
    )
    #history.append((prompt,""))
    #formatted_prompt = format_prompt(f"{system_prompt}, {prompt}", history)
    formatted_prompt = formatted_prompt
    stream = client.text_generation(formatted_prompt, **generate_kwargs, stream=True, details=True, return_full_text=False)
    output = ""

    for response in stream:
        output += response.token.text
    #history.append((output,history))
    print(output)
    print(main_point[0])
    return output


def question_generate(prompt, history, agent_name=agents[0], sys_prompt="", temperature=0.9, max_new_tokens=256, top_p=0.95, repetition_penalty=1.0,):
#def question_generate(prompt, history):
    seed = random.randint(1,1111111111111111)
    agent=prompts.QUESTION_GENERATOR.format(focus=main_point[0])
    system_prompt=agent
    temperature = float(temperature)
    if temperature < 1e-2:
        temperature = 1e-2
    top_p = float(top_p)

    generate_kwargs = dict(
        temperature=temperature,
        max_new_tokens=max_new_tokens,
        top_p=top_p,
        repetition_penalty=repetition_penalty,
        do_sample=True,
        seed=seed,
    )
    #history.append((prompt,""))
    formatted_prompt = format_prompt(f"{system_prompt}, {prompt}", history)
    stream = client.text_generation(formatted_prompt, **generate_kwargs, stream=True, details=True, return_full_text=False)
    output = ""

    for response in stream:
        output += response.token.text
    #history.append((output,history))

    return output
def create_valid_filename(invalid_filename: str) -> str:
    """Converts invalid characters in a string to be suitable for a filename."""
    invalid_filename.replace(" ","-")
    valid_chars = '-'.join(invalid_filename.split())
    allowed_chars = ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
                      'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
                      'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
                      'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
                      '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '_', '-')
    return ''.join(char for char in valid_chars if char in allowed_chars)
    
def generate(prompt, history, agent_name=agents[0], sys_prompt="", temperature=0.9, max_new_tokens=1048, top_p=0.95, repetition_penalty=1.0,):
    main_point[0]=prompt
    #print(datetime.datetime.now())
    uid=uuid.uuid4()
    current_time = str(datetime.datetime.now())
    
    current_time=current_time.replace(":","-")
    current_time=current_time.replace(".","-")
    print (current_time)
    agent=prompts.AI_REPORT_WRITER
    system_prompt=agent
    temperature = float(temperature)
    if temperature < 1e-2:
        temperature = 1e-2
    top_p = float(top_p)
    hist_out=[]
    sum_out=[]
    json_hist={}
    json_obj={}
    filename=create_valid_filename(f'{prompt}---{current_time}')
    while True:
        seed = random.randint(1,1111111111111111)

        generate_kwargs = dict(
            temperature=temperature,
            max_new_tokens=max_new_tokens2,
            top_p=top_p,
            repetition_penalty=repetition_penalty,
            do_sample=True,
            seed=seed,
        )    
        if prompt.startswith(' \"'):
            prompt=prompt.strip(' \"')
        formatted_prompt = format_prompt(f"{system_prompt}, {prompt}", history)
        if len(formatted_prompt) < (50000):
            print(len(formatted_prompt))
            stream = client.text_generation(formatted_prompt, **generate_kwargs, stream=True, details=True, return_full_text=False)
            output = ""
            #if history:
            #    yield history
        
            for response in stream:
                output += response.token.text
                yield '', [(prompt,output)],summary[0],json_obj, json_hist
            out_json = {"prompt":prompt,"output":output}
        
            prompt = question_generate(output, history)
            #output += prompt
            history.append((prompt,output))
            print ( f'Prompt:: {len(prompt)}')
            #print ( f'output:: {output}')
            print ( f'history:: {len(formatted_prompt)}')
            hist_out.append(out_json)
            #try:
            #    for ea in 
            with open(f'{uid}.json', 'w') as f:
                json_hist=json.dumps(hist_out, indent=4)
                f.write(json_hist)
            f.close()
        
            upload_file(
                path_or_fileobj =f"{uid}.json", 
                path_in_repo = f"test/{filename}.json", 
                repo_id =f"{username}/{dataset_name}", 
                repo_type = "dataset", 
                token=token,
            )
        else:
            formatted_prompt = format_prompt(f"{prompts.COMPRESS_HISTORY_PROMPT.format(history=summary[0],focus=main_point[0])}, {summary[0]}", history)
            
            #current_time = str(datetime.datetime.now().timestamp()).split(".",1)[0]
            #filename=f'{filename}-{current_time}'
            history = []
            output = compress_history(formatted_prompt)
            summary[0]=output
            sum_json = {"summary":summary[0]}
            sum_out.append(sum_json)
            with open(f'{uid}-sum.json', 'w') as f:
                json_obj=json.dumps(sum_out, indent=4)
                f.write(json_obj)
            f.close()
            upload_file(
                path_or_fileobj =f"{uid}-sum.json", 
                path_in_repo = f"summary/{filename}-summary.json", 
                repo_id =f"{username}/{dataset_name}", 
                repo_type = "dataset", 
                token=token,
            )

            
            prompt = question_generate(output, history)
           
    return prompt, history, summary[0],json_obj,json_hist 


with gr.Blocks() as iface:
    gr.HTML("""<center><h1>Chat Roulette</h1><br><h3>This chatbot will respond to itself with additional questions</h3></center>""")
    #chatbot=gr.Chatbot(show_label=False, show_share_button=False, show_copy_button=True, likeable=True, layout="panel"),
    chatbot=gr.Chatbot()
    msg = gr.Textbox()
    with gr.Row():
        submit_b = gr.Button()
        stop_b = gr.Button("Stop")
        clear = gr.ClearButton([msg, chatbot])
    sumbox=gr.Textbox("Summary", max_lines=100)
    with gr.Column():
        sum_out_box=gr.JSON(label="Summaries")
        hist_out_box=gr.JSON(label="History")
        
    sub_b = submit_b.click(generate, [msg,chatbot],[msg,chatbot,sumbox,sum_out_box,hist_out_box])
    sub_e = msg.submit(generate, [msg, chatbot], [msg, chatbot,sumbox,sum_out_box,hist_out_box])
    stop_b.click(None,None,None, cancels=[sub_b,sub_e])
iface.queue(default_concurrency_limit=10).launch()