Excuse me. I can run my streamlit code in VS code and it works well. But there are errors when I wanna make the app public. What is the reason?

The app link:https://thelittleoptom-br6rc76dwtpqepdfm6rrtp.streamlit.app/

the code is:

import streamlit as st
import random
from datetime import datetime
import plotly
import plotly.graph_objects as go
import pandas as pd
import re

st.set_page_config(page_title='Binocular Vision', page_icon=':bar_chart:', layout='centered')

# Define the sidebar navigation
st.sidebar.title('Navigation')
page = st.sidebar.selectbox('Go to', ('Myopia report', 'W4dot', 'Hart Chart'))

# Render the selected page
if page == 'Myopia report':
    st.title('Myopia report')
    st.caption('Enter your Rx, cylinder and axial length in the google spreadsheet : https://docs.google.com/spreadsheets/d/13sSi_xXEtZsVZ-EFh1nWzRkr6IbXFyXbPbM29Nzdtwg/edit#gid=0')
    from google.oauth2 import service_account
    from googleapiclient.discovery import build

# Replace the placeholders with your API credentials
    creds = service_account.Credentials.from_service_account_file('/Users/chakyinli/Downloads/report.json',
    scopes=['https://www.googleapis.com/auth/spreadsheets'])

# Replace the placeholders with your spreadsheet ID and range
    service = build('sheets', 'v4', credentials=creds)
    sheet = service.spreadsheets()
    result = sheet.values().get(spreadsheetId='13sSi_xXEtZsVZ-EFh1nWzRkr6IbXFyXbPbM29Nzdtwg', range= 'Data!A1:D10').execute()

    df = pd.DataFrame(result.get('values', []))
    st.markdown('---')

    def convert_to_datatime(df):
        df.iloc[1:,0]='01-'+df.iloc[1:,0]
        df.iloc[1:,0]=pd.to_datetime(df.iloc[1:,0],format='%d-%b-%y')
        return df

    convert_to_datatime(df)

    st.dataframe(df)
    
    items= st.multiselect('Select the data that you wanna show: ', options=['Myopia', 'Cylinder', 'Axial length'])
    date_of_treatment=df.iloc[1:,0]



    yes_no= st.selectbox('Are you using any myopia control?', options=['No', 'Yes'])
    date_chose= st.selectbox('When do you start myopia control treatment?', options=date_of_treatment)

    fig = go.Figure()
# Line graph visualization
    if 'Myopia' in items:
        fig.add_trace(go.Scatter(x=df.iloc[1:,0], y=df.iloc[1:,1], mode='lines+markers', name='Myopia', line=dict(color='red')))
        if yes_no=='Yes':
            date_chose = pd.to_datetime(date_chose)
            fig.add_vline(x=date_chose, line_width=1, line_dash='dash', line_color='white')
            fig.add_annotation(x=date_chose, y=0, text='Myopia control use', showarrow=False)
    
    

    if 'Axial length' in items:
        fig.add_trace(go.Scatter(x=df.iloc[1:,0], y=df.iloc[1:,3], mode='lines+markers', name='Axial length',line=dict(color='blue')))
        if yes_no=='Yes':
            date_chose = pd.to_datetime(date_chose)
            fig.add_vline(x=date_chose, line_width=2, line_dash='dash', line_color='white')
            fig.add_annotation(x=date_chose, y=0, text='Myopia control use', showarrow=False)
    
    
    if 'Cylinder' in items:
        fig.add_trace(go.Scatter(x=df.iloc[1:,0], y=df.iloc[1:,2], mode='lines+markers', name='cylinder',line=dict(color='green')))
        if yes_no=='Yes':
            date_chose = pd.to_datetime(date_chose)
            fig.add_vline(x=date_chose, line_width=1, line_dash='dash', line_color='white')
            fig.add_annotation(x=date_chose, y=0, text='Myopia control use', showarrow=False)
    
    fig.update_layout(title='Rx and AL Over Time', xaxis_title='Date', yaxis_title='Measurement')
    st.plotly_chart(fig)

