yukee1992 commited on
Commit
61024a5
Β·
verified Β·
1 Parent(s): e286e0f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +70 -11
app.py CHANGED
@@ -87,26 +87,77 @@ def setup_google_drive():
87
  print(f"Google Drive setup failed: {e}")
88
  return None
89
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90
  # Initialize Google Drive service
91
  drive_service = setup_google_drive()
92
-
93
- # Get Shared Drive ID from environment variable
94
  SHARED_DRIVE_ID = os.getenv('SHARED_DRIVE_ID')
95
- if not SHARED_DRIVE_ID:
96
- print("WARNING: SHARED_DRIVE_ID not set. Google Drive saving will fail.")
97
 
98
  def save_to_google_drive(image, prompt):
99
- """Save image to Google Drive"""
100
  if not drive_service:
101
- print("Google Drive not configured, skipping save")
 
 
 
 
102
  return None
103
 
104
  try:
 
 
105
  # Create a filename with timestamp
106
  timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
107
  safe_prompt = "".join(c for c in prompt[:30] if c.isalnum() or c in (' ', '-', '_')).rstrip()
108
  filename = f"storybook_{timestamp}_{safe_prompt}.png"
109
 
 
 
110
  # Convert image to bytes
111
  img_bytes = io.BytesIO()
112
  image.save(img_bytes, format='PNG')
@@ -116,22 +167,30 @@ def save_to_google_drive(image, prompt):
116
  file_metadata = {
117
  'name': filename,
118
  'mimeType': 'image/png',
119
- 'parents': ['root'] # Save to root folder, or specify folder ID
120
  }
121
 
122
- # Upload to Google Drive
 
 
123
  media = MediaIoBaseUpload(img_bytes, mimetype='image/png', resumable=True)
 
 
124
  file = drive_service.files().create(
125
  body=file_metadata,
126
  media_body=media,
 
127
  fields='id, webViewLink'
128
  ).execute()
129
 
130
- print(f"Image saved to Google Drive: {file.get('webViewLink')}")
131
- return file.get('webViewLink')
 
132
 
133
  except Exception as e:
134
- print(f"Failed to save to Google Drive: {e}")
 
 
135
  return None
136
 
137
  # Request model
 
87
  print(f"Google Drive setup failed: {e}")
88
  return None
89
 
90
+ # Google Drive Setup with DEBUGGING
91
+ def setup_google_drive():
92
+ """Initialize Google Drive service with detailed debugging"""
93
+ try:
94
+ print("Setting up Google Drive...")
95
+
96
+ # Get service account credentials from environment variable
97
+ credentials_json = os.getenv('GOOGLE_SERVICE_ACCOUNT_JSON')
98
+ if not credentials_json:
99
+ print("❌ ERROR: GOOGLE_SERVICE_ACCOUNT_JSON environment variable not found")
100
+ return None
101
+
102
+ print("βœ… Found Google service account JSON")
103
+
104
+ # Get Shared Drive ID
105
+ SHARED_DRIVE_ID = os.getenv('SHARED_DRIVE_ID')
106
+ if not SHARED_DRIVE_ID:
107
+ print("❌ ERROR: SHARED_DRIVE_ID environment variable not set")
108
+ return None
109
+
110
+ print(f"βœ… Shared Drive ID: {SHARED_DRIVE_ID}")
111
+
112
+ # Parse the JSON credentials
113
+ try:
114
+ service_account_info = json.loads(credentials_json)
115
+ client_email = service_account_info.get('client_email', 'Unknown')
116
+ print(f"βœ… Service account email: {client_email}")
117
+ except json.JSONDecodeError as e:
118
+ print(f"❌ ERROR: Invalid JSON in service account credentials: {e}")
119
+ return None
120
+
121
+ credentials = service_account.Credentials.from_service_account_info(
122
+ service_account_info,
123
+ scopes=['https://www.googleapis.com/auth/drive.file']
124
+ )
125
+
126
+ # Build the Drive service
127
+ drive_service = build('drive', 'v3', credentials=credentials)
128
+ print("βœ… Google Drive service initialized successfully")
129
+ return drive_service
130
+
131
+ except Exception as e:
132
+ print(f"❌ Google Drive setup failed: {str(e)}")
133
+ import traceback
134
+ traceback.print_exc()
135
+ return None
136
+
137
  # Initialize Google Drive service
138
  drive_service = setup_google_drive()
 
 
139
  SHARED_DRIVE_ID = os.getenv('SHARED_DRIVE_ID')
 
 
140
 
141
  def save_to_google_drive(image, prompt):
142
+ """Save image to Google Drive Shared Drive with detailed debugging"""
143
  if not drive_service:
144
+ print("❌ Google Drive service not available, skipping save")
145
+ return None
146
+
147
+ if not SHARED_DRIVE_ID:
148
+ print("❌ Shared Drive ID not configured, skipping save")
149
  return None
150
 
151
  try:
152
+ print(f"πŸ”„ Attempting to save image to Shared Drive: {SHARED_DRIVE_ID}")
153
+
154
  # Create a filename with timestamp
155
  timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
156
  safe_prompt = "".join(c for c in prompt[:30] if c.isalnum() or c in (' ', '-', '_')).rstrip()
157
  filename = f"storybook_{timestamp}_{safe_prompt}.png"
158
 
159
+ print(f"πŸ“ Filename: {filename}")
160
+
161
  # Convert image to bytes
162
  img_bytes = io.BytesIO()
163
  image.save(img_bytes, format='PNG')
 
167
  file_metadata = {
168
  'name': filename,
169
  'mimeType': 'image/png',
170
+ 'parents': [SHARED_DRIVE_ID] # Save to Shared Drive
171
  }
172
 
173
+ print(f"πŸ“‹ File metadata: {file_metadata}")
174
+
175
+ # Upload to Google Drive with supportsAllDrives=True
176
  media = MediaIoBaseUpload(img_bytes, mimetype='image/png', resumable=True)
177
+
178
+ print("⬆️ Starting upload to Google Drive...")
179
  file = drive_service.files().create(
180
  body=file_metadata,
181
  media_body=media,
182
+ supportsAllDrives=True, # CRITICAL FOR SHARED DRIVES
183
  fields='id, webViewLink'
184
  ).execute()
185
 
186
+ drive_link = file.get('webViewLink')
187
+ print(f"βœ… Image saved to Google Drive: {drive_link}")
188
+ return drive_link
189
 
190
  except Exception as e:
191
+ print(f"❌ Failed to save to Google Drive: {str(e)}")
192
+ import traceback
193
+ traceback.print_exc()
194
  return None
195
 
196
  # Request model