Spaces:
Sleeping
Sleeping
Update main.py
Browse files
main.py
CHANGED
|
@@ -115,81 +115,198 @@ def google_signin():
|
|
| 115 |
return jsonify({'success': True, 'user': {'uid': uid, **user_data}}), 200
|
| 116 |
except Exception as e: return jsonify({'error': str(e)}), 400
|
| 117 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 118 |
# -----------------------------------------------------------------------------
|
| 119 |
-
# 4. SOZO BUSINESS STUDIO API ENDPOINTS
|
| 120 |
# -----------------------------------------------------------------------------
|
| 121 |
|
| 122 |
@app.route('/api/sozo/projects', methods=['POST'])
|
| 123 |
def create_sozo_project():
|
|
|
|
|
|
|
| 124 |
try:
|
| 125 |
token = request.headers.get('Authorization', '').split(' ')[1]
|
| 126 |
uid = verify_token(token)
|
| 127 |
-
if not uid:
|
| 128 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 129 |
file = request.files['file']
|
| 130 |
-
if file.filename == '':
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 131 |
context = request.form.get('context', '')
|
| 132 |
project_id = uuid.uuid4().hex
|
|
|
|
|
|
|
|
|
|
| 133 |
file_bytes = file.read()
|
| 134 |
file.seek(0)
|
| 135 |
ext = Path(file.filename).suffix
|
|
|
|
|
|
|
|
|
|
| 136 |
blob_name = f"sozo_projects/{uid}/{project_id}/data{ext}"
|
| 137 |
blob = bucket.blob(blob_name)
|
| 138 |
blob.upload_from_string(file_bytes, content_type=file.content_type)
|
|
|
|
|
|
|
|
|
|
| 139 |
project_ref = db.reference(f'sozo_projects/{project_id}')
|
| 140 |
-
project_data = {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 141 |
project_ref.set(project_data)
|
|
|
|
|
|
|
|
|
|
| 142 |
df = load_dataframe_safely(io.BytesIO(file_bytes), file.filename)
|
| 143 |
preview_json = df.head().to_json(orient='records')
|
| 144 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 145 |
except Exception as e:
|
| 146 |
-
|
|
|
|
| 147 |
return jsonify({'error': str(e)}), 500
|
| 148 |
|
| 149 |
@app.route('/api/sozo/projects/<string:project_id>/generate-report', methods=['POST'])
|
| 150 |
def generate_sozo_report(project_id):
|
|
|
|
|
|
|
| 151 |
try:
|
| 152 |
token = request.headers.get('Authorization', '').split(' ')[1]
|
| 153 |
uid = verify_token(token)
|
| 154 |
-
if not uid:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 155 |
project_ref = db.reference(f'sozo_projects/{project_id}')
|
| 156 |
project_data = project_ref.get()
|
| 157 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 158 |
|
| 159 |
blob_path = "/".join(project_data['originalDataUrl'].split('/')[4:])
|
| 160 |
blob = bucket.blob(blob_path)
|
| 161 |
file_bytes = blob.download_as_bytes()
|
| 162 |
|
| 163 |
-
|
| 164 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 165 |
project_ref.update(update_data)
|
| 166 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 167 |
except Exception as e:
|
| 168 |
-
|
| 169 |
-
traceback.
|
|
|
|
|
|
|
|
|
|
|
|
|
| 170 |
return jsonify({'error': str(e)}), 500
|
| 171 |
|
| 172 |
@app.route('/api/sozo/projects', methods=['GET'])
|
| 173 |
def get_sozo_projects():
|
|
|
|
|
|
|
| 174 |
try:
|
| 175 |
token = request.headers.get('Authorization', '').split(' ')[1]
|
| 176 |
uid = verify_token(token)
|
| 177 |
-
if not uid:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 178 |
all_projects = db.reference('sozo_projects').order_by_child('uid').equal_to(uid).get()
|
|
|
|
|
|
|
|
|
|
|
|
|
| 179 |
return jsonify(all_projects or {}), 200
|
|
|
|
| 180 |
except Exception as e:
|
|
|
|
| 181 |
return jsonify({'error': str(e)}), 500
|
| 182 |
|
| 183 |
@app.route('/api/sozo/projects/<string:project_id>', methods=['GET'])
|
| 184 |
def get_sozo_project(project_id):
|
|
|
|
|
|
|
| 185 |
try:
|
| 186 |
token = request.headers.get('Authorization', '').split(' ')[1]
|
| 187 |
uid = verify_token(token)
|
| 188 |
-
if not uid:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 189 |
project_data = db.reference(f'sozo_projects/{project_id}').get()
|
| 190 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 191 |
return jsonify(project_data), 200
|
| 192 |
-
|
|
|
|
|
|
|
|
|
|
| 193 |
|
| 194 |
@app.route('/api/sozo/projects/<string:project_id>/markdown', methods=['PUT'])
|
| 195 |
def update_sozo_markdown(project_id):
|
|
|
|
| 115 |
return jsonify({'success': True, 'user': {'uid': uid, **user_data}}), 200
|
| 116 |
except Exception as e: return jsonify({'error': str(e)}), 400
|
| 117 |
|
| 118 |
+
import logging
|
| 119 |
+
|
| 120 |
+
# Configure console logging
|
| 121 |
+
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
| 122 |
+
logger = logging.getLogger(__name__)
|
| 123 |
+
|
| 124 |
# -----------------------------------------------------------------------------
|
| 125 |
+
# 4. SOZO BUSINESS STUDIO API ENDPOINTS WITH LOGGING
|
| 126 |
# -----------------------------------------------------------------------------
|
| 127 |
|
| 128 |
@app.route('/api/sozo/projects', methods=['POST'])
|
| 129 |
def create_sozo_project():
|
| 130 |
+
logger.info("POST /api/sozo/projects - Creating new project")
|
| 131 |
+
|
| 132 |
try:
|
| 133 |
token = request.headers.get('Authorization', '').split(' ')[1]
|
| 134 |
uid = verify_token(token)
|
| 135 |
+
if not uid:
|
| 136 |
+
logger.warning("Unauthorized access attempt to create project")
|
| 137 |
+
return jsonify({'error': 'Unauthorized'}), 401
|
| 138 |
+
|
| 139 |
+
logger.info(f"User {uid} creating project")
|
| 140 |
+
|
| 141 |
+
if 'file' not in request.files:
|
| 142 |
+
logger.warning(f"User {uid} - No file provided")
|
| 143 |
+
return jsonify({'error': 'No file part'}), 400
|
| 144 |
+
|
| 145 |
file = request.files['file']
|
| 146 |
+
if file.filename == '':
|
| 147 |
+
logger.warning(f"User {uid} - Empty filename")
|
| 148 |
+
return jsonify({'error': 'No selected file'}), 400
|
| 149 |
+
|
| 150 |
+
logger.info(f"User {uid} - Processing file: {file.filename}")
|
| 151 |
+
|
| 152 |
context = request.form.get('context', '')
|
| 153 |
project_id = uuid.uuid4().hex
|
| 154 |
+
|
| 155 |
+
logger.info(f"Generated project ID: {project_id}")
|
| 156 |
+
|
| 157 |
file_bytes = file.read()
|
| 158 |
file.seek(0)
|
| 159 |
ext = Path(file.filename).suffix
|
| 160 |
+
|
| 161 |
+
logger.info(f"File size: {len(file_bytes)} bytes, extension: {ext}")
|
| 162 |
+
|
| 163 |
blob_name = f"sozo_projects/{uid}/{project_id}/data{ext}"
|
| 164 |
blob = bucket.blob(blob_name)
|
| 165 |
blob.upload_from_string(file_bytes, content_type=file.content_type)
|
| 166 |
+
|
| 167 |
+
logger.info(f"File uploaded to storage: {blob_name}")
|
| 168 |
+
|
| 169 |
project_ref = db.reference(f'sozo_projects/{project_id}')
|
| 170 |
+
project_data = {
|
| 171 |
+
'uid': uid,
|
| 172 |
+
'status': 'uploaded',
|
| 173 |
+
'createdAt': datetime.utcnow().isoformat(),
|
| 174 |
+
'userContext': context,
|
| 175 |
+
'originalDataUrl': blob.public_url,
|
| 176 |
+
'originalFilename': file.filename
|
| 177 |
+
}
|
| 178 |
project_ref.set(project_data)
|
| 179 |
+
|
| 180 |
+
logger.info(f"Project data saved to database: {project_id}")
|
| 181 |
+
|
| 182 |
df = load_dataframe_safely(io.BytesIO(file_bytes), file.filename)
|
| 183 |
preview_json = df.head().to_json(orient='records')
|
| 184 |
+
|
| 185 |
+
logger.info(f"Project {project_id} created successfully for user {uid}")
|
| 186 |
+
|
| 187 |
+
return jsonify({
|
| 188 |
+
'success': True,
|
| 189 |
+
'project_id': project_id,
|
| 190 |
+
'preview': json.loads(preview_json)
|
| 191 |
+
}), 201
|
| 192 |
+
|
| 193 |
except Exception as e:
|
| 194 |
+
logger.error(f"Error creating project: {str(e)}")
|
| 195 |
+
logger.error(f"Traceback: {traceback.format_exc()}")
|
| 196 |
return jsonify({'error': str(e)}), 500
|
| 197 |
|
| 198 |
@app.route('/api/sozo/projects/<string:project_id>/generate-report', methods=['POST'])
|
| 199 |
def generate_sozo_report(project_id):
|
| 200 |
+
logger.info(f"POST /api/sozo/projects/{project_id}/generate-report - Generating report")
|
| 201 |
+
|
| 202 |
try:
|
| 203 |
token = request.headers.get('Authorization', '').split(' ')[1]
|
| 204 |
uid = verify_token(token)
|
| 205 |
+
if not uid:
|
| 206 |
+
logger.warning(f"Unauthorized access attempt to generate report for project {project_id}")
|
| 207 |
+
return jsonify({'error': 'Unauthorized'}), 401
|
| 208 |
+
|
| 209 |
+
logger.info(f"User {uid} generating report for project {project_id}")
|
| 210 |
+
|
| 211 |
project_ref = db.reference(f'sozo_projects/{project_id}')
|
| 212 |
project_data = project_ref.get()
|
| 213 |
+
|
| 214 |
+
if not project_data or project_data.get('uid') != uid:
|
| 215 |
+
logger.warning(f"Project {project_id} not found or unauthorized for user {uid}")
|
| 216 |
+
return jsonify({'error': 'Project not found or unauthorized'}), 404
|
| 217 |
+
|
| 218 |
+
logger.info(f"Project {project_id} validated for user {uid}")
|
| 219 |
|
| 220 |
blob_path = "/".join(project_data['originalDataUrl'].split('/')[4:])
|
| 221 |
blob = bucket.blob(blob_path)
|
| 222 |
file_bytes = blob.download_as_bytes()
|
| 223 |
|
| 224 |
+
logger.info(f"Downloaded file data for project {project_id}, size: {len(file_bytes)} bytes")
|
| 225 |
+
|
| 226 |
+
draft_data = generate_report_draft(
|
| 227 |
+
io.BytesIO(file_bytes),
|
| 228 |
+
project_data['originalFilename'],
|
| 229 |
+
project_data['userContext'],
|
| 230 |
+
uid,
|
| 231 |
+
project_id,
|
| 232 |
+
bucket
|
| 233 |
+
)
|
| 234 |
+
|
| 235 |
+
logger.info(f"Report draft generated for project {project_id}")
|
| 236 |
+
|
| 237 |
+
update_data = {
|
| 238 |
+
'status': 'draft',
|
| 239 |
+
'rawMarkdown': draft_data['raw_md'],
|
| 240 |
+
'chartUrls': draft_data['chartUrls']
|
| 241 |
+
}
|
| 242 |
project_ref.update(update_data)
|
| 243 |
+
|
| 244 |
+
logger.info(f"Project {project_id} updated with draft data")
|
| 245 |
+
|
| 246 |
+
return jsonify({
|
| 247 |
+
'success': True,
|
| 248 |
+
'project': {**project_data, **update_data}
|
| 249 |
+
}), 200
|
| 250 |
+
|
| 251 |
except Exception as e:
|
| 252 |
+
logger.error(f"Error generating report for project {project_id}: {str(e)}")
|
| 253 |
+
logger.error(f"Traceback: {traceback.format_exc()}")
|
| 254 |
+
db.reference(f'sozo_projects/{project_id}').update({
|
| 255 |
+
'status': 'failed',
|
| 256 |
+
'error': str(e)
|
| 257 |
+
})
|
| 258 |
return jsonify({'error': str(e)}), 500
|
| 259 |
|
| 260 |
@app.route('/api/sozo/projects', methods=['GET'])
|
| 261 |
def get_sozo_projects():
|
| 262 |
+
logger.info("GET /api/sozo/projects - Fetching user projects")
|
| 263 |
+
|
| 264 |
try:
|
| 265 |
token = request.headers.get('Authorization', '').split(' ')[1]
|
| 266 |
uid = verify_token(token)
|
| 267 |
+
if not uid:
|
| 268 |
+
logger.warning("Unauthorized access attempt to fetch projects")
|
| 269 |
+
return jsonify({'error': 'Unauthorized'}), 401
|
| 270 |
+
|
| 271 |
+
logger.info(f"User {uid} fetching projects")
|
| 272 |
+
|
| 273 |
all_projects = db.reference('sozo_projects').order_by_child('uid').equal_to(uid).get()
|
| 274 |
+
|
| 275 |
+
project_count = len(all_projects) if all_projects else 0
|
| 276 |
+
logger.info(f"Found {project_count} projects for user {uid}")
|
| 277 |
+
|
| 278 |
return jsonify(all_projects or {}), 200
|
| 279 |
+
|
| 280 |
except Exception as e:
|
| 281 |
+
logger.error(f"Error fetching projects: {str(e)}")
|
| 282 |
return jsonify({'error': str(e)}), 500
|
| 283 |
|
| 284 |
@app.route('/api/sozo/projects/<string:project_id>', methods=['GET'])
|
| 285 |
def get_sozo_project(project_id):
|
| 286 |
+
logger.info(f"GET /api/sozo/projects/{project_id} - Fetching project")
|
| 287 |
+
|
| 288 |
try:
|
| 289 |
token = request.headers.get('Authorization', '').split(' ')[1]
|
| 290 |
uid = verify_token(token)
|
| 291 |
+
if not uid:
|
| 292 |
+
logger.warning(f"Unauthorized access attempt to fetch project {project_id}")
|
| 293 |
+
return jsonify({'error': 'Unauthorized'}), 401
|
| 294 |
+
|
| 295 |
+
logger.info(f"User {uid} fetching project {project_id}")
|
| 296 |
+
|
| 297 |
project_data = db.reference(f'sozo_projects/{project_id}').get()
|
| 298 |
+
|
| 299 |
+
if not project_data or project_data.get('uid') != uid:
|
| 300 |
+
logger.warning(f"Project {project_id} not found or unauthorized for user {uid}")
|
| 301 |
+
return jsonify({'error': 'Project not found or unauthorized'}), 404
|
| 302 |
+
|
| 303 |
+
logger.info(f"Project {project_id} fetched successfully for user {uid}")
|
| 304 |
+
|
| 305 |
return jsonify(project_data), 200
|
| 306 |
+
|
| 307 |
+
except Exception as e:
|
| 308 |
+
logger.error(f"Error fetching project {project_id}: {str(e)}")
|
| 309 |
+
return jsonify({'error': str(e)}), 500
|
| 310 |
|
| 311 |
@app.route('/api/sozo/projects/<string:project_id>/markdown', methods=['PUT'])
|
| 312 |
def update_sozo_markdown(project_id):
|