admin08077 commited on
Commit
1a7d39e
·
verified ·
1 Parent(s): 940ae8c

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +929 -0
app.py ADDED
@@ -0,0 +1,929 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Import necessary libraries
2
+ import streamlit as st
3
+ import requests
4
+ import base64
5
+ import uuid
6
+ import os
7
+ import hashlib
8
+ from datetime import datetime, date, timedelta
9
+ from dotenv import load_dotenv
10
+ import pandas as pd
11
+ from sklearn.ensemble import IsolationForest # For anomaly detection
12
+ from cryptography.fernet import Fernet # For encryption
13
+ import jwt # For JWT authentication
14
+ from sklearn.linear_model import LinearRegression # For predictive analytics
15
+ import numpy as np
16
+ import stripe
17
+ import plotly.express as px
18
+ from qiskit import Aer, QuantumCircuit, execute # For quantum computing simulation
19
+ from web3 import Web3 # For blockchain interaction
20
+ from web3.middleware import geth_poa_middleware # For Infura with PoA networks
21
+ import openai # For OpenAI ChatGPT integration
22
+ from github import Github # For GitHub API
23
+ from huggingface_hub import HfApi, HfFolder, Repository # For Hugging Face API
24
+ from requests.auth import HTTPBasicAuth
25
+ from oauthlib.oauth1 import Client # For MasterCard OAuth1
26
+ import json
27
+ import cv2
28
+ from pyzbar import pyzbar
29
+ from streamlit_webrtc import webrtc_streamer, VideoTransformerBase
30
+
31
+ # Set page config
32
+ st.set_page_config(
33
+ page_title="TransactPro: The Ultimate Financial Platform",
34
+ page_icon="💳",
35
+ layout="wide",
36
+ )
37
+
38
+ # Load environment variables securely
39
+ def load_env_vars():
40
+ load_dotenv()
41
+ env_vars = os.environ
42
+ return env_vars
43
+
44
+ env_vars = load_env_vars()
45
+
46
+ # Securely retrieve API keys
47
+ def get_env_var(key):
48
+ return env_vars.get(key)
49
+
50
+ # Initialize API keys and configurations
51
+ stripe.api_key = get_env_var('STRIPE_API_KEY')
52
+ plaid_client_id = get_env_var('PLAID_CLIENT_ID')
53
+ plaid_secret = get_env_var('PLAID_SECRET')
54
+ plaid_env = get_env_var('PLAID_ENV') or 'sandbox'
55
+ citibank_client_id = get_env_var('CITIBANK_CLIENT_ID')
56
+ citibank_client_secret = get_env_var('CITIBANK_CLIENT_SECRET')
57
+ citibank_api_key = get_env_var('CITIBANK_API_KEY')
58
+ mt_api_key = get_env_var('MT_API_KEY')
59
+ mt_organization_id = get_env_var('MT_ORG_ID')
60
+ github_token = get_env_var('GITHUB_TOKEN')
61
+ huggingface_token = get_env_var('HUGGINGFACE_TOKEN')
62
+ openai_api_key = get_env_var('OPENAI_API_KEY')
63
+ infura_project_id = get_env_var('INFURA_PROJECT_ID')
64
+ metamask_account_address = get_env_var('METAMASK_ACCOUNT_ADDRESS')
65
+ metamask_private_key = get_env_var('METAMASK_PRIVATE_KEY')
66
+ visa_api_key = get_env_var('VISA_API_KEY')
67
+ visa_api_secret = get_env_var('VISA_API_SECRET')
68
+ visa_cert_path = get_env_var('VISA_CERT_PATH')
69
+ mastercard_consumer_key = get_env_var('MASTERCARD_CONSUMER_KEY')
70
+ mastercard_private_key = get_env_var('MASTERCARD_PRIVATE_KEY')
71
+ pipedream_url = get_env_var('PIPEDREAM_URL')
72
+
73
+ # Set OpenAI API key
74
+ openai.api_key = openai_api_key
75
+
76
+ # Initialize Web3
77
+ if infura_project_id:
78
+ infura_url = f"https://mainnet.infura.io/v3/{infura_project_id}"
79
+ web3 = Web3(Web3.HTTPProvider(infura_url))
80
+ # For PoA networks like Ropsten or Rinkeby, use the following line
81
+ # web3.middleware_onion.inject(geth_poa_middleware, layer=0)
82
+ else:
83
+ web3 = None
84
+
85
+ # Initialize GitHub and Hugging Face clients
86
+ github_client = Github(github_token) if github_token else None
87
+ hf_api = HfApi()
88
+ if huggingface_token:
89
+ HfFolder.save_token(huggingface_token)
90
+ else:
91
+ huggingface_token = HfFolder.get_token()
92
+
93
+ # Initialize Plaid client
94
+ from plaid.api import plaid_api
95
+ from plaid.model import *
96
+ from plaid.api_client import ApiClient
97
+ from plaid.configuration import Configuration
98
+
99
+ plaid_environment = {
100
+ 'sandbox': plaid.Environment.Sandbox,
101
+ 'development': plaid.Environment.Development,
102
+ 'production': plaid.Environment.Production,
103
+ }
104
+
105
+ plaid_config = Configuration(
106
+ host=plaid_environment.get(plaid_env, plaid.Environment.Sandbox),
107
+ api_key={
108
+ 'clientId': plaid_client_id,
109
+ 'secret': plaid_secret,
110
+ }
111
+ )
112
+ plaid_api_client = ApiClient(plaid_config)
113
+ plaid_client = plaid_api.PlaidApi(plaid_api_client)
114
+
115
+ # JWT Authentication
116
+ def authenticate_user():
117
+ st.sidebar.title("User Authentication")
118
+ username = st.sidebar.text_input("Username")
119
+ password = st.sidebar.text_input("Password", type="password")
120
+ if st.sidebar.button("Login"):
121
+ # Hash the password (Use a secure method in production)
122
+ hashed_password = hashlib.sha256(password.encode()).hexdigest()
123
+ # Check credentials (Replace with real authentication)
124
+ if username == 'user' and hashed_password == hashlib.sha256("password".encode()).hexdigest():
125
+ token = jwt.encode({'user': username}, 'secret', algorithm='HS256')
126
+ st.session_state['auth_token'] = token
127
+ st.success("Logged in successfully!")
128
+ else:
129
+ st.error("Invalid username or password")
130
+
131
+ if 'auth_token' not in st.session_state:
132
+ authenticate_user()
133
+ else:
134
+ # Proceed with the application
135
+
136
+ # Title of the app
137
+ st.title("TransactPro: The Ultimate Financial Platform")
138
+ st.sidebar.header("Navigation")
139
+
140
+ # Main application navigation
141
+ service_choice = st.sidebar.selectbox("Choose a Service", [
142
+ "Dashboard",
143
+ "In-Store Scanner & Payment",
144
+ "Citibank Services",
145
+ "Plaid Services",
146
+ "Stripe Services",
147
+ "Modern Treasury Services",
148
+ "GitHub Integration",
149
+ "Hugging Face Integration",
150
+ "Blockchain Integration",
151
+ "Visa Services",
152
+ "MasterCard Services",
153
+ "Pipedream Integration",
154
+ "Financial Analysis",
155
+ "Budgeting Tools",
156
+ "AI Chatbot",
157
+ "Quantum Portfolio Optimization",
158
+ ])
159
+
160
+ # In-Store Scanner & Payment
161
+ if service_choice == "In-Store Scanner & Payment":
162
+ st.header("In-Store Item Scanner and Payment")
163
+
164
+ # Mock database of items
165
+ ITEM_DATABASE = {
166
+ "123456789012": {"name": "Product A", "price": 9.99},
167
+ "987654321098": {"name": "Product B", "price": 19.99},
168
+ # Add more items as needed
169
+ }
170
+
171
+ # Function to get item details
172
+ def get_item_details(code):
173
+ return ITEM_DATABASE.get(code)
174
+
175
+ # Video transformer for barcode scanning
176
+ class BarcodeScanner(VideoTransformerBase):
177
+ def __init__(self):
178
+ self.result = None
179
+
180
+ def transform(self, frame):
181
+ image = frame.to_ndarray(format="bgr24")
182
+ barcodes = pyzbar.decode(image)
183
+
184
+ for barcode in barcodes:
185
+ (x, y, w, h) = barcode.rect
186
+ cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)
187
+
188
+ barcode_data = barcode.data.decode("utf-8")
189
+ barcode_type = barcode.type
190
+
191
+ text = f"{barcode_data} ({barcode_type})"
192
+ cv2.putText(image, text, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
193
+ self.result = barcode_data
194
+
195
+ return image
196
+
197
+ st.write("Scan an item to view details and purchase.")
198
+
199
+ # Start barcode scanner
200
+ barcode_scanner = BarcodeScanner()
201
+ webrtc_ctx = webrtc_streamer(
202
+ key="barcode-scanner",
203
+ video_transformer_factory=lambda: barcode_scanner,
204
+ async_transform=True,
205
+ )
206
+
207
+ if webrtc_ctx.video_transformer:
208
+ barcode_data = barcode_scanner.result
209
+ if barcode_data:
210
+ item_details = get_item_details(barcode_data)
211
+ if item_details:
212
+ st.success(f"Item Scanned: {item_details['name']}")
213
+ st.write(f"Price: ${item_details['price']:.2f}")
214
+
215
+ if st.button("Purchase"):
216
+ # Process payment
217
+ try:
218
+ # In a real application, collect payment details securely
219
+ # For demonstration, we'll simulate a successful payment
220
+ st.write("Payment processed successfully.")
221
+
222
+ # Update Modern Treasury ledger
223
+ mt_response = create_mt_ledger_transaction(
224
+ amount=item_details['price'],
225
+ description=f"Purchase of {item_details['name']}"
226
+ )
227
+ if mt_response:
228
+ st.write("Ledger updated successfully.")
229
+ else:
230
+ st.write("Failed to update ledger.")
231
+ except Exception as e:
232
+ st.error(f"Error processing payment: {e}")
233
+ else:
234
+ st.error("Item not found in database.")
235
+
236
+ def create_mt_ledger_transaction(amount, description):
237
+ url = "https://app.moderntreasury.com/api/ledger_transactions"
238
+ credentials = f"{mt_organization_id}:{mt_api_key}"
239
+ base64_credentials = base64.b64encode(credentials.encode()).decode('utf-8')
240
+ headers = {
241
+ "Authorization": f"Basic {base64_credentials}",
242
+ "Content-Type": "application/json",
243
+ "Accept": "application/json"
244
+ }
245
+ data = {
246
+ "description": description,
247
+ "status": "posted",
248
+ "ledger_entries": [
249
+ {
250
+ "amount": int(amount * 100), # Convert to cents
251
+ "direction": "debit",
252
+ "ledger_account_id": "ledger_account_id_debit", # Replace with your ledger account ID
253
+ },
254
+ {
255
+ "amount": int(amount * 100),
256
+ "direction": "credit",
257
+ "ledger_account_id": "ledger_account_id_credit", # Replace with your ledger account ID
258
+ },
259
+ ]
260
+ }
261
+ response = requests.post(url, headers=headers, json=data)
262
+ if response.status_code in [200, 201]:
263
+ return response.json()
264
+ else:
265
+ st.error(f"Modern Treasury Error: {response.text}")
266
+ return None
267
+
268
+ # Citibank Services
269
+ elif service_choice == "Citibank Services":
270
+ st.header("Citibank Services")
271
+
272
+ # Citibank API class
273
+ class CitibankAPI:
274
+ def __init__(self, client_id, client_secret, api_key):
275
+ self.client_id = client_id
276
+ self.client_secret = client_secret
277
+ self.api_key = api_key
278
+ self.access_token = self.get_access_token()
279
+ self.base_url = "https://sandbox.apihub.citi.com/gcb/api/v1"
280
+
281
+ def get_access_token(self):
282
+ url = "https://sandbox.apihub.citi.com/gcb/api/clientCredentials/oauth2/token/us/gcb"
283
+ headers = {
284
+ 'Authorization': 'Basic ' + base64.b64encode((self.client_id + ':' + self.client_secret).encode()).decode(),
285
+ 'Content-Type': 'application/x-www-form-urlencoded'
286
+ }
287
+ data = 'grant_type=client_credentials&scope=/api'
288
+ response = requests.post(url, headers=headers, data=data)
289
+ if response.status_code == 200:
290
+ return response.json().get('access_token')
291
+ else:
292
+ st.error("Failed to obtain Citibank access token.")
293
+ return None
294
+
295
+ def get_accounts(self):
296
+ url = f"{self.base_url}/accounts"
297
+ headers = {
298
+ 'Authorization': f"Bearer {self.access_token}",
299
+ 'Accept': 'application/json'
300
+ }
301
+ response = requests.get(url, headers=headers)
302
+ return response.json()
303
+
304
+ def get_account_details(self, account_id):
305
+ url = f"{self.base_url}/accounts/{account_id}"
306
+ headers = {
307
+ 'Authorization': f"Bearer {self.access_token}",
308
+ 'Accept': 'application/json'
309
+ }
310
+ response = requests.get(url, headers=headers)
311
+ return response.json()
312
+
313
+ def create_account(self, account_data):
314
+ url = f"{self.base_url}/accounts"
315
+ headers = {
316
+ 'Authorization': f"Bearer {self.access_token}",
317
+ 'Content-Type': 'application/json',
318
+ 'Accept': 'application/json'
319
+ }
320
+ response = requests.post(url, headers=headers, json=account_data)
321
+ return response.json()
322
+
323
+ def initiate_payment(self, payment_data):
324
+ url = f"{self.base_url}/payments"
325
+ headers = {
326
+ 'Authorization': f"Bearer {self.access_token}",
327
+ 'Content-Type': 'application/json',
328
+ 'Accept': 'application/json'
329
+ }
330
+ response = requests.post(url, headers=headers, json=payment_data)
331
+ return response.json()
332
+
333
+ citibank_api_instance = CitibankAPI(citibank_client_id, citibank_client_secret, citibank_api_key)
334
+ citibank_action = st.selectbox("Choose an Action", [
335
+ "View Accounts",
336
+ "View Account Details",
337
+ "Create Account",
338
+ "Initiate Payment",
339
+ ])
340
+
341
+ if citibank_action == "View Accounts":
342
+ accounts = citibank_api_instance.get_accounts()
343
+ st.json(accounts)
344
+ elif citibank_action == "View Account Details":
345
+ account_id = st.text_input("Enter Account ID")
346
+ if st.button("Get Account Details"):
347
+ details = citibank_api_instance.get_account_details(account_id)
348
+ st.json(details)
349
+ elif citibank_action == "Create Account":
350
+ st.subheader("Create a New Account")
351
+ account_name = st.text_input("Account Name")
352
+ account_type = st.selectbox("Account Type", ["Savings", "Checking"])
353
+ currency = st.text_input("Currency", value="USD")
354
+ if st.button("Create Account"):
355
+ account_data = {
356
+ "accountName": account_name,
357
+ "accountType": account_type,
358
+ "currency": currency
359
+ }
360
+ result = citibank_api_instance.create_account(account_data)
361
+ st.json(result)
362
+ elif citibank_action == "Initiate Payment":
363
+ st.subheader("Initiate a Payment")
364
+ from_account = st.text_input("From Account ID")
365
+ to_account = st.text_input("To Account Number")
366
+ amount = st.number_input("Amount", min_value=0.0)
367
+ currency = st.text_input("Currency", value="USD")
368
+ description = st.text_input("Description")
369
+ if st.button("Initiate Payment"):
370
+ payment_data = {
371
+ "sourceAccountId": from_account,
372
+ "transactionAmount": {
373
+ "amount": amount,
374
+ "currency": currency
375
+ },
376
+ "destinationAccountNumber": to_account,
377
+ "paymentMethod": "InternalTransfer",
378
+ "paymentCurrency": currency,
379
+ "remarks": description
380
+ }
381
+ result = citibank_api_instance.initiate_payment(payment_data)
382
+ st.json(result)
383
+
384
+ # Plaid Services
385
+ elif service_choice == "Plaid Services":
386
+ st.header("Plaid Services")
387
+ if not plaid_client_id or not plaid_secret:
388
+ st.error("Please provide Plaid API credentials.")
389
+ else:
390
+ plaid_action = st.selectbox("Choose an Action", [
391
+ "Link Account",
392
+ "Get Accounts",
393
+ "Get Transactions",
394
+ ])
395
+
396
+ if 'plaid_access_token' not in st.session_state:
397
+ st.session_state['plaid_access_token'] = None
398
+
399
+ if plaid_action == "Link Account":
400
+ st.subheader("Link a Bank Account")
401
+ # Create link token
402
+ user_id = str(uuid.uuid4())
403
+ request = LinkTokenCreateRequest(
404
+ products=[Products('transactions')],
405
+ client_name='TransactPro',
406
+ country_codes=[CountryCode('US')],
407
+ language='en',
408
+ user=LinkTokenCreateRequestUser(client_user_id=user_id)
409
+ )
410
+ response = plaid_client.link_token_create(request)
411
+ link_token = response['link_token']
412
+ st.write("Use this link token in your frontend to initialize Plaid Link.")
413
+ st.code(link_token)
414
+ st.session_state['plaid_link_token'] = link_token
415
+ elif plaid_action == "Get Accounts":
416
+ if st.session_state['plaid_access_token']:
417
+ accounts_request = AccountsGetRequest(access_token=st.session_state['plaid_access_token'])
418
+ accounts_response = plaid_client.accounts_get(accounts_request)
419
+ st.json(accounts_response.to_dict())
420
+ else:
421
+ st.error("No access token available. Please link an account first.")
422
+ elif plaid_action == "Get Transactions":
423
+ if st.session_state['plaid_access_token']:
424
+ start_date = (date.today() - timedelta(days=30)).strftime('%Y-%m-%d')
425
+ end_date = date.today().strftime('%Y-%m-%d')
426
+ transactions_request = TransactionsGetRequest(
427
+ access_token=st.session_state['plaid_access_token'],
428
+ start_date=start_date,
429
+ end_date=end_date
430
+ )
431
+ transactions_response = plaid_client.transactions_get(transactions_request)
432
+ st.json(transactions_response.to_dict())
433
+ else:
434
+ st.error("No access token available. Please link an account first.")
435
+
436
+ # Stripe Services
437
+ elif service_choice == "Stripe Services":
438
+ st.header("Stripe Services")
439
+ stripe_action = st.selectbox("Choose an Action", [
440
+ "Create Customer",
441
+ "Charge Customer",
442
+ "View Charges",
443
+ ])
444
+
445
+ if stripe_action == "Create Customer":
446
+ st.subheader("Create a New Customer")
447
+ email = st.text_input("Customer Email")
448
+ description = st.text_input("Description")
449
+ if st.button("Create Customer"):
450
+ customer = stripe.Customer.create(
451
+ email=email,
452
+ description=description
453
+ )
454
+ st.success("Customer created successfully.")
455
+ st.json(customer)
456
+ elif stripe_action == "Charge Customer":
457
+ st.subheader("Charge a Customer")
458
+ customer_id = st.text_input("Customer ID")
459
+ amount = st.number_input("Amount (in cents)", min_value=50)
460
+ currency = st.text_input("Currency", value="usd")
461
+ description = st.text_input("Description")
462
+ if st.button("Charge Customer"):
463
+ charge = stripe.Charge.create(
464
+ customer=customer_id,
465
+ amount=int(amount),
466
+ currency=currency,
467
+ description=description
468
+ )
469
+ st.success("Charge created successfully.")
470
+ st.json(charge)
471
+ elif stripe_action == "View Charges":
472
+ st.subheader("List Charges")
473
+ charges = stripe.Charge.list()
474
+ st.json(charges)
475
+
476
+ # Modern Treasury Services
477
+ elif service_choice == "Modern Treasury Services":
478
+ st.header("Modern Treasury Services")
479
+ mt_action = st.selectbox("Choose an Action", [
480
+ "View Payment Orders",
481
+ "Create Payment Order",
482
+ ])
483
+
484
+ def get_mt_headers():
485
+ credentials = f"{mt_organization_id}:{mt_api_key}"
486
+ base64_credentials = base64.b64encode(credentials.encode()).decode('utf-8')
487
+ return {
488
+ "Authorization": f"Basic {base64_credentials}",
489
+ "Content-Type": "application/json",
490
+ "Accept": "application/json"
491
+ }
492
+
493
+ if mt_action == "View Payment Orders":
494
+ url = "https://app.moderntreasury.com/api/payment_orders"
495
+ headers = get_mt_headers()
496
+ response = requests.get(url, headers=headers)
497
+ if response.status_code == 200:
498
+ st.json(response.json())
499
+ else:
500
+ st.error(f"Error: {response.text}")
501
+ elif mt_action == "Create Payment Order":
502
+ st.subheader("Create a New Payment Order")
503
+ amount = st.number_input("Amount", min_value=0.0)
504
+ direction = st.selectbox("Direction", ["credit", "debit"])
505
+ currency = st.text_input("Currency", value="USD")
506
+ description = st.text_input("Description")
507
+ if st.button("Create Payment Order"):
508
+ url = "https://app.moderntreasury.com/api/payment_orders"
509
+ headers = get_mt_headers()
510
+ data = {
511
+ "amount": int(amount * 100), # Convert to cents
512
+ "direction": direction,
513
+ "currency": currency,
514
+ "description": description
515
+ }
516
+ response = requests.post(url, headers=headers, json=data)
517
+ if response.status_code == 201:
518
+ st.success("Payment Order created successfully.")
519
+ st.json(response.json())
520
+ else:
521
+ st.error(f"Error: {response.text}")
522
+
523
+ # GitHub Integration
524
+ elif service_choice == "GitHub Integration":
525
+ st.header("GitHub Repository Management")
526
+ if not github_client:
527
+ st.error("Please provide your GitHub Personal Access Token in the environment variables.")
528
+ else:
529
+ github_action = st.selectbox("Choose an Action", [
530
+ "List Repositories",
531
+ "Create Repository",
532
+ "Add File to Repository",
533
+ "List Repository Contents",
534
+ ])
535
+
536
+ if github_action == "List Repositories":
537
+ st.subheader("Your GitHub Repositories")
538
+ try:
539
+ repos = github_client.get_user().get_repos()
540
+ repo_list = [repo.full_name for repo in repos]
541
+ st.write(repo_list)
542
+ except Exception as e:
543
+ st.error(f"Error: {e}")
544
+
545
+ elif github_action == "Create Repository":
546
+ st.subheader("Create a New Repository")
547
+ repo_name = st.text_input("Repository Name")
548
+ repo_description = st.text_area("Repository Description")
549
+ private = st.checkbox("Private Repository")
550
+ if st.button("Create Repository"):
551
+ try:
552
+ user = github_client.get_user()
553
+ repo = user.create_repo(
554
+ name=repo_name,
555
+ description=repo_description,
556
+ private=private
557
+ )
558
+ st.success(f"Repository '{repo.full_name}' created successfully!")
559
+ st.write(f"URL: {repo.html_url}")
560
+ except Exception as e:
561
+ st.error(f"Error: {e}")
562
+
563
+ elif github_action == "Add File to Repository":
564
+ st.subheader("Add a File to a Repository")
565
+ repo_name = st.text_input("Repository Name (e.g., username/repo)")
566
+ file_path = st.text_input("File Path in Repository (e.g., folder/filename.py)")
567
+ file_content = st.text_area("File Content")
568
+ commit_message = st.text_input("Commit Message", value="Add new file via TransactPro app")
569
+ if st.button("Add File"):
570
+ try:
571
+ repo = github_client.get_repo(repo_name)
572
+ # Check if the file already exists
573
+ try:
574
+ contents = repo.get_contents(file_path)
575
+ # If the file exists, update it
576
+ repo.update_file(
577
+ path=file_path,
578
+ message=commit_message,
579
+ content=file_content,
580
+ sha=contents.sha,
581
+ branch="main"
582
+ )
583
+ st.success(f"File '{file_path}' updated in repository '{repo_name}' successfully!")
584
+ except Exception:
585
+ # If the file does not exist, create it
586
+ repo.create_file(
587
+ path=file_path,
588
+ message=commit_message,
589
+ content=file_content,
590
+ branch="main"
591
+ )
592
+ st.success(f"File '{file_path}' added to repository '{repo_name}' successfully!")
593
+ except Exception as e:
594
+ st.error(f"Error: {e}")
595
+
596
+ elif github_action == "List Repository Contents":
597
+ st.subheader("List Contents of a Repository")
598
+ repo_name = st.text_input("Repository Name (e.g., username/repo)")
599
+ if st.button("List Contents"):
600
+ try:
601
+ repo = github_client.get_repo(repo_name)
602
+ contents = repo.get_contents("")
603
+ while contents:
604
+ file_content = contents.pop(0)
605
+ if file_content.type == "dir":
606
+ contents.extend(repo.get_contents(file_content.path))
607
+ else:
608
+ st.write(file_content.path)
609
+ except Exception as e:
610
+ st.error(f"Error: {e}")
611
+
612
+ # Hugging Face Integration
613
+ elif service_choice == "Hugging Face Integration":
614
+ st.header("Hugging Face Model Management")
615
+ if not huggingface_token:
616
+ st.error("Please provide your Hugging Face Token in the environment variables.")
617
+ else:
618
+ huggingface_action = st.selectbox("Choose an Action", [
619
+ "List Models",
620
+ "Upload Model",
621
+ "Create Space",
622
+ "Download Model",
623
+ ])
624
+
625
+ if huggingface_action == "List Models":
626
+ st.subheader("Your Hugging Face Models")
627
+ try:
628
+ user_info = hf_api.whoami(token=huggingface_token)
629
+ models = hf_api.list_models(author=user_info['name'], token=huggingface_token)
630
+ model_list = [model.modelId for model in models]
631
+ st.write(model_list)
632
+ except Exception as e:
633
+ st.error(f"Error: {e}")
634
+
635
+ elif huggingface_action == "Upload Model":
636
+ st.subheader("Upload a Model to Hugging Face")
637
+ model_name = st.text_input("Model Name (e.g., username/model_name)")
638
+ model_files = st.file_uploader("Select Model Files", accept_multiple_files=True)
639
+ if st.button("Upload Model"):
640
+ try:
641
+ repo_url = hf_api.create_repo(name=model_name, token=huggingface_token)
642
+ repo = Repository(local_dir=model_name, clone_from=repo_url, use_auth_token=huggingface_token)
643
+ repo.git_pull()
644
+ for model_file in model_files:
645
+ with open(os.path.join(model_name, model_file.name), "wb") as f:
646
+ f.write(model_file.getbuffer())
647
+ repo.git_add()
648
+ repo.git_commit("Upload model files")
649
+ repo.git_push()
650
+ st.success(f"Model '{model_name}' uploaded successfully!")
651
+ st.write(f"Model URL: https://huggingface.co/{model_name}")
652
+ except Exception as e:
653
+ st.error(f"Error: {e}")
654
+
655
+ elif huggingface_action == "Create Space":
656
+ st.subheader("Create a New Hugging Face Space")
657
+ space_name = st.text_input("Space Name (e.g., username/space_name)")
658
+ sdk = st.selectbox("Select SDK", ["streamlit", "gradio", "dash", "static"])
659
+ if st.button("Create Space"):
660
+ try:
661
+ repo_url = hf_api.create_repo(name=space_name, repo_type="space", space_sdk=sdk, token=huggingface_token)
662
+ st.success(f"Space '{space_name}' created successfully!")
663
+ st.write(f"Space URL: https://huggingface.co/spaces/{space_name}")
664
+ except Exception as e:
665
+ st.error(f"Error: {e}")
666
+
667
+ elif huggingface_action == "Download Model":
668
+ st.subheader("Download a Model from Hugging Face")
669
+ model_id = st.text_input("Model ID (e.g., username/model_name)")
670
+ if st.button("Download Model"):
671
+ try:
672
+ model_dir = hf_api.download_repo(repo_id=model_id, repo_type='model', local_dir=model_id, token=huggingface_token)
673
+ st.success(f"Model '{model_id}' downloaded successfully!")
674
+ st.write(f"Model Directory: {model_dir}")
675
+ except Exception as e:
676
+ st.error(f"Error: {e}")
677
+
678
+ # Blockchain Integration
679
+ elif service_choice == "Blockchain Integration":
680
+ st.header("Blockchain Integration with Metamask and Infura")
681
+ if not web3:
682
+ st.error("Please provide your Infura Project ID in the environment variables.")
683
+ else:
684
+ blockchain_action = st.selectbox("Choose an Action", [
685
+ "View Account Balance",
686
+ "Send Transaction",
687
+ "View Transaction Details",
688
+ ])
689
+
690
+ if blockchain_action == "View Account Balance":
691
+ st.subheader("View Ethereum Account Balance")
692
+ account_address = st.text_input("Enter Ethereum Account Address", value=metamask_account_address)
693
+ if st.button("Get Balance"):
694
+ try:
695
+ balance_wei = web3.eth.get_balance(account_address)
696
+ balance_eth = web3.fromWei(balance_wei, 'ether')
697
+ st.write(f"Balance: {balance_eth} ETH")
698
+ except Exception as e:
699
+ st.error(f"Error: {e}")
700
+
701
+ elif blockchain_action == "Send Transaction":
702
+ st.subheader("Send Ethereum Transaction")
703
+ to_address = st.text_input("Recipient Ethereum Address")
704
+ amount = st.number_input("Amount in ETH", min_value=0.0)
705
+ gas_price = st.number_input("Gas Price (Gwei)", min_value=1.0, value=50.0)
706
+ if st.button("Send Transaction"):
707
+ if not metamask_private_key:
708
+ st.error("Please provide your Metamask Private Key in the environment variables.")
709
+ else:
710
+ try:
711
+ # Build transaction
712
+ nonce = web3.eth.getTransactionCount(metamask_account_address)
713
+ tx = {
714
+ 'nonce': nonce,
715
+ 'to': to_address,
716
+ 'value': web3.toWei(amount, 'ether'),
717
+ 'gas': 21000,
718
+ 'gasPrice': web3.toWei(gas_price, 'gwei'),
719
+ }
720
+ # Sign transaction
721
+ signed_tx = web3.eth.account.sign_transaction(tx, metamask_private_key)
722
+ # Send transaction
723
+ tx_hash = web3.eth.sendRawTransaction(signed_tx.rawTransaction)
724
+ st.success(f"Transaction sent! TX Hash: {web3.toHex(tx_hash)}")
725
+ except Exception as e:
726
+ st.error(f"Error: {e}")
727
+
728
+ elif blockchain_action == "View Transaction Details":
729
+ st.subheader("View Ethereum Transaction Details")
730
+ tx_hash = st.text_input("Enter Transaction Hash")
731
+ if st.button("Get Transaction Details"):
732
+ try:
733
+ tx = web3.eth.getTransaction(tx_hash)
734
+ st.json(dict(tx))
735
+ except Exception as e:
736
+ st.error(f"Error: {e}")
737
+
738
+ # Visa Services
739
+ elif service_choice == "Visa Services":
740
+ st.header("Visa API Integration")
741
+ visa_action = st.selectbox("Choose an Action", [
742
+ "Get Transaction Details",
743
+ "Initiate Payment",
744
+ ])
745
+
746
+ if not visa_api_key or not visa_api_secret or not visa_cert_path:
747
+ st.error("Please provide Visa API credentials and certificate path.")
748
+ else:
749
+ if visa_action == "Get Transaction Details":
750
+ transaction_id = st.text_input("Enter Transaction ID")
751
+ if st.button("Get Details"):
752
+ url = f"https://sandbox.api.visa.com/visadirect/v1/transaction/{transaction_id}"
753
+ headers = {
754
+ "Accept": "application/json",
755
+ "Content-Type": "application/json"
756
+ }
757
+ response = requests.get(
758
+ url,
759
+ headers=headers,
760
+ auth=(
761
+ visa_api_key,
762
+ visa_api_secret
763
+ ),
764
+ cert=(visa_cert_path, visa_cert_path)
765
+ )
766
+ if response.status_code == 200:
767
+ st.json(response.json())
768
+ else:
769
+ st.error(f"Error: {response.text}")
770
+ elif visa_action == "Initiate Payment":
771
+ st.subheader("Initiate a Payment")
772
+ # Implement payment initiation with Visa API
773
+ st.info("Payment initiation with Visa API is not implemented in this example.")
774
+
775
+ # MasterCard Services
776
+ elif service_choice == "MasterCard Services":
777
+ st.header("MasterCard API Integration")
778
+ mastercard_action = st.selectbox("Choose an Action", [
779
+ "Get Account Details",
780
+ "Process Payment",
781
+ ])
782
+
783
+ if not mastercard_consumer_key or not mastercard_private_key:
784
+ st.error("Please provide MasterCard API credentials.")
785
+ else:
786
+ if mastercard_action == "Get Account Details":
787
+ account_id = st.text_input("Enter Account ID")
788
+ if st.button("Get Account Details"):
789
+ url = f"https://sandbox.api.mastercard.com/account/{account_id}"
790
+ headers = {
791
+ "Accept": "application/json",
792
+ "Content-Type": "application/json"
793
+ }
794
+ # Implement OAuth1 authentication for MasterCard API
795
+ client = Client(
796
+ client_key=mastercard_consumer_key,
797
+ rsa_key=mastercard_private_key,
798
+ signature_method='RSA-SHA1'
799
+ )
800
+ uri, headers, body = client.sign(
801
+ url,
802
+ http_method='GET',
803
+ body='',
804
+ headers=headers
805
+ )
806
+ response = requests.get(uri, headers=headers)
807
+ if response.status_code == 200:
808
+ st.json(response.json())
809
+ else:
810
+ st.error(f"Error: {response.text}")
811
+ elif mastercard_action == "Process Payment":
812
+ st.subheader("Process a Payment")
813
+ # Implement payment processing with MasterCard API
814
+ st.info("Payment processing with MasterCard API is not implemented in this example.")
815
+
816
+ # Pipedream Integration
817
+ elif service_choice == "Pipedream Integration":
818
+ st.header("Pipedream Workflow Trigger")
819
+ if not pipedream_url:
820
+ st.error("Please provide your Pipedream Workflow URL in the environment variables.")
821
+ else:
822
+ event_name = st.text_input("Event Name")
823
+ data = st.text_area("Event Data (JSON format)")
824
+ if st.button("Trigger Workflow"):
825
+ try:
826
+ event_data = json.loads(data)
827
+ event_data['event_name'] = event_name
828
+ response = requests.post(pipedream_url, json=event_data)
829
+ if response.status_code == 200:
830
+ st.success("Pipedream workflow triggered successfully.")
831
+ else:
832
+ st.error(f"Failed to trigger workflow: {response.text}")
833
+ except json.JSONDecodeError:
834
+ st.error("Invalid JSON data.")
835
+
836
+ # Financial Analysis
837
+ elif service_choice == "Financial Analysis":
838
+ st.header("Financial Analysis and Insights")
839
+ # Fetch transaction data from APIs or use sample data
840
+ transactions = [
841
+ {'date': '2023-01-01', 'amount': -50, 'category': 'Groceries'},
842
+ {'date': '2023-01-02', 'amount': -200, 'category': 'Rent'},
843
+ {'date': '2023-01-03', 'amount': -15, 'category': 'Coffee'},
844
+ # ... more transactions
845
+ ]
846
+ df_transactions = pd.DataFrame(transactions)
847
+
848
+ # Visualization
849
+ fig = px.bar(df_transactions, x='date', y='amount', color='category', title="Spending Over Time")
850
+ st.plotly_chart(fig)
851
+
852
+ # Anomaly Detection
853
+ model = IsolationForest(contamination=0.1)
854
+ df_transactions['anomaly'] = model.fit_predict(df_transactions[['amount']])
855
+ anomalies = df_transactions[df_transactions['anomaly'] == -1]
856
+ st.subheader("Detected Anomalies")
857
+ st.write(anomalies)
858
+
859
+ # Predictive Analytics
860
+ st.subheader("Predictive Analytics")
861
+ df_transactions['timestamp'] = pd.to_datetime(df_transactions['date']).astype(np.int64) // 10**9
862
+ X = df_transactions[['timestamp']]
863
+ y = df_transactions['amount']
864
+ reg_model = LinearRegression()
865
+ reg_model.fit(X, y)
866
+ future_dates = pd.date_range(start=date.today(), periods=30)
867
+ future_timestamps = future_dates.astype(np.int64) // 10**9
868
+ X_future = pd.DataFrame(future_timestamps, columns=['timestamp'])
869
+ y_pred = reg_model.predict(X_future)
870
+ pred_df = pd.DataFrame({'date': future_dates, 'predicted_amount': y_pred})
871
+ fig_pred = px.line(pred_df, x='date', y='predicted_amount', title="Predicted Future Spending")
872
+ st.plotly_chart(fig_pred)
873
+
874
+ # Budgeting Tools
875
+ elif service_choice == "Budgeting Tools":
876
+ st.header("Budgeting and Financial Planning")
877
+ budget_categories = ['Rent', 'Groceries', 'Entertainment', 'Utilities', 'Miscellaneous']
878
+ budgets = {}
879
+ for category in budget_categories:
880
+ budgets[category] = st.number_input(f"{category} Budget", min_value=0.0, format="%0.2f")
881
+ st.subheader("Your Budget Overview")
882
+ budget_df = pd.DataFrame(list(budgets.items()), columns=['Category', 'Budget'])
883
+ st.table(budget_df)
884
+ # Compare with actual spending
885
+ actual_spending = {'Rent': 1800, 'Groceries': 450, 'Entertainment': 300, 'Utilities': 200, 'Miscellaneous': 150}
886
+ spending_df = pd.DataFrame(list(actual_spending.items()), columns=['Category', 'Spent'])
887
+ comparison_df = budget_df.merge(spending_df, on='Category')
888
+ comparison_df['Difference'] = comparison_df['Budget'] - comparison_df['Spent']
889
+ st.subheader("Budget vs Actual Spending")
890
+ st.table(comparison_df)
891
+
892
+ # AI Chatbot with OpenAI's ChatGPT API
893
+ elif service_choice == "AI Chatbot":
894
+ st.header("AI-Powered Financial Assistant with ChatGPT")
895
+ if not openai_api_key:
896
+ st.error("Please provide your OpenAI API Key in the environment variables.")
897
+ else:
898
+ user_input = st.text_input("You: ")
899
+ if user_input:
900
+ try:
901
+ response = openai.ChatCompletion.create(
902
+ model="gpt-3.5-turbo",
903
+ messages=[
904
+ {"role": "system", "content": "You are a helpful financial assistant."},
905
+ {"role": "user", "content": user_input},
906
+ ],
907
+ )
908
+ assistant_response = response['choices'][0]['message']['content']
909
+ st.text_area("Assistant:", value=assistant_response, height=200)
910
+ except Exception as e:
911
+ st.error(f"Error: {e}")
912
+
913
+ # Quantum Portfolio Optimization
914
+ elif service_choice == "Quantum Portfolio Optimization":
915
+ st.header("Quantum Portfolio Optimization Simulation")
916
+ num_qubits = 3
917
+ qc = QuantumCircuit(num_qubits)
918
+ qc.h(range(num_qubits))
919
+ qc.measure_all()
920
+ simulator = Aer.get_backend('qasm_simulator')
921
+ result = execute(qc, simulator, shots=1024).result()
922
+ counts = result.get_counts()
923
+ st.write("Simulation Results:")
924
+ st.write(counts)
925
+ # Interpret the results for portfolio optimization
926
+
927
+ # Display footer
928
+ st.sidebar.markdown("Powered by Streamlit")
929
+ st.sidebar.markdown("Made by Citibank Demo Business Inc.")