Repository navigation
Expand file tree
/
Copy pathapp.py
More file actions
executable file
·220 lines (193 loc) · 7.77 KB
/
Copy pathapp.py
File metadata and controls
executable file
·220 lines (193 loc) · 7.77 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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
# app.py
import os
import json
import re
import time
import configparser
from flask import Flask, render_template, send_from_directory, jsonify, request, abort
from durationCache import getDurationsForFiles
from archiveManager import archiveMarkedFiles
DATA_DIR = os.environ.get('DATA_DIR', 'data')
if not os.path.isabs(DATA_DIR):
DATA_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), DATA_DIR)
os.makedirs(DATA_DIR, exist_ok=True)
print(f"[startup] DATA_DIR resolved to: {DATA_DIR}")
CONFIG_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'config.ini')
ARCHIVE_DIR = os.environ.get('ARCHIVE_DIR', 'archive')
if not os.path.isabs(ARCHIVE_DIR):
ARCHIVE_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), ARCHIVE_DIR)
os.makedirs(ARCHIVE_DIR, exist_ok=True)
print(f"[startup] ARCHIVE_DIR resolved to: {ARCHIVE_DIR}")
app = Flask(__name__)
def load_tags():
cfg = configparser.ConfigParser()
if os.path.exists(CONFIG_FILE):
cfg.read(CONFIG_FILE, encoding='utf-8')
columns = []
for i in range(1, 7):
key = f'list_col{i}'
if cfg.has_option('tags', key):
raw = cfg.get('tags', key).strip()
col = [t for t in raw.split(',') if t]
if col:
columns.append(col)
return columns
def save_tags_columns(columns):
cfg = configparser.ConfigParser()
if os.path.exists(CONFIG_FILE):
cfg.read(CONFIG_FILE, encoding='utf-8')
if not cfg.has_section('tags'):
cfg.add_section('tags')
for i, col in enumerate(columns, 1):
cfg.set('tags', f'list_col{i}', ','.join(col))
with open(CONFIG_FILE, 'w', encoding='utf-8') as f:
cfg.write(f)
def save_tags(tags):
cfg = configparser.ConfigParser()
if os.path.exists(CONFIG_FILE):
cfg.read(CONFIG_FILE, encoding='utf-8')
if not cfg.has_section('tags'):
cfg.add_section('tags')
cfg.set('tags', 'list', ','.join(tags))
with open(CONFIG_FILE, 'w', encoding='utf-8') as f:
cfg.write(f)
def split_tags(prefix):
# split by digit boundaries: 1b2k -> ['1b','2k']
parts = re.findall(r'\d+[a-zA-Z]+|[a-zA-Z]+\d+|\d+|[a-zA-Z]+', prefix)
# regroup: digit(s)+letter(s) or letter(s)+digit(s)
tags = re.findall(r'(?:\d+[a-zA-Z_-]+|[a-zA-Z_-]+\d+)', prefix)
if not tags:
tags = parts
return [t for t in tags if t]
@app.route('/')
def index():
return render_template("index.html")
@app.route('/files')
def list_files():
startTime = time.time()
os.makedirs(DATA_DIR, exist_ok=True)
mp4Names = []
mtimeMap = {}
jsonExistsMap = {}
with os.scandir(DATA_DIR) as entries:
for entry in entries:
if entry.name.lower().endswith('.mp4') and entry.is_file():
mp4Names.append(entry.name)
mtimeMap[entry.name] = entry.stat().st_mtime
jsonPath = os.path.join(DATA_DIR, os.path.splitext(entry.name)[0] + '.json')
jsonExistsMap[entry.name] = os.path.exists(jsonPath)
print(f"[list_files] found {len(mp4Names)} mp4 files, scanning durations...")
durationMap = getDurationsForFiles(DATA_DIR, mp4Names)
files = []
for name in mp4Names:
files.append({
'name': name,
'mtime': mtimeMap[name],
'duration': durationMap.get(name, '--:--'),
'has_json': jsonExistsMap[name]
})
files.sort(key=lambda x: x['mtime'], reverse=True)
elapsed = time.time() - startTime
print(f"[list_files] completed in {elapsed:.3f}s, {len(files)} files returned")
return jsonify(files)
@app.route('/video/<filename>')
def serve_video(filename):
safe = os.path.basename(filename)
fp = os.path.join(DATA_DIR, safe)
if not os.path.exists(fp):
abort(404)
return send_from_directory(DATA_DIR, safe, conditional=True)
@app.route('/save_markers', methods=['POST'])
def save_markers():
data = request.get_json()
filename = os.path.basename(data.get('file', ''))
if not filename:
return jsonify({'ok': False, 'error': 'no file'})
json_path = os.path.join(DATA_DIR, os.path.splitext(filename)[0] + '.json')
try:
with open(json_path, 'w', encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False, indent=2)
return jsonify({'ok': True})
except Exception as e:
return jsonify({'ok': False, 'error': str(e)})
@app.route('/load_markers/<filename>')
def load_markers(filename):
safe = os.path.basename(filename)
json_path = os.path.join(DATA_DIR, os.path.splitext(safe)[0] + '.json')
if os.path.exists(json_path):
with open(json_path, 'r', encoding='utf-8') as f:
data = json.load(f)
return jsonify(data)
return jsonify({'markers': [], 'segments': []})
@app.route('/delete', methods=['POST'])
def delete_files():
data = request.get_json()
errors = []
for name in data.get('files', []):
safe = os.path.basename(name)
for ext in [safe, os.path.splitext(safe)[0] + '.json']:
fp = os.path.join(DATA_DIR, ext)
try:
if os.path.exists(fp):
os.remove(fp)
except Exception as e:
errors.append(str(e))
if errors:
return jsonify({'ok': False, 'error': '; '.join(errors)})
return jsonify({'ok': True})
@app.route('/rename', methods=['POST'])
def rename_file():
data = request.get_json()
old_name = os.path.basename(data.get('old_name', ''))
new_name = os.path.basename(data.get('new_name', ''))
prefix = data.get('prefix', '')
if not old_name or not new_name:
return jsonify({'ok': False, 'error': 'invalid names'})
old_mp4 = os.path.join(DATA_DIR, old_name)
new_mp4 = os.path.join(DATA_DIR, new_name)
old_json = os.path.join(DATA_DIR, os.path.splitext(old_name)[0] + '.json')
new_json = os.path.join(DATA_DIR, os.path.splitext(new_name)[0] + '.json')
if not os.path.exists(old_mp4):
return jsonify({'ok': False, 'error': 'source not found'})
if os.path.exists(new_mp4):
return jsonify({'ok': False, 'error': 'target file already exists'})
try:
os.rename(old_mp4, new_mp4)
if os.path.exists(old_json):
os.rename(old_json, new_json)
# update file field inside json
with open(new_json, 'r', encoding='utf-8') as f:
jdata = json.load(f)
jdata['file'] = new_name
with open(new_json, 'w', encoding='utf-8') as f:
json.dump(jdata, f, ensure_ascii=False, indent=2)
return jsonify({'ok': True})
except Exception as e:
return jsonify({'ok': False, 'error': str(e)})
@app.route('/tags')
def get_tags():
return jsonify({'columns': load_tags()})
@app.route('/archive', methods=['POST'])
def archiveMarked():
startTime = time.time()
os.makedirs(ARCHIVE_DIR, exist_ok=True)
candidateNames = []
with os.scandir(DATA_DIR) as entries:
for entry in entries:
if entry.name.lower().endswith('.mp4') and entry.is_file():
jsonPath = os.path.join(DATA_DIR, os.path.splitext(entry.name)[0] + '.json')
if os.path.exists(jsonPath):
candidateNames.append(entry.name)
print(f"[archiveMarked] found {len(candidateNames)} marked video(s) eligible for archive")
result = archiveMarkedFiles(DATA_DIR, ARCHIVE_DIR, candidateNames)
elapsed = time.time() - startTime
print(f"[archiveMarked] request completed in {elapsed:.3f}s "
f"archivedCount={result['archivedCount']} errorCount={len(result['errors'])}")
return jsonify({
'ok': True,
'archivedCount': result['archivedCount'],
'archivedFiles': result['archivedFiles'],
'errors': result['errors']
})
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0', port=5000)