Zelyanoth commited on
Commit
0608375
·
1 Parent(s): b3c01df

feat(content): enhance logging for Gradio client initialization and API calls

Browse files
backend/api/posts.py CHANGED
@@ -118,16 +118,10 @@ def _generate_post_task(user_id, job_id, job_store, hugging_key):
118
  'error': None
119
  }
120
 
121
- # Log that the background task has started
122
- current_app.logger.info(f"Starting background post generation task for user_id: {user_id}, job_id: {job_id}")
123
-
124
  # Generate content using content service
125
  # Pass the Hugging Face key directly to the service
126
  content_service = ContentService(hugging_key=hugging_key)
127
- current_app.logger.info(f"ContentService created successfully for user_id: {user_id}")
128
-
129
  generated_result = content_service.generate_post_content(user_id)
130
- current_app.logger.info(f"Content generation completed successfully for user_id: {user_id}, result type: {type(generated_result)}")
131
 
132
  # Handle the case where generated_result might be a tuple, list, or string
133
  # image_data could be bytes (from base64) or a string (URL)
@@ -151,8 +145,6 @@ def _generate_post_task(user_id, job_id, job_store, hugging_key):
151
  'error': None
152
  }
153
 
154
- current_app.logger.info(f"Background task completed for job_id: {job_id}, status set to completed")
155
-
156
  except Exception as e:
157
  error_message = str(e)
158
  safe_log_message(f"Generate post background task error: {error_message}")
@@ -162,7 +154,6 @@ def _generate_post_task(user_id, job_id, job_store, hugging_key):
162
  'result': None,
163
  'error': error_message
164
  }
165
- current_app.logger.error(f"Background task failed for job_id: {job_id}, error: {error_message}")
166
 
167
  @posts_bp.route('/generate', methods=['POST'])
168
  @jwt_required()
 
118
  'error': None
119
  }
120
 
 
 
 
121
  # Generate content using content service
122
  # Pass the Hugging Face key directly to the service
123
  content_service = ContentService(hugging_key=hugging_key)
 
 
124
  generated_result = content_service.generate_post_content(user_id)
 
125
 
126
  # Handle the case where generated_result might be a tuple, list, or string
127
  # image_data could be bytes (from base64) or a string (URL)
 
145
  'error': None
146
  }
147
 
 
 
148
  except Exception as e:
149
  error_message = str(e)
150
  safe_log_message(f"Generate post background task error: {error_message}")
 
154
  'result': None,
155
  'error': error_message
156
  }
 
157
 
158
  @posts_bp.route('/generate', methods=['POST'])
159
  @jwt_required()
backend/services/content_service.py CHANGED
@@ -9,6 +9,7 @@ from flask import current_app
9
  from gradio_client import Client
10
  from PIL import Image
11
  import base64
 
12
 
13
  class ContentService:
14
  """Service for AI content generation using Hugging Face models."""
@@ -32,7 +33,58 @@ class ContentService:
32
  raise RuntimeError("Hugging Face API key not provided and not available in app config. "
33
  "Please provide the key when initializing ContentService.")
34
 
35
- self.client = Client("Zelyanoth/Linkedin_poster_dev", token=self.hugging_key)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
 
37
  def validate_unicode_content(self, content):
38
  """Validate Unicode content while preserving original formatting and spaces."""
@@ -139,12 +191,22 @@ class ContentService:
139
  if self.client is None:
140
  self._initialize_client()
141
 
142
- current_app.logger.info(f"Calling Gradio API with user_id: {user_id}")
 
 
 
 
 
143
  result = self.client.predict(
144
  code=user_id,
145
  api_name="/poster_linkedin"
146
  )
147
- current_app.logger.info(f"Gradio API response received: {type(result)}")
 
 
 
 
 
148
 
149
 
150
  # Handle the case where result might be a tuple from Gradio
 
9
  from gradio_client import Client
10
  from PIL import Image
11
  import base64
12
+ import logging
13
 
14
  class ContentService:
