I'm trying to build a simple web app for generating random numbers using IBMQ (Qiskit) and Streamlit. However, if there is no IBMQ saved account it should wait for the user to enter the API token and if the token is valid then proceed further and load IBMQ backends. Below is the code which I have written:


# -*- coding: utf-8 -*-
Created on Sun Jan 31 01:30:00 2021

@author: ShadabHussain

import warnings 
import requests
import streamlit as st

from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, IBMQ
from qiskit.tools.monitor import job_monitor

st.set_page_config(page_title='QRNG', page_icon=None, layout='centered', initial_sidebar_state='auto')

st.markdown("<h1 style='text-align: center; color: black;'>Quantum Random Number Generator</h1>", unsafe_allow_html=True)

quantum_computer = st.sidebar.selectbox("Select Quantum Computer Type", ['IBMQ'])

subheader = "using "+ quantum_computer
st.markdown(f"<h1 style='text-align: center; color: black;'>{subheader}</h1>", unsafe_allow_html=True)

def about(quantum_computer):
    if quantum_computer == "IBMQ":
        text = "Qiskit is an open source SDK for working with quantum computers at the level of pulses, circuits and application modules. It accelerates the development of quantum applications by providing the complete set of tools needed for interacting with quantum systems and simulators."
        link = 'https://qiskit.org/'
        link_text = 'For Qiskit Documentation'
    st.markdown(f"<body style='text-align: center; color: black;'>{text}</body>", unsafe_allow_html=True)
    st.markdown(f"<h4 align='center'> <a href={link}>{link_text}</a> </h4>", unsafe_allow_html=True)

def ibmq_qrng(minimum, maximum):
    q = QuantumRegister(num_q, 'q')
    c = ClassicalRegister(num_q, 'c')

    circuit = QuantumCircuit(q, c)
    circuit.h(q)  # Applies hadamard gate to all qubits
    circuit.measure(q, c)  # Measures all qubits

    job = execute(circuit, backend, shots=1)
    counts = job.result().get_counts()
    result = int(counts.most_frequent(), 2)
    result1 = minimum + result % (maximum+1 - minimum)
    return result1

if quantum_computer == "IBMQ": 
    api_key = None
    except Exception as e:
        api_key = st.sidebar.text_input("Enter IBMQ API Key")
        if api_key != None:
            IBMQ.save_account(api_key, overwrite=True)
    provider = IBMQ.get_provider(hub='ibm-q')
    device = st.sidebar.selectbox("Select Quantum Device", [str(each) for each in provider.backends()])
    backend = provider.get_backend(device)
    if device == "ibmq_qasm_simulator":
        num_q = 32
        num_q = 5
    minimum = st.sidebar.number_input("Minimum Random Number", value=0)
    maximum = st.sidebar.number_input("Maximum Random Number", min_value=minimum+1, value=minimum+1)

num_rand_numbers = st.sidebar.number_input("Number of Random Numbers to be Generated", min_value=1, value=1)

def display_result(result1):
    if 'result1' in locals():
        st.markdown(f"<h2 style='text-align: center; color: black;'>Sampling {num_rand_numbers} random number between {minimum} and {maximum}: {result1}</h2>", unsafe_allow_html=True)

if st.sidebar.button("Generate Random Number"):
    if num_rand_numbers <1:
        st.markdown(f"<h3 style='text-align: center; color: black;'>Please enter number of random numbers to be generated 1 or greater then 1</h3>", unsafe_allow_html=True)
        if quantum_computer == "IBMQ":
            if num_rand_numbers==1:
                result1 = ibmq_qrng(minimum, maximum)
                result1 = []
                for i in range(num_rand_numbers):
                    result1.append(ibmq_qrng(minimum, maximum))
    st.markdown(f"<h3 style='text-align: center; color: black;'>Click on 'Generate Random Number' button</h3>", unsafe_allow_html=True)

For running the above code you should have IBMQ API token (https://quantum-computing.ibm.com/account) and python installed on your system with the below dependencies:

pip install qiskit streamlit

Command to run the code:

streamlit run filename.py

When I'm running the app, I'm getting the following error:

enter image description here

Is there any better way of exception handling for qiskit and streamlit?

  • $\begingroup$ From the error message, the exception is thrown when IBMQ.save_account is called. This method call happens outside your try-block. You may need to add another try-except for this statement as well. $\endgroup$ – Egretta.Thula Feb 14 at 18:44
  • 3
    $\begingroup$ I’m voting to close this question because the following 3 reasons: 1) it is a purely code question that belongs to stackoverflow.com/questions/tagged/qiskit ; 2) OP made no effort to extract the minimal problematic part; 3) Duplicated, since OP already asked this question in quantumcomputing.stackexchange.com/q/15910/1859 $\endgroup$ – luciano Feb 15 at 8:39
  • $\begingroup$ @luciano just because SO has a qiskit tag doesn't mean qiskit questions have to go there. If you eant specific types of qiskit questions to go there as a QCSE policy then please try to gather support for that at QCSE Meta. It's also not a duplicate of the user's other question. $\endgroup$ – user1271772 Feb 15 at 22:11
  • 1
    $\begingroup$ it's exactly the same problem with the exactly same exception that can be solved in the exactly same way! At least the previous one was a minimum failing example. We can discuss point 1, no problem. Even two 2, sure. But 3 fully applies! $\endgroup$ – luciano Feb 16 at 7:25
  • $\begingroup$ @luciano its not exactly the same problem, the exception raised is the same here but the way streamlit behaves is different, as the streamlit text_input option doesn't wait for the input and it moves to the next block of coding coz of which exception is not getting handled here in a better way. Also, the solution which you suggested before of running the loop 3 times for handling exception was not very much ideal for exception handling, I was looking for a better way but maybe coz of limitation with Qiskit we are not able to do it $\endgroup$ – Shadab Hussain Feb 17 at 2:19

By looking at the code, it seems the problem is in api_key != None. If api_key is the empty string (which is the case, based on the error), you try to save it. Probably you can change the check for something like not api_key. We talked about this in https://quantumcomputing.stackexchange.com/a/15919/1859


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.