Spaces:
Build error
Build error
Merge pull request #12 from east-and-west-magic/feature-call-ai
Browse filesFiles changed (5)
- app.py+27-53
- app_util.py+8-1
- cache.pyDeleted-40
- call_ai.pyAdded+37
- str_util.pyAdded+5
1234567891011121314151617181920211 unmodified line23242526272829307 unmodified lines383940414243444512 unmodified lines58596061626327 unmodified lines919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141import requestsimport jsonimport osfrom datetime import datetimefrom zoneinfo import ZoneInfoimport gradio as grfrom gradio_client import Clientfrom extract import extractimport app_utilimport cachefrom pgsoft.pgconst.const import service_list, functionality_list, game_listfrom pgsoft.pgdate.date_utils import beijing######################## proxy version#######################proxy_version = "1.0.0-2023-12-12-a" # use cachet = datetime.now()t = t.astimezone(ZoneInfo("Asia/Shanghai"))1 unmodified linet = t.astimezone(ZoneInfo("America/Los_Angeles"))print(f"[Seattle]: {t.replace(microsecond=0)}")# assert Falsespaces = {"b_demo_hf": "stevez-ai",7 unmodified linesspace = "stevez-ai"if identity in spaces:space = spaces[identity]filepath = os.sep.join(["cache", "cached_ai.json"])cache.load_cache(filepath)def run(hf_token, service, game, functionality, nlp_command):12 unmodified linesspace = redirecturl = f"https://{space}.hf.space"if token is None or token == "":return "please specify hf token"27 unmodified lineselse:outp = {"status": "OK", "result": json.loads(res)["result"]}else:try:assert "games" in service_listif service == "games":print(f"{beijing()} [{user_name}] [{game}] {nlp_command}")outp = cache.get_cache(nlp_command)if outp is None:client = Client(url,hf_token=token,verbose=False,)calling_start = beijing()print(f"calling ai starts at {calling_start}")res = client.predict(service,game,functionality,nlp_command, # hidden,api_name="/predict",)calling_end = beijing()timecost = calling_end.timestamp() - calling_start.timestamp()print(f"calling ai ends at {calling_end}, costs {timecost:.2f}s")outp = json.loads(res)outp["cache"] = Falsecache.add_cache(nlp_command, outp)else:print(f"[cache] return from cache")# add proxy version info to the outputoutp["proxy-version"] = proxy_versionoutp["user"] = user_nameoutp["game"] = gameif source:outp["source"] = sourcecalling_start = beijing()print(f"calling logger starts at {beijing()}")app_util.call_logger(outp, identity, token)calling_end = beijing()timecost = calling_end.timestamp() - calling_start.timestamp()print(f"calling logger ends at {calling_end}, costs {timecost:.2f}s")except Exception as e:return (f"{type(e)}, {str(e)}. \nyou may want to make "+ "sure your hf_token is correct")service_end = beijing()timecost = service_end.timestamp() - service_start.timestamp()print(12345678910111213141516171819201 unmodified line2223242526277 unmodified lines35363738394012 unmodified lines5354555657585927 unmodified lines87888990919293949596979899100101102103104105106107108109110111112113114115import jsonimport osfrom datetime import datetimefrom zoneinfo import ZoneInfoimport gradio as grfrom extract import extractimport app_utilfrom pgsoft.pgconst.const import service_list, functionality_list, game_listfrom pgsoft.pgdate.date_utils import beijingimport call_aifrom str_util import normalize_text######################## proxy version#######################proxy_version = "1.0.0-2023-12-13-a" # reconstruct ai callingt = datetime.now()t = t.astimezone(ZoneInfo("Asia/Shanghai"))1 unmodified linet = t.astimezone(ZoneInfo("America/Los_Angeles"))print(f"[Seattle]: {t.replace(microsecond=0)}")spaces = {"b_demo_hf": "stevez-ai",7 unmodified linesspace = "stevez-ai"if identity in spaces:space = spaces[identity]def run(hf_token, service, game, functionality, nlp_command):12 unmodified linesspace = redirecturl = f"https://{space}.hf.space"nlp_command = normalize_text(nlp_command)if token is None or token == "":return "please specify hf token"27 unmodified lineselse:outp = {"status": "OK", "result": json.loads(res)["result"]}else:assert "games" in service_listif service == "games":print(f"{beijing()} [{user_name}] [{game}] {nlp_command}")call_ai.from_cache = Trueoutp = call_ai.call_ai(service,game,functionality,nlp_command,url,token,)if isinstance(outp, str):return outp# add proxy version info to the outputoutp["timestamp"] = beijing().__str__()outp["proxy-version"] = proxy_versionoutp["user"] = user_nameoutp["game"] = gameif source:outp["source"] = sourceoutp["cache"] = call_ai.from_cacheapp_util.call_logger(outp, identity, token)service_end = beijing()timecost = service_end.timestamp() - service_start.timestamp()print(
12345678910111213141516175 unmodified lines232425262728import jsonfrom gradio_client import Clientdef call_logger(log_info, caller, hf_token) -> None:######################## logging#######################urls = ["https://hubei-hunan-logger.hf.space","https://hubei-hunan-logger2.hf.space",]for url in urls:try:client = Client(5 unmodified linesprint(f"[logging to {url}] OK")except Exception as e:print(f"[logging to {url}] error: {e}")def call_clouddisk(service, arg, hf_token) -> str | None:12345678910111213141516171819205 unmodified lines26272829303132333435import jsonfrom gradio_client import Clientfrom pgsoft.pgdate.date_utils import beijingdef call_logger(log_info, caller, hf_token) -> None:######################## logging#######################calling_start = beijing()print(f"calling logger starts at {beijing()}")#################################################urls = ["https://hubei-hunan-logger.hf.space","https://hubei-hunan-logger2.hf.space",]for url in urls:try:client = Client(5 unmodified linesprint(f"[logging to {url}] OK")except Exception as e:print(f"[logging to {url}] error: {e}")#################################################calling_end = beijing()timecost = calling_end.timestamp() - calling_start.timestamp()print(f"calling logger ends at {calling_end}, costs {timecost:.2f}s")def call_clouddisk(service, arg, hf_token) -> str | None:
12345678910111213141516171819202122232425262728293031323334353637383940import osimport jsonfrom pgsoft.pgdate.date_utils import beijing
cache_ai = {}
def normalize_text(text: str) -> str: text = text.lower() tmp = text.split(" ") tmp = [word for word in tmp if word != ""] return " ".join(tmp)
def load_cache(filepath: str): """load cached ai calling from a json file""" global cache_ai if os.path.exists(filepath): with open(filepath, "r+") as f: cache_ai = json.load(f)
def add_cache(command: str, result: dict): """add a cache of ai calling""" command = normalize_text(command) result["command"] = command
global cache_ai cache_ai[command] = result print(f'[cache] added "{command}"')
def get_cache(command: str) -> dict | None: """return a cached ai calling with new "timestamp" """ command = normalize_text(command) outp = cache_ai.get(command) if outp: outp["timestamp"] = beijing().__str__() outp["cache"] = True return outp12345678910111213141516171819202122232425262728293031323334353637from functools import cachefrom gradio_client import Clientfrom pgsoft.pgdate.date_utils import beijingimport json
from_cache = True
@cachedef call_ai(service, game, functionality, nlp_command, url, hf_token): calling_start = beijing() print(f"calling ai starts at {calling_start}") try: client = Client( url, hf_token=hf_token, verbose=False, ) res = client.predict( service, game, functionality, nlp_command, # hidden, api_name="/predict", ) except Exception as e: return ( f"{type(e)}, {str(e)}. \nyou may want to make " + "sure your hf_token is correct" ) calling_end = beijing() timecost = calling_end.timestamp() - calling_start.timestamp() print(f"calling ai ends at {calling_end}, costs {timecost:.2f}s") outp = json.loads(res) global from_cache from_cache = False return outp12345def normalize_text(text: str) -> str: text = text.lower() tmp = text.split(" ") tmp = [word for word in tmp if word != ""] return " ".join(tmp)app.py+27-53
app_util.py+8-1
cache.pyDeleted-40
call_ai.pyAdded+37
str_util.pyAdded+5