if page == 'W4dot':
    st.title('Worth 4 dot')
    st.write('Sensory fusion testing')
    # Add content specific to the Home page

    st.markdown('---')

    st.caption('Please wear your red-green goggles')
    col1, col2 = st.columns(2)
    
    with col1:
        red_picker = st.slider('Adjust the red color so that you can only see the red dot with your left eye',
                       100, 255, 200, 1)
        red_color = (red_picker, 0.0, 0.0)
        st.write('Selected red color:', red_color)
    with col2:
        blue_picker = st.slider('Adjust the blue color so that you can only see the blue dot with your right eye',
                       0, 255, 0, 1)
        blue_color = (0, blue_picker,150)
        st.write('Selected blue color:', blue_color)
# Define the CSS style for the circles
    circle_style = f"""
    <style>
    .container {{
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    height: 400px;
    }}

    .line {{
    display: flex;
    justify-content: center;
    align-items: center;
    margin-bottom: 50px;
    }}

    .circle {{
        width: 100px;
    height: 100px;
    border-radius: 50%;
    margin: 0px 80px;
}}

.red-circle {{
    background-color: rgb{red_color};
}}

.blue-circle {{
    background-color: rgb{blue_color};
}}

.white-circle {{
    background-color: white;
}}
</style>
"""

# Display the circles using HTML and CSS
    st.markdown(circle_style, unsafe_allow_html=True)
    st.markdown('<div class="container">'
           '<div class="line">'
            '<div class="circle red-circle"></div>'
            '</div>'
            '<div class="line">'
            '<div class="circle blue-circle"></div>'
            '<div class="circle blue-circle"></div>'
            '</div>'
            '<div class="line">'
            '<div class="circle white-circle"></div>'
            '</div>'
            '</div>', unsafe_allow_html=True)

if page == 'Hart Chart':
    st.empty()  # Clear the existing content
    st.title('Welcome to the Hart Chart')
    st.subheader('Antisuppression Hart Chart')
    import random


    def random_letter():
        return chr(random.randint(65, 90))

# Adjust the red color using a slider
    col1, col2 = st.columns(2)
    
    with col1:
        red_picker = st.slider('Adjust the red color so that you can only see the red dot with your left eye',
                       100, 255, 200, 1)
        red_color = (red_picker, 0.0, 0.0)
        st.write('Selected red color:', red_color)
    with col2:
        blue_picker = st.slider('Adjust the blue color so that you can only see the blue dot with your right eye',
                       0, 255, 0, 1)
        blue_color = (0, blue_picker,150)
        st.write('Selected blue color:', blue_color)    


    words = [random_letter() for _ in range(20)]
    font_size = 50
    colored_words = []
    for word in words:
        color_choice = random.choice(["red", "blue"])
        if color_choice == "red":
            colored_words.append("<span style='color: rgb{};font-size: {}px;'>{}</span>".format(red_color,font_size, word))
        else:
            colored_words.append("<span style='color: rgb{};font-size: {}px;'>{}</span>".format(blue_color, font_size, word))

    line_1 = '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'.join(colored_words[:5])
    line_2 = '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'.join(colored_words[15:20])
    line_3 = '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'.join(colored_words[6:11])
    line_4 = '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'.join(colored_words[11:16])

    line_1 = line_1.format(red_color=red_color)
    line_2 = line_2.format(blue_color=blue_color)
    line_3 = line_3.format(red_color=red_color)
    line_4 = line_4.format(blue_color=blue_color)

    st.markdown(line_1, unsafe_allow_html=True)
    st.markdown(line_2, unsafe_allow_html=True)
    st.markdown(line_3, unsafe_allow_html=True)
    st.markdown(line_4, unsafe_allow_html=True)
    st.button('Randomise it!!')

Thank you

Hi @Chak_Yin

