aibankse / app.py
admin08077's picture
Update app.py
406cdfd verified
import os, subprocess, time, yaml, json, inspect, requests
import gradio as gr
from aibanking import Jocall3
# 1. Start Prism Mock Server
with open(".stats.yml", 'r') as f:
stats = yaml.safe_load(f)
OPENAPI_URL = stats.get('openapi_spec_url')
print(f"πŸš€ Starting Prism Mock Server...")
subprocess.Popen(["prism", "mock", OPENAPI_URL, "-p", "4010", "-h", "0.0.0.0"])
# 2. Get API Key and Wait for Authorization
API_KEY = os.environ.get("X_API_KEY", "default-mock-key")
max_retries = 30
prism_ready = False
for i in range(max_retries):
try:
response = requests.get(
"http://127.0.0.1:4010/system/status",
headers={"x-api-key": API_KEY},
timeout=1
)
if response.status_code < 500:
print("βœ… Prism authorized and ready!")
prism_ready = True
break
except:
print(f"⏳ Waiting for Prism... ({i+1}/{max_retries})")
time.sleep(2)
# 3. Setup SDK Client
client = Jocall3(base_url="http://127.0.0.1:4010", api_key=API_KEY)
# 4. Map the ENTIRE SDK for 152 Endpoints
RESOURCES = {
"Accounts": client.accounts,
"Accounts - Statements": client.accounts.statements,
"Accounts - Transactions": client.accounts.transactions,
"Accounts - Overdraft": client.accounts.overdraft_settings,
"AI - Ads": client.ai.ads,
"AI - Ads Generate": client.ai.ads.generate,
"AI - Advisor": client.ai.advisor,
"AI - Advisor Chat": client.ai.advisor.chat,
"AI - Advisor Tools": client.ai.advisor.tools,
"AI - Agent": client.ai.agent,
"AI - Agent Prompts": client.ai.agent.prompts,
"AI - Incubator": client.ai.incubator,
"AI - Incubator Pitch": client.ai.incubator.pitch,
"AI - Models": client.ai.models,
"AI - Oracle": client.ai.oracle,
"AI - Oracle Predictions": client.ai.oracle.predictions,
"AI - Oracle Simulations": client.ai.oracle.simulations,
"Corporate": client.corporate,
"Corporate - Anomalies": client.corporate.anomalies,
"Corporate - Compliance": client.corporate.compliance,
"Corporate - Compliance Audits": client.corporate.compliance.audits,
"Corporate - Governance": client.corporate.governance,
"Corporate - Gov Proposals": client.corporate.governance.proposals,
"Corporate - Risk": client.corporate.risk,
"Corporate - Fraud": client.corporate.risk.fraud,
"Corporate - Fraud Rules": client.corporate.risk.fraud.rules,
"Corporate - Treasury": client.corporate.treasury,
"Corporate - Treasury CashFlow": client.corporate.treasury.cash_flow,
"Corporate - Treasury Liquidity": client.corporate.treasury.liquidity,
"Corporate - Treasury Sweeping": client.corporate.treasury.sweeping,
"Investments": client.investments,
"Investments - Assets": client.investments.assets,
"Investments - Performance": client.investments.performance,
"Investments - Portfolios": client.investments.portfolios,
"Lending": client.lending,
"Lending - Applications": client.lending.applications,
"Lending - Decisions": client.lending.decisions,
"Marketplace": client.marketplace,
"Marketplace - Offers": client.marketplace.offers,
"Payments": client.payments,
"Payments - Domestic": client.payments.domestic,
"Payments - International": client.payments.international,
"Payments - FX": client.payments.fx,
"Sustainability": client.sustainability,
"Sustainability - Impact": client.sustainability.impact,
"Sustainability - Offsets": client.sustainability.offsets,
"System": client.system,
"System - Notifications": client.system.notifications,
"System - Sandbox": client.system.sandbox,
"System - Verification": client.system.verification,
"System - Webhooks": client.system.webhooks,
"Transactions": client.transactions,
"Transactions - Insights": client.transactions.insights,
"Transactions - Recurring": client.transactions.recurring,
"Users": client.users,
"Users - Password Reset": client.users.password_reset,
"Users - Me": client.users.me,
"Users - Me Biometrics": client.users.me.biometrics,
"Users - Me Devices": client.users.me.devices,
"Users - Me Preferences": client.users.me.preferences,
"Users - Me Security": client.users.me.security,
"Web3": client.web3,
"Web3 - Contracts": client.web3.contracts,
"Web3 - Network": client.web3.network,
"Web3 - NFTs": client.web3.nfts,
"Web3 - Transactions": client.web3.transactions,
"Web3 - Wallets": client.web3.wallets,
}
# --- Logic Handlers ---
def get_methods(res_name):
res = RESOURCES.get(res_name)
methods = [m for m, _ in inspect.getmembers(res, predicate=inspect.ismethod) if not m.startswith('_')]
return gr.Dropdown(choices=sorted(methods))
def generate_payload(res_name, method_name):
try:
res = RESOURCES.get(res_name)
method = getattr(res, method_name)
sig = inspect.signature(method)
payload = {}
for name, param in sig.parameters.items():
if name in ['extra_headers', 'extra_query', 'extra_body', 'timeout', 'self']: continue
if "amount" in name or "deposit" in name or "limit" in name: payload[name] = 1000.0
elif "id" in name or "token" in name or "iban" in name or "bic" in name: payload[name] = "string_id"
elif "bool" in str(param.annotation): payload[name] = True
else: payload[name] = "string"
return json.dumps(payload, indent=2)
except:
return "{}"
def run_api(res_name, method_name, params_json):
try:
res = RESOURCES.get(res_name)
method = getattr(res, method_name)
kwargs = json.loads(params_json) if params_json.strip() else {}
output = method(**kwargs)
if hasattr(output, 'to_dict'): return json.dumps(output.to_dict(), indent=2)
return json.dumps(output, indent=2) if output is not None else "βœ… Success: Command Processed"
except Exception as e:
return f"❌ Error: {str(e)}"
# --- UI Layout ---
with gr.Blocks(theme=gr.themes.Default(primary_hue="blue")) as demo:
gr.Markdown("# πŸ›οΈ Jocall3 SDK Ultimate Explorer")
gr.Markdown("Testing all 152 endpoints of the `aibanking` SDK via Prism Mocking.")
with gr.Row():
with gr.Column(scale=1):
res_choice = gr.Dropdown(sorted(list(RESOURCES.keys())), label="1. Resource Group")
method_choice = gr.Dropdown([], label="2. SDK Method")
params_input = gr.TextArea(label="3. Arguments (Auto-Generated JSON)", lines=12)
run_btn = gr.Button("πŸš€ EXECUTE COMMAND", variant="primary")
with gr.Column(scale=2):
output_display = gr.Code(label="SDK Response", language="json", lines=30)
res_choice.change(get_methods, inputs=res_choice, outputs=method_choice)
method_choice.change(generate_payload, inputs=[res_choice, method_choice], outputs=params_input)
# We name the function run_api here to match the gradio_client requirements
run_btn.click(
run_api,
inputs=[res_choice, method_choice, params_input],
outputs=output_display,
api_name="run_api"
)
if __name__ == "__main__":
demo.launch(server_name="0.0.0.0", server_port=7860)