MZhaovo commited on
Commit
b3cdf66
·
1 Parent(s): 0137c6b

fix: 优化账单获取、显示方式

Browse files
Files changed (2) hide show
  1. ChuanhuChatbot.py +2 -12
  2. modules/openai_func.py +27 -69
ChuanhuChatbot.py CHANGED
@@ -9,7 +9,7 @@ from modules.utils import *
9
  from modules.presets import *
10
  from modules.overwrites import *
11
  from modules.chat_func import *
12
- from modules.openai_func import get_usage, get_dollar_usage_for_current_month
13
 
14
  logging.basicConfig(
15
  level=logging.DEBUG,
@@ -272,20 +272,15 @@ with gr.Blocks(css=customCSS, theme=small_and_beautiful_theme) as demo:
272
  fn=get_usage, inputs=[user_api_key], outputs=[usageTxt], show_progress=False
273
  )
274
 
275
- get_dollar_usage_args = dict(
276
- fn=get_dollar_usage_for_current_month, inputs=[user_api_key], outputs=[usageTxt], show_progress=False
277
- )
278
 
279
  # Chatbot
280
  cancelBtn.click(cancel_outputing, [], [])
281
 
282
  user_input.submit(**transfer_input_args).then(**chatgpt_predict_args).then(**end_outputing_args)
283
  user_input.submit(**get_usage_args)
284
- user_input.submit(**get_dollar_usage_args)
285
 
286
  submitBtn.click(**transfer_input_args).then(**chatgpt_predict_args).then(**end_outputing_args)
287
  submitBtn.click(**get_usage_args)
288
- submitBtn.click(**get_dollar_usage_args)
289
 
290
  emptyBtn.click(
291
  reset_state,
@@ -312,7 +307,6 @@ with gr.Blocks(css=customCSS, theme=small_and_beautiful_theme) as demo:
312
  show_progress=True,
313
  ).then(**end_outputing_args)
314
  retryBtn.click(**get_usage_args)
315
- retryBtn.click(**get_dollar_usage_args)
316
 
317
  delFirstBtn.click(
318
  delete_first_conversation,
@@ -345,13 +339,9 @@ with gr.Blocks(css=customCSS, theme=small_and_beautiful_theme) as demo:
345
  show_progress=True,
346
  )
347
  reduceTokenBtn.click(**get_usage_args)
348
- reduceTokenBtn.click(**get_dollar_usage_args)
349
 
350
  # ChatGPT
351
- if get_usage(user_api_key) == "**您的免费额度已用完**":
352
- keyTxt.change(submit_key, keyTxt, [user_api_key, status_display]).then(**get_dollar_usage_args)
353
- else:
354
- keyTxt.change(submit_key, keyTxt, [user_api_key, status_display]).then(**get_usage_args)
355
 
356
  # Template
357
  templateRefreshBtn.click(get_template_names, None, [templateFileSelectDropdown])
 
9
  from modules.presets import *
10
  from modules.overwrites import *
11
  from modules.chat_func import *
12
+ from modules.openai_func import get_usage
13
 
14
  logging.basicConfig(
15
  level=logging.DEBUG,
 
272
  fn=get_usage, inputs=[user_api_key], outputs=[usageTxt], show_progress=False
273
  )
274
 
 
 
 
275
 
276
  # Chatbot
277
  cancelBtn.click(cancel_outputing, [], [])
278
 
279
  user_input.submit(**transfer_input_args).then(**chatgpt_predict_args).then(**end_outputing_args)
280
  user_input.submit(**get_usage_args)
 
281
 
282
  submitBtn.click(**transfer_input_args).then(**chatgpt_predict_args).then(**end_outputing_args)
283
  submitBtn.click(**get_usage_args)
 
284
 
285
  emptyBtn.click(
286
  reset_state,
 
307
  show_progress=True,
308
  ).then(**end_outputing_args)
309
  retryBtn.click(**get_usage_args)
 
310
 
311
  delFirstBtn.click(
312
  delete_first_conversation,
 
339
  show_progress=True,
340
  )
341
  reduceTokenBtn.click(**get_usage_args)
 
342
 
343
  # ChatGPT
344
+ keyTxt.change(submit_key, keyTxt, [user_api_key, status_display]).then(**get_usage_args)
 
 
 
345
 
346
  # Template
347
  templateRefreshBtn.click(get_template_names, None, [templateFileSelectDropdown])