15
  """Service for AI content generation using Hugging Face models."""
 
33
  raise RuntimeError("Hugging Face API key not provided and not available in app config. "
34
  "Please provide the key when initializing ContentService.")
35
 
36
+ try:
37
+ current_app.logger.info(f"Initializing Gradio client with Hugging Face Space: Zelyanoth/Linkedin_poster_dev")
38
+ current_app.logger.info(f"Hugging Face API key presence: {bool(self.hugging_key)}")
39
+ except RuntimeError:
40
+ # If outside app context, use basic logging
41
+ logging.info(f"Initializing Gradio client with Hugging Face Space: Zelyanoth/Linkedin_poster_dev")
42
+ logging.info(f"Hugging Face API key presence: {bool(self.hugging_key)}")
43
+
44
+ try:
45
+ # Check if the Hugging Face Space exists and is accessible before creating the client
46
+ self.client = Client("Zelyanoth/Linkedin_poster_dev", hf_token=self.hugging_key)
47
+
48
+ # Log success using safe approach
49
+ try:
50
+ current_app.logger.info("Gradio client initialized successfully")
51
+ except RuntimeError:
52
+ logging.info("Gradio client initialized successfully")
53
+
54
+ # Test if the API endpoint exists
55
+ try:
56
+ # Get the list of available API endpoints to verify the service is available
57
+ api_endpoints = self.client.view_api().named_endpoints
58
+ if '/poster_linkedin' not in api_endpoints:
59
+ try:
60
+ current_app.logger.warning("API endpoint '/poster_linkedin' not found in Hugging Face Space")
61
+ except RuntimeError:
62
+ logging.warning("API endpoint '/poster_linkedin' not found in Hugging Face Space")
63
+ raise Exception("Required API endpoint '/poster_linkedin' not available in Hugging Face Space")
64
+ except Exception as api_check_error:
65
+ try:
66
+ current_app.logger.warning(f"Could not verify API endpoints: {str(api_check_error)}")
67
+ except RuntimeError:
68
+ logging.warning(f"Could not verify API endpoints: {str(api_check_error)}")
69
+
70
+ except Exception as e:
71
+ error_msg = f"Failed to initialize Gradio client: {str(e)}"
72
+
73
+ # Log error using safe approach
74
+ try:
75
+ current_app.logger.error(error_msg)
76
+ except RuntimeError:
77
+ logging.error(error_msg)
78
+
79
+ # Provide more specific error based on the type of failure
80
+ if "404" in str(e) or "not found" in str(e).lower():
81
+ error_msg += " - The Hugging Face Space 'Zelyanoth/Linkedin_poster_dev' may not exist"
82
+ elif "401" in str(e) or "unauthorized" in str(e).lower() or "invalid token" in str(e).lower():
83
+ error_msg += " - The Hugging Face token may be invalid or missing required permissions"
84
+ elif "timeout" in str(e).lower() or "connection" in str(e).lower() or "network" in str(e).lower():
85
+ error_msg += " - Network connectivity issue or timeout"
86
+
87
+ raise Exception(error_msg)
88
 
89
  def validate_unicode_content(self, content):
90
  """Validate Unicode content while preserving original formatting and spaces."""
 
191
  if self.client is None:
192
  self._initialize_client()
193
 
194
+ try:
195
+ current_app.logger.info(f"Calling Gradio API with user_id: {user_id}")
196
+ except RuntimeError:
197
+ # If outside app context, use basic logging
198
+ logging.info(f"Calling Gradio API with user_id: {user_id}")
199
+
200
  result = self.client.predict(
201
  code=user_id,
202
  api_name="/poster_linkedin"
203
  )
204
+
205
+ try:
206
+ current_app.logger.info(f"Gradio API response received: {type(result)}")
207
+ except RuntimeError:
208
+ # If outside app context, use basic logging
209
+ logging.info(f"Gradio API response received: {type(result)}")
210
 
211
 
212
  # Handle the case where result might be a tuple from Gradio