rairo commited on
Commit
343240f
·
verified ·
1 Parent(s): 5e3d55f

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +71 -28
main.py CHANGED
@@ -8,7 +8,7 @@ import requests
8
  import json
9
  import pandas as pd
10
  from datetime import datetime
11
- from flask import Flask, request, jsonify
12
  from flask_cors import CORS, cross_origin
13
  from firebase_admin import credentials, db, storage, auth
14
  import firebase_admin
@@ -16,6 +16,8 @@ from PIL import ImageFont, ImageDraw, Image
16
  import logging
17
  import traceback
18
  from video_gen import create_video
 
 
19
 
20
 
21
  # Initialize Flask app and CORS
@@ -610,8 +612,10 @@ def view_videos():
610
  except Exception as e:
611
  return jsonify({'error': str(e)}), 500
612
 
613
- @app.route('/api/download/story_asset/<story_id>', methods=['GET'])
614
- def download_story_asset(story_id):
 
 
615
  try:
616
  # --- Authentication ---
617
  auth_header = request.headers.get('Authorization', '')
@@ -622,7 +626,7 @@ def download_story_asset(story_id):
622
  if not uid:
623
  return jsonify({'error': 'Invalid or expired token'}), 401
624
 
625
- # --- Check if the Story Exists and Belongs to the User ---
626
  stories_ref = db.reference('stories')
627
  story_record = stories_ref.child(story_id).get()
628
 
@@ -631,30 +635,69 @@ def download_story_asset(story_id):
631
  if story_record.get('uid') != uid:
632
  return jsonify({'error': 'Unauthorized'}), 403
633
 
634
- # --- Determine the Asset Type ---
635
- video_url = story_record.get("video_url", None)
636
- audio_url = story_record.get("audio_url", None) # Add if audio files exist
637
- image_url = story_record.get("image_url", None) # Add if images exist
638
-
639
- # Prioritize video > audio > image
640
- file_url = video_url or audio_url or image_url
641
- if not file_url:
642
- return jsonify({'error': 'No asset found for this story'}), 404
643
-
644
- # --- If Stored in Firebase Storage, Generate a Signed URL ---
645
- if "firebasestorage.googleapis.com" in file_url:
646
- bucket = storage.bucket()
647
- blob_path = file_url.split('/o/')[-1].split('?')[0] # Extract path
648
- blob = bucket.blob(blob_path)
649
- signed_url = blob.generate_signed_url(expiration=600) # Valid for 10 minutes
650
- return jsonify({"download_url": signed_url})
651
-
652
- # --- If Stored Locally, Serve the File ---
653
- local_path = os.path.join("uploads", file_url) # Adjust path accordingly
654
- if os.path.exists(local_path):
655
- return send_file(local_path, as_attachment=True)
656
-
657
- return jsonify({'error': 'File not found'}), 404
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
658
 
659
  except Exception as e:
660
  return jsonify({'error': str(e)}), 500
 
8
  import json
9
  import pandas as pd
10
  from datetime import datetime
11
+ from flask import Flask, request, jsonify, send_file
12
  from flask_cors import CORS, cross_origin
13
  from firebase_admin import credentials, db, storage, auth
14
  import firebase_admin
 
16
  import logging
17
  import traceback
18
  from video_gen import create_video
19
+ import zipfile
20
+ from fpdf import FPDF
21
 
22
 
23
  # Initialize Flask app and CORS
 
612
  except Exception as e:
613
  return jsonify({'error': str(e)}), 500
614
 
615
+
616
+
617
+ @app.route('/api/download/story_archive/<story_id>', methods=['GET'])
618
+ def download_story_archive(story_id):
619
  try:
620
  # --- Authentication ---
621
  auth_header = request.headers.get('Authorization', '')
 
626
  if not uid:
627
  return jsonify({'error': 'Invalid or expired token'}), 401
628
 
