Spaces:
Runtime error
Runtime error
Download google_sheets_client.py from videy/upload-image-to-cloud: direct link, hf CLI and curl.
- Browser
- Download file 7.28 kB
-
https://huggingface.co/spaces/videy/upload-image-to-cloud/resolve/main/google_sheets_client.py
- Command line
-
hf download hf://spaces/videy/upload-image-to-cloud/google_sheets_client.py
-
curl -L -o google_sheets_client.py https://huggingface.co/spaces/videy/upload-image-to-cloud/resolve/main/google_sheets_client.py
7.28 kB
| """ | |
| Google Sheets API ํด๋ผ์ด์ธํธ - ์๋น์ค ๊ณ์ ์ธ์ฆ ๋ฒ์ | |
| """ | |
| import json | |
| import os | |
| from typing import Dict, List, Optional, Tuple | |
| from google.oauth2 import service_account | |
| from googleapiclient.discovery import build | |
| from googleapiclient.errors import HttpError | |
| class GoogleSheetsClient: | |
| """Google Sheets API ํด๋ผ์ด์ธํธ (์๋น์ค ๊ณ์ ๋ฒ์ )""" | |
| def __init__(self, service_account_info: Dict, spreadsheet_id: str): | |
| """ | |
| Args: | |
| service_account_info: ์๋น์ค ๊ณ์ ์ ๋ณด ๋์ ๋๋ฆฌ | |
| spreadsheet_id: Google Sheets ์คํ๋ ๋์ํธ ID | |
| """ | |
| self.spreadsheet_id = spreadsheet_id | |
| self.service = None | |
| # ์๋น์ค ๊ณ์ ์ ๋ณด๋ก credentials ์์ฑ | |
| self.credentials = service_account.Credentials.from_service_account_info( | |
| service_account_info, | |
| scopes=['https://www.googleapis.com/auth/spreadsheets'] | |
| ) | |
| # Google Sheets API ์๋น์ค ๊ฐ์ฒด ์์ฑ | |
| self._build_service() | |
| def _build_service(self): | |
| """Google Sheets API ์๋น์ค ๊ฐ์ฒด ๋น๋""" | |
| try: | |
| self.service = build('sheets', 'v4', credentials=self.credentials) | |
| except Exception as e: | |
| raise Exception(f"Google Sheets ์๋น์ค ์ด๊ธฐํ ์คํจ: {str(e)}") | |
| def get_sheet_data(self, sheet_name: str, range_notation: str = None) -> Tuple[bool, any]: | |
| """์ํธ ๋ฐ์ดํฐ ์กฐํ""" | |
| try: | |
| if range_notation: | |
| range_param = f"{sheet_name}!{range_notation}" | |
| else: | |
| range_param = sheet_name | |
| result = self.service.spreadsheets().values().get( | |
| spreadsheetId=self.spreadsheet_id, | |
| range=range_param | |
| ).execute() | |
| values = result.get('values', []) | |
| return True, values | |
| except HttpError as e: | |
| return False, f"๋ฐ์ดํฐ ์กฐํ ์คํจ: {e.error_details}" | |
| except Exception as e: | |
| return False, f"๋ฐ์ดํฐ ์กฐํ ์ค ์ค๋ฅ: {str(e)}" | |
| def append_row(self, sheet_name: str, values: List[str]) -> Tuple[bool, str]: | |
| """์ํธ์ ์ ํ ์ถ๊ฐ""" | |
| try: | |
| body = { | |
| 'values': [values], | |
| 'majorDimension': 'ROWS' | |
| } | |
| result = self.service.spreadsheets().values().append( | |
| spreadsheetId=self.spreadsheet_id, | |
| range=f"{sheet_name}", | |
| valueInputOption='USER_ENTERED', | |
| insertDataOption='INSERT_ROWS', | |
| body=body | |
| ).execute() | |
| updated_cells = result.get('updates', {}).get('updatedCells', 0) | |
| return True, f"์ฑ๊ณต์ ์ผ๋ก {updated_cells}๊ฐ ์ ์ด ์ถ๊ฐ๋์์ต๋๋ค" | |
| except HttpError as e: | |
| return False, f"ํ ์ถ๊ฐ ์คํจ: {e.error_details}" | |
| except Exception as e: | |
| return False, f"ํ ์ถ๊ฐ ์ค ์ค๋ฅ: {str(e)}" | |
| def get_last_row_number(self, sheet_name: str) -> Tuple[bool, int]: | |
| """์ํธ์ ๋ง์ง๋ง ํ ๋ฒํธ ์กฐํ""" | |
| try: | |
| success, data = self.get_sheet_data(sheet_name) | |
| if success: | |
| return True, len(data) | |
| else: | |
| return False, 0 | |
| except Exception as e: | |
| return False, 0 | |
| def add_image_url(self, sheet_name: str, image_url: str) -> Tuple[bool, str]: | |
| """์ด๋ฏธ์ง URL์ ์ํธ์ ์ถ๊ฐ""" | |
| try: | |
| # ๋ง์ง๋ง ํ ๋ฒํธ ํ์ธ | |
| success, last_row = self.get_last_row_number(sheet_name) | |
| # ์ ํ์ ์ด๋ฏธ์ง URL ์ถ๊ฐ | |
| success, message = self.append_row(sheet_name, [image_url]) | |
| if success: | |
| new_row_number = last_row + 1 | |
| return True, f"ํ {new_row_number}์ ์ด๋ฏธ์ง URL์ด ์ถ๊ฐ๋์์ต๋๋ค: {image_url}" | |
| else: | |
| return False, message | |
| except Exception as e: | |
| return False, f"์ด๋ฏธ์ง URL ์ถ๊ฐ ์ค ์ค๋ฅ: {str(e)}" | |
| def create_sheets_client_from_service_account(service_account_info: Dict, spreadsheet_id: str) -> GoogleSheetsClient: | |
| """์๋น์ค ๊ณ์ ์ ๋ณด๋ก Google Sheets ํด๋ผ์ด์ธํธ ์์ฑ""" | |
| return GoogleSheetsClient(service_account_info, spreadsheet_id) | |
| def create_sheets_client_from_env(spreadsheet_id: str) -> Optional[GoogleSheetsClient]: | |
| """ํ๊ฒฝ ๋ณ์์์ ์๋น์ค ๊ณ์ ์ ๋ณด๋ฅผ ์ฝ์ด ํด๋ผ์ด์ธํธ ์์ฑ""" | |
| # ํ๊ฒฝ ๋ณ์์์ ์๋น์ค ๊ณ์ ์ ๋ณด ์ฝ๊ธฐ | |
| service_account_json = os.getenv('GOOGLE_SERVICE_ACCOUNT_JSON') | |
| if service_account_json: | |
| try: | |
| service_account_info = json.loads(service_account_json) | |
| return GoogleSheetsClient(service_account_info, spreadsheet_id) | |
| except json.JSONDecodeError: | |
| raise Exception("GOOGLE_SERVICE_ACCOUNT_JSON ํ๊ฒฝ ๋ณ์๊ฐ ์ฌ๋ฐ๋ฅธ JSON ํ์์ด ์๋๋๋ค") | |
| # ๋๋ ํ์ผ์์ ์ฝ๊ธฐ | |
| service_account_file = os.getenv('GOOGLE_SERVICE_ACCOUNT_FILE', 'service_account.json') | |
| if os.path.exists(service_account_file): | |
| with open(service_account_file, 'r') as f: | |
| service_account_info = json.load(f) | |
| return GoogleSheetsClient(service_account_info, spreadsheet_id) | |
| return None | |
| # ๊ธฐ๋ณธ ์๋น์ค ๊ณ์ ์ ๋ณด (์ค์ Private Key๊ฐ ํ์ํจ) | |
| DEFAULT_SERVICE_ACCOUNT_INFO = { | |
| "type": "service_account", | |
| "project_id": "marketing-automation-463304", | |
| "private_key_id": "dc8e23fa63789d7af4e5f3e947b6ef8dcaee0d67", | |
| "private_key": "", # ์ค์ Private Key ํ์ | |
| "client_email": "img-upload@marketing-automation-463304.iam.gserviceaccount.com", | |
| "client_id": "115745495358423216505", | |
| "auth_uri": "https://accounts.google.com/o/oauth2/auth", | |
| "token_uri": "https://oauth2.googleapis.com/token", | |
| "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs", | |
| "client_x509_cert_url": f"https://www.googleapis.com/robot/v1/metadata/x509/img-upload%40marketing-automation-463304.iam.gserviceaccount.com" | |
| } | |
| # ํ ์คํธ ์ฝ๋ | |
| if __name__ == "__main__": | |
| # ํ ์คํธ ์ค์ | |
| SPREADSHEET_ID = "1tB5rYhBGdReeSg3t-7oFXoq2h2WbejNfzCxiL1cQUxY" | |
| # ์๋น์ค ๊ณ์ ์ ๋ณด (์ค์ Private Key ํ์) | |
| service_account_info = DEFAULT_SERVICE_ACCOUNT_INFO.copy() | |
| service_account_info["private_key"] = "YOUR_PRIVATE_KEY_HERE" # ์ค์ ํค๋ก ๊ต์ฒด ํ์ | |
| try: | |
| # ํด๋ผ์ด์ธํธ ์์ฑ | |
| client = create_sheets_client_from_service_account(service_account_info, SPREADSHEET_ID) | |
| print("โ Google Sheets ํด๋ผ์ด์ธํธ ์์ฑ ์ฑ๊ณต") | |
| # ํ ์คํธ ์ด๋ฏธ์ง URL ์ถ๊ฐ | |
| test_url = "https://example.com/test-image.jpg" | |
| success, message = client.add_image_url("Storyboard", test_url) | |
| if success: | |
| print(f"โ ์ด๋ฏธ์ง URL ์ถ๊ฐ ์ฑ๊ณต: {message}") | |
| else: | |
| print(f"โ ์ด๋ฏธ์ง URL ์ถ๊ฐ ์คํจ: {message}") | |
| except Exception as e: | |
| print(f"โ ์ค๋ฅ ๋ฐ์: {str(e)}") | |