File size: 17,025 Bytes
78ffba0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5306510
78ffba0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b20408a
 
fd7d7b0
 
 
 
 
 
 
 
 
b20408a
fd7d7b0
 
 
b20408a
 
fd7d7b0
b20408a
fd7d7b0
 
 
 
996864d
fd7d7b0
b8ddc1d
 
 
996864d
24df928
 
 
 
996864d
 
 
 
 
 
 
 
 
 
5496e8b
24df928
5496e8b
a87b772
24df928
 
 
 
 
 
7daa200
5496e8b
298d1b7
a3d6cea
fd7d7b0
 
 
 
 
5dae906
5651960
fd7d7b0
b20408a
5dae906
 
fd7d7b0
9a103c5
 
050899a
5dae906
fd7d7b0
 
 
 
 
 
 
 
 
 
 
a87b772
fd47974
 
a87b772
fd47974
 
 
 
51c9975
 
a87b772
51c9975
fd47974
 
 
7b16cb8
1f68202
7b16cb8
 
5e7e224
a87b772
7b16cb8
 
 
 
 
 
 
9c3db7a
 
c81be02
9c3db7a
 
7b16cb8
9c3db7a
1385c99
9c3db7a
 
 
7b16cb8
fa072ac
7b16cb8
 
b20408a
4a906d0
913c48f
4a906d0
52523f8
 
69ba09b
913c48f
 
4a906d0
389922e
7b16cb8
a87b772
7b16cb8
9c3db7a
 
 
389922e
 
 
7b16cb8
9c3db7a
 
 
 
389922e
9c3db7a
 
 
 
 
143a130
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69ba09b
 
 
 
 
 
 
5496e8b
 
a87b772
5496e8b
 
 
 
1f68202
f10c738
5496e8b
 
 
 
1f68202
f10c738
69ba09b
 
6dd8a98
1f68202
5496e8b
 
 
 
 
f10c738
69ba09b
 
6dd8a98
5496e8b
 
 
1f68202
9c3db7a
 
78ffba0
 
 
 
 
 
 
 
 
9c3db7a
2772476
6c3e32d
5dae906
2329a6b
9a103c5
2329a6b
589ac10
8029c32
 
fd7d7b0
78ffba0
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
import gradio as gr
import time
import random
import json
import mysql.connector
import os
import csv
import spaces
import torch

from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
from threading import Thread
from typing import Iterator
from huggingface_hub import Repository, hf_hub_download
from datetime import datetime

# for fetch_personalized_data
import mysql.connector
import urllib.parse
import urllib.request

# for saving chat history as JSON - not used 
import atexit
import os
from huggingface_hub import HfApi, HfFolder

# for saving chat history as dataset - not used
import huggingface_hub
from huggingface_hub import Repository
from datetime import datetime

# for saving chat history as dataset - used 
import sqlite3
import huggingface_hub
import gradio as gr
import pandas as pd
import shutil
import os
import datetime
from apscheduler.schedulers.background import BackgroundScheduler

DATASET_REPO_URL = "https://huggingface.co/datasets/botsi/trust-game-llama-2-chat-history"
DATA_DIRECTORY = "data"  # Separate directory for storing data files
DATA_FILENAME = "newmarion.csv"  # Default filename
DATA_FILE = os.path.join("data", DATA_FILENAME)

HF_TOKEN = os.environ.get("HF_TOKEN")
print("is none?", HF_TOKEN is None)
print("hfh", huggingface_hub.__version__)

repo = Repository(
    local_dir=DATA_DIRECTORY, clone_from=DATASET_REPO_URL
)

MAX_MAX_NEW_TOKENS = 2048
DEFAULT_MAX_NEW_TOKENS = 1024
MAX_INPUT_TOKEN_LENGTH = int(os.getenv("MAX_INPUT_TOKEN_LENGTH", "4096"))

DESCRIPTION = """\
# This is your personal space to chat. 
You can ask anything. 
"""