629
+ # --- Fetch the Story ---
630
  stories_ref = db.reference('stories')
631
  story_record = stories_ref.child(story_id).get()
632
 
 
635
  if story_record.get('uid') != uid:
636
  return jsonify({'error': 'Unauthorized'}), 403
637
 
638
+ # --- Create ZIP File ---
639
+ zip_buffer = io.BytesIO()
640
+ with zipfile.ZipFile(zip_buffer, "w", zipfile.ZIP_DEFLATED) as zipf:
641
+
642
+ # --- Generate a PDF with Story Content ---
643
+ pdf = FPDF()
644
+ pdf.set_auto_page_break(auto=True, margin=15)
645
+ pdf.add_page()
646
+ pdf.set_font("Arial", size=12)
647
+ pdf.multi_cell(0, 10, f"Story ID: {story_id}\n\n")
648
+ pdf.multi_cell(0, 10, f"Title: {story_record.get('title', 'Untitled')}\n\n")
649
+ pdf.multi_cell(0, 10, f"Full Story:\n\n{story_record.get('full_story', '')}\n\n")
650
+
651
+ # Add sections if available
652
+ sections = story_record.get("sections", [])
653
+ for idx, section in enumerate(sections):
654
+ pdf.add_page()
655
+ pdf.set_font("Arial", style='B', size=14)
656
+ pdf.multi_cell(0, 10, f"Section {idx + 1}\n")
657
+ pdf.set_font("Arial", size=12)
658
+ pdf.multi_cell(0, 10, section)
659
+
660
+ # Save PDF to buffer and add to ZIP
661
+ pdf_buffer = io.BytesIO()
662
+ pdf.output(pdf_buffer)
663
+ pdf_buffer.seek(0)
664
+ zipf.writestr(f"{story_id}.pdf", pdf_buffer.read())
665
+
666
+ # --- Generate a TXT file with Story Content ---
667
+ txt_content = f"Story ID: {story_id}\n\n"
668
+ txt_content += f"Title: {story_record.get('title', 'Untitled')}\n\n"
669
+ txt_content += f"Full Story:\n\n{story_record.get('full_story', '')}\n\n"
670
+
671
+ # Add sections if available
672
+ for idx, section in enumerate(sections):
673
+ txt_content += f"\n\nSection {idx + 1}:\n{section}"
674
+
675
+ # Add TXT file to ZIP
676
+ zipf.writestr(f"{story_id}.txt", txt_content)
677
+
678
+ # --- Download Images ---
679
+ image_urls = story_record.get("image_urls", []) # Expecting a list of image URLs
680
+ for idx, img_url in enumerate(image_urls):
681
+ if "firebasestorage.googleapis.com" in img_url:
682
+ bucket = storage.bucket()
683
+ blob_path = img_url.split('/o/')[-1].split('?')[0]
684
+ blob = bucket.blob(blob_path)
685
+ image_data = blob.download_as_bytes()
686
+ zipf.writestr(f"image_{idx + 1}.jpg", image_data)
687
+
688
+ # --- Download Audio Files ---
689
+ audio_urls = story_record.get("audio_urls", []) # Expecting a list of audio URLs
690
+ for idx, audio_url in enumerate(audio_urls):
691
+ if "firebasestorage.googleapis.com" in audio_url:
692
+ bucket = storage.bucket()
693
+ blob_path = audio_url.split('/o/')[-1].split('?')[0]
694
+ blob = bucket.blob(blob_path)
695
+ audio_data = blob.download_as_bytes()
696
+ zipf.writestr(f"audio_{idx + 1}.mp3", audio_data)
697
+
698
+ # --- Serve ZIP File ---
699
+ zip_buffer.seek(0)
700
+ return send_file(zip_buffer, mimetype='application/zip', as_attachment=True, download_name=f"story_{story_id}.zip")
701
 
702
  except Exception as e:
703
  return jsonify({'error': str(e)}), 500