admin08077 commited on
Commit
d9c1cf8
Β·
verified Β·
1 Parent(s): 6dda95d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +147 -131
app.py CHANGED
@@ -55,9 +55,9 @@ BLOCKCHAIN_NODE_URL = st.sidebar.text_input("Blockchain Node URL", value="https:
55
  # Hardcoded Smart Contract Address
56
  CONTRACT_ADDRESS = "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48" # USDC Token Address
57
 
58
- # OpenAI Configuration
59
  st.sidebar.subheader("πŸ€– OpenAI Configuration")
60
- OPENAI_API_KEY = st.sidebar.text_input("OpenAI API Key", type="password")
61
 
62
  # ========================
63
  # Validate Configuration Inputs
@@ -70,34 +70,24 @@ if not BLOCKCHAIN_NODE_URL.startswith("http"):
70
  config_valid = False
71
  config_errors.append("Blockchain Node URL must start with http or https.")
72
 
73
- if not st.sidebar:
74
- config_valid = False
75
- config_errors.append("Blockchain Node URL is required.")
76
-
77
- if not CONTRACT_ADDRESS.startswith("0x") or len(CONTRACT_ADDRESS) != 42:
78
  config_valid = False
79
  config_errors.append("Invalid Smart Contract Address.")
80
 
81
- if not OPENAI_API_KEY:
82
- config_valid = False
83
- config_errors.append("OpenAI API Key is required.")
84
-
85
- if db_type == "PostgreSQL":
86
- if not all([pg_host, pg_port, pg_user, pg_password, pg_db]):
87
- config_valid = False
88
- config_errors.append("All PostgreSQL configuration fields must be filled.")
89
-
90
  if not config_valid:
91
  st.error("⚠️ **Configuration Errors:**")
92
  for error in config_errors:
93
  st.error(f"- {error}")
94
  st.stop()
95
 
96
- # ========================
97
- # Initialize OpenAI API
98
- # ========================
99
-
100
- openai.api_key = OPENAI_API_KEY
 
 
 
101
 
102
  # ========================
103
  # Database Setup
@@ -124,6 +114,7 @@ class Token(Base):
124
  owner_id = Column(Integer, ForeignKey('users.id'), nullable=False)
125
  value = Column(Float, nullable=False)
126
  text = Column(String(256), nullable=False) # Text to store on blockchain
 
127
  verified = Column(Boolean, default=False)
128
  verification_hash = Column(String(64))
129
  created_at = Column(DateTime, default=datetime.utcnow)
@@ -204,6 +195,8 @@ def calculate_token_grade(ai_output):
204
  Sends AI output back to AI to grade it based on a predefined rubric.
205
  Returns the grade which determines the number of tokens.
206
  """
 
 
207
  try:
208
  # Define the grading rubric as a prompt
209
  grading_prompt = f"""
@@ -239,6 +232,8 @@ def process_ai(input_text):
239
  """
240
  Processes input text using OpenAI's GPT-4 API.
241
  """
 
 
242
  try:
243
  response = openai.Completion.create(
244
  engine="text-davinci-003", # Use 'gpt-4' if available
@@ -296,75 +291,88 @@ if authentication_status:
296
  col1.metric("Tokens", f"{user.balance:.2f}")
297
  col2.metric("Staked Tokens", f"{user.staked:.2f}")
298
 
299
- # Create Tabs
300
- tabs = st.tabs(["AI Query", "Token Management", "Staking", "Trading", "Transaction History", "Chat", "About Me"])
 
 
 
 
 
 
 
301
 
302
  # ========================
303
- # AI Query Submission
304
  # ========================
305
- with tabs[0]:
306
- st.subheader("πŸ€– Submit AI Query")
307
- with st.form("ai_query_form"):
308
- input_text = st.text_area("Enter your query here...", height=100)
309
- submit_button = st.form_submit_button(label='Submit')
310
-
311
- if submit_button:
312
- if input_text.strip() == "":
313
- st.error("❌ Input text cannot be empty.")
314
- else:
315
- with st.spinner("πŸ” Processing your AI query..."):
316
- ai_output = process_ai(input_text)
317
- if ai_output.startswith("❌"):
318
- st.error(ai_output)
319
  else:
320
- st.success("βœ… AI Query Processed!")
321
- st.write(f"**AI Output:** {ai_output}")
322
- # Grade AI Output
323
- token_amount = calculate_token_grade(ai_output)
324
- if token_amount > 0:
325
- # Mint Token via API
326
- token_address = user.blockchain_address
327
- token_contract = CONTRACT_ADDRESS # Using hardcoded contract address
328
- balance = "100" # Adjust as needed
329
- mint_success, mint_response = mint_tokens_via_api(token_address, token_contract, balance)
330
- if mint_success:
331
- st.success("βœ… Token minted successfully via API!")
332
- st.write(f"**API Response:** {json.dumps(mint_response, indent=2)}")
333
- # Update local database
334
- token = Token(
335
- id=str(uuid.uuid4()),
336
- owner_id=user.id,
337
- value=token_amount,
338
- text=input_text, # Store the input text
339
- verified=False,
340
- verification_hash=hashlib.sha256(ai_output.encode()).hexdigest()
341
- )
342
- session.add(token)
343
- session.commit()
344
- # Update user's balance
345
- user.balance += token_amount
346
- session.commit()
347
- # Record transaction
348
- transaction = Transaction(
349
- user_id=user.id,
350
- token_id=token.id,
351
- action='minted',
352
- value=token_amount,
353
- hash=token.verification_hash
354
- )
355
- session.add(transaction)
356
- session.commit()
357
- st.write(f"**Token ID:** {token.id}")
358
- st.write(f"**Tokens Earned:** {token_amount:.2f}")
359
- else:
360
- st.error(f"❌ Token minting failed: {mint_response}")
361
  else:
362
- st.error("❌ Token amount determined as zero. Please try again.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
363
 
364
  # ========================
365
  # Token Management
366
  # ========================
367
- with tabs[1]:
 
 
 
368
  st.subheader("πŸͺ™ Your Tokens")
369
  tokens = session.query(Token).filter_by(owner_id=user.id).all()
370
  if tokens:
@@ -373,6 +381,7 @@ if authentication_status:
373
  token_info = {
374
  "Token ID": token.id,
375
  "Value": f"{token.value:.2f}",
 
376
  "Text": token.text,
377
  "Verified": "Yes" if token.verified else "No",
378
  "Verification Hash": token.verification_hash or "N/A",
@@ -386,7 +395,8 @@ if authentication_status:
386
  # ========================
387
  # Staking
388
  # ========================
389
- with tabs[2]:
 
390
  st.subheader("πŸ“ˆ Stake Tokens")
391
  with st.form("stake_form"):
392
  stake_amount = st.number_input("Amount to Stake", min_value=0.0, step=1.0)
@@ -421,7 +431,8 @@ if authentication_status:
421
  # ========================
422
  # Trading
423
  # ========================
424
- with tabs[3]:
 
425
  st.subheader("πŸ”„ Trade Tokens")
426
  with st.form("trade_form"):
427
  seller_username = st.text_input("Seller Username")
@@ -463,7 +474,8 @@ if authentication_status:
463
  # ========================
464
  # Transaction History
465
  # ========================
466
- with tabs[4]:
 
467
  st.subheader("πŸ“œ Transaction History")
468
  transactions = session.query(Transaction).filter_by(user_id=user.id).order_by(Transaction.timestamp.desc()).all()
469
  if transactions:
@@ -481,51 +493,54 @@ if authentication_status:
481
  st.write("πŸ“­ No transactions found.")
482
 
483
  # ========================
484
- # Chat Interface
485
  # ========================
486
- with tabs[5]:
487
- st.subheader("πŸ’¬ Chat with CITIBANK DEMO BUSINESS INC AI")
488
- if 'chat_history' not in st.session_state:
489
- st.session_state['chat_history'] = []
490
-
491
- def get_ai_response(user_input):
492
- """
493
- Generate AI response using OpenAI.
494
- """
495
- try:
496
- response = openai.Completion.create(
497
- engine="text-davinci-003", # Use 'gpt-4' if available
498
- prompt=user_input,
499
- max_tokens=150,
500
- temperature=0.7,
501
- n=1,
502
- stop=None
503
- )
504
- ai_output = response.choices[0].text.strip()
505
- return ai_output
506
- except Exception as e:
507
- return f"❌ Error processing AI output: {str(e)}"
508
-
509
- user_input = st.text_input("You:", key="chat_input")
510
-
511
- if st.button("Send"):
512
- if user_input.strip() == "":
513
- st.warning("❌ Please enter a message.")
514
- else:
515
- st.session_state.chat_history.append(("You", user_input))
516
- ai_response = get_ai_response(user_input)
517
- st.session_state.chat_history.append(("CITIBANK AI", ai_response))
518
-
519
- for sender, message in st.session_state.chat_history:
520
- if sender == "You":
521
- st.markdown(f"**You:** {message}")
522
- else:
523
- st.markdown(f"**CITIBANK AI:** {message}")
 
 
524
 
525
  # ========================
526
  # About Me Tab
527
  # ========================
528
- with tabs[6]:
 
529
  st.subheader("ℹ️ About CITIBANK DEMO BUSINESS INC AI Crypto Ecosystem")
530
  st.markdown("""
531
  ### 🌟 Overview
@@ -533,14 +548,14 @@ if authentication_status:
533
 
534
  ### πŸš€ Features
535
  - **User Authentication:** Secure registration and login system with hashed passwords.
536
- - **AI Query Submission:** Submit queries to the AI and receive insightful responses.
537
- - **AI Grading Mechanism:** AI evaluates its own outputs based on a predefined rubric to determine token rewards.
538
  - **Token Minting:** Earn tokens based on the AI-generated content's quality.
539
  - **Token Management:** View and manage your tokens, including verification status.
540
  - **Staking:** Stake your tokens to earn rewards and support the ecosystem.
541
  - **Trading:** Trade tokens with other users within the ecosystem.
542
  - **Transaction History:** Transparent logs of all your activities.
543
- - **Chat Interface:** Interact with the AI through a dedicated chat box.
544
  - **About Section:** Detailed information about the ecosystem and its functionalities.
545
 
546
  ### πŸ› οΈ Technology Stack
@@ -548,7 +563,7 @@ if authentication_status:
548
  - **Frontend:** Streamlit Interface with Tabs
549
  - **Blockchain:** Solidity, Ethereum (or any EVM-compatible blockchain)
550
  - **Database:** SQLite (for demonstration) or PostgreSQL (for production)
551
- - **AI Services:** OpenAI GPT-4 API
552
 
553
  ### πŸ”’ Security
554
  - **Password Hashing:** User passwords are securely hashed using industry-standard algorithms.
@@ -574,8 +589,8 @@ if authentication_status:
574
 
575
  st.sidebar.header("πŸͺ™ Mint Token")
576
  with st.sidebar.form("mint_token_form"):
577
- mint_address = st.text_input("Recipient Address (0x...)")
578
- mint_text = st.text_input("Mint Text")
579
  mint_button = st.form_submit_button(label='Mint Token')
580
 
581
  if mint_button:
@@ -584,7 +599,7 @@ if authentication_status:
584
  elif not (mint_address.startswith("0x") and len(mint_address) == 42):
585
  st.sidebar.error("❌ Invalid Blockchain Address format.")
586
  else:
587
- with st.spinner("πŸ” Minting tokens and storing text..."):
588
  # Mint tokens via external API
589
  token_contract = CONTRACT_ADDRESS # Using hardcoded contract address
590
  balance = "100" # Adjust as needed or make it dynamic
@@ -600,6 +615,7 @@ if authentication_status:
600
  owner_id=user.id,
601
  value=100.0, # Assuming balance is 100 tokens
602
  text=mint_text, # Store the input text
 
603
  verified=False,
604
  verification_hash=hashlib.sha256(mint_text.encode()).hexdigest()
605
  )
 
55
  # Hardcoded Smart Contract Address
56
  CONTRACT_ADDRESS = "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48" # USDC Token Address
57
 
58
+ # OpenAI Configuration (Optional)
59
  st.sidebar.subheader("πŸ€– OpenAI Configuration")
60
+ OPENAI_API_KEY = st.sidebar.text_input("OpenAI API Key (Optional)", type="password")
61
 
62
  # ========================
63
  # Validate Configuration Inputs
 
70
  config_valid = False
71
  config_errors.append("Blockchain Node URL must start with http or https.")
72
 
73
+ if not (CONTRACT_ADDRESS.startswith("0x") and len(CONTRACT_ADDRESS) == 42):
 
 
 
 
74
  config_valid = False
75
  config_errors.append("Invalid Smart Contract Address.")
76
 
 
 
 
 
 
 
 
 
 
77
  if not config_valid:
78
  st.error("⚠️ **Configuration Errors:**")
79
  for error in config_errors:
80
  st.error(f"- {error}")
81
  st.stop()
82
 
83
+ # Initialize OpenAI API if API key is provided
84
+ if OPENAI_API_KEY:
85
+ openai.api_key = OPENAI_API_KEY
86
+ openai_enabled = True
87
+ st.sidebar.success("πŸ”Œ OpenAI Connected")
88
+ else:
89
+ openai_enabled = False
90
+ st.sidebar.info("πŸ€– OpenAI not connected. AI features are disabled.")
91
 
92
  # ========================
93
  # Database Setup
 
114
  owner_id = Column(Integer, ForeignKey('users.id'), nullable=False)
115
  value = Column(Float, nullable=False)
116
  text = Column(String(256), nullable=False) # Text to store on blockchain
117
+ recipient_address = Column(String(42), nullable=False) # Address receiving tokens
118
  verified = Column(Boolean, default=False)
119
  verification_hash = Column(String(64))
120
  created_at = Column(DateTime, default=datetime.utcnow)
 
195
  Sends AI output back to AI to grade it based on a predefined rubric.
196
  Returns the grade which determines the number of tokens.
197
  """
198
+ if not openai_enabled:
199
+ return 0 # No grading if OpenAI is not enabled
200
  try:
201
  # Define the grading rubric as a prompt
202
  grading_prompt = f"""
 
232
  """
233
  Processes input text using OpenAI's GPT-4 API.
234
  """
235
+ if not openai_enabled:
236
+ return "❌ OpenAI is not configured. Please provide an OpenAI API Key to use AI features."
237
  try:
238
  response = openai.Completion.create(
239
  engine="text-davinci-003", # Use 'gpt-4' if available
 
291
  col1.metric("Tokens", f"{user.balance:.2f}")
292
  col2.metric("Staked Tokens", f"{user.staked:.2f}")
293
 
294
+ # Create Tabs based on OpenAI configuration
295
+ tabs_titles = ["Token Management", "Staking", "Trading", "Transaction History"]
296
+ if openai_enabled:
297
+ tabs_titles.insert(0, "AI Query")
298
+ tabs_titles.append("Chat")
299
+
300
+ tabs_titles.append("About Me")
301
+
302
+ tabs = st.tabs(tabs_titles)
303
 
304
  # ========================
305
+ # AI Query Submission (Optional)
306
  # ========================
307
+ if openai_enabled:
308
+ with tabs[0]:
309
+ st.subheader("πŸ€– Submit AI Query")
310
+ with st.form("ai_query_form"):
311
+ input_text = st.text_area("Enter your query here...", height=100)
312
+ submit_button = st.form_submit_button(label='Submit')
313
+
314
+ if submit_button:
315
+ if input_text.strip() == "":
316
+ st.error("❌ Input text cannot be empty.")
 
 
 
 
317
  else:
318
+ with st.spinner("πŸ” Processing your AI query..."):
319
+ ai_output = process_ai(input_text)
320
+ if ai_output.startswith("❌"):
321
+ st.error(ai_output)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
322
  else:
323
+ st.success("βœ… AI Query Processed!")
324
+ st.write(f"**AI Output:** {ai_output}")
325
+ # Grade AI Output
326
+ token_amount = calculate_token_grade(ai_output)
327
+ if token_amount > 0:
328
+ # Mint Token via API
329
+ token_address = user.blockchain_address
330
+ token_contract = CONTRACT_ADDRESS # Using hardcoded contract address
331
+ balance = "100" # Adjust as needed
332
+ mint_success, mint_response = mint_tokens_via_api(token_address, token_contract, balance)
333
+ if mint_success:
334
+ st.success("βœ… Token minted successfully via API!")
335
+ st.write(f"**API Response:** {json.dumps(mint_response, indent=2)}")
336
+ # Update local database
337
+ token = Token(
338
+ id=str(uuid.uuid4()),
339
+ owner_id=user.id,
340
+ value=token_amount,
341
+ text=input_text, # Store the input text
342
+ recipient_address=token_address,
343
+ verified=False,
344
+ verification_hash=hashlib.sha256(ai_output.encode()).hexdigest()
345
+ )
346
+ session.add(token)
347
+ session.commit()
348
+ # Update user's balance
349
+ user.balance += token_amount
350
+ session.commit()
351
+ # Record transaction
352
+ transaction = Transaction(
353
+ user_id=user.id,
354
+ token_id=token.id,
355
+ action='minted',
356
+ value=token_amount,
357
+ hash=token.verification_hash
358
+ )
359
+ session.add(transaction)
360
+ session.commit()
361
+ st.write(f"**Token ID:** {token.id}")
362
+ st.write(f"**Tokens Earned:** {token_amount:.2f}")
363
+ st.write(f"**Stored Text:** {token.text}")
364
+ else:
365
+ st.error(f"❌ Token minting failed: {mint_response}")
366
+ else:
367
+ st.error("❌ Token amount determined as zero. Please try again.")
368
 
369
  # ========================
370
  # Token Management
371
  # ========================
372
+ token_tab_index = 0
373
+ if openai_enabled:
374
+ token_tab_index = 1
375
+ with tabs[token_tab_index]:
376
  st.subheader("πŸͺ™ Your Tokens")
377
  tokens = session.query(Token).filter_by(owner_id=user.id).all()
378
  if tokens:
 
381
  token_info = {
382
  "Token ID": token.id,
383
  "Value": f"{token.value:.2f}",
384
+ "Recipient Address": token.recipient_address,
385
  "Text": token.text,
386
  "Verified": "Yes" if token.verified else "No",
387
  "Verification Hash": token.verification_hash or "N/A",
 
395
  # ========================
396
  # Staking
397
  # ========================
398
+ staking_tab_index = token_tab_index + 1
399
+ with tabs[staking_tab_index]:
400
  st.subheader("πŸ“ˆ Stake Tokens")
401
  with st.form("stake_form"):
402
  stake_amount = st.number_input("Amount to Stake", min_value=0.0, step=1.0)
 
431
  # ========================
432
  # Trading
433
  # ========================
434
+ trading_tab_index = staking_tab_index + 1
435
+ with tabs[trading_tab_index]:
436
  st.subheader("πŸ”„ Trade Tokens")
437
  with st.form("trade_form"):
438
  seller_username = st.text_input("Seller Username")
 
474
  # ========================
475
  # Transaction History
476
  # ========================
477
+ transaction_history_tab_index = trading_tab_index + 1
478
+ with tabs[transaction_history_tab_index]:
479
  st.subheader("πŸ“œ Transaction History")
480
  transactions = session.query(Transaction).filter_by(user_id=user.id).order_by(Transaction.timestamp.desc()).all()
481
  if transactions:
 
493
  st.write("πŸ“­ No transactions found.")
494
 
495
  # ========================
496
+ # Chat Interface (Optional)
497
  # ========================
498
+ if openai_enabled:
499
+ chat_tab_index = transaction_history_tab_index + 1
500
+ with tabs[chat_tab_index]:
501
+ st.subheader("πŸ’¬ Chat with CITIBANK DEMO BUSINESS INC AI")
502
+ if 'chat_history' not in st.session_state:
503
+ st.session_state['chat_history'] = []
504
+
505
+ def get_ai_response(user_input):
506
+ """
507
+ Generate AI response using OpenAI.
508
+ """
509
+ try:
510
+ response = openai.Completion.create(
511
+ engine="text-davinci-003", # Use 'gpt-4' if available
512
+ prompt=user_input,
513
+ max_tokens=150,
514
+ temperature=0.7,
515
+ n=1,
516
+ stop=None
517
+ )
518
+ ai_output = response.choices[0].text.strip()
519
+ return ai_output
520
+ except Exception as e:
521
+ return f"❌ Error processing AI output: {str(e)}"
522
+
523
+ user_input = st.text_input("You:", key="chat_input")
524
+
525
+ if st.button("Send"):
526
+ if user_input.strip() == "":
527
+ st.warning("❌ Please enter a message.")
528
+ else:
529
+ st.session_state.chat_history.append(("You", user_input))
530
+ ai_response = get_ai_response(user_input)
531
+ st.session_state.chat_history.append(("CITIBANK AI", ai_response))
532
+
533
+ for sender, message in st.session_state.chat_history:
534
+ if sender == "You":
535
+ st.markdown(f"**You:** {message}")
536
+ else:
537
+ st.markdown(f"**CITIBANK AI:** {message}")
538
 
539
  # ========================
540
  # About Me Tab
541
  # ========================
542
+ about_me_tab_index = transaction_history_tab_index + (2 if openai_enabled else 1)
543
+ with tabs[about_me_tab_index]:
544
  st.subheader("ℹ️ About CITIBANK DEMO BUSINESS INC AI Crypto Ecosystem")
545
  st.markdown("""
546
  ### 🌟 Overview
 
548
 
549
  ### πŸš€ Features
550
  - **User Authentication:** Secure registration and login system with hashed passwords.
551
+ - **AI Query Submission:** Submit queries to the AI and receive insightful responses. *(Requires OpenAI API Key)*
552
+ - **AI Grading Mechanism:** AI evaluates its own outputs based on a predefined rubric to determine token rewards. *(Requires OpenAI API Key)*
553
  - **Token Minting:** Earn tokens based on the AI-generated content's quality.
554
  - **Token Management:** View and manage your tokens, including verification status.
555
  - **Staking:** Stake your tokens to earn rewards and support the ecosystem.
556
  - **Trading:** Trade tokens with other users within the ecosystem.
557
  - **Transaction History:** Transparent logs of all your activities.
558
+ - **Chat Interface:** Interact with the AI through a dedicated chat box. *(Requires OpenAI API Key)*
559
  - **About Section:** Detailed information about the ecosystem and its functionalities.
560
 
561
  ### πŸ› οΈ Technology Stack
 
563
  - **Frontend:** Streamlit Interface with Tabs
564
  - **Blockchain:** Solidity, Ethereum (or any EVM-compatible blockchain)
565
  - **Database:** SQLite (for demonstration) or PostgreSQL (for production)
566
+ - **AI Services:** OpenAI GPT-4 API *(Optional)*
567
 
568
  ### πŸ”’ Security
569
  - **Password Hashing:** User passwords are securely hashed using industry-standard algorithms.
 
589
 
590
  st.sidebar.header("πŸͺ™ Mint Token")
591
  with st.sidebar.form("mint_token_form"):
592
+ mint_address = st.text_input("Recipient Address (0x...)", value="")
593
+ mint_text = st.text_input("Mint Text", value="")
594
  mint_button = st.form_submit_button(label='Mint Token')
595
 
596
  if mint_button:
 
599
  elif not (mint_address.startswith("0x") and len(mint_address) == 42):
600
  st.sidebar.error("❌ Invalid Blockchain Address format.")
601
  else:
602
+ with st.sidebar.spinner("πŸ” Minting tokens and storing text..."):
603
  # Mint tokens via external API
604
  token_contract = CONTRACT_ADDRESS # Using hardcoded contract address
605
  balance = "100" # Adjust as needed or make it dynamic
 
615
  owner_id=user.id,
616
  value=100.0, # Assuming balance is 100 tokens
617
  text=mint_text, # Store the input text
618
+ recipient_address=mint_address,
619
  verified=False,
620
  verification_hash=hashlib.sha256(mint_text.encode()).hexdigest()
621
  )