Example #1
0
 def GET(self, id):
     page_info = PageInfo('Personal')
     ans1, temp1_user = infoDBserver.get_user(session.get_user_id())
     ans2, temp2_user = infoDBserver.get_user(session.get_user_id())
     if ans1 and ans2:
         current_user1 = transclass.user_trans(temp1_user)
         current_user2 = transclass.user_trans(temp2_user)
         return render.personal(current_user1, current_user2, page_info)
     else:
         raise web.notfound()
Example #2
0
 def GET(self, id):
     page_info = PageInfo('Personal')
     ans1, temp1_user = infoDBserver.get_user(session.get_user_id())
     ans2, temp2_user = infoDBserver.get_user(session.get_user_id())
     if ans1 and ans2:
         current_user1 = transclass.user_trans(temp1_user)
         current_user2 = transclass.user_trans(temp2_user)
         return render.personal(current_user1, current_user2, page_info)
     else:
         raise web.notfound()
Example #3
0
 def GET(self):
     page_info = PageInfo('About us')
     ans, temp_user = infoDBserver.get_user(session.get_user_id())
     if ans:
         current_user = transclass.user_trans(temp_user)
         return render.about(current_user, page_info)
     return render.about("", page_info)
Example #4
0
    def POST(self, id, encodedURL):
        session_id = session.get_user_id()
        userId = int(id)
        if userId != session_id:
            js = {}
            js['ok'] = False
            js['message'] = "web.notfound()"
            ans = json.dumps(js)
            return ans
            # raise web.notfound()

        newKey = None
        try:
            with open(tmp_img_path(id), 'rb') as f:
                uploadURL = base64.urlsafe_b64decode(str(encodedURL))
                newKey, err = fs.putFile(f, uploadURL)
                if err != None:
                    web.debug(err)
                    js = {}
                    js['ok'] = False
                    js['message'] = u"头像上传失败"
                    ans = json.dumps(js)
                    return ans
                    # raise web.seeother('/personal_edit/' + id)
        except IOError:
            pass

        x = web.input()
        web.debug(x.uname)
        web.debug(x.email)
        web.debug(newKey)

        ans, temp_user = infoDBserver.get_user(session_id)
        if not ans:
            raise web.notfound()

        if x.uname:
            temp_user.userName = x.uname
        if x.email:
            temp_user.mail = x.email
        if newKey:
            temp_user.picKey = newKey

        js = {}
        js['ok'] = True
        js['message'] = "Everything is OK~"

        ret = infoDBserver.modify_user(userId, temp_user)
        if not ret:
            web.debug(ret)
            js['ok'] = False
            js['message'] = 'update user info failed.'
            try:
                os.remove(tmp_img_path(id))
            except:
                pass

        ans = json.dumps(js)
        return ans
Example #5
0
    def POST(self, id):
        if session.get_user_id() != int(id):
            raise web.notfound()

        x = web.input(up_file={})
        type1 = web.input().file_type
        self.__convert_to_portrait(x['up_file'].file, type1, tmp_img_path(id))
        return web.ctx.home + web.ctx.fullpath
Example #6
0
 def GET(self, id):
     page_info = PageInfo('Edit')
     ans1, temp_video = infoDBserver.get_video(id)
     ans2, temp_user = infoDBserver.get_user(session.get_user_id())
     if ans1 and ans2:
         current_video = transclass.video_trans(temp_video)
         current_user = transclass.user_trans(temp_user)
         return render.edit(current_video, current_user, page_info)
     else:
         raise web.nofound()
     return render.edit(current_video, current_user, page_info)
Example #7
0
    def GET(self, id):
        if session.get_user_id() != int(id):
            raise web.notfound()

        web.header('Content-Type', 'image/jpeg')
        web.header('Content-Length', str(os.path.getsize(tmp_img_path(id))))
        try:
            with open(tmp_img_path(id), 'rb') as f:
                return f.read()
        except:
            raise web.notfound()
Example #8
0
 def GET(self, id):
     page_info = PageInfo('Edit')
     ans1, temp_video = infoDBserver.get_video(id)
     ans2, temp_user = infoDBserver.get_user(session.get_user_id())
     if ans1 and ans2:
         current_video = transclass.video_trans(temp_video)
         current_user = transclass.user_trans(temp_user)
         return render.edit(current_video,current_user,page_info)
     else:
         raise web.nofound()
     return render.edit(current_video, current_user, page_info)
Example #9
0
 def GET(self, id):
     page_info = PageInfo('Video')
     ans1, temp_video = infoDBserver.get_video(id)
     current_video = transclass.video_trans(temp_video)
     ans2, temp_user = infoDBserver.get_user(session.get_user_id())
     current_user = transclass.user_trans(temp_user)
     ans3, temp_user = infoDBserver.get_user(current_video.owner)
     video_owner = transclass.user_trans(temp_user)
     if ans1 and ans2 and ans3:
         return render.video(current_video,current_user,video_owner,page_info)
     else:
         raise web.nofound() 
Example #10
0
 def GET(self, id):
     page_info = PageInfo('Video')
     ans1, temp_video = infoDBserver.get_video(id)
     current_video = transclass.video_trans(temp_video)
     ans2, temp_user = infoDBserver.get_user(session.get_user_id())
     current_user = transclass.user_trans(temp_user)
     ans3, temp_user = infoDBserver.get_user(current_video.owner)
     video_owner = transclass.user_trans(temp_user)
     if ans1 and ans2 and ans3:
         return render.video(current_video, current_user, video_owner,
                             page_info)
     else:
         raise web.nofound()
Example #11
0
    def GET(self):
        uploadURL, err = fs.putAuth()
        if err != None:
            web.debug(err)
            raise web.notfound()
        encodedURL = base64.urlsafe_b64encode(uploadURL)

        page_info = PageInfo('Upload')
        ans, temp_user = infoDBserver.get_user(session.get_user_id())
        if ans:
            current_user = transclass.user_trans(temp_user)
            return render.upload(current_user, page_info,encodedURL)
        else:
            return web.notfound()
