admin08077 commited on
Commit
5259670
Β·
verified Β·
1 Parent(s): cd17d1b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +109 -75
app.py CHANGED
@@ -21,7 +21,7 @@ from sqlalchemy.orm import sessionmaker, relationship
21
  from werkzeug.security import generate_password_hash, check_password_hash
22
 
23
  import openai
24
- from web3 import Web3
25
 
26
  # ========================
27
  # Streamlit Configuration UI
@@ -112,7 +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
- 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
 
@@ -196,43 +196,41 @@ class Blockchain:
196
  },
197
  {
198
  "inputs": [
199
- {"internalType": "address", "name": "owner", "type": "address"},
200
- {"internalType": "uint256", "name": "value", "type": "uint256"},
201
- {"internalType": "string", "name": "hash", "type": "string"}
202
  ],
203
  "name": "mintToken",
204
  "outputs": [
205
  {"internalType": "uint256", "name": "", "type": "uint256"}
206
  ],
207
- "stateMutability": "nonpayable",
208
  "type": "function"
209
  },
210
  {
211
  "inputs": [
212
- {"internalType": "string", "name": "data", "type": "string"}
213
- ],
214
- "name": "verifyData",
215
- "outputs": [
216
- {"internalType": "bool", "name": "", "type": "bool"}
217
  ],
 
 
218
  "stateMutability": "nonpayable",
219
  "type": "function"
220
  }
221
  ]
222
  return sample_abi
223
 
224
- def mint_token(self, owner_address, value, verification_hash):
225
  """
226
- Mints a new token on the blockchain.
227
  Returns the token ID.
228
  """
229
  nonce = self.web3.eth.get_transaction_count(self.account.address)