# License and Acceptable Use Policy by Meta  
LICENSE = """
<p/>

---
This demo is governed by the [original license](https://ai.meta.com/llama/license/) and [acceptable use policy](https://ai.meta.com/llama/use-policy/). 
The most recent copy of this policy can be found at ai.meta.com/llama/use-policy.
"""

if not torch.cuda.is_available():
    DESCRIPTION += "\n<p>Running on CPU 🥶 This demo does not work on CPU.</p>"


if torch.cuda.is_available():
    model_id = "meta-llama/Llama-2-7b-chat-hf"
    model = AutoModelForCausalLM.from_pretrained(model_id, torch_dtype=torch.float16, device_map="auto")
    tokenizer = AutoTokenizer.from_pretrained(model_id)
    tokenizer.use_default_system_prompt = False
 
## trust-game-llama-2-7b-chat
# app.py 
def get_default_system_prompt():
    BSYS, ESYS = "<<SYS>>\n", "\n<</SYS>>\n\n"

    DEFAULT_SYSTEM_PROMPT = f"""You are a friendly chat assistant. First, wait for a question. Do not talk before being asked. When the user says hi, politely ask what he/she wants to know.
    Do not tell any more! 
    If asked about Marion, you can answer the following: There are only two Marions, one is currently working at Accenture and the other one will shortly begin a new job at BMW. 
    She recently quit Accenture. Nicknames by her friends include botsi and botsokrates. Her favorite project was Hypercare. Kathy/Kathi is her colleague at Accenture. Anita is her colleague at Accenture.
    """
    print(DEFAULT_SYSTEM_PROMPT)
    return DEFAULT_SYSTEM_PROMPT

## trust-game-llama-2-7b-chat
# app.py
def construct_input_prompt(chat_history, message):
    input_prompt = f"<s>[INST] <<SYS>>\n{get_default_system_prompt()}\n<</SYS>>\n\n "
    for user, assistant in chat_history:
        input_prompt += f"{user} [/INST] {assistant} <s>[INST] "
    input_prompt += f"{message} [/INST] "
    return input_prompt