Example #12
0
    def GET(self):
        uploadURL, err = fs.putAuth()
        if err != None:
            web.debug(err)
            raise web.notfound()
        encodedURL = base64.urlsafe_b64encode(uploadURL)

        page_info = PageInfo('Upload')
        ans, temp_user = infoDBserver.get_user(session.get_user_id())
        if ans:
            current_user = transclass.user_trans(temp_user)
            return render.upload(current_user, page_info, encodedURL)
        else:
            return web.notfound()
Example #13
0
 def GET(self):
     temp = session.is_logged()
     if temp:
         page_info = PageInfo('Index')
         current_userid = session.get_user_id()
         ans, temp_user = infoDBserver.get_user(current_userid)
         if ans:
             current_user = transclass.user_trans(temp_user)
         else:
             raise web.seeother('/login')
         return render.index(current_user, page_info)
         ##current_user = default_user
         ##return render.index(default_user, page_info)
     else:
         raise web.seeother('/login')
Example #14
0
 def GET(self):
     temp = session.is_logged()
     if temp:
         page_info = PageInfo('Index')
         current_userid = session.get_user_id()
         ans, temp_user = infoDBserver.get_user(current_userid)
         if ans: 
             current_user = transclass.user_trans(temp_user)
         else:
             raise web.seeother('/login')
         return render.index(current_user, page_info)
         ##current_user = default_user
         ##return render.index(default_user, page_info)
     else:
         raise web.seeother('/login')
Example #15
0
def main():
    """ 
    This function generates Escola Segura
    """

    # Remove menu da visualizacao
    hide_streamlit_style = """
        <style>
        #MainMenu {visibility: hidden;}
        footer {visibility: hidden;}
        </style>

        """
    st.markdown(hide_streamlit_style, unsafe_allow_html=True)

    # SESSION STATE
    time.sleep(
        0.05
    )  # minimal wait time so we give time for the user session to appear in steamlit
    session_state = session.SessionState.get(
        key=session.get_user_id(),
        update=False,
        state_name="Acre",
        state_id="AC",
        city_name="Todos",
        administrative_level="Todos",
        refresh=False,
        reset=False,
        already_generated_user_id=None,
        pages_open=None,
        amplitude_events=None,
        button_styles=dict(),
        continuation_selection=None,
        button_simule=0,
        section1_organize=False,
        section2_manage=False,
    )

    PAGES = {"Escola Segura": es, "Quem somos?": ab}

    page = st.sidebar.radio(
        "Menu",
        list(PAGES.keys()),
    )

    if __name__ == "__main__":
        PAGES[page].main(session_state)
        utils.applyButtonStyles(session_state)
Example #16
0
 def POST(self,id):
     data = web.input()
     page_info = PageInfo('Edit')
     ##return render.edit(default_video, default_user,page_info)
     ans, temp_video = infoDBserver.modify_video(id, videoName = data.video_name, intro =  data.video_intro)
     ans2, temp_user = infoDBserver.get_user(session.get_user_id())
     if ans2:
         current_user = transclass.user_trans(temp_user)
     else:
         raise web.nofound()
     if ans:
         current_video = transclass.video_trans(temp_video)
         page_info = PageInfo('Edit',message = '保存成功!')
         raise web.seeother('/video/'+str(current_video.id))
     else:
         page_info = PageInfo('Edit',error = '保存失败,请再试!')
         return render.edit(current_video,current_user,page_info)
Example #17
0
 def POST(self,id):
     current_userid = session.get_user_id()
     ans, bigFollow = infoDBserver.insert_follow(current_userid, id)
     if ans != False:
         usersFind, current_user = infoDBserver.get_user(current_userid)
         success, bigNotice = infoDBserver.insert_notice(current_userid, id, 1, str(current_user.userName)+' is following you. Click it to see.', '/personal/'+str(current_userid))
         js = {}
         js['ok'] = True
         js['message'] = '成功添加好友!'
         return_message = json.dumps(js)
         return return_message
     else:
         js = {}
         js['ok'] = False
         js['message'] = '添加好友失败!'
         return_message = json.dumps(js)
         return return_message
Example #18
0
    def GET(self):
        temp = session.is_logged()
        if temp:
            page_info = PageInfo('Index')
            current_userid = session.get_user_id()
            ans, temp_videoList = infoDBserver.get_video()
            recommend_videoList = transclass.videoList_trans(temp_videoList)
            ans, temp_user = infoDBserver.get_user(current_userid)
            if ans:
                current_user = transclass.user_trans(temp_user)
            else:
                raise web.seeother('/login')

            funcs.getNotices(current_userid)
            funcs.getFriends(current_userid)
            return render.index(current_user, recommend_videoList , page_info)
        else:
            raise web.seeother('/login')
Example #19
0
    def GET(self, id):
        session_id = session.get_user_id()
        if int(id) != session_id:
            raise web.notfound()

        uploadURL, err = fs.putAuth()
        if err != None:
            web.debug(err)
            raise web.notfound()
        encodedURL = base64.urlsafe_b64encode(uploadURL)

        page_info = PageInfo('Personal Edit')
        ans, temp_user = infoDBserver.get_user(session_id)
        if ans:
            current_user = transclass.user_trans(temp_user)
            return render.personal_edit(current_user, page_info, encodedURL)
        else:
            raise web.notfound()
Example #20
0
 def POST(self,id):
     data = web.input()
     username = data.userName
     userpwd = data.userPwd
     success, bigVideo = infoDBserver.get_video(id)
     if success:
         success0, bigUser = infoDBserver.get_user(session.get_user_id())
         if bigUser.userName == username  and bigUser.passwd == userpwd:
             success1 = infoDBserver.delete_video(id)
             if success1:
                 ans = delete2json(True, "successful")
             else:
                 ans = delete2json(False, "郭哥挂了")
         else:
             ans = delete2json(False, "用户名密码错误")
     else:
         ans = delete2json(False, "没有此视频")
     return ans
Example #21
0
 def POST(self, encodedURL):
     uploadURL = base64.urlsafe_b64decode(str(encodedURL))
     x = web.input(up_file={})
     filename = x['up_file'].filename
     type1 = web.input().file_type
     key, err = fs.putFile(x['up_file'].file, uploadURL)
     if err != None:
         web.debug(err)
         raise web.seeother('/upload')
         # do something
         return
     web.debug(key)
     ans1, video = infoDBserver.insert_video(key, session.get_user_id())
     ans2, video2 = infoDBserver.modify_video(video.videoId,videoName = filename, type = type1)
     ##waiting for type changing
     if ans2:
         raise web.seeother('/edit/'+str(video2.videoId))
     else:
         raise web.seeother('/upload')
