nmariotto commited on
Commit
7e481ad
·
verified ·
1 Parent(s): 18cbf7e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +47 -37
app.py CHANGED
@@ -10,17 +10,29 @@ from shapely.geometry import Polygon
10
  from PIL import Image
11
  from io import BytesIO
12
  from concurrent.futures import ThreadPoolExecutor
13
- from google.auth.transport.requests import Request
14
  from google.oauth2.credentials import Credentials
15
- from google_auth_oauthlib.flow import InstalledAppFlow
 
16
  import gspread
17
  import time
18
 
 
 
19
  # 🔥 Initialize Roboflow
20
- API_KEY = st.secrets["roboflow_api_key"]
21
- rf = roboflow.Roboflow(api_key=API_KEY )
22
- project = rf.workspace(st.secrets["roboflow_workspace"]).project(st.secrets["roboflow_project"])
23
- model = project.version(st.secrets["roboflow_version"]).model
 
 
 
 
 
 
 
 
 
 
24
  model.confidence = 80
25
  model.overlap = 25
26
  dpi_value = 300
@@ -28,36 +40,34 @@ dpi_value = 300
28
  with st.expander("⚙️ Advanced Settings", expanded=True):
29
  model.confidence = st.slider("Model Confidence (%)", 20, 100, 80)
30
 
31
- # 📁 Setup Google Drive and Sheets (Híbrido: Local e Hugging Face)
32
- scope = ["https://www.googleapis.com/auth/drive", "https://www.googleapis.com/auth/spreadsheets"]
33
- creds = None
34
-
35
- # Tenta carregar as credenciais a partir do segredo do Hugging Face
36
- # st.secrets.get( ) retorna None se o segredo não existir, evitando erros.
37
- token_json_secret = st.secrets.get("GOOGLE_TOKEN_JSON")
38
-
39
- if token_json_secret:
40
- # Se estiver no Hugging Face, carrega as credenciais a partir do segredo
41
- creds = Credentials.from_authorized_user_info(json.loads(token_json_secret), scope)
42
- else:
43
- # Se estiver rodando localmente, usa o fluxo de arquivos token.json/credentials.json
44
- if os.path.exists('token.json'):
45
- creds = Credentials.from_authorized_user_file('token.json', scope)
46
-
47
- if not creds or not creds.valid:
48
- if creds and creds.expired and creds.refresh_token:
49
- creds.refresh(Request())
50
- else:
51
- flow = InstalledAppFlow.from_client_secrets_file('credentials.json', scope)
52
- creds = flow.run_local_server(port=0)
53
- # Salva o token para futuras execuções locais
54
- with open('token.json', 'w') as token:
55
- token.write(creds.to_json())
56
-
57
- # Constrói os serviços com as credenciais obtidas
58
- drive_service = build("drive", "v3", credentials=creds)
59
- sheets_client = gspread.authorize(creds)
60
- sheet = sheets_client.open_by_url(st.secrets["feedback_sheet_url"]).sheet1
61
 
62
 
63
  # 📌 Helper Functions
@@ -290,4 +300,4 @@ if results:
290
  except Exception as e:
291
  st.error(f"An error occurred during the upload to Google Drive: {e}")
292
  else:
293
- st.success("✅ Feedback saved successfully!")
 
10
  from PIL import Image
11
  from io import BytesIO
12
  from concurrent.futures import ThreadPoolExecutor
 
13
  from google.oauth2.credentials import Credentials
14
+ from googleapiclient.discovery import build
15
+ from googleapiclient.http import MediaIoBaseUpload
16
  import gspread
17
  import time
18
 
19
+ # --- SEÇÃO DE SECRETS CORRIGIDA PARA LER VARIÁVEIS DE AMBIENTE ---
20
+
21
  # 🔥 Initialize Roboflow
22
+ # as variáveis de ambiente passadas pelo comando 'docker run -e'
23
+ API_KEY = os.environ.get("roboflow_api_key" )
24
+ roboflow_workspace = os.environ.get("roboflow_workspace")
25
+ roboflow_project = os.environ.get("roboflow_project")
26
+ roboflow_version = os.environ.get("roboflow_version")
27
+
28
+ # Validação para garantir que as variáveis foram passadas
29
+ if not all([API_KEY, roboflow_workspace, roboflow_project, roboflow_version]):
30
+ st.error("Um ou mais segredos do Roboflow não foram encontrados! Verifique as variáveis de ambiente: roboflow_api_key, roboflow_workspace, roboflow_project, roboflow_version.")
31
+ st.stop()
32
+
33
+ rf = roboflow.Roboflow(api_key=API_KEY)
34
+ project = rf.workspace(roboflow_workspace).project(roboflow_project)
35
+ model = project.version(int(roboflow_version)).model # Garante que a versão seja um inteiro
36
  model.confidence = 80
37
  model.overlap = 25
38
  dpi_value = 300
 
40
  with st.expander("⚙️ Advanced Settings", expanded=True):
41
  model.confidence = st.slider("Model Confidence (%)", 20, 100, 80)
42
 
43
+ # 📁 Setup Google Drive and Sheets
44
+ # a variável de ambiente para a URL da planilha
45
+ feedback_sheet_url = os.environ.get("feedback_sheet_url")
46
+ if not feedback_sheet_url:
47
+ st.error("Secret 'feedback_sheet_url' não foi encontrado! Verifique a variável de ambiente.")
48
+ st.stop()
49
+
50
+ # Lê a variável de ambiente para o token do Google
51
+ google_token_json = os.environ.get("GOOGLE_TOKEN_JSON")
52
+ if not google_token_json:
53
+ st.error("Secret 'GOOGLE_TOKEN_JSON' não foi encontrado! Verifique a variável de ambiente.")
54
+ st.stop()
55
+
56
+ try:
57
+ # Autenticação do Google a partir do token JSON passado como variável de ambiente
58
+ scope = ["https://www.googleapis.com/auth/drive", "https://www.googleapis.com/auth/spreadsheets"]
59
+ # Carrega as informações do token a partir da string JSON
60
+ token_info = json.loads(google_token_json )
61
+ creds = Credentials.from_authorized_user_info(token_info, scope)
62
+
63
+ drive_service = build("drive", "v3", credentials=creds)
64
+ sheets_client = gspread.authorize(creds)
65
+ sheet = sheets_client.open_by_url(feedback_sheet_url).sheet1
66
+ except Exception as e:
67
+ st.error(f"Falha ao autenticar com o Google. Verifique o GOOGLE_TOKEN_JSON. Erro: {e}")
68
+ st.stop()
69
+
70
+ # --- FIM DA SEÇÃO DE SECRETS ---
 
 
71
 
72
 
73
  # 📌 Helper Functions
 
300
  except Exception as e:
301
  st.error(f"An error occurred during the upload to Google Drive: {e}")
302
  else:
303
+ st.success("✅ Feedback saved successfully!")