CoolFace
Apppublic

aaaaasss/0406

sourceHugging Facegpl-3.0updated 3y agoView on Hugging Face
0likes
openai_func.py65 linesDownload Raw Back to modules
1import requests2import logging3from modules.presets import (4    timeout_all,5    USAGE_API_URL,6    BALANCE_API_URL,7    standard_error_msg,8    connection_timeout_prompt,9    error_retrieve_prompt,10    read_timeout_prompt11)12 13from . import shared14from modules.config import retrieve_proxy15import os, datetime16 17def get_billing_data(openai_api_key, billing_url):18    headers = {19        "Content-Type": "application/json",20        "Authorization": f"Bearer {openai_api_key}"21    }22 23    timeout = timeout_all24    with retrieve_proxy():25        response = requests.get(26            billing_url,27            headers=headers,28            timeout=timeout,29        )30 31    if response.status_code == 200:32        data = response.json()33        return data34    else:35        raise Exception(f"API request failed with status code {response.status_code}: {response.text}")36 37 38def get_usage(openai_api_key):39    try:40        curr_time = datetime.datetime.now()41        last_day_of_month = get_last_day_of_month(curr_time).strftime("%Y-%m-%d")42        first_day_of_month = curr_time.replace(day=1).strftime("%Y-%m-%d")43        usage_url = f"{shared.state.usage_api_url}?start_date={first_day_of_month}&end_date={last_day_of_month}"44        try:45            usage_data = get_billing_data(openai_api_key, usage_url)46        except Exception as e:47            logging.error(f"获取API使用情况失败:"+str(e))48            return f"**获取API使用情况失败**"49        rounded_usage = "{:.5f}".format(usage_data['total_usage']/100)50        return f"**本月使用金额** \u3000 ${rounded_usage}"51    except requests.exceptions.ConnectTimeout:52        status_text = standard_error_msg + connection_timeout_prompt + error_retrieve_prompt53        return status_text54    except requests.exceptions.ReadTimeout:55        status_text = standard_error_msg + read_timeout_prompt + error_retrieve_prompt56        return status_text57    except Exception as e:58        logging.error(f"获取API使用情况失败:"+str(e))59        return standard_error_msg + error_retrieve_prompt60 61def get_last_day_of_month(any_day):62    # The day 28 exists in every month. 4 days later, it's always next month63    next_month = any_day.replace(day=28) + datetime.timedelta(days=4)64    # subtracting the number of the current day brings us back one month65    return next_month - datetime.timedelta(days=next_month.day)