文章目录
- 前言
- 一、源码
- 二、运行效果展示
- 总结
前言
昨天发了python查询gpt-key剩余额度和近10天使用额度查询情况的源码,有伙伴反馈很实用,但是如果能封装UI版就更好了
那徐浪老师今天就给大家做一个封装吧!
一、源码
话不多说,直接上源码
import datetime
import requests
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QLabel, QTextEdit, QPlainTextEdit, QPushButtonclass OpenAIUsageMonitor(QWidget):def __init__(self):super().__init__()self.initUI()def initUI(self):self.setWindowTitle('徐浪gpt_key额度查询器')# 创建输入框和标签self.key_input_label = QLabel("请输入要查询的API Keys:")self.key_input = QPlainTextEdit()self.key_input.setPlaceholderText("这里输入key,一行一个,不要有其他不必要的符号")# 创建输出文本框self.output_text = QTextEdit()self.output_text.setReadOnly(True)self.output_text.setPlaceholderText("#### 监控key为:#### #### #### #### #### \n" "#### 总额:############\n""#### 已用:############\n""#### 剩余:############\n")# 创建运行按钮self.run_button = QPushButton("点击查询")self.run_button.clicked.connect(self.run_monitor)# 创建垂直布局layout = QVBoxLayout()layout.addWidget(self.key_input_label)layout.addWidget(self.key_input)layout.addWidget(self.run_button)layout.addWidget(self.output_text)# 设置窗口布局self.setLayout(layout)self.show()def run_monitor(self):self.output_text.clear()api_keys = self.key_input.toPlainText().strip().split('\n')for i, api_key in enumerate(api_keys):api_key = api_key.strip()if not api_key:continueusage_info = self.get_key(api_key)self.output_text.append(f"#### 第 {i + 1}个key的查询数据\n{usage_info}")def get_key(self, api_key):subscription_url = "https://api.openai.com/v1/dashboard/billing/subscription"headers = {"Authorization": "Bearer " + api_key,"Content-Type": "application/json"}subscription_response = requests.get(subscription_url, headers=headers)if subscription_response.status_code == 200:data = subscription_response.json()total = data.get("hard_limit_usd")else:return subscription_response.textstart_date = (datetime.datetime.now() - datetime.timedelta(days=99)).strftime("%Y-%m-%d")end_date = (datetime.datetime.now() + datetime.timedelta(days=1)).strftime("%Y-%m-%d")billing_url = f"https://api.openai.com/v1/dashboard/billing/usage?start_date={start_date}&end_date={end_date}"billing_response = requests.get(billing_url, headers=headers)if billing_response.status_code == 200:data = billing_response.json()total_usage = data.get("total_usage") / 100daily_costs = data.get("daily_costs")days = min(10, len(daily_costs))recent = f"##### 最近{days}天使用情况 \n"for i in range(days):cur = daily_costs[-i - 1]date = datetime.datetime.fromtimestamp(cur.get("timestamp")).strftime("%Y-%m-%d")line_items = cur.get("line_items")cost = 0for item in line_items:cost += item.get("cost")recent += f"\t{date}\t{(cost / 100):.2f} \n"else:return billing_response.textreturn f"\n#### 监控key为:{api_key[:-25] + '*' * 25}\n" \f"#### 总额:\t{total:.2f} \n" \f"#### 已用:\t{total_usage:.2f} \n" \f"#### 剩余:\t{total - total_usage:.2f} \n" \f"\n" + recentif __name__ == '__main__':app = QApplication(sys.argv)monitor = OpenAIUsageMonitor()sys.exit(app.exec_())
二、运行效果展示
总结
喜欢的伙伴自行使用,欢迎一键三连关注徐浪老师