epub / app.py
mr2along's picture
Update app.py
c9c379f verified
raw
history blame
5.91 kB
import asyncio
import websockets
import json
import requests
import logging
import gradio as gr
from datetime import datetime
# Set up logging configuration
#logging.basicConfig(level=logging.INFO)
# Dictionary to store table information
table = {}
def send_form(form_data):
# URL for Google Form
url = "https://docs.google.com/forms/u/0/d/e/1FAIpQLSeDkeewjc5CEZ9ORYJix20rjGWr48WFSBryEqp7D2q5Hsd4PA/formResponse"
try:
# Send POST request with form data
response = requests.post(url, data=form_data)
response.raise_for_status() # Raise exception for HTTP errors
#logging.info("Submitted successfully to Google Form.")
except requests.exceptions.RequestException as e:
logging.error("Failed to submit to Google Form: " + str(e))
def parse_card_values(dtCard):
# Parse card values based on modulus 20
card_values = []
for card in dtCard:
value = dtCard[card] % 20
if value in [1, 14]:
card_values.append(1)
elif value in [11, 12, 13]:
card_values.append(10)
elif value in range(2, 11):
card_values.append(value)
else:
card_values.append("")
return {"CardValues": card_values}
def handle_case_25(data):
# Extract data from case 25
group_id = data['groupID']
player_score = data['playerScore']
banker_score = data['bankerScore']
dt_card = data['dtCard']
card_values = parse_card_values(dt_card)["CardValues"]
# Determine result (Player, Banker, Tie)
if player_score == banker_score:
result = "T"
elif player_score > banker_score:
result = "P"
else:
result = "B"
# Retrieve additional info from table
if group_id in table:
info = table[group_id]
game_no = info['gameNo']
game_no_round = info['gameNoRound']
dealer_name = info['dealerName']
group_type = info['groupType']
else:
game_no = game_no_round = dealer_name = group_type = ""
# Current timestamp
today = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
# Construct form data
record_form = {
"entry.1910151925": group_id,
"entry.345081202": card_values[0],
"entry.790265993": card_values[2],
"entry.266290562": card_values[4],
"entry.1840046760": card_values[1],
"entry.2050858893": card_values[3],
"entry.1372409472": card_values[5],
"entry.211810544": player_score,
"entry.2078666320": banker_score,
"entry.1824106848": result,
"entry.1579231357": group_type,
"entry.911826972": game_no,
"entry.305589575": game_no_round,
"entry.992348569": dealer_name
}
return record_form
async def send_heartbeat(websocket):
# Send a heartbeat message to the WebSocket server
heartbeat_message = {"protocol": 999, "data": {}}
await websocket.send(json.dumps(heartbeat_message))
# Wait for a period of time before sending the next heartbeat
await asyncio.sleep(10) # Send heartbeat every 10 seconds
async def send_login(websocket):
# Create a JSON message containing login information
login_data = {
"protocol": 1,
"data": {
"sid": "ANONYMOUS-1000759",
"dtBetLimitSelectID": {
"101": 99101, "102": 99102, "103": 99103, "104": 99104,
"105": 99105, "106": 99106, "107": 99107, "108": 99108,
"110": 99110, "111": 99111, "112": 99112, "113": 99113,
"125": 99125, "126": 99126, "128": 99128, "129": 99129
},
"bGroupList": False,
"videoName": "HttpFlv",
"videoDelay": 3000,
"userAgent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36"
}
}
login_message = json.dumps(login_data)
# Send the login message to the WebSocket server
await websocket.send(login_message)
async def init_sma_ws():
uri = "wss://a45gs-t.wmetg.com/15101"
try:
async with websockets.connect(uri) as websocket:
# Send login message to the WebSocket server
await send_login(websocket)
logging.info('Login message sent')
await send_heartbeat(websocket)
# Receive and process responses from the server
while True:
try:
response = await websocket.recv()
json_obj = json.loads(response)
protocol = json_obj["protocol"]
if protocol == 21:
info = json_obj["data"]
group_id = info['groupID']
game_no = info['gameNo']
game_no_round = info['gameNoRound']
dealer_name = info['dealerName']
group_type = info['groupType']
table[group_id] = {
'groupType': group_type,
'gameNo': game_no,
'gameNoRound': game_no_round,
'dealerName': dealer_name
}
if protocol == 25:
data = handle_case_25(json_obj["data"])
send_form(data)
except websockets.exceptions.ConnectionClosedError as e:
logging.error(f"Connection closed: {e}")
break
except asyncio.CancelledError:
logging.info("WebSocket connection cancelled.")
except Exception as e:
logging.error(f"Error: {e}")
def websocket_interface():
asyncio.run(init_sma_ws())
iface = gr.Interface(
fn=websocket_interface,
inputs=None,
outputs=gr.Textbox(label="Output"),
title="WebSocket Interface"
)
iface.launch()