adrienbrdne's picture
Update app.py
1b28b80 verified
import io
import os
import json
import streamlit as st
import pandas as pd
from google.oauth2 import service_account
from googleapiclient.discovery import build
from googleapiclient.http import MediaIoBaseDownload, MediaIoBaseUpload
# Environment variables
FOLDER_ID = os.getenv("FOLDER_ID")
GOOGLE_CREDENTIALS = os.environ.get("GOOGLE_CREDENTIALS")
DATASET_NAME = os.environ.get("DATASET_NAME")
def create_new_file_in_drive(username, dataframe_to_upload, credentials_json, folder_id):
"""Crée un nouveau fichier CSV dans Google Drive à partir d'un DataFrame Pandas."""
creds_dict = json.loads(credentials_json)
# Charger les informations d'identification du compte de service
creds = service_account.Credentials.from_service_account_info(creds_dict)
# Construire le service API Drive
service = build('drive', 'v3', credentials=creds)
# Convertir le DataFrame en fichier CSV en mémoire
csv_buffer = io.BytesIO()
dataframe_to_upload.to_csv(csv_buffer, index=False, sep=';', encoding='utf-8')
csv_buffer.seek(0)
# Créer les métadonnées du fichier
filename = f"rating-results-{username}.csv"
file_metadata = {
'name': filename,
'parents': [folder_id]
}
# Télécharger le fichier CSV sur Google Drive
media = MediaIoBaseUpload(csv_buffer, mimetype='text/csv', resumable=True)
file = service.files().create(body=file_metadata, media_body=media, fields='id').execute()
print(f"File '{filename}' created successfully.")
def main():
st.title("Problematic Rating App")
# Initialiser st.session_state.user et st.session_state.page si ce n'est pas déjà fait
if 'user' not in st.session_state:
st.session_state.user = None
if 'page' not in st.session_state:
st.session_state.page = 0 # 0 = page accueil, 1 = page notation
# Page d'accueil pour saisir le nom de l'utilisateur
if st.session_state.page == 0:
st.session_state.user = st.text_input("Enter your name:")
if st.session_state.user:
st.session_state.page = 1
st.rerun() # important
else:
st.stop()
# Charger le fichier CSV
try:
df = pd.read_csv(DATASET_NAME, sep=';')
except FileNotFoundError:
st.error(f"{DATASET_NAME} not found. Please upload the file.")
return
# Initialisation des variables de session
if 'problem_index' not in st.session_state:
st.session_state.problem_index = 0
if 'formulation_index' not in st.session_state:
st.session_state.formulation_index = 0
if 'results' not in st.session_state:
st.session_state.results = []
if 'specificity' not in st.session_state:
st.session_state.specificity = None
if 'clarity' not in st.session_state:
st.session_state.clarity = None
if 'priority' not in st.session_state:
st.session_state.priority = None
# Afficher la problématique à noter
if st.session_state.problem_index < len(df):
problem = df.iloc[st.session_state.problem_index]
formulation_types = ['original_form', 'perspective_shift', 'paraphrase', 'structural_transformation']
current_formulation = formulation_types[st.session_state.formulation_index]
st.write(f"Technical problem {st.session_state.problem_index + 1}/{len(df)}")
st.write(f"Formulation {st.session_state.formulation_index + 1}/4")
st.write(problem[current_formulation])
# Menu déroulant pour la notation
st.write("Rate the problem on the following three criteria:")
col1, col2, col3 = st.columns(3)
with col1:
st.session_state.specificity = st.radio("Specificity", options=[0, 1, 2, 3, 4, 5, "Don't know"], index=None)
with col2:
st.session_state.clarity = st.radio("Clarity", options=[0, 1, 2, 3, 4, 5, "Don't know"], index=None)
with col3:
st.session_state.priority = st.radio("Priority Order", options=[0, 1, 2, 3, 4, 5, "Don't know"], index=None)
# Bouton pour passer à la formulation suivante ou à la problématique suivante
if st.button("Next"):
# Vérifier si le nom d'utilisateur est défini
if st.session_state.user:
st.session_state.results.append({
'user': st.session_state.user,
'formulation': current_formulation,
'problematic': problem[current_formulation],
'specificity': st.session_state.specificity,
'clarity': st.session_state.clarity,
'priority': st.session_state.priority
})
st.session_state.formulation_index += 1
if st.session_state.formulation_index == 4:
st.session_state.formulation_index = 0
st.session_state.problem_index += 1
st.rerun()
else:
st.warning("Please enter your name before proceeding.")
else:
# Afficher un message de remerciement et générer le fichier CSV
st.write("Thanks for rating the problems!")
st.session_state.results_df = pd.DataFrame(st.session_state.results)
create_new_file_in_drive(st.session_state.user, st.session_state.results_df, GOOGLE_CREDENTIALS, FOLDER_ID)
if __name__ == "__main__":
main()