I’ve edited your post so that the code snippet is shown properly (adding ``` before and after the code snippet.

I went to your app and it is giving the following error:

ModuleNotFoundError: This app has encountered an error. The original error message is redacted to prevent data leaks. Full error details have been recorded in the logs (if you're on Streamlit Cloud, click on 'Manage app' in the lower right of your app).
Traceback:
File "/home/adminuser/venv/lib/python3.9/site-packages/streamlit/runtime/scriptrunner/script_runner.py", line 542, in _run_script
    exec(code, module.__dict__)
File "/mount/src/thelittleoptom/BVweb.py", line 4, in <module>
    import plotly

which indicates that your prerequisite libraries are missing (e.g. plotly).

Next, I went to your GitHub repo and it seems that requirements.txt file is missing which is where all the prerequisite library dependencies used by the app are defined.

To fix your app, please create a the requirements.txt file and list all the libraries that your app is using, such as:

streamlit
plotly
pandas

These fixes should resolve the issue that your facing.

Hope this helps!

2 Likes

Thank you so much. I am able to deploy but there is another error.
FileNotFoundError: This app has encountered an error. The original error message is redacted to prevent data leaks. Full error details have been recorded in the logs (if you’re on Streamlit Cloud, click on ‘Manage app’ in the lower right of your app).

Traceback:

File "/home/adminuser/venv/lib/python3.9/site-packages/streamlit/runtime/scriptrunner/script_runner.py", line 535, in _run_script
    exec(code, module.__dict__)File "/mount/src/thelittleoptom/BVweb.py", line 23, in <module>
    creds = service_account.Credentials.from_service_account_file('/Users/chakyinli/Downloads/report.json',File "/home/adminuser/venv/lib/python3.9/site-packages/google/oauth2/service_account.py", line 258, in from_service_account_file
    info, signer = _service_account_info.from_filename(File "/home/adminuser/venv/lib/python3.9/site-packages/google/auth/_service_account_info.py", line 78, in from_filename
    with io.open(filename, "r", encoding="utf-8") as json_file:

I try to use my code to assess the google excel but it is not allowed in the web. May i know what the problem is?

I am thking that there may be an error in this code
creds = service_account.Credentials.from_service_account_file(
‘/Users/chakyinli/Downloads/report.json’,
scopes=[‘https://www.googleapis.com/auth/spreadsheets’]

because the json file is stored in my computer? but streamlit cannot read the json file so it is not ok to read the google spreadhsheet? How can I solve this problem? thank you

Hi,

Have you tried putting all files that you want the app to access within the same folder?

If the Excel file is located in the same folder as the app, it should be accessible.

If using Google Sheets, we have a tutorial guide for that:

1 Like

df = conn.read()
^^^^^^^^^^^
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-Hi and thank you. I tried to use your method. However, the error is nowL

packages/streamlit_gsheets/gsheets_connection.py", line 570, in read
return self.client.read(
^^^^^^^^^^^^^^^^^
File “/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/streamlit_gsheets/gsheets_connection.py”, line 419, in read
raise ValueError(“Spreadsheet must be specified”)
ValueError: Spreadsheet must be specified

In my previous codes, i used this method and it work in localhost.
from google.oauth2 import service_account
from googleapiclient.discovery import build

Replace the placeholders with your API credentials

creds = service_account.Credentials.from_service_account_file('/Users/chakyinli/Downloads/report.json',
scopes=['https://www.googleapis.com/auth/spreadsheets'])

Replace the placeholders with your spreadsheet ID and range

service = build('sheets', 'v4', credentials=creds)
sheet = service.spreadsheets()
result = sheet.values().get(spreadsheetId='13sSi_xXEtZsVZ-EFh1nWzRkr6IbXFyXbPbM29Nzdtwg', range= 'Data!A1:D10').execute()

May I know if there is any chance that i can upload my google API json file to streamlit and it can run it?

thank you

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.