admin08077 commited on
Commit
6e3e70f
Β·
verified Β·
1 Parent(s): 94891e7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +248 -147
app.py CHANGED
@@ -69,7 +69,7 @@ if not BLOCKCHAIN_NODE_URL.startswith("http"):
69
  config_valid = False
70
  config_errors.append("Blockchain Node URL must start with http or https.")
71
 
72
- if not Web3.isAddress(CONTRACT_ADDRESS):
73
  config_valid = False
74
  config_errors.append("Invalid Smart Contract Address.")
75
 
@@ -112,6 +112,7 @@ class User(Base):
112
  password = Column(String(200), nullable=False)
113
  balance = Column(Float, default=0.0)
114
  staked = Column(Float, default=0.0)
 
115
  tokens = relationship('Token', backref='owner', lazy=True)
116
  transactions = relationship('Transaction', backref='user', lazy=True)
117
 
@@ -319,12 +320,12 @@ passwords = [user.password for user in users]
319
  if users:
320
  authenticator = stauth.Authenticate(
321
  names, usernames, passwords,
322
- 'citibank_ai_crypto', 'abcdef', cookie_expiry_days=1
323
  )
324
  else:
325
  authenticator = stauth.Authenticate(
326
  [], [], [],
327
- 'citibank_ai_crypto', 'abcdef', cookie_expiry_days=1
328
  )
329
 
330
  name, authentication_status, username = authenticator.login('Login', 'main')
@@ -334,7 +335,7 @@ if authentication_status:
334
  authenticator.logout('Logout', 'sidebar')
335
 
336
  # ========================
337
- # User Dashboard
338
  # ========================
339
 
340
  st.header("🌟 Dashboard 🌟")
@@ -348,165 +349,260 @@ if authentication_status:
348
  col1.metric("Tokens", f"{user.balance}")
349
  col2.metric("Staked Tokens", f"{user.staked}")
350
 
 
 
 
351
  # ========================
352
  # AI Query Submission
353
  # ========================
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
354
 
355
- st.subheader("πŸ€– Submit AI Query")
356
- with st.form("ai_query_form"):
357
- input_text = st.text_area("Enter your query here...", height=100)
358
- submit_button = st.form_submit_button(label='Submit')
359
-
360
- if submit_button:
361
- if input_text.strip() == "":
362
- st.error("❌ Input text cannot be empty.")
 
 
 
 
 
 
 
 
 
 
363
  else:
364
- with st.spinner("πŸ” Processing your AI query..."):
365
- ai_output = process_ai(input_text)
366
- if ai_output.startswith("❌"):
367
- st.error(ai_output)
 
 
 
 
 
 
 
 
 
 
 
 
368
  else:
369
- st.success("βœ… AI Query Processed!")
370
- st.write(f"**AI Output:** {ai_output}")
371
- # Mint Token
372
- token_id = str(uuid.uuid4())
373
- token_value = calculate_token_value(ai_output)
374
- token = Token(
375
- id=token_id,
376
- owner_id=user.id,
377
- value=token_value,
378
- verified=False
379
  )
380
- session.add(token)
381
  session.commit()
382
  # Record transaction
383
  transaction = Transaction(
384
  user_id=user.id,
385
- token_id=token.id,
386
- action='submitted_ai_query',
387
- value=token.value
388
  )
389
  session.add(transaction)
390
  session.commit()
391
- st.write(f"**Token ID:** {token_id}")
 
 
392
 
393
  # ========================
394
- # Display Tokens
395
  # ========================
