vchat / app.py
Hongsen's picture
Create app.py
59b0692
import numpy as np
import gradio as gr
import requests
from bardapi.constants import SESSION_HEADERS
from bardapi import Bard
import threading
import logging
import json
import os
def load_cookie(element_name):
with open(os.getcwd() + "/" + "bard.json", "r", encoding="utf-8") as file:
data = json.load(file)
if isinstance(data, list):
for item in data:
if item.get("name") == element_name:
return item.get("value")
return None
def _refresh_cookie(session, force=False, inputData=None):
s = session
cookies = []
if force == True:
if inputData != None:
rcookies = inputData
else:
rcookies = {
'__Secure-1PSID': 'cAjTLu0tbHFzi4i7SN02J-Sk09hAUxRW2cRweWXdOv43S3XcfSqm6GRkIfXU_MLI040bXg.',
'__Secure-1PSIDCC':'ACA-OxNf3jPFp4Q2EGce1dvSnC_Rmc0LwNHrxHMXtx6J9tK2KiNhQesn1qV2SYxSsXYNjYIFAUk',
'__Secure-1PSIDTS':'sidts-CjEB3e41haWxCIIO6I3Uglgpesu4OIQtj8xcUsXy2vo4wH_iI9g5W2XqS4mYXA0R5V3kEAA'
}
cookies.append({'name': '__Secure-1PSID', 'value': rcookies['__Secure-1PSID']})
cookies.append({'name': '__Secure-1PSIDTS', 'value': rcookies['__Secure-1PSIDTS']})
cookies.append({'name': '__Secure-1PSIDCC', 'value': rcookies['__Secure-1PSIDCC']})
for k, v in s.cookies.get_dict().items():
cookies.append({'name': k, 'value': v})
with open("bard.json", "w") as outfile:
outfile.write(json.dumps(cookies))
"""
curl 'https://accounts.google.com/RotateCookies' \
-H 'authority: accounts.google.com' \
-H 'accept: */*' \
-H 'accept-language: zh-CN,zh;q=0.9' \
-H 'cache-control: no-cache' \
-H 'content-type: application/json' \
-H 'cookie: CONSENT=PENDING+126; SOCS=CAISHwgCEhJnd3NfMjAyMzA5MTktMF9SQzEaBXpoLUNOIAEaBgiAj66oBg; OTZ=7216350_24_24__24_; SID=bgjTLuZd5FNRwaqPlNR-g4YJZjm_Gso043r6aomscB7qpTCthr0ofKjCkOKcrvZc6M8bFQ.; __Secure-1PSID=bgjTLuZd5FNRwaqPlNR-g4YJZjm_Gso043r6aomscB7qpTCtCtmdXnqmmvICf_dqN2E0Ew.; __Secure-3PSID=bgjTLuZd5FNRwaqPlNR-g4YJZjm_Gso043r6aomscB7qpTCtgQaKSr89I03JVG_tgACzhA.; HSID=AlvhATI6KzcNKnabh; SSID=Ae8TCtjtt27en1e44; APISID=g5cwoAMD8d2_sO11/A-Rwczmgi0udFgCoQ; SAPISID=OzZnHNamhN3jXLNC/A2vmqDIgjbrTejueT; __Secure-1PAPISID=OzZnHNamhN3jXLNC/A2vmqDIgjbrTejueT; __Secure-3PAPISID=OzZnHNamhN3jXLNC/A2vmqDIgjbrTejueT; ACCOUNT_CHOOSER=AFx_qI7_HEzgTYKnWcZUdfRgVgKIae2pD7PXhhfk44t3IwPv_ecwcqhG0Of35gtj_CJan2ftXCcI-pbHHiuHrI-uBgwRN3prTpTlK-lfdTcLGIeK7EX-bQmUk-RP5eyvTibD2B1TeFIk; SEARCH_SAMESITE=CgQItpkB; LSID=o.console.cloud.google.com|o.myaccount.google.com|s.HK|s.youtube:bgjTLs6wckDwgc9bMe0STv7Ddq2FdtHhlBl1QZNfwXDMEEIif8dB7SQdook7LsRyaLoo0g.; __Host-1PLSID=o.console.cloud.google.com|o.myaccount.google.com|s.HK|s.youtube:bgjTLs6wckDwgc9bMe0STv7Ddq2FdtHhlBl1QZNfwXDMEEIiq0UCdDLPvW9AYTEoD10U2A.; __Host-3PLSID=o.console.cloud.google.com|o.myaccount.google.com|s.HK|s.youtube:bgjTLs6wckDwgc9bMe0STv7Ddq2FdtHhlBl1QZNfwXDMEEIi7K0n0ZBE55ocXwF_87WeRQ.; __Host-GAPS=1:kiYlEzR-7QR6lpenXGRKZdnXzGV6tjibaIhaGTaU0EZ49y1_dA9_GnN-GfJ2_2FiiyJlq75j3ycG4NTdvXCI4E0_pmfstA:5ib-ikZoBeIN7BET; AEC=Ackid1Tlb_Cwsk2VvvwFAn486fnHL27O-kzZtpJLRzf6WBHs9TZUyOIviQ; NID=511=JTxtvHyIWGcJdIXl9QiMeIudlBg-h08jlOKyQGQbEb-tUBlFOAX3B-RElc47doqva2WB-EWnkeT6DVLlBwP3v7sYSJqnMN5oXP7RojJT_FQ-XtxxYS_Io_q-_IDh3uwUPXXtJsxgJr95aHghqkxgdkBHIiUC9yvLcGwIjVQOySuOPIXIJNIXVKGQOmvIeRWnlUAEzxIVVSvgyirUJj2vRU-nmQ-It_k9tcM1t_vmepTdoT4RdJHRdPqV6AQrEd1llZvSGPxmZusAhfzBeJy2NOUn96zS4zpsh1897x_BPd_62uiELKCAO0_haso8FuL6E40HseWGhvhPgKR2vaCMyPoF4d0j; 1P_JAR=2023-10-10-10; __Secure-1PSIDTS=sidts-CjIB3e41hVwPZ-GA-le4Qb8npu9IgvD-BIaueTRorj7f0euJUNARPE7QMdM907q2f-pUVRAA; __Secure-3PSIDTS=sidts-CjIB3e41hVwPZ-GA-le4Qb8npu9IgvD-BIaueTRorj7f0euJUNARPE7QMdM907q2f-pUVRAA; SIDCC=ACA-OxOmjCOQXoVSBIpW9MaHGfCgY8vgHeTdKdn5m91k_ExTUlvNxz4yz2bHIm2YO4GzE2viNEw; __Secure-1PSIDCC=ACA-OxNJir5rKUGGcgK7Qs4DVftEa14sbyZbpuczcTox1OhSlX15KmaNz2thUSCOit_4gkMOLok; __Secure-3PSIDCC=ACA-OxOsXDQ0RoYiLiu1EysjUZU_tD3rPxSMXjZWC-iWGTg1ETB0gmzuJ55H8gAgv7S_8dXo_Zc' \
-H 'origin: https://accounts.google.com' \
-H 'pragma: no-cache' \
-H 'referer: https://accounts.google.com/RotateCookiesPage?og_pid=658&rot=3&origin=https%3A%2F%2Fbard.google.com&exp_id=3701166' \
-H 'sec-ch-ua: "Google Chrome";v="117", "Not;A=Brand";v="8", "Chromium";v="117"' \
-H 'sec-ch-ua-arch: "arm"' \
-H 'sec-ch-ua-bitness: "64"' \
-H 'sec-ch-ua-full-version: "117.0.5938.149"' \
-H 'sec-ch-ua-full-version-list: "Google Chrome";v="117.0.5938.149", "Not;A=Brand";v="8.0.0.0", "Chromium";v="117.0.5938.149"' \
-H 'sec-ch-ua-mobile: ?0' \
-H 'sec-ch-ua-model: ""' \
-H 'sec-ch-ua-platform: "macOS"' \
-H 'sec-ch-ua-platform-version: "13.4.1"' \
-H 'sec-ch-ua-wow64: ?0' \
-H 'sec-fetch-dest: empty' \
-H 'sec-fetch-mode: same-origin' \
-H 'sec-fetch-site: same-origin' \
-H 'user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36' \
-H 'x-chrome-id-consistency-request: version=1,client_id=77185425430.apps.googleusercontent.com,device_id=8d089f9c-340b-4b9a-91aa-176c7fc95f62,signin_mode=all_accounts,signout_mode=show_confirmation' \
-H 'x-client-data: CJW2yQEIprbJAQipncoBCIaMywEIlKHLAQiGoM0BCNy9zQEIucrNAQjD0c0BCInTzQEI0tbNAQj11s0BCKfYzQEIl9nNAQj5wNQVGPTJzQE=' \
--data-raw '[658,"-3903137320083272820"]' \
--compressed
"""
def rotateCookie():
url = 'https://accounts.google.com/RotateCookies'
session, token = getSession()
headers = {
"accept": "*/*",
"accept-language": "zh-CN,zh;q=0.9",
"cache-control": "no-cache",
"content-type": "application/json",
"pragma": "no-cache",
"sec-ch-ua": "\"Google Chrome\";v=\"117\", \"Not;A=Brand\";v=\"8\", \"Chromium\";v=\"117\"",
"sec-ch-ua-arch": "\"arm\"",
"sec-ch-ua-bitness": "\"64\"",
"sec-ch-ua-full-version": "\"117.0.5938.149\"",
"sec-ch-ua-full-version-list": "\"Google Chrome\";v=\"117.0.5938.149\", \"Not;A=Brand\";v=\"8.0.0.0\", \"Chromium\";v=\"117.0.5938.149\"",
"sec-ch-ua-mobile": "?0",
"sec-ch-ua-model": "\"\"",
"sec-ch-ua-platform": "\"macOS\"",
"sec-ch-ua-platform-version": "\"13.4.1\"",
"sec-ch-ua-wow64": "?0",
"sec-fetch-dest": "empty",
"sec-fetch-mode": "same-origin",
"sec-fetch-site": "same-origin",
"x-chrome-id-consistency-request": "version=1,client_id=77185425430.apps.googleusercontent.com,device_id=8d089f9c-340b-4b9a-91aa-176c7fc95f62,signin_mode=all_accounts,signout_mode=show_confirmation",
"x-client-data": "CJW2yQEIprbJAQipncoBCIaMywEIlKHLAQiGoM0BCNy9zQEIucrNAQjD0c0BCInTzQEI0tbNAQj11s0BCKfYzQEIl9nNAQj5wNQVGPTJzQE=",
}
data = "[658,\"-3903137320083272820\"]"
cookies = session.cookies
r = requests.post(url, headers=headers, cookies=cookies, data=data)
session.cookies.update(r.cookies)
_refresh_cookie(session)
def autoRotate():
threading.Timer(600, autoRotate).start()
print("rotate cookie")
rotateCookie()
def getSession():
_1PSID = load_cookie("__Secure-1PSID")
_1PSIDTS = load_cookie("__Secure-1PSIDTS")
_1PSIDCC = load_cookie("__Secure-1PSIDCC")
session = requests.Session()
session.headers = SESSION_HEADERS
session.cookies.set("__Secure-1PSID", _1PSID)
session.cookies.set("__Secure-1PSIDTS", _1PSIDTS)
session.cookies.set("__Secure-1PSIDCC", _1PSIDCC)
return session, _1PSID
def _bard(question, image=None):
session, token = getSession()
bard = Bard(token = token, session = session)
if image != None:
result = bard.ask_about_image(question, image)
else:
result = bard.get_answer(question)
print(result)
_refresh_cookie(bard.session)
return result
def initLogger():
logging.basicConfig(filename="app.log",
filemode='a',
format='%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s',
datefmt='%H:%M:%S',
level=logging.INFO)
logging.info("init logger")
def refreshFromUI(x):
pre = "refresh:"
if x.strip() != "" and x.startswith(pre):
inputData = x[len(pre):]
if len(inputData) > 0:
cookies = json.loads(inputData)
_refresh_cookie(requests.Session(), True, cookies)
return "ok"
def bard_text(x):
ok = refreshFromUI(x)
if ok != None:
return ok
res = _bard(x)
logger = logging.getLogger('app')
logger.info(json.dumps({"q":x, "a":res, "i":None},separators=(',', ':')))
return res['content']
def bard_image(img, x):
img_content = open(img, 'rb').read()
res = _bard(x, img_content)
logger = logging.getLogger('app')
logger.info(json.dumps({"q":x, "a":res, "i":img}, separators=(',', ':')))
return img, res['content']
def init():
initLogger()
#_refresh_cookie(requests.Session(), True)
autoRotate()
pass
with gr.Blocks() as demo:
init()
gr.Markdown("A viture tool of label image with google bard.")
with gr.Tab("Text"):
text_input = gr.Textbox()
text_output = gr.Markdown()
text_button = gr.Button("submit")
with gr.Tab("Image"):
with gr.Row():
image_input = gr.Image(type='filepath')
image_output = gr.Image(type='filepath')
with gr.Row():
image_text_input = gr.Textbox()
image_text_output = gr.Markdown()
image_button = gr.Button("submit")
text_button.click(bard_text, inputs=text_input, outputs=text_output)
image_button.click(bard_image, inputs=[image_input, image_text_input], outputs=[image_output, image_text_output])
demo.launch()