Delete api
Browse filesFiles changed (10)
- api/__init__.pyDeleted
- api/__pycache__/dummy.txtDeleted-1
- api/app.pyDeleted-41
- api/auth.pyDeleted-10
- api/config.pyDeleted-226
- api/logger.pyDeleted-20
- api/models.pyDeleted-14
- api/routes.pyDeleted-62
- api/utils.pyDeleted-252
- api/validate.pyDeleted-62
1
1234567891011121314151617181920212223242526272829303132333435363738394041from fastapi import FastAPI, Request
from starlette.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from api.logger import setup_logger
from api.routes import router
logger = setup_logger(__name__)
def create_app():
app = FastAPI(
title="NiansuhAI API Gateway",
docs_url=None, # Disable Swagger UI
redoc_url=None, # Disable ReDoc
openapi_url=None, # Disable OpenAPI schema
)
# CORS settings
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # Adjust as needed for security
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Include routes
app.include_router(router)
# Global exception handler for better error reporting
@app.exception_handler(Exception)
async def global_exception_handler(request: Request, exc: Exception):
logger.error(f"An error occurred: {str(exc)}")
return JSONResponse(
status_code=500,
content={"message": "An internal server error occurred."},
)
return app
app = create_app()12345678910from fastapi import Depends, HTTPException
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from api.config import APP_SECRET
security = HTTPBearer()
def verify_app_secret(credentials: HTTPAuthorizationCredentials = Depends(security)):
if credentials.credentials != APP_SECRET:
raise HTTPException(status_code=403, detail="Invalid APP_SECRET")
return credentials.credentials123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226import osfrom dotenv import load_dotenv
load_dotenv()
BASE_URL = "https://www.blackbox.ai"headers = { 'accept': '*/*', 'accept-language': 'zh-CN,zh;q=0.9', 'content-type': 'application/json', 'origin': 'https://www.blackbox.ai', 'priority': 'u=1, i', 'sec-ch-ua': '"Chromium";v="130", "Google Chrome";v="130", "Not?A_Brand";v="99"', 'sec-ch-ua-mobile': '?0', 'sec-ch-ua-platform': '"Windows"', 'sec-fetch-dest': 'empty', 'sec-fetch-mode': 'cors', 'sec-fetch-site': 'same-origin', 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36',}APP_SECRET = os.getenv("APP_SECRET")
ALLOWED_MODELS = [ {"id": "blackboxai", "name": "blackboxai"}, {"id": "blackboxai-pro", "name": "blackboxai-pro"}, {"id": "flux", "name": "flux"}, {"id": "llama-3.1-8b", "name": "llama-3.1-8b"}, {"id": "llama-3.1-70b", "name": "llama-3.1-70b"}, {"id": "llama-3.1-405b", "name": "llama-3.1-405"}, {"id": "gpt-4o", "name": "gpt-4o"}, {"id": "gemini-pro", "name": "gemini-pro"}, {"id": "gemini-1.5-flash", "name": "gemini-1.5-flash"}, {"id": "claude-sonnet-3.5", "name": "claude-sonnet-3.5"}, {"id": "PythonAgent", "name": "PythonAgent"}, {"id": "JavaAgent", "name": "JavaAgent"}, {"id": "JavaScriptAgent", "name": "JavaScriptAgent"}, {"id": "HTMLAgent", "name": "HTMLAgent"}, {"id": "GoogleCloudAgent", "name": "GoogleCloudAgent"}, {"id": "AndroidDeveloper", "name": "AndroidDeveloper"}, {"id": "SwiftDeveloper", "name": "SwiftDeveloper"}, {"id": "Next.jsAgent", "name": "Next.jsAgent"}, {"id": "MongoDBAgent", "name": "MongoDBAgent"}, {"id": "PyTorchAgent", "name": "PyTorchAgent"}, {"id": "ReactAgent", "name": "ReactAgent"}, {"id": "XcodeAgent", "name": "XcodeAgent"}, {"id": "AngularJSAgent", "name": "AngularJSAgent"}, {"id": "HerokuAgent", "name": "HerokuAgent"}, {"id": "GodotAgent", "name": "GodotAgent"}, {"id": "GoAgent", "name": "GoAgent"}, {"id": "GitlabAgent", "name": "GitlabAgent"}, {"id": "GitAgent", "name": "GitAgent"}, {"id": "RepoMap", "name": "RepoMap"}, {"id": "gemini-1.5-pro-latest", "name": "gemini-pro"}, {"id": "gemini-1.5-pro", "name": "gemini-1.5-pro"}, {"id": "claude-3-5-sonnet-20240620", "name": "claude-sonnet-3.5"}, {"id": "claude-3-5-sonnet", "name": "claude-sonnet-3.5"}, {"id": "Niansuh", "name": "Niansuh"}, {"id": "o1-preview", "name": "o1-preview"}, {"id": "claude-3-5-sonnet-20241022", "name": "claude-3-5-sonnet-20241022"}, {"id": "claude-3-5-sonnet-x", "name": "claude-3-5-sonnet-x"}, # Added New Agents {"id": "FlaskAgent", "name": "FlaskAgent"}, {"id": "FirebaseAgent", "name": "FirebaseAgent"}, {"id": "FastAPIAgent", "name": "FastAPIAgent"}, {"id": "ErlangAgent", "name": "ErlangAgent"}, {"id": "ElectronAgent", "name": "ElectronAgent"}, {"id": "DockerAgent", "name": "DockerAgent"}, {"id": "DigitalOceanAgent", "name": "DigitalOceanAgent"}, {"id": "BitbucketAgent", "name": "BitbucketAgent"}, {"id": "AzureAgent", "name": "AzureAgent"}, {"id": "FlutterAgent", "name": "FlutterAgent"}, {"id": "YoutubeAgent", "name": "YoutubeAgent"}, {"id": "builderAgent", "name": "builderAgent"},]
MODEL_MAPPING = { "blackboxai": "blackboxai", "blackboxai-pro": "blackboxai-pro", "flux": "flux", "ImageGeneration": "flux", "llama-3.1-8b": "llama-3.1-8b", "llama-3.1-70b": "llama-3.1-70b", "llama-3.1-405b": "llama-3.1-405", "gpt-4o": "gpt-4o", "gemini-pro": "gemini-pro", "gemini-1.5-flash": "gemini-1.5-flash", "claude-sonnet-3.5": "claude-sonnet-3.5", "PythonAgent": "PythonAgent", "JavaAgent": "JavaAgent", "JavaScriptAgent": "JavaScriptAgent", "HTMLAgent": "HTMLAgent", "GoogleCloudAgent": "GoogleCloudAgent", "AndroidDeveloper": "AndroidDeveloper", "SwiftDeveloper": "SwiftDeveloper", "Next.jsAgent": "Next.jsAgent", "MongoDBAgent": "MongoDBAgent", "PyTorchAgent": "PyTorchAgent", "ReactAgent": "ReactAgent", "XcodeAgent": "XcodeAgent", "AngularJSAgent": "AngularJSAgent", "HerokuAgent": "HerokuAgent", "GodotAgent": "GodotAgent", "GoAgent": "GoAgent", "GitlabAgent": "GitlabAgent", "GitAgent": "GitAgent", "RepoMap": "RepoMap", # Additional mappings "gemini-flash": "gemini-1.5-flash", "claude-3.5-sonnet": "claude-sonnet-3.5", "flux": "flux", "gemini-1.5-pro-latest": "gemini-pro", "gemini-1.5-pro": "gemini-1.5-pro", "claude-3-5-sonnet-20240620": "claude-sonnet-3.5", "claude-3-5-sonnet": "claude-sonnet-3.5", "Niansuh": "Niansuh", "o1-preview": "o1-preview", "claude-3-5-sonnet-20241022": "claude-3-5-sonnet-20241022", "claude-3-5-sonnet-x": "claude-3-5-sonnet-x", # Added New Agents "FlaskAgent": "FlaskAgent", "FirebaseAgent": "FirebaseAgent", "FastAPIAgent": "FastAPIAgent", "ErlangAgent": "ErlangAgent", "ElectronAgent": "ElectronAgent", "DockerAgent": "DockerAgent", "DigitalOceanAgent": "DigitalOceanAgent", "BitbucketAgent": "BitbucketAgent", "AzureAgent": "AzureAgent", "FlutterAgent": "FlutterAgent", "YoutubeAgent": "YoutubeAgent", "builderAgent": "builderAgent",}
# Agent modesAGENT_MODE = { 'flux': {'mode': True, 'id': "ImageGenerationLV45LJp", 'name': "flux"}, 'Niansuh': {'mode': True, 'id': "NiansuhAIk1HgESy", 'name': "Niansuh"}, 'o1-preview': {'mode': True, 'id': "o1Dst8La8", 'name': "o1-preview"}, 'claude-3-5-sonnet-20241022': {'mode': True, 'id': "Claude-Sonnet-3.5zO2HZSF", 'name': "claude-3-5-sonnet-20241022"}, 'claude-3-5-sonnet-x': {'mode': True, 'id': "Claude-Sonnet-3.52022JE0UdQ3", 'name': "claude-3-5-sonnet-x"},}
TRENDING_AGENT_MODE = { "blackboxai": {}, "gemini-1.5-flash": {'mode': True, 'id': 'Gemini'}, "llama-3.1-8b": {'mode': True, 'id': "llama-3.1-8b"}, 'llama-3.1-70b': {'mode': True, 'id': "llama-3.1-70b"}, 'llama-3.1-405b': {'mode': True, 'id': "llama-3.1-405"}, 'blackboxai-pro': {'mode': True, 'id': "BLACKBOXAI-PRO"}, 'PythonAgent': {'mode': True, 'id': "Python Agent"}, 'JavaAgent': {'mode': True, 'id': "Java Agent"}, 'JavaScriptAgent': {'mode': True, 'id': "JavaScript Agent"}, 'HTMLAgent': {'mode': True, 'id': "HTML Agent"}, 'GoogleCloudAgent': {'mode': True, 'id': "Google Cloud Agent"}, 'AndroidDeveloper': {'mode': True, 'id': "Android Developer"}, 'SwiftDeveloper': {'mode': True, 'id': "Swift Developer"}, 'Next.jsAgent': {'mode': True, 'id': "Next.js Agent"}, 'MongoDBAgent': {'mode': True, 'id': "MongoDB Agent"}, 'PyTorchAgent': {'mode': True, 'id': "PyTorch Agent"}, 'ReactAgent': {'mode': True, 'id': "React Agent"}, 'XcodeAgent': {'mode': True, 'id': "Xcode Agent"}, 'AngularJSAgent': {'mode': True, 'id': "AngularJS Agent"}, 'HerokuAgent': {'mode': True, 'id': "HerokuAgent"}, 'GodotAgent': {'mode': True, 'id': "GodotAgent"}, 'GoAgent': {'mode': True, 'id': "GoAgent"}, 'GitlabAgent': {'mode': True, 'id': "GitlabAgent"}, 'GitAgent': {'mode': True, 'id': "GitAgent"}, 'RepoMap': {'mode': True, 'id': "repomap"}, # Added New Agents 'FlaskAgent': {'mode': True, 'id': "FlaskAgent"}, 'FirebaseAgent': {'mode': True, 'id': "FirebaseAgent"}, 'FastAPIAgent': {'mode': True, 'id': "FastAPIAgent"}, 'ErlangAgent': {'mode': True, 'id': "ErlangAgent"}, 'ElectronAgent': {'mode': True, 'id': "ElectronAgent"}, 'DockerAgent': {'mode': True, 'id': "DockerAgent"}, 'DigitalOceanAgent': {'mode': True, 'id': "DigitalOceanAgent"}, 'BitbucketAgent': {'mode': True, 'id': "BitbucketAgent"}, 'AzureAgent': {'mode': True, 'id': "AzureAgent"}, 'FlutterAgent': {'mode': True, 'id': "FlutterAgent"}, 'YoutubeAgent': {'mode': True, 'id': "YoutubeAgent"}, 'builderAgent': {'mode': True, 'id': "builderAgent"},}
# Model prefixesMODEL_PREFIXES = { 'gpt-4o': '@GPT-4o', 'gemini-pro': '@Gemini-PRO', 'PythonAgent': '@Python Agent', 'JavaAgent': '@Java Agent', 'JavaScriptAgent': '@JavaScript Agent', 'HTMLAgent': '@HTML Agent', 'GoogleCloudAgent': '@Google Cloud Agent', 'AndroidDeveloper': '@Android Developer', 'SwiftDeveloper': '@Swift Developer', 'Next.jsAgent': '@Next.js Agent', 'MongoDBAgent': '@MongoDB Agent', 'PyTorchAgent': '@PyTorch Agent', 'ReactAgent': '@React Agent', 'XcodeAgent': '@Xcode Agent', 'AngularJSAgent': '@AngularJS Agent', 'HerokuAgent': '@Heroku Agent', 'GodotAgent': '@Godot Agent', 'GoAgent': '@Go Agent', 'GitlabAgent': '@Gitlab Agent', 'GitAgent': '@Gitlab Agent', 'blackboxai-pro': '@BLACKBOXAI-PRO', 'flux': '@Image Generation', # Add any additional prefixes if necessary # Added New Agents 'FlaskAgent': '@Flask Agent', 'FirebaseAgent': '@Firebase Agent', 'FastAPIAgent': '@FastAPI Agent', 'ErlangAgent': '@Erlang Agent', 'ElectronAgent': '@Electron Agent', 'DockerAgent': '@Docker Agent', 'DigitalOceanAgent': '@DigitalOcean Agent', 'BitbucketAgent': '@Bitbucket Agent', 'AzureAgent': '@Azure Agent', 'FlutterAgent': '@Flutter Agent', 'YoutubeAgent': '@Youtube Agent', 'builderAgent': '@builder Agent',}1234567891011121314151617181920import logging
def setup_logger(name): logger = logging.getLogger(name) if not logger.handlers: logger.setLevel(logging.INFO) # Set to INFO to avoid DEBUG logs in production formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
# Console handler console_handler = logging.StreamHandler() console_handler.setFormatter(formatter) logger.addHandler(console_handler)
# File handler for errors (optional) # error_file_handler = logging.FileHandler('error.log') # error_file_handler.setFormatter(formatter) # error_file_handler.setLevel(logging.ERROR) # logger.addHandler(error_file_handler)
return logger1234567891011121314from typing import List, Optional
from pydantic import BaseModel
class Message(BaseModel):
role: str
content: str | list
class ChatRequest(BaseModel):
model: str
messages: List[Message]
stream: Optional[bool] = False
temperature: Optional[float] = 0.5
top_p: Optional[float] = 0.9
max_tokens: Optional[int] = 999999991234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162import jsonfrom fastapi import APIRouter, Depends, HTTPException, Request, Responsefrom fastapi.responses import StreamingResponsefrom api.auth import verify_app_secretfrom api.config import ALLOWED_MODELSfrom api.models import ChatRequestfrom api.utils import process_non_streaming_response, process_streaming_responsefrom api.logger import setup_logger
logger = setup_logger(__name__)
router = APIRouter()
@router.options("/v1/chat/completions")@router.options("/api/v1/chat/completions")async def chat_completions_options(): return Response( status_code=200, headers={ "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Methods": "POST, OPTIONS", "Access-Control-Allow-Headers": "Content-Type, Authorization", }, )
@router.get("/v1/models")@router.get("/api/v1/models")async def list_models(): return {"object": "list", "data": ALLOWED_MODELS}
@router.post("/v1/chat/completions")@router.post("/api/v1/chat/completions")async def chat_completions( request: ChatRequest, app_secret: str = Depends(verify_app_secret)): logger.info("Entering chat_completions route") logger.info(f"Received request: {request}") logger.info(f"App secret: {app_secret}") logger.info(f"Received chat completion request for model: {request.model}")
if request.model not in [model["id"] for model in ALLOWED_MODELS]: raise HTTPException( status_code=400, detail=f"Model {request.model} is not allowed. Allowed models are: {', '.join(model['id'] for model in ALLOWED_MODELS)}", )
if request.stream: logger.info("Streaming response") return StreamingResponse(process_streaming_response(request), media_type="text/event-stream") else: logger.info("Non-streaming response") return await process_non_streaming_response(request)
@router.route('/') @router.route('/healthz') @router.route('/ready') @router.route('/alive') @router.route('/status') @router.get("/health")def health_check(request: Request): return Response(content=json.dumps({"status": "ok"}), media_type="application/json") 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252from datetime import datetimefrom http.client import HTTPExceptionimport jsonfrom typing import Any, Dict, Optionalimport uuid
import httpxfrom api import validatefrom api.config import MODEL_MAPPING, headers, AGENT_MODE, TRENDING_AGENT_MODEfrom fastapi import Depends, HTTPException as FastAPIHTTPExceptionfrom fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from api.config import APP_SECRET, BASE_URLfrom api.models import ChatRequest
from api.logger import setup_logger
logger = setup_logger(__name__)
# Initialize HTTPBearer for security dependencysecurity = HTTPBearer()
def create_chat_completion_data( content: str, model: str, timestamp: int, finish_reason: Optional[str] = None) -> Dict[str, Any]: """ Create a dictionary representing a chat completion chunk.
Args: content (str): The content of the message. model (str): The model used for the chat. timestamp (int): The timestamp of the creation. finish_reason (Optional[str], optional): The reason for finishing. Defaults to None.
Returns: Dict[str, Any]: A dictionary representing the chat completion chunk. """ return { "id": f"chatcmpl-{uuid.uuid4()}", "object": "chat.completion.chunk", "created": timestamp, "model": model, "choices": [ { "index": 0, "delta": {"content": content, "role": "assistant"}, "finish_reason": finish_reason, } ], "usage": None, }
def verify_app_secret(credentials: HTTPAuthorizationCredentials = Depends(security)): """ Verify the application secret from the HTTP authorization credentials.
Args: credentials (HTTPAuthorizationCredentials, optional): The HTTP authorization credentials. Defaults to Depends(security).
Raises: HTTPException: If the APP_SECRET does not match.
Returns: str: The verified credentials. """ if credentials.credentials != APP_SECRET: raise FastAPIHTTPException(status_code=403, detail="Invalid APP_SECRET") return credentials.credentials
def message_to_dict(message): """ Convert a message object to a dictionary.
Args: message: The message object to convert.
Returns: Dict[str, Any]: The dictionary representation of the message. """ if isinstance(message.content, str): return {"role": message.role, "content": message.content} elif isinstance(message.content, list) and len(message.content) == 2: return { "role": message.role, "content": message.content[0]["text"], "data": { "imageBase64": message.content[1]["image_url"]["url"], "fileText": "", "title": "snapshot", }, } else: return {"role": message.role, "content": message.content}
async def process_streaming_response(request: ChatRequest): """ Process a streaming response from the chat API.
Args: request (ChatRequest): The chat request containing all necessary information.
Yields: str: The streaming data chunks formatted as server-sent events. """ agent_mode = AGENT_MODE.get(request.model, {}) trending_agent_mode = TRENDING_AGENT_MODE.get(request.model, {})
# Log reduced information logger.info( f"Streaming request for model: '{request.model}', " f"agent mode: {agent_mode}, trending agent mode: {trending_agent_mode}" )
json_data = { "messages": [message_to_dict(msg) for msg in request.messages], "previewToken": None, "userId": None, "codeModelMode": True, "agentMode": agent_mode, "trendingAgentMode": trending_agent_mode, "isMicMode": False, "userSystemPrompt": None, "maxTokens": request.max_tokens, "playgroundTopP": request.top_p, "playgroundTemperature": request.temperature, "isChromeExt": False, "githubToken": None, "clickedAnswer2": False, "clickedAnswer3": False, "clickedForceWebSearch": False, "visitFromDelta": False, "mobileClient": False, "userSelectedModel": MODEL_MAPPING.get(request.model), "validated": validate.getHid() }
async with httpx.AsyncClient() as client: try: async with client.stream( "POST", f"{BASE_URL}/api/chat", headers=headers, json=json_data, timeout=100, ) as response: response.raise_for_status() timestamp = int(datetime.now().timestamp()) async for line in response.aiter_lines(): if line: content = line + "\n" if "https://www.blackbox.ai" in content: validate.getHid(True) content = "Hid has been refreshed; feel free to restart the conversation.\n" yield f"data: {json.dumps(create_chat_completion_data(content, request.model, timestamp))}\n\n" break # Remove the specific pattern without affecting markdown content = content.replace("$@$v=undefined-rv1$@$", "") yield f"data: {json.dumps(create_chat_completion_data(content, request.model, timestamp))}\n\n"
# Indicate the end of the stream yield f"data: {json.dumps(create_chat_completion_data('', request.model, timestamp, 'stop'))}\n\n" yield "data: [DONE]\n\n" except httpx.HTTPStatusError as e: logger.error(f"HTTP error occurred: {e}") raise FastAPIHTTPException(status_code=e.response.status_code, detail=str(e)) except httpx.RequestError as e: logger.error(f"Error occurred during request: {e}") raise FastAPIHTTPException(status_code=500, detail=str(e))
async def process_non_streaming_response(request: ChatRequest): """ Process a non-streaming response from the chat API.
Args: request (ChatRequest): The chat request containing all necessary information.
Returns: Dict[str, Any]: The full response from the chat API formatted appropriately. """ agent_mode = AGENT_MODE.get(request.model, {}) trending_agent_mode = TRENDING_AGENT_MODE.get(request.model, {})
# Log reduced information logger.info( f"Non-streaming request for model: '{request.model}', " f"agent mode: {agent_mode}, trending agent mode: {trending_agent_mode}" )
json_data = { "messages": [message_to_dict(msg) for msg in request.messages], "previewToken": None, "userId": None, "codeModelMode": True, "agentMode": agent_mode, "trendingAgentMode": trending_agent_mode, "isMicMode": False, "userSystemPrompt": None, "maxTokens": request.max_tokens, "playgroundTopP": request.top_p, "playgroundTemperature": request.temperature, "isChromeExt": False, "githubToken": None, "clickedAnswer2": False, "clickedAnswer3": False, "clickedForceWebSearch": False, "visitFromDelta": False, "mobileClient": False, "userSelectedModel": MODEL_MAPPING.get(request.model), "validated": validate.getHid() }
full_response = "" async with httpx.AsyncClient() as client: try: async with client.stream( method="POST", url=f"{BASE_URL}/api/chat", headers=headers, json=json_data, timeout=100, ) as response: response.raise_for_status() async for chunk in response.aiter_text(): full_response += chunk
if "https://www.blackbox.ai" in full_response: validate.getHid(True) full_response = "Hid has been refreshed; feel free to restart the conversation."
# Remove the specific pattern without affecting markdown full_response = full_response.replace("$@$v=undefined-rv1$@$", "")
return { "id": f"chatcmpl-{uuid.uuid4()}", "object": "chat.completion", "created": int(datetime.now().timestamp()), "model": request.model, "choices": [ { "index": 0, "message": {"role": "assistant", "content": full_response}, "finish_reason": "stop", } ], "usage": None, } except httpx.HTTPStatusError as e: logger.error(f"HTTP error occurred: {e}") raise FastAPIHTTPException(status_code=e.response.status_code, detail=str(e)) except httpx.RequestError as e: logger.error(f"Error occurred during request: {e}") raise FastAPIHTTPException(status_code=500, detail=str(e))1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162import requestsimport reimport time
base_url = "https://www.blackbox.ai"headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"}
# Cache variablescached_hid = Nonecache_time = 0CACHE_DURATION = 36000 # Cache duration in seconds (10 hour)
def getHid(force_refresh=False): global cached_hid, cache_time current_time = time.time()
# Check if a forced refresh is needed or if the cached values are still valid. if not force_refresh and cached_hid and (current_time - cache_time) < CACHE_DURATION: print("using cached_hid:", cached_hid) return cached_hid
try: # Retrieve the initial HTML content. response = requests.get(base_url, headers=headers) response.raise_for_status() content = response.text
# Use a regular expression to find specific `static/chunks` paths. pattern = r"static/chunks/app/layout-[a-zA-Z0-9]+\.js" match = re.search(pattern, content)
if match: # Construct the full URL of the JS file. js_path = match.group() full_url = f"{base_url}/_next/{js_path}"
# Request the content of the JS file. js_response = requests.get(full_url, headers=headers) js_response.raise_for_status()
# In JS content, use a regular expression to search for h-value. h_pattern = r'h="([0-9a-f-]+)"' h_match = re.search(h_pattern, js_response.text)
if h_match: h_value = h_match.group(1) print("Found the h-value.", h_value) # Update the cache. cached_hid = h_value cache_time = current_time return h_value else: print("The h-value was not found in the JS content.") return None else: print("The specified JS file path was not found in the HTML content.") return None except requests.exceptions.RequestException as e: print(f"An error occurred. {e}") return Noneapi/__init__.pyDeleted
api/__pycache__/dummy.txtDeleted-1
api/app.pyDeleted-41
api/auth.pyDeleted-10
api/config.pyDeleted-226
api/logger.pyDeleted-20
api/models.pyDeleted-14
api/routes.pyDeleted-62
api/utils.pyDeleted-252
api/validate.pyDeleted-62