Example #22
0
 def POST(self, id):
     data = web.input()
     page_info = PageInfo('Edit')
     ##return render.edit(default_video, default_user,page_info)
     ans, temp_video = infoDBserver.modify_video(id,
                                                 videoName=data.video_name,
                                                 intro=data.video_intro)
     ans2, temp_user = infoDBserver.get_user(session.get_user_id())
     if ans2:
         current_user = transclass.user_trans(temp_user)
     else:
         raise web.nofound()
     if ans:
         current_video = transclass.video_trans(temp_video)
         page_info = PageInfo('Edit', message='保存成功!')
         raise web.seeother('/video/' + str(current_video.id))
     else:
         page_info = PageInfo('Edit', error='保存失败,请再试!')
         return render.edit(current_video, current_user, page_info)
Example #23
0
    def POST(self, id):
        userId = int(id)
        session_id = session.get_user_id()
        if userId != session_id:
            js = {}
            js['ok'] = False
            js['message'] = "404 notfound"
            ans = json.dumps(js)
            return ans
            # raise web.notfound()

        data = web.input()

        ans, temp_user = infoDBserver.check_userId(session_id, data.cpassword)
        if not ans:
            web.debug('auth failed.')
            js = {}
            js['ok'] = False
            js['message'] = 'check_userId failed'
            ans = json.dumps(js)
            return ans

        if data.npassword != data.cnpassword:
            web.debug('two passwords missmatch.')
            js = {}
            js['ok'] = False
            js['message'] = 'passwords mismatch'
            ans = json.dumps(js)
            return ans

        js = {}
        js['ok'] = True
        js['message'] = "succeeded"
        web.debug(data.npassword)
        if data.npassword != None:
            _, ret = infoDBserver.modify_userPasswd(userId, data.npassword)
            if not ret:
                web.debug(ret)
                js['ok'] = False
                js['message'] = 'update user passwd failed.'
        ans = json.dumps(js)
        return ans
Example #24
0
    def POST(self,id):
        data = web.input()
        currentuser_id = session.get_user_id()
        reply_userid = data.toId
        content = data.content
        ans, bigComment = infoDBserver.insert_comment(id, currentuser_id, reply_userid, content)
        if ans:
            success, bigVideo = infoDBserver.get_video(id)
            success0, bigUser = infoDBserver.get_user(currentuser_id)
            if success:
                success1, bigNotice = infoDBserver.insert_notice(currentuser_id, bigVideo.ownerId, 2, str(bigUser.userName)+' replied to your video', '/video/'+str(id))
                if data.toId!=None:
                    success2, bigNotice = infoDBserver.insert_notice(currentuser_id, data.toId, 2, str(bigUser.userName)+' replied to your comments in video '+str(bigVideo.videoName),'/video/'+str(id))
            comments = []
            comments.append(transclass.comment_trans(bigComment))
            return_message = comment2json(True,comments)

        else:
            return_message = comment2json(False, None)

        return return_message
Example #25
0
 def POST(self, encodedURL):
     uploadURL = base64.urlsafe_b64decode(str(encodedURL))
     x = web.input(up_file={})
     filename = x['up_file'].filename
     type1 = web.input().file_type
     key, err = fs.putFile(x['up_file'].file, uploadURL)
     if err != None:
         web.debug(err)
         raise web.seeother('/upload')
         # do something
         return
     web.debug(key)
     ans1, video = infoDBserver.insert_video(key, session.get_user_id())
     ans2, video2 = infoDBserver.modify_video(video.videoId,
                                              videoName=filename,
                                              type=type1)
     ##waiting for type changing
     if ans2:
         raise web.seeother('/edit/' + str(video2.videoId))
     else:
         raise web.seeother('/upload')
