-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.py
More file actions
177 lines (141 loc) · 5.72 KB
/
utils.py
File metadata and controls
177 lines (141 loc) · 5.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
import json
import time
import os
import zipfile
import io
from pathlib import Path
import streamlit as st
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter
from reportlab.lib.units import inch
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.enums import TA_LEFT, TA_CENTER
def save_user_preferences(prefs):
"""Save user preferences to local file"""
prefs_file = Path.home() / ".scriptflow_prefs.json"
try:
with open(prefs_file, 'w') as f:
json.dump(prefs, f)
except Exception:
pass # Fail silently if can't save
def load_user_preferences():
"""Load user preferences from local file"""
prefs_file = Path.home() / ".scriptflow_prefs.json"
try:
if prefs_file.exists():
with open(prefs_file, 'r') as f:
return json.load(f)
except Exception:
pass
# Default preferences
return {
'model_size_index': 1,
'output_dir': str(Path.home() / "Transcriptions"),
'formats': ['txt', 'srt'],
'quality': '720p'
}
def create_cta_section():
"""Create 🧠 VidMind CTA section"""
st.markdown("""
<div style='background-color: #f0f2f6; padding: 20px; border-radius: 10px; text-align: center; margin: 10px 0; color: #31333F;'>
<h4 style='margin: 0; color: #31333F;'>🧠 Supercharge Your Learning with VidMind</h4>
<p style='margin: 5px 0; font-size: 14px;'>Transform any content into a personalized learning experience with AI-powered summaries, flashcards, quizzes, and more.</p>
<a href="https://github.com/yomazini/media-downloader-andtrascript" target="_blank" style="text-decoration: none;">
<button style="background-color: #ff4b4b; color: white; border: none; padding: 10px 20px; border-radius: 5px; cursor: pointer;">
🚀 Explore VidMind for FREE
</button>
</a>
</div>
""", unsafe_allow_html=True)
def format_file_size(bytes_size):
"""Format file size in human readable format"""
for unit in ['B', 'KB', 'MB', 'GB']:
if bytes_size < 1024:
return f"{bytes_size:.1f} {unit}"
bytes_size /= 1024
return f"{bytes_size:.1f} TB"
def create_pdf_from_text(text, title="Transcript"):
"""Create PDF from text with basic formatting"""
buffer = io.BytesIO()
# Create PDF
doc = SimpleDocTemplate(buffer, pagesize=letter,
rightMargin=72, leftMargin=72,
topMargin=72, bottomMargin=18)
# Styles
styles = getSampleStyleSheet()
title_style = ParagraphStyle(
'CustomTitle',
parent=styles['Heading1'],
fontSize=18,
alignment=TA_CENTER,
spaceAfter=30
)
body_style = ParagraphStyle(
'CustomBody',
parent=styles['Normal'],
fontSize=11,
alignment=TA_LEFT,
spaceAfter=12,
leading=16
)
# Build PDF content
story = []
# Title
story.append(Paragraph(title, title_style))
story.append(Spacer(1, 20))
# Body text - split into paragraphs
paragraphs = text.split('\n\n')
for para in paragraphs:
if para.strip():
# Escape special characters for ReportLab
para_clean = para.replace('<', '<').replace(
'>', '>').replace('&', '&')
story.append(Paragraph(para_clean, body_style))
# Build PDF
doc.build(story)
# Get PDF data
pdf_data = buffer.getvalue()
buffer.close()
return pdf_data
def merge_transcripts(results, format_type="Plain Text", separator="=== TITLE ==="):
"""Merge multiple transcripts into one document"""
merged_content = []
for i, result in enumerate(results):
title = result['title']
text = result['text']
if format_type == "Plain Text":
section_header = separator.replace("TITLE", title)
merged_content.append(f"{section_header}\n{text}")
elif format_type == "With Timestamps":
section_header = separator.replace(
"TITLE", f"{title} ({result.get('duration', 0):.1f}s)")
merged_content.append(f"{section_header}\n{text}")
elif format_type == "Sectioned by Title":
merged_content.append(f"# {title}\n\n{text}")
# Add spacing between sections
if i < len(results) - 1:
merged_content.append("\n" + "="*50 + "\n")
return "\n\n".join(merged_content)
def create_batch_zip(results):
"""Create ZIP file containing all transcripts"""
zip_buffer = io.BytesIO()
with zipfile.ZipFile(zip_buffer, 'w', zipfile.ZIP_DEFLATED) as zip_file:
for i, result in enumerate(results):
# Add text file
filename = f"{i+1:02d}_{result['title'][:30]}.txt"
# Clean filename
filename = "".join(c for c in filename if c.isalnum()
or c in (' ', '-', '_', '.')).rstrip()
zip_file.writestr(filename, result['text'])
# Add summary file
summary = f"Batch Export Summary\n"
summary += f"Generated: {time.strftime('%Y-%m-%d %H:%M:%S')}\n"
summary += f"Total Files: {len(results)}\n"
summary += f"Total Duration: {sum(r.get('duration', 0) for r in results):.1f}s\n"
summary += f"Total Words: {sum(len(r['text'].split()) for r in results):,}\n\n"
summary += "Files included:\n"
for i, result in enumerate(results, 1):
summary += f"{i:02d}. {result['title']} ({result.get('language', 'unknown')}, {result.get('duration', 0):.1f}s)\n"
zip_file.writestr("_SUMMARY.txt", summary)
return zip_buffer.getvalue()