|
from googleapiclient.discovery import build |
|
from google.oauth2.service_account import Credentials |
|
from fuzzywuzzy import process |
|
import os |
|
|
|
SCOPES = ["https://www.googleapis.com/auth/drive.readonly"] |
|
FOLDER_ID = "1hqfPQnsVL2Ld8hu0GRIqcuOp-eDz-CAX" |
|
|
|
SERVICE_ACCOUNT_FILE = os.path.join(os.getcwd(), "./files/credenciais.json") |
|
def authenticate_drive(): |
|
"""Autentica no Google Drive usando uma conta de serviço.""" |
|
credentials = Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE, scopes=SCOPES) |
|
service = build("drive", "v3", credentials=credentials) |
|
return service |
|
|
|
def list_files_recursive(service, folder_id, path=""): |
|
"""Lista todos os arquivos e subpastas no Google Drive de forma recursiva.""" |
|
query = f"'{folder_id}' in parents and trashed = false" |
|
response = service.files().list( |
|
q=query, |
|
spaces="drive", |
|
fields="files(id, name, mimeType, parents)", |
|
).execute() |
|
|
|
files = response.get("files", []) |
|
all_files = [] |
|
|
|
for file in files: |
|
|
|
current_path = f"{path}/{file['name']}" |
|
all_files.append({"id": file["id"], "name": file["name"], "path": current_path}) |
|
|
|
|
|
if file["mimeType"] == "application/vnd.google-apps.folder": |
|
all_files.extend(list_files_recursive(service, file["id"], current_path)) |
|
|
|
return all_files |
|
|
|
def find_file_by_name(files, search_name): |
|
"""Encontra um arquivo com nome aproximado utilizando fuzzy matching.""" |
|
|
|
file_names = [file["name"] for file in files] |
|
best_match, score = process.extractOne(search_name, file_names) |
|
|
|
if score >= 80: |
|
matching_files = [file for file in files if file["name"] == best_match] |
|
return matching_files |
|
else: |
|
return [] |
|
|
|
def search_file_in_drive(search_name): |
|
"""Procura o arquivo mais relevante no Google Drive e retorna o link.""" |
|
service = authenticate_drive() |
|
print("Autenticado com sucesso no Google Drive!") |
|
|
|
|
|
files = list_files_recursive(service, FOLDER_ID) |
|
|
|
if not files: |
|
print("Nenhum arquivo encontrado na pasta!") |
|
return None |
|
|
|
print(f"Total de arquivos encontrados: {len(files)}") |
|
|
|
|
|
matching_files = find_file_by_name(files, search_name) |
|
|
|
if matching_files: |
|
best_file = matching_files[0] |
|
link = f"https://drive.google.com/file/d/{best_file['id']}/view" |
|
print(f"Arquivo encontrado: {best_file['name']}") |
|
print(f"Link: {link}") |
|
return link |
|
else: |
|
print(f"Nenhum arquivo encontrado com nome aproximado '{search_name}'.") |
|
return None |
|
|
|
|