44import random
55import string
66import asyncio
7+ import async_timeout
8+ import aiohttp , aiofiles
79import requests
810import pytz
911import logging
1315from fastapi .responses import JSONResponse , StreamingResponse
1416from starlette .middleware .cors import CORSMiddleware
1517from typing import Any
18+ import g4f
1619from g4f import ChatCompletion , Provider , BaseProvider , models
1720from cachetools import LRUCache
18- import httpx
19- import check
21+
22+ import aiofiles
23+ import async_timeout
24+
25+ from fp .fp import FreeProxy
26+ import concurrent .futures
2027
2128app = FastAPI ()
2229app .add_middleware (GZipMiddleware )
2734 allow_headers = ["*" ],
2835)
2936
30- # Кэш для хранения данных из API
31- api_cache = LRUCache (maxsize = 1000 )
37+ cache_ttl_secs = 600
38+ api_cache = LRUCache (maxseze = 1000 )
39+
40+ def get_proxy ():
41+ proxy = FreeProxy (rand = True , timeout = 1 ).get ()
42+ return proxy
3243
33- # Асинхронная функция для получения данных из API
34- async def get_data_from_api (url : str ) -> Any :
35- if url in api_cache :
36- return api_cache [url ]
37- else :
38- async with httpx .AsyncClient () as client :
39- response = await client .get (url )
40- data = response .json ()
41- api_cache [url ] = data
44+ async def get_data_from_api (url , session ):
45+ async with async_timeout .timeout (cache_ttl_secs ):
46+ async with session .get (url ) as response :
47+ data = await response .json ()
48+ api_cache [url ] = (data , datetime .now ())
4249 return data
4350
4451@app .post ("/chat/completions" )
@@ -93,7 +100,7 @@ async def chat_completions(request: Request):
93100 },
94101 }
95102
96- async def streaming ():
103+ def streaming ():
97104 for chunk in response :
98105 completion_data = {
99106 "id" : f"chatcmpl-{ completion_id } " ,
@@ -110,11 +117,11 @@ async def streaming():
110117 }
111118 ],
112119 }
113-
120+
114121 content = json .dumps (completion_data , separators = ("," , ":" ))
115122 yield f"data: { content } \n \n "
116- await asyncio .sleep (0.1 )
117-
123+ time .sleep (0.1 )
124+
118125 end_completion_data : dict [str , Any ] = {
119126 "id" : f"chatcmpl-{ completion_id } " ,
120127 "object" : "chat.completion.chunk" ,
@@ -130,7 +137,7 @@ async def streaming():
130137 }
131138 content = json .dumps (end_completion_data , separators = ("," , ":" ))
132139 yield f"data: { content } \n \n "
133-
140+
134141 return StreamingResponse (streaming (), media_type = 'text/event-stream' )
135142
136143@app .get ("/v1/dashboard/billing/subscription" )
@@ -248,41 +255,94 @@ async def get_providers():
248255 pass
249256 return JSONResponse (providers_data )
250257
251- def setup_logging ():
252- root_logger = logging .getLogger ()
253- root_logger .setLevel (logging .DEBUG )
258+ def process_provider (provider_name , model_name ):
259+ try :
260+ p = getattr (g4f .Provider , provider_name )
261+ provider_status = {
262+ "provider" : provider_name ,
263+ "model" : model_name ,
264+ "url" : p .url ,
265+ "status" : ""
266+ }
267+
268+ # Проверяем только модель 'gpt-3.5-turbo' для провайдеров Wewordle и Qidinam
269+ if provider_name in ['Wewordle' , 'Qidinam' , 'DeepAi' , 'GetGpt' , 'Yqcloud' ] and model_name != 'gpt-3.5-turbo' :
270+ provider_status ['status' ] = 'Inactive'
271+ #print(f"{provider_name} with {model_name} skipped")
272+ return provider_status
254273
255- handler = logging .StreamHandler ()
256- formatter = logging .Formatter ('%(asctime)s - %(name)s - %(levelname)s - %(message)s' )
257- handler .setFormatter (formatter )
274+ try :
275+ response = ChatCompletion .create (model = model_name , provider = p ,
276+ messages = [{"role" : "user" , "content" : "Say 'Hello World!'" }], stream = False )
277+ if any (word in response for word in ['Hello World' , 'Hello' , 'hello' , 'world' ]):
278+ provider_status ['status' ] = 'Active'
279+ #print(f"{provider_name} with {model_name} say: {response}")
280+ else :
281+ provider_status ['status' ] = 'Inactive'
282+ #print(f"{provider_name} with {model_name} say: Inactive")
283+ except Exception as e :
284+ provider_status ['status' ] = 'Inactive'
285+ # print(f"{provider_name} with {model_name} say: Error")
286+
287+ return provider_status
288+ except :
289+ return None
290+
291+ async def run_check_script ():
292+ session = aiohttp .ClientSession ()
293+ while True :
294+ models = [model for model in g4f .models .ModelUtils .convert if model .startswith ('gpt-' ) or model .startswith ('claude' ) or model .startswith ('text-' )]
295+ providers = [provider for provider in dir (g4f .Provider ) if not provider .startswith ('__' )]
296+
297+ status = {'data' : []}
298+ with concurrent .futures .ThreadPoolExecutor () as executor :
299+ futures = []
300+ for provider_name in providers :
301+ for model_name in models :
302+ future = executor .submit (process_provider , provider_name , model_name )
303+ futures .append (future )
304+
305+ for future in concurrent .futures .as_completed (futures ):
306+ result = future .result ()
307+ if result is not None and result ['status' ] == 'Active' :
308+ status ['data' ].append (result )
258309
259- root_logger .addHandler (handler )
310+ print (status )
311+ status ['key' ] = "test"
312+ tz = pytz .timezone ('Asia/Shanghai' )
313+ now = datetime .now (tz )
314+ print (now )
315+ status ['time' ] = now .strftime ("%Y-%m-%d %H:%M:%S" )
316+
317+ if status ['data' ]:
318+ # Здесь мы используем aiofiles для асинхронного записывания в файл
319+ async with aiofiles .open ('status.json' , 'w' ) as f :
320+ await f .write (json .dumps (status ))
321+
322+ # Pause for 5 minutes before starting the next cycle
323+ time .sleep (360 )
260324
261325# Асинхронная функция для обновления кэша данных из API
262326async def update_api_cache ():
263327 while True :
264328 try :
265329 # Обновление данных каждые 10 минут
266- await asyncio .sleep (600 )
330+ await asyncio .sleep (360 )
267331 api_cache .clear ()
268332 except :
269333 pass
270334
271335# Запуск асинхронных задач
272336async def run_tasks ():
273- tasks = [
274- asyncio .create_task (update_api_cache ())
275- ]
276- await asyncio .gather (* tasks )
277-
337+ while True :
338+ await asyncio .gather (run_check_script ())
339+ await asyncio .sleep (300 )
340+
278341# Запуск приложения
279342def main ():
280- setup_logging ()
281- tz = pytz .timezone ('Asia/Shanghai' )
282- now = datetime .now (tz )
283- print (now )
284- asyncio .run (run_tasks ())
285- check .main ()
343+ loop = asyncio .get_event_loop ()
344+ loop .run_until_complete (run_tasks ())
345+ loop .close ()
286346
287347if __name__ == "__main__" :
288348 main ()
0 commit comments