IPFS-survey / app.py
arthurcarvalho's picture
Upload 2 files
b50be44
import streamlit as st
import requests
import json
import web3
# Global Variables
radio_options = ["Comedy", "Drama", "Documentary"]
# Auxiliary function to disable buttons
def button_disable():
st.session_state["disabled"] = True
# Changing the App title
st.set_page_config(page_title="IPFS-Based Survey",)
# Page title
st.title('Sample Survey')
# The following code centralizes all the buttons
st.markdown("<style>.row-widget.stButton {text-align: center;}</style>", unsafe_allow_html=True)
# Initialize state
if "current_page" not in st.session_state:
st.session_state["current_page"] = 1
st.session_state["Q1"] = ""
st.session_state["Q2"] = None
st.session_state["Q3"] = False
st.session_state["disabled"] = False
# Page 1
if st.session_state["current_page"] == 1:
st.header('Please start by watching the video below', divider = 'gray')
video_file = open('./media/sample-5s.mp4', 'rb')
video_bytes = video_file.read()
st.video(video_bytes)
if st.button('Next'):
st.session_state["current_page"] += 1
st.rerun()
# Page 2
elif st.session_state["current_page"] == 2:
st.session_state["Q1"] = st.text_area(r"$\textsf{\Large Q1: What is the meaning of life?}$",
value = st.session_state["Q1"])
st.markdown("# <br>", unsafe_allow_html=True)
option_selected = st.radio(r"$\textsf{\Large Q2: What's your favorite movie genre?}$",
radio_options,
index = st.session_state["Q2"])
for i, x in enumerate(radio_options):
if x == option_selected:
st.session_state["Q2"] = i
break
st.markdown("# <br>", unsafe_allow_html=True)
col1, col2 = st.columns(2)
with col1:
if st.button('Back'):
st.session_state["current_page"] -= 1
st.rerun()
with col2:
if st.button('Next'):
st.session_state["current_page"] += 1
st.rerun()
# Page 3
elif st.session_state["current_page"] == 3:
st.session_state["Q3"] = st.checkbox('Check if you like this survey',
value = st.session_state["Q3"],
disabled = st.session_state["disabled"])
st.markdown("# <br>", unsafe_allow_html=True)
col1, col2 = st.columns(2)
with col1:
button1 = st.button('Back', disabled = st.session_state["disabled"])
if button1:
st.session_state["current_page"] -= 1
st.rerun()
with col2:
button2 = st.button('Submit Responses',
disabled = st.session_state["disabled"],
on_click = button_disable)
st.markdown("# <br>", unsafe_allow_html=True)
if st.session_state["disabled"]:
with st.spinner(r"$\textsf{\normalsize Storing data on IPFS and Ethereum. This operation might take a few minutes. Please wait!}$"):
try:
response = {'file': json.dumps({"Q1":st.session_state["Q1"],
"Q2":radio_options[st.session_state["Q2"]],
"Q3":st.session_state["Q3"]
})
}
response = requests.post('https://ipfs.infura.io:5001/api/v0/add',
files=response,
auth=(st.secrets["username"], st.secrets["password"]))
IPFS_hash = response.json()["Hash"]
print(IPFS_hash)
# Connect to the Ethereum blockchain
w3 = web3.Web3(web3.HTTPProvider(st.secrets["infura"]))
# Get the contract address
caller = "0xbdB61Ada027eF27ef0709D3848Db1Dd13c96F970"
ABI = '[ { "anonymous": false, "inputs": [ { "indexed": false, "internalType": "string", "name": "data", "type": "string" } ], "name": "Store", "type": "event" }, { "inputs": [ { "internalType": "string", "name": "_IPFSHash", "type": "string" } ], "name": "storeHash", "outputs": [], "stateMutability": "nonpayable", "type": "function" } ]'
# Create a contract instance. Address is equal to the address of the smart contract
contract = w3.eth.contract(address= "0x1e14B06209ACD932EF7731632999Cf4aE1b86e5c", abi=ABI)
# Call your function: 11155111 is Sepolia's id
call_function = contract.functions.storeHash(IPFS_hash).build_transaction({"chainId": 11155111,
"from": caller,
"nonce": w3.eth.get_transaction_count(caller)}) # Initialize address nonce
# Sign transaction
signed_tx = w3.eth.account.sign_transaction(call_function, private_key=st.secrets["pk"])
# Send transaction
send_tx = w3.eth.send_raw_transaction(signed_tx.rawTransaction)
# Wait for transaction receipt
tx_receipt = w3.eth.wait_for_transaction_receipt(send_tx)
print(tx_receipt)
st.success('Data successfully stored. Thank you for taking the survey!', icon="✅")
st.info(f'The IPFS hash is: {IPFS_hash}', icon="ℹ️")
st.info(f'The Ethereum hash is: {tx_receipt.logs[0].transactionHash.hex()}', icon="ℹ️")
except Exception as e:
print(e)
st.error(f'An error ocurred. Here is the error message: {e}', icon="🚨")