396
-
397
- st.subheader("πŸͺ™ Your Tokens")
398
- tokens = session.query(Token).filter_by(owner_id=user.id).all()
399
- if tokens:
400
- token_data = []
401
- for token in tokens:
402
- token_info = {
403
- "Token ID": token.id,
404
- "Value": token.value,
405
- "Verified": "Yes" if token.verified else "No",
406
- "Verification Hash": token.verification_hash or "N/A",
407
- "Created At": token.created_at.strftime('%Y-%m-%d %H:%M:%S')
408
- }
409
- token_data.append(token_info)
410
- st.table(token_data)
411
- else:
412
- st.write("πŸ“­ You have no tokens yet.")
413
-
414
- # ========================
415
- # Trade Tokens
416
- # ========================
417
-
418
- st.subheader("πŸ”„ Trade Tokens")
419
- with st.form("trade_form"):
420
- seller_username = st.text_input("Seller Username")
421
- token_id = st.text_input("Token ID")
422
- trade_button = st.form_submit_button(label='Trade Token')
423
-
424
- if trade_button:
425
- if seller_username.strip() == "" or token_id.strip() == "":
426
- st.error("❌ Seller username and Token ID are required.")
427
- else:
428
- seller = session.query(User).filter_by(username=seller_username).first()
429
- if not seller:
430
- st.error("❌ Seller not found.")
431
  else:
432
- token = session.query(Token).filter_by(id=token_id, owner_id=seller.id).first()
433
- if not token:
434
- st.error("❌ Token not found or unauthorized.")
435
  else:
436
- # Transfer ownership
437
- token.owner_id = user.id
438
- session.commit()
439
- # Update balances
440
- seller.balance -= token.value
441
- user.balance += token.value
442
- session.commit()
443
- # Record transaction
444
- transaction = Transaction(
445
- user_id=user.id,
446
- token_id=token.id,
447
- action='trade',
448
- value=token.value
449
- )
450
- session.add(transaction)
451
- session.commit()
452
- st.success("βœ… Trade successful.")
453
- st.write(f"**New Balance:** {user.balance}")
454
- st.write(f"**Token Value:** {token.value}")
 
 
 
 
455
 
456
  # ========================
457
- # Stake Tokens
458
  # ========================
459
-
460
- st.subheader("πŸ“ˆ Stake Tokens")
461
- with st.form("stake_form"):
462
- stake_amount = st.number_input("Amount to Stake", min_value=0.0, step=1.0)
463
- stake_button = st.form_submit_button(label='Stake Tokens')
464
-
465
- if stake_button:
466
- if stake_amount <= 0:
467
- st.error("❌ Stake amount must be greater than zero.")
468
- elif user.balance < stake_amount:
469
- st.error("❌ Insufficient balance.")
 
 
 
470
  else:
471
- user.balance -= stake_amount
472
- user.staked += stake_amount
473
- stake = Stake(
474
- user_id=user.id,
475
- amount=stake_amount
476
- )
477
- session.add(stake)
478
- session.commit()
479
- # Record transaction
480
- transaction = Transaction(
481
- user_id=user.id,
482
- action='stake',
483
- value=stake_amount
484
- )
485
- session.add(transaction)
486
- session.commit()
487
- st.success("βœ… Staked successfully.")
488
- st.write(f"**New Balance:** {user.balance}")
489
- st.write(f"**Total Staked:** {user.staked}")
490
 
491
  # ========================
492
- # Transaction History
493
  # ========================
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
494
 
