botsi's picture
Update app.py
affcab3 verified
raw
history blame
3.22 kB
import gradio as gr
import time
import random
import json
# To test open trust-game-llama2-7b in terminal,
# open conda environment via conda activate
# and run this file via python3 data_fetcher.py
# Example from here: https://www.techgropse.com/blog/how-to-return-sql-data-in-json-format-python/
# Use the built-in json module and the pymysql package if using MySQL as database:
import mysql.connector
import json
import requests
import urllib.parse
import urllib.request
# fetch data from the decisions database
def fetch_data_as_json():
# Connect to the database
conn = mysql.connector.connect(
host="18.153.94.89",
user="root",
password="N12RXMKtKxRj",
database="lionessdb"
)
# Create a cursor object
cursor = conn.cursor()
# Execute the SQL query
query = "SELECT playerNr, subjectNr, initialCredit, transfer1, tripledAmount1, keptForSelf1, returned1, " \
"newCreditRound2, transfer2, tripledAmount2, keptForSelf2, returned2, results2rounds, " \
"newCreditRound3, transfer3, tripledAmount3, keptForSelf3, returned3, results3rounds FROM e5390g37096_decisions"
cursor.execute(query)
# Fetch all rows and convert to a list of dictionaries
rows = cursor.fetchall()
result = []
for row in rows:
d = {}
for i, col in enumerate(cursor.description):
d[col[0]] = row[i]
result.append(d)
# Convert the list of dictionaries to JSON
json_result = json.dumps(result)
# Close the database connection
conn.close()
# Return the JSON result
return json_result
# Call the function to fetch data as JSON
json_result = fetch_data_as_json()
# Print or use the json_result variable as needed
print(json_result)
get_window_url_params = """
function() {
const params = new URLSearchParams(window.location.search);
const url_params = Object.fromEntries(params);
return url_params;
}
"""
with gr.Blocks() as demo:
gr.Markdown("""##Please insert`read query`in order to get the URL Parameters from the chatbot""")
url_params = gr.JSON({}, visible=False, label="URL Params")
chatbot = gr.Chatbot().style(height=500)
msg = gr.Textbox()
clear = gr.Button("Clear")
json_result = fetch_data_as_json()
def user(user_message, url_params, history):
return "", history + [[user_message, None]]
def bot(history, url_params):
if "read query" in history[-1][0]:
bot_message = f"""
here your URL params:
{json.dumps(url_params, indent=4)}
"""
else:
bot_message = random.choice(["Yes", "No"])
history[-1][1] = bot_message
time.sleep(1)
return history
msg.submit(user, inputs=[msg, url_params, chatbot], outputs=[msg, chatbot], queue=False).then(
fn=bot, inputs=[chatbot, url_params], outputs=[chatbot]
)
clear.click(lambda: None, None, chatbot, queue=False)
demo.load(
fn=lambda x: x,
inputs=[url_params],
outputs=[url_params],
_js=get_window_url_params,
queue=False
)
demo.launch()