Spaces:
Sleeping
Sleeping
Update app/google_oauth.py
Browse files- app/google_oauth.py +163 -144
app/google_oauth.py
CHANGED
|
@@ -1,144 +1,163 @@
|
|
| 1 |
-
import json
|
| 2 |
-
import os
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
from google.
|
| 7 |
-
from
|
| 8 |
-
from
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
"https://www.googleapis.com/auth/
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import os
|
| 3 |
+
import tempfile
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
|
| 6 |
+
from google.auth.transport.requests import Request
|
| 7 |
+
from google.oauth2.credentials import Credentials
|
| 8 |
+
from google_auth_oauthlib.flow import Flow
|
| 9 |
+
from googleapiclient.discovery import build
|
| 10 |
+
|
| 11 |
+
SCOPES = [
|
| 12 |
+
"https://www.googleapis.com/auth/spreadsheets",
|
| 13 |
+
"https://www.googleapis.com/auth/drive.file",
|
| 14 |
+
]
|
| 15 |
+
TOKEN_FILENAME = "google_token.json"
|
| 16 |
+
DATA_DIR = Path("/data")
|
| 17 |
+
FALLBACK_DATA_DIR = Path(tempfile.gettempdir()) / "tcc2_agent"
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class GoogleOAuthError(RuntimeError):
|
| 21 |
+
pass
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class GoogleAuthRequiredError(GoogleOAuthError):
|
| 25 |
+
pass
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def _resolve_data_dir():
|
| 29 |
+
preferred_dir = os.environ.get("GOOGLE_TOKEN_DIR", "").strip()
|
| 30 |
+
candidates = [Path(preferred_dir)] if preferred_dir else []
|
| 31 |
+
candidates.extend([DATA_DIR, FALLBACK_DATA_DIR])
|
| 32 |
+
|
| 33 |
+
for directory in candidates:
|
| 34 |
+
try:
|
| 35 |
+
directory.mkdir(parents=True, exist_ok=True)
|
| 36 |
+
return directory
|
| 37 |
+
except OSError:
|
| 38 |
+
continue
|
| 39 |
+
|
| 40 |
+
raise GoogleOAuthError(
|
| 41 |
+
"Nao foi possivel criar um diretorio para armazenar o token OAuth. "
|
| 42 |
+
"Defina GOOGLE_TOKEN_DIR para um caminho gravavel."
|
| 43 |
+
)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def get_token_path():
|
| 47 |
+
return _resolve_data_dir() / TOKEN_FILENAME
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def _client_config():
|
| 51 |
+
client_id = os.environ.get("GOOGLE_CLIENT_ID", "").strip()
|
| 52 |
+
client_secret = os.environ.get("GOOGLE_CLIENT_SECRET", "").strip()
|
| 53 |
+
redirect_uri = os.environ.get("GOOGLE_REDIRECT_URI", "").strip()
|
| 54 |
+
|
| 55 |
+
missing = [
|
| 56 |
+
name
|
| 57 |
+
for name, value in {
|
| 58 |
+
"GOOGLE_CLIENT_ID": client_id,
|
| 59 |
+
"GOOGLE_CLIENT_SECRET": client_secret,
|
| 60 |
+
"GOOGLE_REDIRECT_URI": redirect_uri,
|
| 61 |
+
}.items()
|
| 62 |
+
if not value
|
| 63 |
+
]
|
| 64 |
+
if missing:
|
| 65 |
+
raise GoogleOAuthError("Variaveis OAuth ausentes: " + ", ".join(missing))
|
| 66 |
+
|
| 67 |
+
return {
|
| 68 |
+
"web": {
|
| 69 |
+
"client_id": client_id,
|
| 70 |
+
"client_secret": client_secret,
|
| 71 |
+
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
|
| 72 |
+
"token_uri": "https://oauth2.googleapis.com/token",
|
| 73 |
+
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
|
| 74 |
+
"redirect_uris": [redirect_uri],
|
| 75 |
+
}
|
| 76 |
+
}
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def build_flow(state=None):
|
| 80 |
+
redirect_uri = os.environ.get("GOOGLE_REDIRECT_URI", "").strip()
|
| 81 |
+
flow = Flow.from_client_config(_client_config(), scopes=SCOPES, state=state)
|
| 82 |
+
flow.redirect_uri = redirect_uri
|
| 83 |
+
return flow
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def get_authorization_url():
|
| 87 |
+
flow = build_flow()
|
| 88 |
+
authorization_url, state = flow.authorization_url(
|
| 89 |
+
access_type="offline",
|
| 90 |
+
prompt="consent",
|
| 91 |
+
include_granted_scopes="true",
|
| 92 |
+
)
|
| 93 |
+
return authorization_url, state
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def save_credentials(credentials):
|
| 97 |
+
token_path = get_token_path()
|
| 98 |
+
token_path.write_text(credentials.to_json(), encoding="utf-8")
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def load_credentials():
|
| 102 |
+
token_path = get_token_path()
|
| 103 |
+
if not token_path.exists():
|
| 104 |
+
return None
|
| 105 |
+
|
| 106 |
+
try:
|
| 107 |
+
payload = json.loads(token_path.read_text(encoding="utf-8"))
|
| 108 |
+
credentials = Credentials.from_authorized_user_info(payload, SCOPES)
|
| 109 |
+
except Exception:
|
| 110 |
+
return None
|
| 111 |
+
|
| 112 |
+
if credentials.expired and credentials.refresh_token:
|
| 113 |
+
try:
|
| 114 |
+
credentials.refresh(Request())
|
| 115 |
+
save_credentials(credentials)
|
| 116 |
+
except Exception:
|
| 117 |
+
return None
|
| 118 |
+
|
| 119 |
+
if not credentials.valid:
|
| 120 |
+
return None
|
| 121 |
+
|
| 122 |
+
return credentials
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def get_sheets_service():
|
| 126 |
+
credentials = load_credentials()
|
| 127 |
+
if credentials is None:
|
| 128 |
+
raise GoogleAuthRequiredError(
|
| 129 |
+
"Google Sheets nao autorizado. Acesse /auth/google primeiro."
|
| 130 |
+
)
|
| 131 |
+
|
| 132 |
+
return build("sheets", "v4", credentials=credentials, cache_discovery=False)
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def append_feedback_to_sheet(feedback_data):
|
| 136 |
+
spreadsheet_id = os.environ.get("GOOGLE_SPREADSHEET_ID", "").strip()
|
| 137 |
+
if not spreadsheet_id:
|
| 138 |
+
raise GoogleOAuthError("GOOGLE_SPREADSHEET_ID nao configurado.")
|
| 139 |
+
|
| 140 |
+
service = get_sheets_service()
|
| 141 |
+
fields = [
|
| 142 |
+
"timestamp",
|
| 143 |
+
"query",
|
| 144 |
+
"product_id",
|
| 145 |
+
"product_name",
|
| 146 |
+
"categoria_inferida",
|
| 147 |
+
"feedback",
|
| 148 |
+
"motivo",
|
| 149 |
+
"score_final",
|
| 150 |
+
"score_semantico",
|
| 151 |
+
"bonus_lexical",
|
| 152 |
+
"penalidade_feedback",
|
| 153 |
+
"user_message",
|
| 154 |
+
]
|
| 155 |
+
row = [[str(feedback_data.get(field, "") or "") for field in fields]]
|
| 156 |
+
|
| 157 |
+
return service.spreadsheets().values().append(
|
| 158 |
+
spreadsheetId=spreadsheet_id,
|
| 159 |
+
range="Feedback!A:Z",
|
| 160 |
+
valueInputOption="USER_ENTERED",
|
| 161 |
+
insertDataOption="INSERT_ROWS",
|
| 162 |
+
body={"values": row},
|
| 163 |
+
).execute()
|