## trust-game-llama-2-7b-chat
# app.py 
@spaces.GPU
def generate(
    request: gr.Request, # To fetch query params
    message: str,
    chat_history: list[tuple[str, str]],
    # input_prompt: str,
    max_new_tokens: int = 1024,
    temperature: float = 0.6,
    top_p: float = 0.9,
    top_k: int = 50,
    repetition_penalty: float = 1.2,
) -> Iterator[str]: # Change return type hint to Iterator[str]

    conversation = []
    
    # Fetch query params 
    params = {
        key: value for key, value in request.query_params.items()
    }
    print('those are the query params')
    print(params)

    print("Request headers dictionary:", request.headers)
    print("IP address:", request.client.host)
    print("Query parameters:", params)
    
    # Construct the input prompt using the functions from the system_prompt_config module
    input_prompt = construct_input_prompt(chat_history, message)

    # Move the condition here after the assignment
    if input_prompt:
        conversation.append({"role": "system", "content": input_prompt})

    # Convert input prompt to tensor
    input_ids = tokenizer(input_prompt, return_tensors="pt").to(model.device)

    for user, assistant in chat_history:
        conversation.extend([{"role": "user", "content": user}, {"role": "assistant", "content": assistant}])
    conversation.append({"role": "user", "content": message})

    input_ids = tokenizer.apply_chat_template(conversation, return_tensors="pt")
    if input_ids.shape[1] > MAX_INPUT_TOKEN_LENGTH:
        input_ids = input_ids[:, -MAX_INPUT_TOKEN_LENGTH:]
        gr.Warning(f"Trimmed input from conversation as it was longer than {MAX_INPUT_TOKEN_LENGTH} tokens.")
    input_ids = input_ids.to(model.device)

    # Set up the TextIteratorStreamer
    streamer = TextIteratorStreamer(tokenizer, timeout=10.0, skip_prompt=True, skip_special_tokens=True)
    
    # Set up the generation arguments
    generate_kwargs = dict(
        input_ids=input_ids,
        streamer=streamer,
        max_new_tokens=max_new_tokens,
        do_sample=True,
        top_p=top_p,
        top_k=top_k,
        temperature=temperature,
        num_beams=1,
        repetition_penalty=repetition_penalty,
    )

    # Start the model generation thread
    t = Thread(target=model.generate, kwargs=generate_kwargs)
    t.start()

    # Yield generated text chunks
    outputs = []
    for text in streamer:
        outputs.append(text)
        yield "".join(outputs)

    # Fix bug that last answer is not recorded! 
    # Parse the outputs into a readable sentence and record them
    # Filter out empty strings and join the remaining strings with spaces
    readable_sentence = ' '.join(filter(lambda x: x.strip(), outputs))
    # Print the readable sentence
    print(readable_sentence)

    # Save chat history to .csv file on HuggingFace Hub 
    # Generate filename with bot id and session id
    filename = f"{DATA_FILENAME}"
    data_file = os.path.join(DATA_DIRECTORY, filename)
    
    # Generate timestamp
    timestamp = datetime.datetime.now()
    
    # Check if the file already exists
    if os.path.exists(data_file):
        # If file exists, load existing data
        existing_data = pd.read_csv(data_file)
        
        # Add timestamp column
        conversation_df = pd.DataFrame(conversation)
        conversation_df['ip_address'] = request.client.host
        conversation_df['readable_sentence'] = readable_sentence
        conversation_df['timestamp'] = timestamp
        
        # Append new conversation to existing data
        updated_data = pd.concat([existing_data, conversation_df], ignore_index=True)
        updated_data.to_csv(data_file, index=False)
    else:
        # If file doesn't exist, create new file with conversation data
        conversation_df = pd.DataFrame(conversation)
        conversation_df['ip_address'] = request.client.host
        conversation_df['readable_sentence'] = readable_sentence
        conversation_df['timestamp'] = timestamp
        conversation_df.to_csv(data_file, index=False)

    print("Updating .csv")
    repo.push_to_hub(blocking=False, commit_message=f"Updating data at {timestamp}")

chat_interface = gr.ChatInterface(
    fn=generate,
    retry_btn=None,
    clear_btn=None,
    undo_btn=None,
    chatbot=gr.Chatbot(avatar_images=('user.png', 'bot.png'), bubble_full_width=False), 
    examples=[
        ["What is your favorite fruit?"],
        ["What do you think about AI in the workplace?"],
    ],
)

with gr.Blocks(css="style.css", theme=gr.themes.Default(primary_hue=gr.themes.colors.emerald, secondary_hue=gr.themes.colors.indigo)) as demo:
    gr.Markdown(DESCRIPTION)
    chat_interface.render()
    gr.Markdown(LICENSE)
    
if __name__ == "__main__":
    demo.queue(max_size=20).launch()  # Launching the interface with queueing and maximum size limit
    # demo.launch(share=True, debug=True)  # Uncomment this line if you want to launch the interface with sharing and debug mode






