-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
415 lines (340 loc) · 10.9 KB
/
app.py
File metadata and controls
415 lines (340 loc) · 10.9 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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
import os
import logging
from datetime import datetime
from typing import Any, Dict, Tuple, Union
from flask import (
Flask,
request,
redirect,
url_for,
render_template,
send_from_directory,
flash,
Response,
)
import json
from src.config import AppConfig
from src.services import FigmaService, ProcessingPipeline, FileService, VideoService
from src.repositories import ManifestRepository
from src.models import Video
from src.exceptions import ValidationError, SignBridgeError
from src.utils import timed_execution, RequestValidator
# Configure logging
logging.basicConfig(
level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
)
logger = logging.getLogger(__name__)
# Initialize application configuration
config = AppConfig.from_env()
figma_service = FigmaService(config.figma)
pipeline_service = ProcessingPipeline(config)
file_service = FileService()
manifest_repository = ManifestRepository(
manifest_path=os.path.join(config.content_dir, "manifest.json")
)
video_service = VideoService(
config=config,
pipeline_service=pipeline_service,
file_service=file_service,
manifest_repository=manifest_repository,
)
# Legacy compatibility - maintain these for existing code
BASE_DIR = config.base_dir
UPLOAD_DIR = config.upload_dir
OUT_DIR = config.out_dir
app = Flask(__name__)
app.secret_key = config.secret_key
# Compatibility wrappers for existing code
def get_figma_url() -> str:
"""Get Figma URL from configuration."""
return config.figma.url or ""
def get_figma_tokens() -> dict:
"""Fetch design tokens from Figma API."""
return figma_service.get_design_tokens()
def write_hardcoded_sigml(output_sigml: str) -> None:
"""Overwrite output_sigml with a fixed two-hand SiGML for demo sentence.
This guarantees the avatar will sign with both hands regardless of STT/Gloss.
"""
sigml_text = """<sigml>
<hns_sign gloss="XIN_CHAO">
<hamnosys_manual>
<hamsymmlr/>
<hamparbegin/>
<hamflathand/><hamthumboutmod/><hamextfingerur/><hampalml/>
<hamplus/><hamflathand/><hamthumboutmod/><hamextfingerul/><hampalml/>
<hamparend/>
<hammoveu/><hamsmallmod/>
</hamnosys_manual>
</hns_sign>
<hns_sign gloss="HOM_NAY">
<hamnosys_manual>
<hamsymmlr/>
<hamparbegin/>
<hamflathand/><hamextfingero/><hampalml/>
<hamplus/><hamflathand/><hamextfingerol/><hampalml/>
<hamparend/>
<hammoved/><hamsmallmod/>
</hamnosys_manual>
</hns_sign>
<hns_sign gloss="TOI">
<hamnosys_manual>
<hamfinger2/><hamthumbacrossmod/><hamextfingeril/><hampalmr/><hamtouch/>
</hamnosys_manual>
</hns_sign>
<hns_sign gloss="CHIA_SE">
<hamnosys_manual>
<hamsymmlr/>
<hamparbegin/>
<hamceeall/><hamextfingeror/><hampalml/>
<hamplus/><hamceeall/><hamextfingerol/><hampalml/>
<hamparend/>
<hammoveo/><hamsmallmod/>
</hamnosys_manual>
</hns_sign>
<hns_sign gloss="Y_TUONG">
<hamnosys_manual>
<hamfist/><hamthumbacrossmod/><hamextfingeror/><hampalml/>
<hammoveu/><hamarcu/>
</hamnosys_manual>
</hns_sign>
<hns_sign gloss="GIAO_DUC">
<hamnosys_manual>
<hamsymmlr/>
<hamparbegin/>
<hamceeall/><hamextfingeror/><hampalml/>
<hamplus/><hamceeall/><hamextfingerol/><hampalml/>
<hamparend/>
<hammoveu/>
</hamnosys_manual>
</hns_sign>
<hns_sign gloss="DU_AN">
<hamnosys_manual>
<hamsymmlr/>
<hamparbegin/>
<hamflathand/><hamextfingeror/><hampalml/>
<hamplus/><hamflathand/><hamextfingerol/><hampalml/>
<hamparend/>
<hammoveu/><hamsmallmod/>
</hamnosys_manual>
</hns_sign>
<hns_sign gloss="AI">
<hamnosys_manual>
<hamsymmlr/>
<hamparbegin/>
<hamflathand/><hamextfingeror/><hampalml/>
<hamplus/><hamflathand/><hamextfingerol/><hampalml/>
<hamparend/>
<hammoveo/>
</hamnosys_manual>
</hns_sign>
<hns_sign gloss="GIUP">
<hamnosys_manual>
<hamfinger2/><hamthumbacrossmod/><hamextfingeril/><hampalmr/><hamtouch/>
</hamnosys_manual>
</hns_sign>
<hns_sign gloss="NGUOI_DIEC">
<hamnosys_manual>
<hamfinger23/><hamextfingerui/><hampalml/><hamear/><hamtouch/>
</hamnosys_manual>
</hns_sign>
<hns_sign gloss="TIEP_CAN">
<hamnosys_manual>
<hamsymmlr/>
<hamparbegin/>
<hamflathand/><hamextfingeror/><hampalml/>
<hamplus/><hamflathand/><hamextfingerol/><hampalml/>
<hamparend/>
<hammovei/><hamsmallmod/>
</hamnosys_manual>
</hns_sign>
<hns_sign gloss="NOI_DUNG">
<hamnosys_manual>
<hamsymmlr/>
<hamparbegin/>
<hamfinger2/><hamthumbacrossmod/><hamextfingerl/><hampalml/>
<hamplus/><hamfinger2/><hamthumbacrossmod/><hamextfingeru/><hampalml/>
<hamparend/>
<hamtouch/>
</hamnosys_manual>
</hns_sign>
<hns_sign gloss="HOC_TAP">
<hamnosys_manual>
<hamfist/><hamthumbacrossmod/><hambetween/>
<hamflathand/><hamextfingeru/><hampalml/><hamtouch/>
</hamnosys_manual>
</hns_sign>
<hns_sign gloss="DE_DANG_HON">
<hamnosys_manual>
<hamfinger2/><hamthumbacrossmod/><hamextfingeril/><hampalmr/><hamtouch/>
</hamnosys_manual>
</hns_sign>
</sigml>
"""
with open(output_sigml, "w", encoding="utf-8") as f:
f.write(sigml_text)
@app.route("/")
@timed_execution
def index() -> str:
"""Render main landing page with video list.
Returns:
Rendered HTML template
"""
videos = manifest_repository.get_all_videos()
# Convert to dict for template compatibility
videos_data = [v.to_dict() for v in videos]
return render_template(
"index.html",
videos=videos_data,
figma_url=get_figma_url(),
figma_tokens=get_figma_tokens(),
)
@app.route("/watch/<vid>")
@timed_execution
def watch(vid: str) -> Union[str, Response]:
"""Display video with sign language avatar.
Args:
vid: Video identifier
Returns:
Rendered HTML template or redirect
"""
try:
# Get video data from service
viewing_data = video_service.get_video_for_viewing(vid)
# Support embed mode for hub iframe
is_embed = request.args.get("embed") == "1"
return render_template(
"result.html",
video=None,
video_url=viewing_data.video_url,
sigml=viewing_data.sigml_filename,
playlist=None,
embed=is_embed,
)
except ValidationError:
flash("Video không tồn tại trong manifest")
return redirect(url_for("index"))
except SignBridgeError as e:
flash(f"Lỗi: {e}")
return redirect(url_for("index"))
@app.route("/hub")
def hub() -> str:
"""Render learning hub page.
Returns:
Rendered HTML template
"""
videos = manifest_repository.get_all_videos()
# Convert to dict for template compatibility
videos_data = [v.to_dict() for v in videos]
return render_template("hub.html", videos=videos_data)
@app.route("/assets/<path:filename>")
def serve_assets(filename: str) -> Response:
"""Serve static asset files.
Args:
filename: Asset filename
Returns:
File response
"""
return send_from_directory(os.path.join(BASE_DIR, "assets"), filename)
@app.route("/upload", methods=["POST"])
@timed_execution
def upload() -> Response:
"""Handle video upload and processing.
Returns:
Redirect response to preview page or index on error
"""
video_file = request.files.get("video")
try:
# Process video through service
result = video_service.upload_and_process(video_file)
if not result.success:
flash(f"Xử lý lỗi: {result.error_message}")
return redirect(url_for("index"))
# Redirect to preview
return redirect(
url_for(
"preview",
video=result.video_filename,
sigml=result.sigml_filename,
playlist=result.playlist_filename,
)
)
except ValidationError as e:
logger.warning(f"Validation error in upload: {e}")
flash(str(e))
return redirect(url_for("index"))
except SignBridgeError as e:
logger.error(f"Processing error in upload: {e}", exc_info=True)
flash(f"Lỗi xử lý: {e}")
return redirect(url_for("index"))
@app.route("/preview")
def preview() -> str:
"""Preview endpoint for iframe embed in Interactive Demo.
Returns:
Rendered HTML template
"""
video = request.args.get("video")
sigml = request.args.get("sigml")
playlist_name = request.args.get("playlist")
video_url = url_for("serve_upload", filename=video) if video else None
return render_template(
"result.html",
video=video,
video_url=video_url,
sigml=sigml,
playlist=playlist_name,
embed=True,
)
@app.route("/result")
def result():
video = request.args.get("video")
sigml = request.args.get("sigml")
playlist_name = request.args.get("playlist")
return render_template(
"result.html", video=video, sigml=sigml, playlist=playlist_name
)
@app.route("/add_to_hub", methods=["POST"])
@timed_execution
def add_to_hub() -> Tuple[Dict[str, Any], int]:
"""Add uploaded video to Learning Hub (manifest.json).
Returns:
Tuple of (JSON response, HTTP status code)
"""
video_filename = request.form.get("video")
sigml_filename = request.form.get("sigml")
title = request.form.get("title", "Video mới")
try:
# Validate filenames to prevent path traversal
RequestValidator.validate_filename(video_filename)
RequestValidator.validate_filename(sigml_filename)
# Add video through service
video_id = video_service.add_to_learning_hub(
video_filename=video_filename, sigml_filename=sigml_filename, title=title
)
logger.info(f"Video added to hub: {video_id}")
return {"success": True, "videoId": video_id}, 200
except ValidationError as e:
logger.warning(f"Validation error in add_to_hub: {e}")
return {"success": False, "error": str(e)}, 400
except SignBridgeError as e:
logger.error(f"Error in add_to_hub: {e}", exc_info=True)
return {"success": False, "error": str(e)}, 500
@app.route("/static/uploads/<path:filename>")
def serve_upload(filename: str) -> Response:
"""Serve uploaded files.
Args:
filename: Upload filename
Returns:
File response
"""
return send_from_directory(UPLOAD_DIR, filename)
@app.route("/out/<path:filename>")
def serve_out(filename: str) -> Response:
"""Serve output files (transcripts, SiGML, etc.).
Args:
filename: Output filename
Returns:
File response
"""
return send_from_directory(OUT_DIR, filename)
if __name__ == "__main__":
app.run(host="0.0.0.0", port=5001, debug=True)