Update petal.py
This commit is contained in:
parent
886337a866
commit
a54754070e
1 changed files with 18 additions and 16 deletions
|
@ -16,46 +16,48 @@ BASE_COST_GPT_3_5 = Decimal('0.002') # gpt-3.5-turbo: $0.002 / 1K tokens
|
|||
THIRD_PARTY_MULTIPLIER = Decimal('1.5')
|
||||
PROFIT_MULTIPLIER = Decimal('1.1') # At the time we are really just trying to break even
|
||||
PRICE_PER_1K_TOKEN = BASE_COST_GPT_3_5 * THIRD_PARTY_MULTIPLIER * PROFIT_MULTIPLIER
|
||||
USD_TO_CNY = Decimal('7.3') # Assuming 1 USD = 7.3 CNY
|
||||
CNY_TO_PETAL = 100 # 100 petal = 1 CNY
|
||||
|
||||
|
||||
async def get_exchange_rate():
|
||||
async def get_petal_exchange_rate():
|
||||
api_key = Config('exchange_rate_api_key')
|
||||
api_url = f'https://v6.exchangerate-api.com/v6/{api_key}/pair/USD/CNY/1.0'
|
||||
data = await get_url(api_url, 200, fmt='json')
|
||||
if data['result'] == "success":
|
||||
return data['conversion_result']
|
||||
petal_value = data['conversion_result'] * CNY_TO_PETAL
|
||||
return {"petal": petal_value}
|
||||
return None
|
||||
|
||||
|
||||
async def load_or_refresh_cache():
|
||||
cache_dir = Config('cache_path')
|
||||
file_path = os.path.join(cache_dir, 'exchange_rate_cache.json')
|
||||
file_path = os.path.join(cache_dir, 'petal_exchange_rate_cache.json')
|
||||
if os.path.exists(file_path):
|
||||
modified_time = datetime.fromtimestamp(os.path.getmtime(file_path))
|
||||
expiration_time = modified_time + timedelta(days=1)
|
||||
next_day = modified_time + timedelta(days=1)
|
||||
expiration_time = datetime(next_day.year, next_day.month, next_day.day, 0, 0, 0)
|
||||
current_time = datetime.now()
|
||||
if current_time < expiration_time:
|
||||
with open(file_path, 'r') as file:
|
||||
data = json.load(file)
|
||||
return data
|
||||
return data["petal"]
|
||||
|
||||
exchange_rate_data = await get_exchange_rate()
|
||||
if exchange_rate_data:
|
||||
exchanged_petal_data = await get_petal_exchange_rate()
|
||||
if exchanged_petal_data:
|
||||
with open(file_path, 'w') as file:
|
||||
json.dump(exchange_rate_data, file)
|
||||
return exchange_rate_data
|
||||
json.dump(exchanged_petal_data, file)
|
||||
return exchange_rate_data["petal"]
|
||||
return None
|
||||
|
||||
|
||||
async def count_petal(tokens):
|
||||
exchange_rate = await load_or_refresh_cache()
|
||||
if exchange_rate:
|
||||
USD_TO_CNY = Decimal(exchange_rate).quantize(Decimal('0.00'))
|
||||
else:
|
||||
USD_TO_CNY = Decimal('7.3') # Assuming 1 USD = 7.3 CNY
|
||||
CNY_TO_PETAL = 100 # 100 petal = 1 CNY
|
||||
petal_exchange_rate = await load_or_refresh_cache()
|
||||
price = tokens / ONE_K * PRICE_PER_1K_TOKEN
|
||||
petal = price * USD_TO_CNY * CNY_TO_PETAL
|
||||
if petal_exchange_rate:
|
||||
petal = price * Decimal(exchange_rate).quantize(Decimal('0.00'))
|
||||
else:
|
||||
petal = price * USD_TO_CNY * CNY_TO_PETAL
|
||||
return petal
|
||||
|
||||
|
||||
|
|
Reference in a new issue