'''# Original code from https://huggingface.co/spaces/huggingface-projects/llama-2-7b-chat
# Modified for trust game purposes

import gradio as gr
import time
import random
import json
import mysql.connector
import os
import csv
import spaces
import torch

from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
from threading import Thread
from typing import Iterator
from huggingface_hub import Repository, hf_hub_download
from datetime import datetime

# for fetch_personalized_data
import mysql.connector
import urllib.parse
import urllib.request

# for saving chat history as JSON - not used 
import atexit
import os
from huggingface_hub import HfApi, HfFolder

# for saving chat history as dataset - not used
import huggingface_hub
from huggingface_hub import Repository
from datetime import datetime

# for saving chat history as dataset - used 
import sqlite3
import huggingface_hub
import gradio as gr
import pandas as pd
import shutil
import os
import datetime
from apscheduler.schedulers.background import BackgroundScheduler


DATASET_REPO_URL = "https://huggingface.co/datasets/botsi/trust-game-llama-2-chat-history"
DATA_DIRECTORY = "data"  # Separate directory for storing data files
DATA_FILENAME = "marion.csv"  # Default filename
DATA_FILE = os.path.join("data", DATA_FILENAME)

HF_TOKEN = os.environ.get("HF_TOKEN")
print("is none?", HF_TOKEN is None)
print("hfh", huggingface_hub.__version__)

repo = Repository(
    local_dir=DATA_DIRECTORY, clone_from=DATASET_REPO_URL
)

MAX_MAX_NEW_TOKENS = 2048
DEFAULT_MAX_NEW_TOKENS = 1024
MAX_INPUT_TOKEN_LENGTH = int(os.getenv("MAX_INPUT_TOKEN_LENGTH", "4096"))

DESCRIPTION = """\
# This is your personal space to chat. 
You can ask anything. 
"""

# License and Acceptable Use Policy by Meta  
LICENSE = """
<p/>

---
This demo is governed by the [original license](https://ai.meta.com/llama/license/) and [acceptable use policy](https://ai.meta.com/llama/use-policy/). 
The most recent copy of this policy can be found at ai.meta.com/llama/use-policy.
"""

if not torch.cuda.is_available():
    DESCRIPTION += "\n<p>Running on CPU 🥶 This demo does not work on CPU.</p>"


if torch.cuda.is_available():
    model_id = "meta-llama/Llama-2-7b-chat-hf"
    model = AutoModelForCausalLM.from_pretrained(model_id, torch_dtype=torch.float16, device_map="auto")
    tokenizer = AutoTokenizer.from_pretrained(model_id)
    tokenizer.use_default_system_prompt = False
 
## trust-game-llama-2-7b-chat
# app.py 
def get_default_system_prompt():
    #BOS, EOS = "<s>", "</s>" 
    #BINST, EINST = "[INST]", "[/INST]"
    BSYS, ESYS = "<<SYS>>\n", "\n<</SYS>>\n\n"

    DEFAULT_SYSTEM_PROMPT = f"""You are a friendly chat assistant. First, wait for a question. Do not talk before being asked. When the user says hi, politely ask what he/she wants to know.
    Do not tell any more! 
    If asked about Marion, you can answer the following: There are only two Marions, one is currently working at Accenture and the other one will shortly begin a new job at BMW. 
    She recently quit Accenture. Nicknames by her friends include botsi and botsokrates. Her favorite project was Hypercare. Kathy/Kathi is her colleague at Accenture. Anita is her colleague at Accenture.
    """
    print(DEFAULT_SYSTEM_PROMPT)
    return DEFAULT_SYSTEM_PROMPT


## trust-game-llama-2-7b-chat
# app.py
def construct_input_prompt(chat_history, message):
    input_prompt = f"<s>[INST] <<SYS>>\n{get_default_system_prompt()}\n<</SYS>>\n\n "
    for user, assistant in chat_history:
        input_prompt += f"{user} [/INST] {assistant} <s>[INST] "
    input_prompt += f"{message} [/INST] "
    return input_prompt

## trust-game-llama-2-7b-chat
# app.py 
@spaces.GPU
def generate(
    request: gr.Request, # To fetch query params
    message: str,
    chat_history: list[tuple[str, str]],
    # input_prompt: str,
    max_new_tokens: int = 1024,
    temperature: float = 0.6,
    top_p: float = 0.9,
    top_k: int = 50,
    repetition_penalty: float = 1.2,
) -> Iterator[str]: # Change return type hint to Iterator[str]

    conversation = []
    
    # Fetch query params 
    params = {
        key: value for key, value in gr.Request.query_params.items()
    }
    print('those are the query params')
    print(params)

    print("Request headers dictionary:", gr.Request.headers)
    print("IP address:", gr.Request.client.host)
    print("Query parameters:", params)
    
    # Construct the input prompt using the functions from the system_prompt_config module
    input_prompt = construct_input_prompt(chat_history, message)

    # Move the condition here after the assignment
    if input_prompt:
        conversation.append({"role": "system", "content": input_prompt})

    # Convert input prompt to tensor
    input_ids = tokenizer(input_prompt, return_tensors="pt").to(model.device)

    for user, assistant in chat_history:
        conversation.extend([{"role": "user", "content": user}, {"role": "assistant", "content": assistant}])
    conversation.append({"role": "user", "content": message})

    input_ids = tokenizer.apply_chat_template(conversation, return_tensors="pt")
    if input_ids.shape[1] > MAX_INPUT_TOKEN_LENGTH:
        input_ids = input_ids[:, -MAX_INPUT_TOKEN_LENGTH:]
        gr.Warning(f"Trimmed input from conversation as it was longer than {MAX_INPUT_TOKEN_LENGTH} tokens.")
    input_ids = input_ids.to(model.device)

    # Set up the TextIteratorStreamer
    streamer = TextIteratorStreamer(tokenizer, timeout=10.0, skip_prompt=True, skip_special_tokens=True)
    
    # Set up the generation arguments
    generate_kwargs = dict(
        {"input_ids": input_ids},
        streamer=streamer,
        max_new_tokens=max_new_tokens,
        do_sample=True,
        top_p=top_p,
        top_k=top_k,
        temperature=temperature,
        num_beams=1,
        repetition_penalty=repetition_penalty,
    )

    # Start the model generation thread
    t = Thread(target=model.generate, kwargs=generate_kwargs)
    t.start()

    # Yield generated text chunks
    outputs = []
    for text in streamer:
        outputs.append(text)
        yield "".join(outputs)

    # Fix bug that last answer is not recorded! 
    # Parse the outputs into a readable sentence and record them
    # Filter out empty strings and join the remaining strings with spaces
    readable_sentence = ' '.join(filter(lambda x: x.strip(), outputs))
    # Print the readable sentence
    print(readable_sentence)

    # Save chat history to .csv file on HuggingFace Hub 
    # Generate filename with bot id and session id
    filename = f"{DATA_FILENAME}"
    data_file = os.path.join(DATA_DIRECTORY, filename)
    
    # Generate timestamp
    timestamp = datetime.datetime.now()
    
    # Check if the file already exists
    if os.path.exists(data_file):
        # If file exists, load existing data
        existing_data = pd.read_csv(data_file)
        
        # Add timestamp column
        conversation_df = pd.DataFrame(conversation)
        conversation_df['ip_address'] = request.client.host
        conversation_df['readable_sentence'] = readable_sentence
        conversation_df['timestamp'] = timestamp
        
        # Append new conversation to existing data
        updated_data = pd.concat([existing_data, conversation_df], ignore_index=True)
        updated_data.to_csv(data_file, index=False)
    else:
        # If file doesn't exist, create new file with conversation data
        conversation_df = pd.DataFrame(conversation)
        conversation_df['ip_address'] = request.client.host
        conversation_df['readable_sentence'] = readable_sentence
        conversation_df['timestamp'] = timestamp
        conversation_df.to_csv(data_file, index=False)

    print("Updating .csv")
    repo.push_to_hub(blocking=False, commit_message=f"Updating data at {timestamp}")

chat_interface = gr.ChatInterface(
    fn=generate,
    retry_btn=None,
    clear_btn=None,
    undo_btn=None,
    chatbot=gr.Chatbot(avatar_images=('user.png', 'bot.png'), bubble_full_width = False), 
    examples=[
        ["What is your favorite fruit?"],
        ["What do you think about AI in the workplace?"],
    ],
)

with gr.Blocks(css="style.css", theme=gr.themes.Default(primary_hue=gr.themes.colors.emerald,secondary_hue=gr.themes.colors.indigo)) as demo:
    gr.Markdown(DESCRIPTION)
    chat_interface.render()
    gr.Markdown(LICENSE)
    
if __name__ == "__main__":
    demo.queue(max_size=20).launch()
    #demo.queue(max_size=20)
    demo.launch(share=True, debug=True)
'''