495
- st.subheader("πŸ“œ Transaction History")
496
- transactions = session.query(Transaction).filter_by(user_id=user.id).order_by(Transaction.timestamp.desc()).all()
497
- if transactions:
498
- transaction_data = []
499
- for tx in transactions:
500
- tx_info = {
501
- "Action": tx.action,
502
- "Value": tx.value,
503
- "Hash": tx.hash or "N/A",
504
- "Timestamp": tx.timestamp.strftime('%Y-%m-%d %H:%M:%S')
505
- }
506
- transaction_data.append(tx_info)
507
- st.table(transaction_data)
508
- else:
509
- st.write("πŸ“­ No transactions found.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
510
 
511
  # ========================
512
  # Background Task for Verification
@@ -527,19 +623,23 @@ if authentication_status:
527
  # Interact with blockchain to verify and mint token
528
  try:
529
  tx_hash = blockchain.verify_output(verification_hash)
530
- minted_token_id = blockchain.mint_token(user.web3.toChecksumAddress(token.owner.username), token.value, verification_hash) # Replace with actual owner address
 
 
 
 
 
531
  if minted_token_id:
532
  # Update token status
533
  token.verified = True
534
  token.verification_hash = verification_hash
535
  session.commit()
536
  # Update user's balance
537
- user = session.query(User).get(token.owner_id)
538
- user.balance += token.value
539
  session.commit()
540
  # Record transaction
541
  transaction = Transaction(
542
- user_id=user.id,
543
  token_id=token.id,
544
  action='minted',
545
  value=token.value,
@@ -570,20 +670,21 @@ st.sidebar.subheader("πŸ“’ Register New User")
570
  with st.sidebar.form("register_form"):
571
  new_username = st.text_input("New Username")
572
  new_password = st.text_input("New Password", type="password")
 
573
  register_button = st.form_submit_button(label='Register')
574
 
575
  if register_button:
576
- if not new_username or not new_password:
577
- st.sidebar.error("❌ Username and password are required.")
 
 
578
  elif session.query(User).filter_by(username=new_username).first():
579
  st.sidebar.error("❌ Username already exists.")
 
 
580
  else:
581
  hashed_password = generate_password_hash(new_password)
582
- new_user = User(username=new_username, password=hashed_password)
583
  session.add(new_user)
584
  session.commit()
585
  st.sidebar.success("βœ… User registered successfully!")
586
-
587
- # ========================
588
- # End of app.py
589
- # ========================
 
69
  config_valid = False
70
  config_errors.append("Blockchain Node URL must start with http or https.")
71
 
72
+ if not Web3.is_address(CONTRACT_ADDRESS):
73
  config_valid = False
74
  config_errors.append("Invalid Smart Contract Address.")
75
 
 
112
  password = Column(String(200), nullable=False)
113
  balance = Column(Float, default=0.0)
114
  staked = Column(Float, default=0.0)
115
+ blockchain_address = Column(String(42), unique=True, nullable=False) # Added blockchain address
116
  tokens = relationship('Token', backref='owner', lazy=True)
117
  transactions = relationship('Transaction', backref='user', lazy=True)
118
 
 
320
  if users:
321
  authenticator = stauth.Authenticate(
322
  names, usernames, passwords,
323
+ 'citibank_demo_business_inc_ai_crypto', 'abcdef', cookie_expiry_days=1
324
  )
325
  else:
326
  authenticator = stauth.Authenticate(
327
  [], [], [],
328
+ 'citibank_demo_business_inc_ai_crypto', 'abcdef', cookie_expiry_days=1
329
  )
330
 
331
  name, authentication_status, username = authenticator.login('Login', 'main')
 
335
  authenticator.logout('Logout', 'sidebar')
336
 
337
  # ========================
338
+ # User Dashboard with Tabs
339
  # ========================
340
 
341
  st.header("🌟 Dashboard 🌟")
 
349
  col1.metric("Tokens", f"{user.balance}")
350
  col2.metric("Staked Tokens", f"{user.staked}")
351
 
352
+ # Create Tabs
353
+ tabs = st.tabs(["AI Query", "Token Management", "Staking", "Trading", "Transaction History", "Chat", "About Me"])
354
+
355
  # ========================
356
  # AI Query Submission
357
  # ========================
358
+ with tabs[0]:
359
+ st.subheader("πŸ€– Submit AI Query")
360
+ with st.form("ai_query_form"):
361
+ input_text = st.text_area("Enter your query here...", height=100)
362
+ submit_button = st.form_submit_button(label='Submit')
363
+
364
+ if submit_button:
365
+ if input_text.strip() == "":
366
+ st.error("❌ Input text cannot be empty.")
367
+ else:
368
+ with st.spinner("πŸ” Processing your AI query..."):
369
+ ai_output = process_ai(input_text)
370
+ if ai_output.startswith("❌"):
371
+ st.error(ai_output)
372
+ else:
373
+ st.success("βœ… AI Query Processed!")
374
+ st.write(f"**AI Output:** {ai_output}")
375
+ # Mint Token
376
+ token_id = str(uuid.uuid4())
377
+ token_value = calculate_token_value(ai_output)
378
+ token = Token(
379
+ id=token_id,
380
+ owner_id=user.id,
381
+ value=token_value,
382
+ verified=False
383
+ )
384
+ session.add(token)
385
+ session.commit()
386
+ # Record transaction
387
+ transaction = Transaction(
388
+ user_id=user.id,
389
+ token_id=token.id,
390
+ action='submitted_ai_query',
391
+ value=token.value
392
+ )
393
+ session.add(transaction)
394
+ session.commit()
395
+ st.write(f"**Token ID:** {token_id}")
396
 
397
+ # ========================
398
+ # Token Management
399
+ # ========================
400
+ with tabs[1]:
401
+ st.subheader("πŸͺ™ Your Tokens")
402
+ tokens = session.query(Token).filter_by(owner_id=user.id).all()
403
+ if tokens:
404
+ token_data = []
405
+ for token in tokens:
406
+ token_info = {
407
+ "Token ID": token.id,
408
+ "Value": token.value,
409
+ "Verified": "Yes" if token.verified else "No",
410
+ "Verification Hash": token.verification_hash or "N/A",
411
+ "Created At": token.created_at.strftime('%Y-%m-%d %H:%M:%S')
412
+ }
413
+ token_data.append(token_info)
414
+ st.table(token_data)
415
  else:
416
+ st.write("πŸ“­ You have no tokens yet.")
417
+
418
+ # ========================
419
+ # Staking
420
+ # ========================
421
+ with tabs[2]:
422
+ st.subheader("πŸ“ˆ Stake Tokens")
423
+ with st.form("stake_form"):
424
+ stake_amount = st.number_input("Amount to Stake", min_value=0.0, step=1.0)
425
+ stake_button = st.form_submit_button(label='Stake Tokens')
426
+
427
+ if stake_button:
428
+ if stake_amount <= 0:
429
+ st.error("❌ Stake amount must be greater than zero.")
430
+ elif user.balance < stake_amount:
431
+ st.error("❌ Insufficient balance.")
432
  else:
433
+ user.balance -= stake_amount
434
+ user.staked += stake_amount
435
+ stake = Stake(
436
+ user_id=user.id,
437
+ amount=stake_amount
 
 
 
 
 
438
  )
439
+ session.add(stake)
440
  session.commit()
441
  # Record transaction
442
  transaction = Transaction(
443
  user_id=user.id,
444
+ action='stake',
445
+ value=stake_amount
 
446
  )
447
  session.add(transaction)
448
  session.commit()
449
+ st.success("βœ… Staked successfully.")
450
+ st.write(f"**New Balance:** {user.balance}")
451
+ st.write(f"**Total Staked:** {user.staked}")
452
 
453
  # ========================
454
+ # Trading
455
  # ========================
456
+ with tabs[3]:
457
+ st.subheader("πŸ”„ Trade Tokens")
458
+ with st.form("trade_form"):
459
+ seller_username = st.text_input("Seller Username")
460
+ token_id = st.text_input("Token ID")
461
+ trade_button = st.form_submit_button(label='Trade Token')
462
+
463
+ if trade_button:
464
+ if seller_username.strip() == "" or token_id.strip() == "":
465
+ st.error("❌ Seller username and Token ID are required.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
466
  else:
467
+ seller = session.query(User).filter_by(username=seller_username).first()
468
+ if not seller:
469
+ st.error("❌ Seller not found.")
470
  else:
471
+ token = session.query(Token).filter_by(id=token_id, owner_id=seller.id).first()
472
+ if not token:
473
+ st.error("❌ Token not found or unauthorized.")
474
+ else:
475
+ # Transfer ownership
476
+ token.owner_id = user.id
477
+ session.commit()
478
+ # Update balances
479
+ seller.balance -= token.value
480
+ user.balance += token.value
481
+ session.commit()
482
+ # Record transaction
483
+ transaction = Transaction(
484
+ user_id=user.id,
485
+ token_id=token.id,
486
+ action='trade',
487
+ value=token.value
488
+ )
489
+ session.add(transaction)
490
+ session.commit()
491
+ st.success("βœ… Trade successful.")
492
+ st.write(f"**New Balance:** {user.balance}")
493
+ st.write(f"**Token Value:** {token.value}")
494
 
495
  # ========================
496
+ # Transaction History
497
  # ========================
498
+ with tabs[4]:
499
+ st.subheader("πŸ“œ Transaction History")
500
+ transactions = session.query(Transaction).filter_by(user_id=user.id).order_by(Transaction.timestamp.desc()).all()
501
+ if transactions:
502
+ transaction_data = []
503
+ for tx in transactions:
504
+ tx_info = {
505
+ "Action": tx.action,
506
+ "Value": tx.value,
507
+ "Hash": tx.hash or "N/A",
508
+ "Timestamp": tx.timestamp.strftime('%Y-%m-%d %H:%M:%S')
509
+ }
510
+ transaction_data.append(tx_info)
511
+ st.table(transaction_data)
512
  else:
513
+ st.write("πŸ“­ No transactions found.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
514
 
515
  # ========================
516
+ # Chat Interface
517
  # ========================
518
+ with tabs[5]:
519
+ st.subheader("πŸ’¬ Chat with CITIBANK DEMO BUSINESS INC")
520
+ if 'chat_history' not in st.session_state:
521
+ st.session_state['chat_history'] = []
522
+
523
+ def get_ai_response(user_input):
524
+ """
525
+ Generate AI response using OpenAI.
526
+ """
527
+ try:
528
+ response = openai.Completion.create(
529
+ engine="text-davinci-003", # Use 'gpt-4' if available
530
+ prompt=user_input,
531
+ max_tokens=150,
532
+ temperature=0.7,
533
+ n=1,
534
+ stop=None
535
+ )
536
+ ai_output = response.choices[0].text.strip()
537
+ return ai_output
538
+ except Exception as e:
539
+ return f"❌ Error processing AI output: {str(e)}"
540
+
541
+ user_input = st.text_input("You:", key="chat_input")
542
+
543
+ if st.button("Send"):
544
+ if user_input.strip() == "":
545
+ st.warning("❌ Please enter a message.")
546
+ else:
547
+ st.session_state.chat_history.append(("You", user_input))
548
+ ai_response = get_ai_response(user_input)
549
+ st.session_state.chat_history.append(("CITIBANK AI", ai_response))
550
+
551
+ for sender, message in st.session_state.chat_history:
552
+ if sender == "You":
553
+ st.markdown(f"**You:** {message}")
554
+ else:
555
+ st.markdown(f"**CITIBANK AI:** {message}")
556
 
557
+ # ========================
558
+ # About Me Tab
559
+ # ========================
560
+ with tabs[6]:
561
+ st.subheader("ℹ️ About CITIBANK DEMO BUSINESS INC AI Crypto Ecosystem")
562
+ st.markdown("""
563
+ ### 🌟 Overview
564
+ The **CITIBANK DEMO BUSINESS INC AI Crypto Ecosystem** is a cutting-edge platform that seamlessly integrates **Artificial Intelligence** with **Blockchain Technology** to create a **self-sustaining** and **monetizable** ecosystem. This system empowers users to interact with AI services, earn and manage cryptocurrency tokens, and participate in a transparent and decentralized economy.
565
+
566
+ ### πŸš€ Features
567
+ - **User Authentication:** Secure registration and login system with hashed passwords.
568
+ - **AI Query Submission:** Submit queries to the AI and receive insightful responses.
569
+ - **Token Minting:** Earn tokens based on the value of AI outputs.
570
+ - **Token Management:** View and manage your tokens, including verification status.
571
+ - **Staking:** Stake your tokens to earn rewards and support the network.
572
+ - **Trading:** Trade tokens with other users within the ecosystem.
573
+ - **Transaction History:** Transparent logs of all your activities.
574
+ - **Chat Interface:** Interact with the AI through a dedicated chat box.
575
+ - **About Section:** Detailed information about the ecosystem and its functionalities.
576
+
577
+ ### πŸ› οΈ Technology Stack
578
+ - **Backend:** Streamlit, SQLAlchemy, Web3.py
579
+ - **Frontend:** Streamlit Interface with Tabs
580
+ - **Blockchain:** Solidity, Ethereum (or any EVM-compatible blockchain)
581
+ - **Database:** SQLite (for demonstration) or PostgreSQL (for production)
582
+ - **AI Services:** OpenAI GPT-4 API
583
+
584
+ ### πŸ”’ Security
585
+ - **Password Hashing:** User passwords are securely hashed using industry-standard algorithms.
586
+ - **Blockchain Security:** All interactions with the blockchain are handled securely using Web3.py.
587
+ - **Input Validation:** Comprehensive validation to prevent vulnerabilities like SQL injection and XSS attacks.
588
+ - **Secure Data Handling:** Sensitive information such as private keys and API keys are managed securely within the application interface.
589
+
590
+ ### 🌐 Deployment
591
+ The application is optimized for deployment on **Hugging Face Spaces**, ensuring accessibility and scalability. Users can configure all necessary settings directly through the Streamlit interface, eliminating the need for external environment variables.
592
+
593
+ ### πŸ“ˆ Scalability
594
+ - **Modular Design:** Each component is isolated for independent scaling and maintenance.
595
+ - **Efficient Database Management:** Utilizing SQLAlchemy for optimized interactions.
596
+ - **Asynchronous Processing:** Background threads handle long-running tasks like blockchain verification without blocking the main application.
597
+
598
+ ### πŸ“ž Contact
599
+ **James Burvel O'Callaghan III**
600
+ Email: james.ocallaghan@example.com
601
+ **CITIBANK DEMO BUSINESS INC**
602
+
603
+ ---
604
+ *Embark on this transformative journey with **CITIBANK DEMO BUSINESS INC** to redefine the synergy between AI and blockchain, creating an unparalleled decentralized economy.*
605
+ """)
606
 
607
  # ========================
608
  # Background Task for Verification
 
623
  # Interact with blockchain to verify and mint token
624
  try:
625
  tx_hash = blockchain.verify_output(verification_hash)
626
+ # Assuming the user's blockchain address is stored in 'blockchain_address'
627
+ owner = session.query(User).filter_by(id=token.owner_id).first()
628
+ if not owner.blockchain_address:
629
+ st.warning(f"⚠️ User {owner.username} does not have a blockchain address. Skipping token {token.id}.")
630
+ continue
631
+ minted_token_id = blockchain.mint_token(owner.blockchain_address, token.value, verification_hash)
632
  if minted_token_id:
633
  # Update token status
634
  token.verified = True
635
  token.verification_hash = verification_hash
636
  session.commit()
637
  # Update user's balance
638
+ owner.balance += token.value
 
639
  session.commit()
640
  # Record transaction
641
  transaction = Transaction(
642
+ user_id=owner.id,
643
  token_id=token.id,
644
  action='minted',
645
  value=token.value,
 
670
  with st.sidebar.form("register_form"):
671
  new_username = st.text_input("New Username")
672
  new_password = st.text_input("New Password", type="password")
673
+ blockchain_address = st.text_input("Blockchain Address (0x...)")
674
  register_button = st.form_submit_button(label='Register')
675
 
676
  if register_button:
677
+ if not new_username or not new_password or not blockchain_address:
678
+ st.sidebar.error("❌ All fields are required.")
679
+ elif not Web3.is_address(blockchain_address):
680
+ st.sidebar.error("❌ Invalid Blockchain Address.")
681
  elif session.query(User).filter_by(username=new_username).first():
682
  st.sidebar.error("❌ Username already exists.")
683
+ elif session.query(User).filter_by(blockchain_address=blockchain_address).first():
684
+ st.sidebar.error("❌ Blockchain address already in use.")
685
  else:
686
  hashed_password = generate_password_hash(new_password)
687
+ new_user = User(username=new_username, password=hashed_password, blockchain_address=blockchain_address)
688
  session.add(new_user)
689
  session.commit()
690
  st.sidebar.success("βœ… User registered successfully!")