def main():
    session_state = session.SessionState.get(
        key=session.get_user_id(),
        update=False,
        state_name="Acre",
        state_id="AC",
        city_name="Todos",
        administrative_level="Todos",
        refresh=False,
        reset=False,
        already_generated_user_id=None,
        pages_open=None,
        amplitude_events=None,
        button_styles=dict(),
        continuation_selection=None,
        button_simule=0,
        section1_organize=False,
        section2_manage=False,
    )
    utils.localCSS("style.css")
    config = yaml.load(open("config/config.yaml", "r"), Loader=yaml.FullLoader)
    df = get_data(config)
    genSelectBox(df, session_state)

    params = dict()
    main_icon = utils.load_image("imgs/simulation_main_icon.png")
    st.write(
        f"""
            <div class="text-title-section minor-padding">
                 Quantos <span class="bold main-orange-span">estudantes e professores(as)</span> retornam às salas de aula em diferentes modelos?
            </div>
            <div class="container main-padding" style="padding-left:0px;">
                <div class="container minor-padding main-orange-span" style="font-size: 20px; color:#FF934A; font-weight: bold;"> 
                    <img class="minor-icon" src="data:image/png;base64,{main_icon}" alt="Fonte: Flaticon">
                    Simule o retorno
                </div>
                <div class="minor-padding">
                    O retorno às atividades presenciais deve ser pensado em etapas para definir não só <b>quem pode retornar</b>, mas também <b>como</b>. Trazemos abaixo um passo a passo para construir a simulação da sua rede - experimente!
                </div>
                 <div class="minor-padding" style="font-size: 20px; color:#FF934A; font-weight: bold;">
                    <br>Para qual etapa de ensino você está planejando?
            </div>
            """,
        unsafe_allow_html=True,
    )

    # TODO: colocar por estado somente também
    # if city_name:
    data = df[
        (df["city_name"] == session_state.city_name)
        & (df["administrative_level"] == session_state.administrative_level)]
    col1, col2 = st.beta_columns([0.9, 0.2])
    with col1:
        education_phase = st.selectbox(
            "", data["education_phase"].sort_values().unique())
        data = data[data["education_phase"] == education_phase]
    with col2:
        st.write(
            f"""<div class="container">
                <br>
                </div>
                <br>
            """,
            unsafe_allow_html=True,
        )

    st.write(
        f"""<br>
            <div class="container" style="padding-left:0px;">
                <div class="minor-padding" style="font-size: 20px; color:#FF934A;"><b>1. Escolha o modelo de retorno às atividades</b></div>
                <div class="minor-padding">
                    Existem diversos modelos possíveis de retorno avaliadas de acordo com as etapas de aprendizado. Separamos abaixo 5 opções possíveis indicadas pela UNESCO.
                </div>
            </div>
        """,
        unsafe_allow_html=True,
    )

    UNESCO_models = {
        'Totalmente Presencial': {
            "description":
            """Neste modelo, todos os estudantes <b>retornam às aulas
            presenciais padrão</b>, isto é, os mesmos horários em sala de
            aula, porém seguindo os novos protocolos de distanciamento e segurança
            sanitária.
            <br><br><b>Por que este modelo?</b><br>
            Modelo tradicional, onde os estudantes e docentes estão habituados.""",
            "hours_per_day": 5,
            "priority": False
        },
        'Aulas presenciais + Tarefas remota': {
            "description": """Neste modelo professores(as) <b>transmitem
            conceitos para os estudantes presencialmente</b>, e, em seguida,
            <b>estudantes completam exercícios e tarefas em casa</b>.
            <br><br><b>Por que este modelo?</b><br>
            Alunos e professores mantêm um contato próximo, e estudantes podem tirar dúvidas durante a exposição da matéria.""",
            "hours_per_day": 3,
            "priority": False
        },
        'Aulas por vídeo + Tarefas presenciais': {
            "description": """Neste modelo estudantes <b>aprendem
            novos conceitos de forma remota</b> e, em seguida, <b>concluem exercícios e 
            tarefas presencialmente</b> com o(a) professor(a).
            <br><br><b>Por que este modelo?</b><br>
            Alunos e professores mantêm o convívio, e os estudantes podem tirar dúvidas 
            urante a realização dos exercícios e se beneficiarem com as dúvidas dos colegas.""",
            "hours_per_day": 2,
            "priority": False
        },
        'Grupo prioritário presencial': {
            "description":
            """Neste modelo, os professores têm uma <b>aula normal completa com um grupo
            de estudantes presencial, enquanto outro grupo acompanha remotamente 
            por meio de videoconferência (VC)</b>.
            <br><br><b>Por que este modelo?</b>
            Turma mantém o convívio, mesmo que virtual, e os professores atentem todos da turma no mesmo momento.""",
            "hours_per_day": 5,
            "priority": True
        }
    }

    col1_1, col1_2, col1_3, col1_4 = st.beta_columns([0.35, 0.05, 0.85, 0.3])
    with col1_1:
        params["education_model"] = st.selectbox("",
                                                 list(UNESCO_models.keys()))
        params["priority"] = UNESCO_models[
            params["education_model"]]["priority"]
    with col1_2:
        st.write(
            f"""
            <div class="container main-padding">
                <br>
            </div>
            """,
            unsafe_allow_html=True,
        )
    with col1_3:
        # Sobre o modelo
        st.write(
            f"""
                <div class="col light-green-simulator-bg card-simulator" style="border-radius:30px;">
                    <div style="font-family: 'Roboto Condensed', sans-serif; padding:10px; margin-bottom:0px; margin-top: 16px;margin-left: 16px; margin-right: 16px;">
                        <b>{params["education_model"]}</b>
                        <br><br>{UNESCO_models[params["education_model"]]["description"]}
                        <br><br><b><a href="https://en.unesco.org/sites/default/files/unesco-covid-19-response-toolkit-hybrid-learning.pdf">FONTE: UNESCO</a></b>
                    </div>
                    <div class="button-position" style="margin-bottom: 0px;padding: 10px;margin-top: 16px;margin-right: 16px;margin-left: 16px;">
                        <a href="#entenda-modelo">
                            <button class="button-protocolos" style="border-radius: .25rem; font-size:16px; margin-right: 10px;margin-left: 10px;">
                                leia sobre todos os modelos >
                            </button>
                        </a>
                    </div>
                    <div class="button-position" style="margin-bottom: 0px;padding: 10px;margin-top: 16px;margin-right: 16px;margin-left: 16px;">
                        <a href="#entenda-etapa">
                            <button class="button-protocolos" style="border-radius: .25rem; font-size:16px; margin-right: 10px;margin-left: 10px;">
                                veja considerações por etapa de ensino >
                            </button>
                        </a>
                    </div>
                </div>
                <div id="entenda-modelo" class="info-modal-window" style="width: 80%; height: 70%;">
                    <div>
                        <a href="#" title="Close" class="info-btn-close" style="color: white;">&times</a>
                        <h1 class="main-orange-span bold" style="padding: 0px 50px 0px 50px;">Modelos</h1>
                        <div style="font-size: 16px; padding: 0px 50px 0px 50px;">
                            Abaixo há o quadro completo. Caso não consiga ver a imagem, clique na imagem para baixa-la ou <a href="https://drive.google.com/u/1/uc?id=1tqBItM8XkLdY9u2wk0ZcPrVcHccgdp1f&export=download">[AQUI]</a>.
                        </div>
                        <a href="https://drive.google.com/u/1/uc?id=1tqBItM8XkLdY9u2wk0ZcPrVcHccgdp1f&export=download"><img style="padding: 50px 50px 50px 50px;" class="images" src="https://i.imgur.com/ZByy47a.jpg"></a>
                    </div>
                </div>
                <div id="entenda-etapa" class="info-modal-window" style="width: 80%; height: 70%;">
                    <div>
                        <a href="#" title="Close" class="info-btn-close" style="color: white;">&times</a>
                        <h1 class="main-orange-span bold" style="padding: 0px 50px 0px 50px;">Etapas de Ensino</h1>
                        <div style="font-size: 16px; padding: 0px 50px 0px 50px;">
                            <br>
                            <b>4 - 8 anos</b><br>
                            Pontos principais para consideração:<br>
                            <li>Crianças desta faixa etária possuem menor risco de apresentar sintomas graves.</li>                            
                            <li>Pais e responsáveis necessitam de creches e suporte para manter demais atividades do dia a dia</li>
                            <li>Eficácia muito baixa do ensino remoto</li><br>
                            <b>8 - 12 anos</b><br>
                            Pontos principais para consideração:<br>
                            <li>Crianças desta faixa etária possuem menor risco de apresentar sintomas graves, mas há maior dificuldade em adotar medidas sanitárias.</li>
                            <li>Já possuem maior autonomia no cotidiano e pode</li><br>
                            <b>12 - 17 anos</b><br>
                            Pontos principais para consideração:<br>
                            <li>Crianças desta faixa etária possuem maior risco intrínseco de contrair e desenvolver sintomas, mas apresentam maior aderência aos protocolos sanitários</li>
                            <li>Logística de agendamento presencial pode ser mais complexa, pois os anos possuem matérias e professores diversos.</li><br>
                            <b>17 - 18 anos</b><br>
                            Pontos principais para consideração:<br>
                            <li>Crianças desta faixa etária possuem maior risco intrínseco de contrair e desenvolver sintomas, mas apresentam maior aderência aos protocolos sanitários.</li>
                            <li>Alta eficácia e adesão ao método remoto</li>
                            <br>Abaixo há o quadro completo. Caso não consiga ver a imagem, clique na imagem para baixa-la ou <a href="https://drive.google.com/u/1/uc?id=1Sj65MXPkRcw6VxojYBLsJ8otIuvpLfq_&export=download">[AQUI]</a>.
                        </div>
                        <a href="https://drive.google.com/u/1/uc?id=1Sj65MXPkRcw6VxojYBLsJ8otIuvpLfq_&export=download"><img style="padding: 50px 50px 50px 50px;" class="images" src="https://i.imgur.com/FyoIFe9.jpg"></a>
                    </div>
                </div>
                """,
            unsafe_allow_html=True,
        )
    with col1_4:
        st.write(
            f"""<div class="container">
                <br>
                </div>
                <br>
            """,
            unsafe_allow_html=True,
        )

    st.write(
        f"""<br>
            <div class="container" style="padding-left:0px;">
                <div class="minor-padding" style="font-size: 20px; color:#FF934A;"><b>2. Escolha quem pode retornar</b></div>
            </div>
        """,
        unsafe_allow_html=True,
    )

    col2a_1, col2a_2, col2a_3, col2a_4 = st.beta_columns(
        [0.35, 0.05, 0.85, 0.3])
    with col2a_1:
        params["number_students"] = st.number_input(
            "Quantos estudantes retornam às aulas presenciais?",
            format="%d",
            value=data["number_students"].values[0],
            step=1,
        )
        if params["priority"]:
            params["number_remote_students"] = st.number_input(
                "Quantos estudantes acompanham às aulas somente de forma remota?",
                format="%d",
                value=data["number_students"].values[0],
                step=1,
            )

    with col2a_2:
        st.write(
            f"""
            <div class="container main-padding">
                <br>
            </div>
            """,
            unsafe_allow_html=True,
        )
    with col2a_3:
        st.write(
            f"""
            <div class="col light-green-simulator-bg card-simulator" style="border-radius:30px;">
                <div class="row" style="font-family: 'Roboto Condensed', sans-serif; margin-bottom:0px; padding:10px;">
                    <b>Iniciamos com total de estudantes reportados no Censo Escolar 2019 (INEP).</b>
                    <br>Você pode alterar esse valor ao lado. Leve em consideração quais grupos de estudantes podem ser vulneráveis ou ter prioridade.
                </div>
                <div class="button-position" style="padding-bottom: 15px;">
                    <a href="#entenda-estudantes">
                        <button class="button-protocolos" style="border-radius: .25rem; font-size:16px; margin-right: 10px;margin-left: 10px;">
                            grupos que requerem atencão especial >
                        </button>
                    </a>
                </div>
            </div>
            <div id="entenda-estudantes" class="info-modal-window" style="width: 80%; height: 70%;">
                <div>
                    <a href="#" title="Close" class="info-btn-close" style="color: white;">&times</a>
                    <h1 class="main-orange-span bold" style="padding: 0px 50px 0px 50px;">Estudantes</h1>
                    <div style="font-size: 20px; padding: 0px 50px 0px 50px;">
                        <b>Grupos que requerem atencão especial</b>
                    </div>
                    <br>
                    <div style="font-size: 16px; padding: 0px 50px 0px 50px;">
                        <b>Exemplos de grupos vulneráveis ou/e marginalizados</b>
                        <li>Minorias</li>
                        <li>Meninas adolescentes</li>
                        <li>Crianças com deficiência de aprendizagem</li>
                        <li>Crianças que vivem em instituições de abrigo</li>
                        <li>Crianças vivendo em condição de pobreza, em residências com alta ocupância ou improvisadas</li>
                        <li>Orfãos</li>
                        <li>Crianças separadas de seus responsáveis</li>
                        <li>Crianças e adolescentes em risco de abandono escolar</li>
                    </div>
                </div>
            </div>
            """,
            unsafe_allow_html=True,
        )
    with col2a_4:
        st.write(
            f"""<div class="container">
                <br>
                </div>
                <br>
            """,
            unsafe_allow_html=True,
        )
    st.write(
        f"""
        <div class="container main-padding">
            <br>
        </div>
        """,
        unsafe_allow_html=True,
    )

    col2b_1, col2b_2, col2b_3, col2b_4 = st.beta_columns(
        [0.35, 0.05, 0.85, 0.3])
    with col2b_1:
        params["number_teachers"] = st.number_input(
            "Quantos professores(as) retornam?",
            format="%d",
            value=data["number_teachers"].values[0],
            step=1,
        )
    col2b_2 = col2a_2
    with col2b_3:
        st.write(
            f"""
            <div class="col light-green-simulator-bg card-simulator" style="border-radius:30px;">
                <div class="row" style="font-family: 'Roboto Condensed', sans-serif; margin-bottom:0px; padding:10px;">
                    <b>Iniciamos com total de professores reportados no Censo Escolar 2019 (INEP).</b> 
                    <br>Você pode alterar esse valor ao lado. Leve em consideração quais grupos de professores podem ser de risco, confortáveis para retorno e outros.
                </div>
                <div class="button-position" style="padding-bottom: 15px;">
                    <a href="#entenda-professores">
                        <button class="button-protocolos" style="border-radius: .25rem; font-size:16px; margin-right: 10px;margin-left: 10px;">
                            como retornar professores(as) >
                        </button>
                    </a>
                </div>
                <div id="entenda-professores" class="info-modal-window" style="width: 80%; height: 70%;">
                    <div>
                        <a href="#" title="Close" class="info-btn-close" style="color: white;">&times</a>
                        <h1 class="main-orange-span bold" style="padding: 0px 50px 0px 50px;">Professores</h1>
                        <div style="font-size: 16px; padding: 0px 50px 0px 50px;">
                            <b>Fatores a serem considerados:</b> grupos vulneráveis, número de casos suspeitos, desconforto da rede com o retorno presencial, dificuldade logística e a disponibilidade de retorno presencial.
                            <br><br>O quadro explicativo traz para cada fator um desafio e uma ação sugerida.
                            <br><br>Caso não consiga ver a imagem, clique na imagem para baixa-la ou <a href="https://drive.google.com/u/1/uc?id=1lLtbEMau4nIj8tZ5rQF51ThV2Q8K1DzE&export=download">[AQUI]</a>.
                        </div>
                        <a href="https://drive.google.com/u/1/uc?id=1lLtbEMau4nIj8tZ5rQF51ThV2Q8K1DzE&export=download"><img style="padding: 50px 50px 50px 50px;" class="images" src="https://i.imgur.com/4ai7xDK.jpg"></a>
                    </div>
                </div>
            </div>
            """,
            unsafe_allow_html=True,
        )
    col2b_4 = col2a_4
    st.write(
        f"""
        <br>
        <div class="container" style="padding-left:0px;">
            <div class="minor-padding" style="font-size: 20px; color:#FF934A;"><b>3. Defina as restrições de retorno</b></div><br>
                </div>
            </div>
        </div>
        """,
        unsafe_allow_html=True,
    )

    col3_1, col3_2, col3_3, col3_4, col3_5, col3_6 = st.beta_columns(
        [0.35, 0.05, 0.4, 0.05, 0.4, 0.3])
    with col3_1:
        params["number_classrooms"] = st.number_input(
            "Quantas salas de aula disponíveis?",
            format="%d",
            value=data["number_classroms"].values[0],
            step=1,
        )
        st.write(
            f"""
            <div class="row" style="margin:0px; padding:10px; background:#DDFBF0; border-radius: 1rem 1rem 1rem 1rem;">
                O número de salas restringe o número de turmas que podem voltar de forma simultânea.
            </div>
        """,
            unsafe_allow_html=True,
        )
    col3_2 = col2a_2
    with col3_3:
        params["max_students_per_class"] = st.slider(
            "Selecione o máximo de estudantes por turma:", 0, 20, 20, 1)
        st.write(
            f"""
            <div class="row" style="margin:0px; padding:10px; background:#DDFBF0; border-radius: 1rem 1rem 1rem 1rem;">
                Limitamos em 20 estudantes por sala para diminiuir o risco de transmissão seguindo critérios sanitários.
            </div>
            """,
            unsafe_allow_html=True,
        )
    col3_4 = col2a_2
    with col3_5:
        params["hours_per_day"] = int(
            st.slider(
                "Selecione o número de horas presenciais diárias na escola por turma:",
                min_value=1,
                max_value=5,
                value=UNESCO_models[params["education_model"]]
                ["hours_per_day"],
                step=1,
            ))

        st.write(
            f"""
            <div class="row" style="margin:0px; padding:10px; background:#DDFBF0; border-radius: 1rem 1rem 1rem 1rem;">
                As restrições sanitárias limitam a quantidade de tempo e estudantes que conseguem retornar à sala de aula.
            </div>

            <div class="container">
            <br>
            </div>
            <br>
            """,
            unsafe_allow_html=True,
        )
    col3_6 = col2a_4

    with st.beta_expander("simular retorno"):
        user_analytics = amplitude.gen_user(utils.get_server_session())
        opening_response = user_analytics.safe_log_event(
            "clicked simule retorno", session_state, is_new_page=True)
        print(params)
        genSimulationResult(params, config)
    '''if st.button("Simular retorno"):
        if st.button("Esconder"):
            pass
        genSimulationResult()
    utils.stylizeButton(
        name="SIMULAR RETORNO",
        style_string="""
        box-sizing: border-box;
        border-radius: 15px; 
        width: 150px;padding: 0.5em;
        text-transform: uppercase;
        font-family: 'Oswald', sans-serif;
        background-color: #0097A7;
        font-weight: bold;
        text-align: center;
        text-decoration: none;font-size: 18px;
        animation-name: fadein;
        animation-duration: 3s;
        margin-top: 1.5em;""",
        session_state=session_state,
    )'''

    # TODO: escrever metodologia v1.2
    with st.beta_expander("ler metodologia"):
        user_analytics = amplitude.gen_user(utils.get_server_session())
        opening_response = user_analytics.safe_log_event(
            "clicked simule metodologia", session_state, is_new_page=True)
        methodology_text = load_markdown_content("methodology_short.md")
        st.write(methodology_text)