modules/openai_func.py CHANGED
@@ -12,91 +12,55 @@ from modules.presets import (
12
 
13
  from modules import shared
14
  from modules.utils import get_proxies
15
- import os
16
- from datetime import datetime, timedelta
17
 
18
- def get_usage_response(openai_api_key):
19
  headers = {
20
  "Content-Type": "application/json",
21
- "Authorization": f"Bearer {openai_api_key}",
22
  }
23
-
24
  timeout = timeout_all
25
-
26
  proxies = get_proxies()
27
- """
28
- 暂不支持修改
29
- if shared.state.balance_api_url != BALANCE_API_URL:
30
- logging.info(f"使用自定义BALANCE API URL: {shared.state.balance_api_url}")
31
- """
32
  response = requests.get(
33
- BALANCE_API_URL,
34
  headers=headers,
35
  timeout=timeout,
36
  proxies=proxies,
37
  )
38
-
39
- return response
 
 
 
 
 
40
 
41
  def get_usage(openai_api_key):
42
  try:
43
- response=get_usage_response(openai_api_key=openai_api_key)
44
- logging.debug(response.json())
45
  try:
46
- balance = response.json().get("total_available") if response.json().get(
47
- "total_available") else 0
48
- total_used = response.json().get("total_used") if response.json().get(
49
- "total_used") else 0
50
  except Exception as e:
51
  logging.error(f"API使用情况解析失败:"+str(e))
52
  balance = 0
53
  total_used=0
54
  return f"**API使用情况解析失败**"
 
55
  if balance == 0:
56
- return f"**您的免费额度已用完**"
57
- return f"**API免费额度使用情况**(已用/余额)\u3000${total_used} / ${balance}"
58
- except requests.exceptions.ConnectTimeout:
59
- status_text = standard_error_msg + connection_timeout_prompt + error_retrieve_prompt
60
- return status_text
61
- except requests.exceptions.ReadTimeout:
62
- status_text = standard_error_msg + read_timeout_prompt + error_retrieve_prompt
63
- return status_text
64
- except Exception as e:
65
- logging.error(f"获取API使用情况失败:"+str(e))
66
- return standard_error_msg + error_retrieve_prompt
67
-
68
- def get_usage_for_current_month_response(openai_api_key):
69
- headers = {
70
- "Content-Type": "application/json",
71
- "Authorization": f"Bearer {openai_api_key}",
72
- }
73
-
74
- timeout = timeout_all
75
- today = datetime.today()
76
- first_day_of_month = today.replace(day=1).date()
77
- last_day_of_month = get_last_day_of_month(today).date()
78
-
79
- proxies = get_proxies()
80
- response = requests.get(
81
- f"{USAGE_API_URL}?start_date={first_day_of_month}&end_date={last_day_of_month}",
82
- headers=headers,
83
- timeout=timeout,
84
- proxies=proxies,
85
- )
86
 
87
- return response
88
-
89
- def get_dollar_usage_for_current_month(openai_api_key):
90
- try:
91
- response=get_usage_for_current_month_response(openai_api_key=openai_api_key)
92
- usage = 0
93
- upper_limit = "120" # hardcoded as 120 dollars for now
94
- try:
95
- usage = round(response.json().get("total_usage")/100, 2) if response.json().get(
96
- "total_usage") else 0
97
- except Exception as e:
98
- logging.error(f"API使用情况解析失败:"+str(e))
99
- return f"**本月API使用情况**(已用/限额)\u3000${usage} / ${upper_limit}"
100
  except requests.exceptions.ConnectTimeout:
101
  status_text = standard_error_msg + connection_timeout_prompt + error_retrieve_prompt
102
  return status_text
@@ -106,9 +70,3 @@ def get_dollar_usage_for_current_month(openai_api_key):
106
  except Exception as e:
107
  logging.error(f"获取API使用情况失败:"+str(e))
108
  return standard_error_msg + error_retrieve_prompt
109
-
110
- def get_last_day_of_month(any_day):
111
- # The day 28 exists in every month. 4 days later, it's always next month
112
- next_month = any_day.replace(day=28) + timedelta(days=4)
113
- # subtracting the number of the current day brings us back one month
114
- return next_month - timedelta(days=next_month.day)
 
12
 
13
  from modules import shared
14
  from modules.utils import get_proxies
15
+ import os, datetime
 
16
 
17
+ def 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_all
 
24
  proxies = get_proxies()
 
 
 
 
 
25
  response = requests.get(
26
+ billing_url,
27
  headers=headers,
28
  timeout=timeout,
29
  proxies=proxies,
30
  )
31
+
32
+ if response.status_code == 200:
33
+ data = response.json()
34
+ return data
35
+ else:
36
+ raise Exception(f"API request failed with status code {response.status_code}: {response.text}")
37
+
38
 
39
  def get_usage(openai_api_key):
40
  try:
41
+ balance_data=get_billing_data(openai_api_key, BALANCE_API_URL)
42
+ logging.debug(balance_data)
43
  try:
44
+ balance = balance_data["total_available"] if balance_data["total_available"] else 0
45
+ total_used = balance_data["total_used"] if balance_data["total_used"] else 0
 
 
46
  except Exception as e:
47
  logging.error(f"API使用情况解析失败:"+str(e))
48
  balance = 0
49
  total_used=0
50
  return f"**API使用情况解析失败**"
51
+
52
  if balance == 0:
53
+ last_day_of_month = datetime.datetime.now().strftime("%Y-%m-%d")
54
+ first_day_of_month = datetime.datetime.now().replace(day=1).strftime("%Y-%m-%d")
55
+ usage_url = f"{USAGE_API_URL}?start_date={first_day_of_month}&end_date={last_day_of_month}"
56
+ try:
57
+ usage_data = get_billing_data(openai_api_key, usage_url)
58
+ except Exception as e:
59
+ logging.error(f"获取API使用情况失败:"+str(e))
60
+ return f"**获取API使用情况失败**"
61
+ return f"**本月使用金额** \u3000 ${usage_data['total_usage'] / 100}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
 
63
+ return f"**免费额度**(已用/余额)\u3000${total_used} / ${balance}"
 
 
 
 
 
 
 
 
 
 
 
 
64
  except requests.exceptions.ConnectTimeout:
65
  status_text = standard_error_msg + connection_timeout_prompt + error_retrieve_prompt
66
  return status_text
 
70
  except Exception as e:
71
  logging.error(f"获取API使用情况失败:"+str(e))
72
  return standard_error_msg + error_retrieve_prompt