230
  tx = self.contract.functions.mintToken(
231
- owner_address,
232
- int(value),
233
  verification_hash
234
  ).buildTransaction({
235
- 'chainId': self.web3.eth.chain_id,
 
236
  'gas': 300000,
237
  'gasPrice': self.web3.toWei('20', 'gwei'),
238
  'nonce': nonce,
@@ -253,14 +251,16 @@ class Blockchain:
253
  st.error(f"❌ Blockchain transaction failed: {str(e)}")
254
  return None
255
 
256
- def verify_output(self, data):
257
  """
258
  Verifies the AI output on the blockchain.
259
- Returns the transaction hash.
260
  """
261
  nonce = self.web3.eth.get_transaction_count(self.account.address)
262
- tx = self.contract.functions.verifyData(data).buildTransaction({
263
- 'chainId': self.web3.eth.chain_id,
 
 
 
264
  'gas': 70000,
265
  'gasPrice': self.web3.toWei('20', 'gwei'),
266
  'nonce': nonce,
@@ -281,12 +281,41 @@ blockchain = Blockchain()
281
  # Utility Functions
282
  # ========================
283
 
284
- def calculate_token_value(ai_output):
285
  """
286
- Calculate token value based on AI output.
287
- For demonstration, we use the length of the output.
288
  """
289
- return float(len(ai_output))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
290
 
291
  def process_ai(input_text):
292
  """
@@ -346,8 +375,8 @@ if authentication_status:
346
  # Display Balance
347
  st.subheader("πŸ’° Your Balance")
348
  col1, col2 = st.columns(2)
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"])
@@ -372,27 +401,40 @@ if authentication_status:
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
@@ -405,7 +447,7 @@ if authentication_status:
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')
@@ -447,8 +489,8 @@ if authentication_status:
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
@@ -489,8 +531,8 @@ if authentication_status:
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
@@ -503,7 +545,7 @@ if authentication_status:
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
  }
@@ -516,7 +558,7 @@ if authentication_status:
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
 
@@ -546,13 +588,13 @@ if authentication_status:
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 DEMO BUSINESS INC 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 DEMO BUSINESS INC AI:** {message}")
556
 
557
  # ========================
558
  # About Me Tab
@@ -566,9 +608,10 @@ if authentication_status:
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.
@@ -591,15 +634,15 @@ if authentication_status:
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
 
599
  ---
600
  *Embark on this transformative journey with **CITIBANK DEMO BUSINESS INC** to redefine the synergy between AI and blockchain, creating an unparalleled decentralized economy.*
601
  """)
602
-
603
  # ========================
604
  # Background Task for Verification
605
  # ========================
@@ -609,7 +652,7 @@ if authentication_status:
609
  Background thread to verify unverified tokens.
610
  """
611
  while True:
612
- time.sleep(10) # Simulate delay
613
  with session:
614
  unverified_tokens = session.query(Token).filter_by(verified=False).all()
615
  for token in unverified_tokens:
@@ -618,26 +661,17 @@ if authentication_status:
618
  verification_hash = hashlib.sha256(data.encode()).hexdigest()
619
  # Interact with blockchain to verify and mint token
620
  try:
621
- tx_hash = blockchain.verify_output(verification_hash)
622
- # Assuming the user's blockchain address is stored in 'blockchain_address'
623
- owner = session.query(User).filter_by(id=token.owner_id).first()
624
- if not owner.blockchain_address:
625
- st.warning(f"⚠️ User {owner.username} does not have a blockchain address. Skipping token {token.id}.")
626
- continue
627
- minted_token_id = blockchain.mint_token(owner.blockchain_address, token.value, verification_hash)
628
- if minted_token_id:
629
  # Update token status
630
  token.verified = True
631
  token.verification_hash = verification_hash
632
  session.commit()
633
- # Update user's balance
634
- owner.balance += token.value
635
- session.commit()
636
  # Record transaction
637
  transaction = Transaction(
638
- user_id=owner.id,
639
  token_id=token.id,
640
- action='minted',
641
  value=token.value,
642
  hash=verification_hash
643
  )
 
21
  from werkzeug.security import generate_password_hash, check_password_hash
22
 
23
  import openai
24
+ from web3 import Web3, exceptions
25
 
26
  # ========================
27
  # Streamlit Configuration UI
 
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) # Ethereum address
116
  tokens = relationship('Token', backref='owner', lazy=True)
117
  transactions = relationship('Transaction', backref='user', lazy=True)
118
 
 
196
  },
197
  {
198
  "inputs": [
199
+ {"internalType": "uint256", "name": "_grade", "type": "uint256"},
200
+ {"internalType": "string", "name": "_hash", "type": "string"}
 
201
  ],
202
  "name": "mintToken",
203
  "outputs": [
204
  {"internalType": "uint256", "name": "", "type": "uint256"}
205
  ],
206
+ "stateMutability": "payable",
207
  "type": "function"
208
  },
209
  {
210
  "inputs": [
211
+ {"internalType": "uint256", "name": "_tokenId", "type": "uint256"},
212
+ {"internalType": "string", "name": "_hash", "type": "string"}
 
 
 
213
  ],
214
+ "name": "verifyToken",
215
+ "outputs": [],
216
  "stateMutability": "nonpayable",
217
  "type": "function"
218
  }
219
  ]
220
  return sample_abi
221
 
222
+ def mint_token(self, owner_address, grade, verification_hash):
223
  """
224
+ Mints a new token on the blockchain based on AI grading.
225
  Returns the token ID.
226
  """
227
  nonce = self.web3.eth.get_transaction_count(self.account.address)
228
  tx = self.contract.functions.mintToken(
229
+ grade,
 
230
  verification_hash
231
  ).buildTransaction({
232
+ 'from': self.account.address,
233
+ 'value': self.web3.toWei('0.01', 'ether'), # Mint fee
234
  'gas': 300000,
235
  'gasPrice': self.web3.toWei('20', 'gwei'),
236
  'nonce': nonce,
 
251
  st.error(f"❌ Blockchain transaction failed: {str(e)}")
252
  return None
253
 
254
+ def verify_output(self, token_id, verification_hash):
255
  """
256
  Verifies the AI output on the blockchain.
 
257
  """
258
  nonce = self.web3.eth.get_transaction_count(self.account.address)
259
+ tx = self.contract.functions.verifyToken(
260
+ token_id,
261
+ verification_hash
262
+ ).buildTransaction({
263
+ 'from': self.account.address,
264
  'gas': 70000,
265
  'gasPrice': self.web3.toWei('20', 'gwei'),
266
  'nonce': nonce,
 
281
  # Utility Functions
282
  # ========================
283
 
284
+ def calculate_token_grade(ai_output):
285
  """
286
+ Sends AI output back to AI to grade it based on a predefined rubric.
287
+ Returns the grade which determines the number of tokens.
288
  """
289
+ try:
290
+ # Define the grading rubric as a prompt
291
+ grading_prompt = f"""
292
+ Please grade the following AI-generated content based on its relevance, coherence, and usefulness.
293
+ Use a scale from 1 to 10, where 10 is highly valuable and 1 is not valuable at all.
294
+
295
+ AI Output:
296
+ \"\"\"
297
+ {ai_output}
298
+ \"\"\"
299
+
300
+ Grade:
301
+ """
302
+ response = openai.Completion.create(
303
+ engine="text-davinci-003", # Use 'gpt-4' if available
304
+ prompt=grading_prompt,
305
+ max_tokens=10,
306
+ temperature=0,
307
+ n=1,
308
+ stop=None
309
+ )
310
+ grade_text = response.choices[0].text.strip()
311
+ grade = int(grade_text)
312
+ # Define maximum tokens per grade
313
+ max_tokens = 100
314
+ token_amount = (grade / 10) * max_tokens
315
+ return token_amount
316
+ except Exception as e:
317
+ st.error(f"❌ Error grading AI output: {str(e)}")
318
+ return 0
319
 
320
  def process_ai(input_text):
321
  """
 
375
  # Display Balance
376
  st.subheader("πŸ’° Your Balance")
377
  col1, col2 = st.columns(2)
378
+ col1.metric("Tokens", f"{user.balance:.2f}")
379
+ col2.metric("Staked Tokens", f"{user.staked:.2f}")
380
 
381
  # Create Tabs
382
  tabs = st.tabs(["AI Query", "Token Management", "Staking", "Trading", "Transaction History", "Chat", "About Me"])
 
401
  else:
402
  st.success("βœ… AI Query Processed!")
403
  st.write(f"**AI Output:** {ai_output}")
404
+ # Grade AI Output
405
+ token_amount = calculate_token_grade(ai_output)
406
+ if token_amount > 0:
407
+ # Mint Token
408
+ verification_hash = hashlib.sha256(ai_output.encode()).hexdigest()
409
+ token_id = blockchain.mint_token(user.blockchain_address, token_amount, verification_hash)
410
+ if token_id:
411
+ # Update local database
412
+ token = Token(
413
+ id=str(uuid.uuid4()),
414
+ owner_id=user.id,
415
+ value=token_amount,
416
+ verified=False,
417
+ verification_hash=verification_hash
418
+ )
419
+ session.add(token)
420
+ session.commit()
421
+ # Update user's balance
422
+ user.balance += token_amount
423
+ session.commit()
424
+ # Record transaction
425
+ transaction = Transaction(
426
+ user_id=user.id,
427
+ token_id=token.id,
428
+ action='minted',
429
+ value=token_amount,
430
+ hash=verification_hash
431
+ )
432
+ session.add(transaction)
433
+ session.commit()
434
+ st.write(f"**Token ID:** {token.id}")
435
+ st.write(f"**Tokens Earned:** {token_amount:.2f}")
436
+ else:
437
+ st.error("❌ Token amount determined as zero. Please try again.")
438
 
439
  # ========================
440
  # Token Management
 
447
  for token in tokens:
448
  token_info = {
449
  "Token ID": token.id,
450
+ "Value": f"{token.value:.2f}",
451
  "Verified": "Yes" if token.verified else "No",
452
  "Verification Hash": token.verification_hash or "N/A",
453
  "Created At": token.created_at.strftime('%Y-%m-%d %H:%M:%S')
 
489
  session.add(transaction)
490
  session.commit()
491
  st.success("βœ… Staked successfully.")
492
+ st.write(f"**New Balance:** {user.balance:.2f}")
493
+ st.write(f"**Total Staked:** {user.staked:.2f}")
494
 
495
  # ========================
496
  # Trading
 
531
  session.add(transaction)
532
  session.commit()
533
  st.success("βœ… Trade successful.")
534
+ st.write(f"**New Balance:** {user.balance:.2f}")
535
+ st.write(f"**Token Value:** {token.value:.2f}")
536
 
537
  # ========================
538
  # Transaction History
 
545
  for tx in transactions:
546
  tx_info = {
547
  "Action": tx.action,
548
+ "Value": f"{tx.value:.2f}" if tx.value else "N/A",
549
  "Hash": tx.hash or "N/A",
550
  "Timestamp": tx.timestamp.strftime('%Y-%m-%d %H:%M:%S')
551
  }
 
558
  # Chat Interface
559
  # ========================
560
  with tabs[5]:
561
+ st.subheader("πŸ’¬ Chat with CITIBANK DEMO BUSINESS INC AI")
562
  if 'chat_history' not in st.session_state:
563
  st.session_state['chat_history'] = []
564
 
 
588
  else:
589
  st.session_state.chat_history.append(("You", user_input))
590
  ai_response = get_ai_response(user_input)
591
+ st.session_state.chat_history.append(("CITIBANK AI", ai_response))
592
 
593
  for sender, message in st.session_state.chat_history:
594
  if sender == "You":
595
  st.markdown(f"**You:** {message}")
596
  else:
597
+ st.markdown(f"**CITIBANK AI:** {message}")
598
 
599
  # ========================
600
  # About Me Tab
 
608
  ### πŸš€ Features
609
  - **User Authentication:** Secure registration and login system with hashed passwords.
610
  - **AI Query Submission:** Submit queries to the AI and receive insightful responses.
611
+ - **AI Grading Mechanism:** AI evaluates its own outputs based on a predefined rubric to determine token rewards.
612
+ - **Token Minting:** Earn tokens based on the AI-generated content's quality.
613
  - **Token Management:** View and manage your tokens, including verification status.
614
+ - **Staking:** Stake your tokens to earn rewards and support the ecosystem.
615
  - **Trading:** Trade tokens with other users within the ecosystem.
616
  - **Transaction History:** Transparent logs of all your activities.
617
  - **Chat Interface:** Interact with the AI through a dedicated chat box.
 
634
  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.
635
 
636
  ### πŸ“ˆ Scalability
637
+ - **Modular Design:** Each component is isolated, allowing for independent scaling and maintenance.
638
  - **Efficient Database Management:** Utilizing SQLAlchemy for optimized interactions.
639
  - **Asynchronous Processing:** Background threads handle long-running tasks like blockchain verification without blocking the main application.
640
+ - **Optimized Blockchain Interactions:** Efficient gas usage and transaction management to handle high volumes of token minting and verification.
641
 
642
  ---
643
  *Embark on this transformative journey with **CITIBANK DEMO BUSINESS INC** to redefine the synergy between AI and blockchain, creating an unparalleled decentralized economy.*
644
  """)
645
+
646
  # ========================
647
  # Background Task for Verification
648
  # ========================
 
652
  Background thread to verify unverified tokens.
653
  """
654
  while True:
655
+ time.sleep(30) # Check every 30 seconds
656
  with session:
657
  unverified_tokens = session.query(Token).filter_by(verified=False).all()
658
  for token in unverified_tokens:
 
661
  verification_hash = hashlib.sha256(data.encode()).hexdigest()
662
  # Interact with blockchain to verify and mint token
663
  try:
664
+ tx_hash = blockchain.verify_output(token.id, verification_hash)
665
+ if tx_hash:
 
 
 
 
 
 
666
  # Update token status
667
  token.verified = True
668
  token.verification_hash = verification_hash
669
  session.commit()
 
 
 
670
  # Record transaction
671
  transaction = Transaction(
672
+ user_id=token.owner_id,
673
  token_id=token.id,
674
+ action='verified',
675
  value=token.value,
676
  hash=verification_hash
677
  )