Example #27
0
def main():

    # SESSION STATE
    time.sleep(
        0.05
    )  # minimal wait time so we give time for the user session to appear in steamlit
    session_state = session.SessionState.get(
        key=session.get_user_id(),
        update=False,
        state_name="Acre",
        state_num_id=None,
        health_region_name="Todos",
        health_region_id=None,
        city_name="Todos",
        city_id=None,
        number_beds=None,
        number_icu_beds=None,
        number_cases=None,
        number_deaths=None,
        population_params=dict(),
        refresh=False,
        reset=False,
        saude_ordem_data=None,
        already_generated_user_id=None,
        pages_open=None,
        amplitude_events=None,
        old_amplitude_events=None,
        button_styles=dict(),
        continuation_selection=None,
    )
    # AMPLITUDE EVENT
    # In those amplitude events objects we are going to save a dict with every state as keys
    # in each state, the value will be something that allows us to identify there is a change or not
    # which in turn allows us to decide if we should log the event or not
    utils.manage_user_existence(utils.get_server_session(), session_state)
    utils.update_user_public_info()
    # CLOSES THE SIDEBAR WHEN THE USER LOADS THE PAGE
    st.write(
        """
    <iframe src="resources/sidebar-closer.html" height=0 width=0>
    </iframe>""",
        unsafe_allow_html=True,
    )
    # For Http debug
    # st.write(utils.parse_headers(utils.get_server_session().ws.request))

    # MENU
    page = st.sidebar.radio(
        "Menu",
        [
            "FarolCovid",
            "Modelos, limitações e fontes",
            "Quem somos?",
        ],
    )

    if page == "FarolCovid":
        if __name__ == "__main__":
            fc.main(session_state)
            utils.applyButtonStyles(session_state)

    elif page == "Quem somos?":
        if __name__ == "__main__":
            tm.main(session_state)

    elif page == "Modelos, limitações e fontes":
        if __name__ == "__main__":
            method.main(session_state)
