# externalID (from database) and PROLIFIC_PID (from URL parameters as query parameter) # Original code from https://huggingface.co/spaces/huggingface-projects/llama-2-13b-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 = "13b.csv" # Default filename DATA_FILE = os.path.join("data", DATA_FILENAME) DB_PASSWORD = os.environ.get("DB_PASSWORD") 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: From discussing strategic game tactics to enjoying casual conversation. For example you could ask, what happened in the last round, what is your probability to win when you invest amount xy, what is my current balance etc. """ # License and Acceptable Use Policy by Meta LICENSE = """
--- 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 += "\nRunning on CPU 🥶 This demo does not work on CPU.
" if torch.cuda.is_available(): model_id = "meta-llama/Llama-2-13b-chat-hf" #model = AutoModelForCausalLM.from_pretrained(model_id, device_map="auto", load_in_4bit=True) 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 # for no LLM vs. 13B use e5390g38028 as database name # for 13B vs. no LLM use e5390g37899 as database name def fetch_personalized_data(externalID): try: # Connect to the database with mysql.connector.connect( host="3.125.179.74", user="root", password=DB_PASSWORD, database="lionessdb" ) as conn: # Create a cursor object with conn.cursor() as cursor: # Query to fetch relevant data from both tables based on externalID = externalID query = """ SELECT e5390g37899_core.playerNr, e5390g37899_core.groupNrStart, e5390g37899_core.subjectNr, e5390g37899_core.onPage, e5390g37899_core.role, e5390g37899_session.externalID, e5390g37899_decisions.initialCredit, e5390g37899_decisions.part, e5390g37899_decisions.transfer1, e5390g37899_decisions.tripledAmount1, e5390g37899_decisions.keptForSelf1, e5390g37899_decisions.returned1, e5390g37899_decisions.totalRound1, e5390g37899_decisions.transfer2, e5390g37899_decisions.tripledAmount2, e5390g37899_decisions.keptForSelf2, e5390g37899_decisions.returned2, e5390g37899_decisions.totalRound2, e5390g37899_decisions.transfer3, e5390g37899_decisions.tripledAmount3, e5390g37899_decisions.keptForSelf3, e5390g37899_decisions.returned3, e5390g37899_decisions.totalRound3, e5390g37899_decisions.transfer4, e5390g37899_decisions.tripledAmount4, e5390g37899_decisions.keptForSelf4, e5390g37899_decisions.returned4, e5390g37899_decisions.totalRound4, e5390g37899_decisions.transfer5, e5390g37899_decisions.tripledAmount5, e5390g37899_decisions.keptForSelf5, e5390g37899_decisions.returned5, e5390g37899_decisions.totalRound5, e5390g37899_decisions.transfer6, e5390g37899_decisions.tripledAmount6, e5390g37899_decisions.keptForSelf6 FROM e5390g37899_core JOIN e5390g37899_session ON e5390g37899_core.playerNr = e5390g37899_session.playerNr JOIN e5390g37899_decisions ON e5390g37899_core.playerNr = e5390g37899_decisions.playerNr WHERE e5390g37899_session.externalID = %s UNION ALL SELECT e5390g37899_core.playerNr, e5390g37899_core.groupNrStart, e5390g37899_core.subjectNr, e5390g37899_core.onPage, e5390g37899_core.role, e5390g37899_session.externalID, e5390g37899_decisions.initialCredit, e5390g37899_decisions.part, e5390g37899_decisions.transfer1, e5390g37899_decisions.tripledAmount1, e5390g37899_decisions.keptForSelf1, e5390g37899_decisions.returned1, e5390g37899_decisions.totalRound1, e5390g37899_decisions.transfer2, e5390g37899_decisions.tripledAmount2, e5390g37899_decisions.keptForSelf2, e5390g37899_decisions.returned2, e5390g37899_decisions.totalRound2, e5390g37899_decisions.transfer3, e5390g37899_decisions.tripledAmount3, e5390g37899_decisions.keptForSelf3, e5390g37899_decisions.returned3, e5390g37899_decisions.totalRound3, e5390g37899_decisions.transfer4, e5390g37899_decisions.tripledAmount4, e5390g37899_decisions.keptForSelf4, e5390g37899_decisions.returned4, e5390g37899_decisions.totalRound4, e5390g37899_decisions.transfer5, e5390g37899_decisions.tripledAmount5, e5390g37899_decisions.keptForSelf5, e5390g37899_decisions.returned5, e5390g37899_decisions.totalRound5, e5390g37899_decisions.transfer6, e5390g37899_decisions.tripledAmount6, e5390g37899_decisions.keptForSelf6 FROM e5390g37899_core JOIN e5390g37899_session ON e5390g37899_core.playerNr = e5390g37899_session.playerNr JOIN e5390g37899_decisions ON e5390g37899_core.playerNr = e5390g37899_decisions.playerNr WHERE e5390g37899_core.groupNrStart IN ( SELECT DISTINCT groupNrStart FROM e5390g37899_core JOIN e5390g37899_session ON e5390g37899_core.playerNr = e5390g37899_session.playerNr WHERE e5390g37899_session.externalID = %s ) AND e5390g37899_session.externalID != %s """ cursor.execute(query,(externalID, externalID, externalID)) # Fetch data row by row data = [{ 'playerNr': row[0], 'groupNrStart': row[1], 'subjectNr': row[2], 'onPage': row[3], 'role': row[4], 'externalID': row[5], 'initialCredit': row[6], 'part': row[7], 'transfer1': row[8], 'tripledAmount1': row[9], 'keptForSelf1': row[10], 'returned1': row[11], 'totalRound1': row[12], 'transfer2': row[13], 'tripledAmount2': row[14], 'keptForSelf2': row[15], 'returned2': row[16], 'totalRound2': row[17], 'transfer3': row[18], 'tripledAmount3': row[19], 'keptForSelf3': row[20], 'returned3': row[21], 'totalRound3': row[22], 'transfer4': row[23], 'tripledAmount4': row[24], 'keptForSelf4': row[25], 'returned4': row[26], 'totalRound4': row[27], 'transfer5': row[28], 'tripledAmount5': row[29], 'keptForSelf5': row[30], 'returned5': row[31], 'totalRound5': row[32], 'transfer6': row[33], 'tripledAmount6': row[34], 'keptForSelf6': row[35] } for row in cursor] print(data) return data except mysql.connector.Error as err: print(f"Error: {err}") return None def extract_variables(all_personalized_data, part): extracted_data = {} if part == "1": rounds = range(1, 4) # Rounds 1-3 for part 1 elif part == "2": rounds = range(4, 7) # Rounds 4-6 for part 2 else: print("No data for the particular part found") return None for data in all_personalized_data: role = map_role(str(data.get('role', 'unknown'))) # Get the role description player_data = {} # Store data for the current player for round_num in rounds: round_key = f'round{round_num - 3 if part == "2" else round_num}' # Adjusting round numbers if part is 2 player_data[round_key] = {} for var in ['transfer', 'tripledAmount', 'keptForSelf', 'returned', 'totalRound']: var_name = f'{var}{round_num}' if role == 'The Dealer' and var == 'tripledAmount': continue # Skip adding 'tripledAmount' for the Dealer if role == 'The Investor' and var == 'keptForSelf': continue # Skip adding 'keptForSelf' for the Investor if data.get(var_name) is not None: player_data[round_key][var] = data[var_name] # Update extracted_data with role prompt as key if role in extracted_data: extracted_data[role].update(player_data) else: extracted_data[role] = player_data return extracted_data # for no LLM vs. 13B '''def map_onPage(onPage): # Define the mapping of onPage values to onPage_filename and onPage_prompt onPage_mapping_dict = { "stage412359.php": ("stage 6", "Round 1: Investor’s turn"), "stage412360.php": ("stage 7", "Round 1: Dealer’s turn"), "stage412361.php": ("stage 8", "Round 2: Investor’s turn"), "stage412362.php": ("stage 9", "Round 2: Dealer’s turn"), "stage412363.php": ("stage 10", "Round 3: Investor’s turn"), "stage412364.php": ("stage 11", "Round 3: Dealer’s turn"), "stage412366.php": ("stage 13", "Round 1: Investor’s turn"), "stage412367.php": ("stage 14", "Round 1: Dealer’s turn"), "stage412368.php": ("stage 15", "Round 2: Investor’s turn"), "stage412369.php": ("stage 16", "Round 2: Dealer’s turn"), "stage412370.php": ("stage 17", "Round 3: Investor’s turn"), "stage412371.php": ("stage 18", "Round 3: Dealer’s turn"), } ''' # for 13B vs. no LLM def map_onPage(onPage): # Define the mapping of onPage values to onPage_filename and onPage_prompt onPage_mapping_dict = { "stage411228.php": ("stage 6", "Round 1: Investor’s turn"), "stage411229.php": ("stage 7", "Round 1: Dealer’s turn"), "stage411230.php": ("stage 8", "Round 2: Investor’s turn"), "stage411231.php": ("stage 9", "Round 2: Dealer’s turn"), "stage411232.php": ("stage 10", "Round 3: Investor’s turn"), "stage411233.php": ("stage 11", "Round 3: Dealer’s turn"), "stage411235.php": ("stage 13", "Round 1: Investor’s turn"), "stage411236.php": ("stage 14", "Round 1: Dealer’s turn"), "stage411237.php": ("stage 15", "Round 2: Investor’s turn"), "stage411238.php": ("stage 16", "Round 2: Dealer’s turn"), "stage411239.php": ("stage 17", "Round 3: Investor’s turn"), "stage411240.php": ("stage 18", "Round 3: Dealer’s turn"), } # Check if onPage is in the mapping if onPage in onPage_mapping_dict: onPage_filename, onPage_prompt = onPage_mapping_dict[onPage] else: # If onPage is not in the mapping, set onPage_filename and onPage_prompt to "unknown" onPage_filename, onPage_prompt = "unknown", "unknown" return onPage_filename, onPage_prompt def map_role(role): # Define the mapping of role numbers to role descriptions role_mapping_dict = { "1": "The Investor", "2": "The Dealer" } # Check if the role is in the mapping if role in role_mapping_dict: role_prompt = role_mapping_dict[role] else: # If the role is not in the mapping, set role_prompt to "unknown" role_prompt = "unknown" return role_prompt def get_default_system_prompt(extracted_data, onPage_prompt, role_prompt): #BOS, EOS = "