Example #28
0
def main():
    # SESSION STATE
    time.sleep(
        0.05
    )  # minimal wait time so we give time for the user session to appear in steamlit
    session_state = session.SessionState.get(
        key=session.get_user_id(),
        update=False,
        state_name="Acre",
        state_num_id=None,
        health_region_name="Todos",
        health_region_id=None,
        city_name="Todos",
        city_id=None,
        number_beds=None,
        number_icu_beds=None,
        number_cases=None,
        number_deaths=None,
        population_params=dict(),
        refresh=False,
        reset=False,
        saude_ordem_data=None,
        already_generated_user_id=None,
        pages_open=None,
        amplitude_events=None,
        old_amplitude_events=None,
        button_styles=dict(),
        continuation_selection=None,
    )
    # AMPLITUDE EVENT
    # In those amplitude events objects we are going to save a dict with every state as keys
    # in each state, the value will be something that allows us to identify there is a change or not
    # which in turn allows us to decide if we should log the event or not
    utils.manage_user_existence(utils.get_server_session(), session_state)
    utils.update_user_public_info()
    # CLOSES THE SIDEBAR WHEN THE USER LOADS THE PAGE
    st.write(
        """
    <iframe src="resources/sidebar-closer.html" height=0 width=0>
    </iframe>""",
        unsafe_allow_html=True,
    )

    # Gambiarra para ter o menu lateral com caracteres especiais e ainda ter várias páginas
    # Retirar depois de encontrar saída mais apropriada
    page_list = [
        "FarolCovid", "Modelos, limitações e fontes", "Quem somos?",
        "Estudo Vacinação", "Vacinômetro"
    ]
    pages_dict = {
        "FarolCovid": "Inicio",
        "Modelos, limitações e fontes": "Metodologia",
        "Quem somos?": "Quem-Somos",
        "Estudo Vacinação": "Estudo-Vacinacao",
        "Vacinômetro": "Vacinometro"
    }
    pages_index = {
        "Inicio": 0,
        "Metodologia": 1,
        "Quem-Somos": 2,
        "Estudo-Vacinacao": 3,
        "Vacinometro": 4
    }
    PAGES = {
        "Inicio": fc,
        "Metodologia": method,
        "Quem-Somos": tm,
        "Estudo-Vacinacao": estudo,
        "Vacinometro": vacina
    }
    query_params = st.experimental_get_query_params()
    if query_params:
        # Gambiarra para redirecionar páginas
        if query_params["page"][0] == '0' or query_params["page"][
                0] == 'FarolCovid':
            query_params["page"][0] = "Inicio"
        elif query_params["page"][0] == '1' or query_params["page"][
                0] == 'Modelos, limitações e fontes':
            query_params["page"][0] = "Metodologia"
        elif query_params["page"][0] == '2' or query_params["page"][
                0] == 'Quem somos?':
            query_params["page"][0] = "Quem-Somos"
        elif query_params["page"][0] == '3' or query_params["page"][
                0] == 'Estudo Vacinação':
            query_params["page"][0] = "Estudo-Vacinacao"
        elif query_params["page"][0] == '4' or query_params["page"][
                0] == 'Vacinômetro':
            query_params["page"][0] = "Vacinometro"
    default = query_params["page"][0] if "page" in query_params else "Inicio"
    page = st.sidebar.radio("Menu", page_list, index=pages_index[default])
    st.experimental_set_query_params(page=pages_dict[page])
    PAGES[pages_dict[page]].main(session_state)
Example #29
0
def main():
    session_state = session.SessionState.get(
        key=session.get_user_id(),
        update=False,
        state_name="Acre",
        state_id="AC",
        city_name="Todos",
        administrative_level="Todos",
        escola="",
        refresh=False,
        reset=False,
        already_generated_user_id=None,
        pages_open=None,
        amplitude_events=None,
        button_styles=dict(),
        continuation_selection=None,
        button_simule=0,
        section1_organize=False,
        section2_manage=False,
        nivelsimulacao=""
    )
    utils.localCSS("localCSS.css")
    he.genHeader("simulation")
    config = yaml.load(open("config/config.yaml", "r"), Loader=yaml.FullLoader)
    # df = get_data()
    subtitle = """Sabemos que no planejamento da reabertura surgem muitas dúvidas... Quantas turmas podem voltar? Quantos litros de álcool gel preciso comprar? 
    <br>
    O retorno às atividades presenciais deve ser planejado segundo as condições da sua rede. Simule abaixo o retorno e veja os recursos e materiais necessários para uma reabertura segura!
    <br>
    <b>Se você é gestor da rede:</b><br>
    Preencha os dados da sua rede e obtenha uma simulação geral das condições de retorno. 
    <br>
    <b>Se você é gestor de uma escola:</b><br>
    Preencha os dados específicos da sua escola, por série ou por etapa de ensino, e obtenha as condições e materiais necessários para voltar ás aulas presenciais com segurança.
    <br><br>
    <b>Selecione o nível que gostaria de simular:</b>
    <br>"""
    utils.main_title(title="<b>Simule o retorno:</b> como organizar a reabertura?", subtitle=subtitle)


    session_state.nivelsimulacao = st.selectbox(
        "",
        # ["Selecione o nível que gostaria de simular:", "Nível Escolar", "Rede Municipal"],
        ["", "Nível Escolar", "Rede Municipal", "Rede Federal", "Rede Estadual"],
    )
    if session_state.nivelsimulacao=="Nível Escolar":
        df = pd.read_csv("pages/dadosporescolas.csv")
        utils.gen_title(title="Selecione sua localização:", subtitle="")
        session_state.state_id = st.selectbox("Estado", df["state_id"].sort_values().unique())
        session_state.state_name = utils.set_state_name(df,session_state.state_id)

        options_city_name = df[df["state_id"] == session_state.state_id]["city_name"].sort_values().unique()
        options_city_name = pd.DataFrame(data=options_city_name, columns=["city_name"])
        session_state.city_name = st.selectbox("Município", options_city_name)

        data = df[(df["state_id"] == session_state.state_id) & (df["city_name"] == session_state.city_name)]
        session_state.escola = st.selectbox(
            "Escola",
            ["", "Minha escola não está na lista"] + list(data["codinep_nomedaescola"]),
        )
        # data = df[(df["state_id"] == session_state.state_id) & (df["city_name"] == session_state.city_name) & (df["nomedaescola"] == session_state.escola)]
        if session_state.escola == "Minha escola não está na lista":
            data = {'Unnamed: 0':[0], 'idescola':[0], 'nomedaescola':[0], 'city_id':[0], 'city_name':[0],'state_id':[0], 'state_name':[0], 'numsalas':[1], 'alunos':[1], 'tipoescola':[0],'professores':[1]}
            data = pd.DataFrame(data, columns=['Unnamed: 0', 'idescola', 'nomedaescola', 'city_id', 'city_name','state_id', 'state_name', 'numsalas', 'alunos', 'tipoescola','professores'])
            params = genQuetions(data)
            if st.button("simular retorno"):
                genSimulationResult(params, config)
        elif session_state.escola != "":
            data = data[data["codinep_nomedaescola"] == session_state.escola]
            params = genQuetions(data)
            if st.button("simular retorno"):
                genSimulationResult(params, config)
    # if session_state.nivelsimulacao=="Nível Escolar Turma":
    #     df = pd.read_csv("pages/dadosporturmasagrupado.csv")
    #     utils.gen_title(title="Selecione sua localização:", subtitle="")
    #     session_state.state_id = st.selectbox("Estado", df["state_id"].sort_values().unique())
    #     session_state.state_name = utils.set_state_name(df,session_state.state_id)

    #     options_city_name = df[df["state_id"] == session_state.state_id]["city_name"].sort_values().unique()
    #     options_city_name = pd.DataFrame(data=options_city_name, columns=["city_name"])
    #     session_state.city_name = st.selectbox("Município", options_city_name)

    #     data = df[(df["state_id"] == session_state.state_id) & (df["city_name"] == session_state.city_name)]
    #     session_state.escola = st.selectbox(
    #         "Escola",
    #         ["Selecione a Escola"] + list(data["codinep_nomedaescola"].unique()),
    #     )
    #     data = data[data["codinep_nomedaescola"] == session_state.escola]
    #     # data = df[(df["state_id"] == session_state.state_id) & (df["city_name"] == session_state.city_name) & (df["nomedaescola"] == session_state.escola)]
    #     if session_state.escola != "Selecione a Escola":
    #         params = genMultiQuetions(data)
    #         if st.button("simular retorno"):
    #             genSimulationResult(params, config)
                
    if session_state.nivelsimulacao=="Rede Municipal":
        df = pd.read_csv("pages/dadosporescolas.csv")
        utils.gen_title(title="Selecione sua localização:", subtitle="")
        session_state.state_id = st.selectbox("Estado", df["state_id"].sort_values().unique())
        session_state.state_name = utils.set_state_name(df,session_state.state_id)
        options_city_name = df[df["state_id"] == session_state.state_id]["city_name"].sort_values().unique()
        options_city_name = pd.DataFrame(data=options_city_name, columns=["city_name"])
        session_state.city_name = st.selectbox("Município", options_city_name)
        escolas_municipio_opcao = st.selectbox(
            "Você gostaria de simular:",
            ["Todas as Escolas do Município", "Escolas de Administração Municipal"],
        )
        if escolas_municipio_opcao=="Todas as Escolas do Município":
            data = df[(df["state_id"] == session_state.state_id) & (df["city_name"] == session_state.city_name)]
        else:
            data = df[(df["state_id"] == session_state.state_id) & (df["city_name"] == session_state.city_name) & (df["tipoescola"] == 3)]
        params = genMunicipioQuetions(data)
        if st.button("simular retorno"):
            genSimulationResultMunicipio(params, config, data)
    
    if session_state.nivelsimulacao=="Rede Federal":
        df = pd.read_csv("pages/dadosporescolas.csv")
        utils.gen_title(title="Selecione sua localização:", subtitle="")
        session_state.state_id = st.selectbox("Estado", df["state_id"].sort_values().unique())
        session_state.state_name = utils.set_state_name(df,session_state.state_id)
        data = df[(df["state_id"] == session_state.state_id) & (df["tipoescola"] == 1)]
        params = genMunicipioQuetions(data)
        if st.button("simular retorno"):
                genSimulationResultMunicipio(params, config, data)
    
    if session_state.nivelsimulacao=="Rede Estadual":
        df = pd.read_csv("pages/dadosporescolas.csv")
        utils.gen_title(title="Selecione sua localização:", subtitle="")
        session_state.state_id = st.selectbox("Estado", df["state_id"].sort_values().unique())
        session_state.state_name = utils.set_state_name(df,session_state.state_id)

        # escolas_estado_opcao = st.selectbox(
        #     "Você gostaria de simular:",
        #     ["Todas as Escolas do Estado", "Escolas de Administração Estadual"],
        # )
        escolas_estado_opcao = st.selectbox(
            "Você gostaria de simular:",
            ["Escolas de Administração Estadual"],
        )
        if escolas_estado_opcao=="Todas as Escolas do Estado":
            data = df[(df["state_id"] == session_state.state_id)]
        else:
            data = df[(df["state_id"] == session_state.state_id) & (df["tipoescola"] == 2)]
        params = genEstadoQuetions(data)
        if st.button("simular retorno"):
            if escolas_estado_opcao=="Todas as Escolas do Estado":
                data = pd.read_csv("pages/redeestadual.csv")
            else:
                data = pd.read_csv("pages/redeestadual.csv")
            genSimulationEstadoResult(params, config, session_state, data)

    tm.genGuia()
    foo.genFooter()