Spaces:
Sleeping

Kompres commited on
Commit
4a979a6
·
verified ·
1 Parent(s): e60ea96

Upload 7 files

Browse files
Files changed (6) hide show
  1. .streamlit/config.toml +21 -0
  2. Dockerfile +35 -0
  3. LICENSE +32 -0
  4. README.md +82 -5
  5. app.py +1365 -0
  6. requirements.txt +2 -0
.streamlit/config.toml ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [server]
2
+ maxUploadSize = 500
3
+ maxMessageSize = 500
4
+ enableCORS = false
5
+ enableXsrfProtection = true
6
+ enableStaticServing = true
7
+ enableWebsocketCompression = true
8
+ fileWatcherType = "none"
9
+
10
+ [browser]
11
+ gatherUsageStats = false
12
+
13
+ [runner]
14
+ fastReruns = true
15
+
16
+ [theme]
17
+ base = "dark"
18
+ primaryColor = "#7c3aed"
19
+ backgroundColor = "#0e1117"
20
+ secondaryBackgroundColor = "#1a1f2e"
21
+ textColor = "#e2e8f0"
Dockerfile ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.11-slim
2
+
3
+ RUN apt-get update && apt-get install -y --no-install-recommends \
4
+ ffmpeg \
5
+ libsm6 \
6
+ libxext6 \
7
+ && apt-get clean \
8
+ && rm -rf /var/lib/apt/lists/*
9
+
10
+ RUN useradd -m -u 1000 appuser
11
+ USER appuser
12
+
13
+ ENV HOME=/home/appuser \
14
+ PATH=/home/appuser/.local/bin:$PATH \
15
+ PYTHONDONTWRITEBYTECODE=1 \
16
+ PYTHONUNBUFFERED=1
17
+
18
+ WORKDIR $HOME/app
19
+
20
+ COPY --chown=appuser ./requirements.txt requirements.txt
21
+ RUN pip install --no-cache-dir --upgrade pip \
22
+ && pip install --no-cache-dir -r requirements.txt
23
+
24
+ COPY --chown=appuser . .
25
+
26
+ EXPOSE 7860
27
+
28
+ HEALTHCHECK --interval=30s --timeout=10s --retries=3 \
29
+ CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:7860/_stcore/health')" || exit 1
30
+
31
+ CMD ["streamlit", "run", "app.py", \
32
+ "--server.port=7860", \
33
+ "--server.address=0.0.0.0", \
34
+ "--server.headless=true", \
35
+ "--browser.gatherUsageStats=false"]
LICENSE ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ GNU GENERAL PUBLIC LICENSE
2
+ Version 3, 29 June 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <[https://fsf.org/](https://fsf.org/)>
5
+ Everyone is permitted to copy and distribute verbatim copies
6
+ of this license document, but changing it is not allowed.
7
+
8
+ Preamble
9
+
10
+ The GNU General Public License is a free, copyleft license for
11
+ software and other kinds of works.
12
+
13
+ The licenses for most software and other practical works are designed
14
+ to take away your freedom to share and change the works. By contrast,
15
+ the GNU General Public License is intended to guarantee your freedom to
16
+ share and change all versions of a program--to make sure it remains free
17
+ software for all its users. We, the Free Software Foundation, use the
18
+ GNU General Public License for most of our software; it applies also to
19
+ any other work released this way by its authors. You can apply it to
20
+ your programs, too.
21
+
22
+ When we speak of free software, we are referring to freedom, not
23
+ price. Our General Public Licenses are designed to make sure that you
24
+ have the freedom to distribute copies of free software (and charge for
25
+ them if you wish), that you receive source code or can get it if you
26
+ want it, that you can change the software or use pieces of it in new
27
+ free programs, and that you know you can do these things.
28
+
29
+ To protect your rights, we need to prevent others from denying you
30
+ these rights or asking you to surrender the rights. Therefore, you have
31
+ certain responsibilities if you distribute copies of the software, or if
32
+ you modify it: responsibilities to respect the freedom of others.
README.md CHANGED
@@ -1,10 +1,87 @@
1
  ---
2
- title: Web
3
- emoji: 🐨
4
- colorFrom: yellow
5
- colorTo: red
6
  sdk: docker
7
  pinned: false
 
8
  ---
9
 
10
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: Kompres
3
+ emoji: 🎬
4
+ colorFrom: purple
5
+ colorTo: indigo
6
  sdk: docker
7
  pinned: false
8
+ license: gpl-3.0
9
  ---
10
 
11
+ # Kompres
12
+
13
+ Kompresi video profesional untuk WhatsApp, Instagram, Telegram, dan platform media sosial lainnya.
14
+
15
+ ## ✨ Fitur
16
+
17
+ ### Kompresi & Encoding
18
+ - **Platform Presets** — Konfigurasi otomatis untuk WhatsApp, Instagram Feed, Instagram Story, Telegram, dan Email
19
+ - **Smart Compression** — Tentukan target ukuran file (MB), bitrate dihitung otomatis
20
+ - **H.264 High Profile** — Encoding efisien dengan kualitas visual tinggi
21
+ - **Kalibrasi Warna BT.709** — Warna akurat, tidak pucat saat dikirim lewat chat
22
+ - **Estimasi Ukuran** — Lihat perkiraan ukuran output sebelum kompresi dimulai
23
+
24
+ ### Format Output
25
+ - **MP4 (H.264)** — Format universal, kompatibel semua platform
26
+ - **WebM (VP9)** — Format terbuka, efisien untuk web
27
+ - **GIF Animasi** — Konversi video ke GIF berkualitas tinggi dengan palettegen
28
+
29
+ ### Editing
30
+ - **Video Trimming** — Potong video ke durasi yang diinginkan
31
+ - **Frame Rate Control** — Ubah FPS output (24, 30, 60)
32
+ - **Aspect Ratio Crop** — Crop otomatis ke 16:9, 9:16, 1:1, atau 4:3
33
+
34
+ ### Perbandingan Hasil
35
+ - **Before/After Slider** — Geser untuk membandingkan frame asli dan hasil kompresi
36
+ - **Detail Teknis** — Tabel perbandingan resolusi, codec, FPS, dan bitrate
37
+ - **Progress Realtime** — Pantau encoding dengan kecepatan (x) dan estimasi waktu sisa
38
+
39
+ ### User Experience
40
+ - **Session Recovery** — Refresh browser? File tidak hilang, klik "Lanjutkan" untuk melanjutkan
41
+ - **Dark/Light Mode** — Toggle tema di sidebar sesuai preferensi
42
+ - **Riwayat Kompresi** — Lihat 10 kompresi terakhir di sidebar
43
+ - **Drag & Drop** — Area upload yang besar dan responsif
44
+ - **Tanpa Watermark** — Hasil kompresi bersih tanpa tanda air
45
+ - **Format Input Lengkap** — Mendukung MP4, MOV, MKV, AVI, dan WebM
46
+
47
+ ## 🚀 Cara Penggunaan
48
+
49
+ 1. Upload video (drag & drop atau klik browse)
50
+ 2. Pilih platform target atau atur parameter manual
51
+ 3. Pilih format output (MP4/WebM/GIF)
52
+ 4. *Opsional:* Aktifkan **Smart Compression** dan masukkan target ukuran
53
+ 5. Klik **Mulai Kompresi**
54
+ 6. Lihat perbandingan before/after
55
+ 7. Download hasil
56
+
57
+ ## 🛠️ Menjalankan Secara Lokal
58
+
59
+ ```bash
60
+ pip install -r requirements.txt
61
+ streamlit run app.py
62
+ ```
63
+
64
+ ## 🐳 Menjalankan dengan Docker
65
+
66
+ ```bash
67
+ docker build -t kompres .
68
+ docker run -p 7860:7860 kompres
69
+ ```
70
+
71
+ ## 📦 Teknologi
72
+
73
+ | Komponen | Teknologi |
74
+ |----------|-----------|
75
+ | Frontend | Streamlit |
76
+ | Video Engine | FFmpeg (H.264, VP9, GIF palettegen) |
77
+ | Runtime | Python 3.11 |
78
+ | Deploy | Docker / Hugging Face Spaces |
79
+
80
+ ## 📄 Lisensi
81
+
82
+ Proyek ini dilisensikan di bawah **GNU General Public License v3.0**.
83
+ Lihat file [LICENSE](LICENSE) untuk detail lengkap.
84
+
85
+ ## 👤 Kredit
86
+
87
+ Dibuat dan dikembangkan oleh **Garden**.
app.py ADDED
@@ -0,0 +1,1365 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Kompres - Kompresi dan optimasi video untuk platform sosial media.
3
+
4
+ Mendukung WhatsApp, Instagram, Telegram dengan encoding H.264 High Profile
5
+ dan kalibrasi warna BT.709.
6
+
7
+ Copyright (C) 2026 Garden
8
+ Licensed under GNU General Public License v3.0
9
+ """
10
+
11
+ import streamlit as st
12
+ import ffmpeg
13
+ import os
14
+ import tempfile
15
+ import pathlib
16
+ import math
17
+ import subprocess
18
+ import re
19
+ import atexit
20
+ import base64
21
+ import json
22
+ import time
23
+ import uuid
24
+
25
+ APP_VERSION = "7.0.0"
26
+ APP_TITLE = "Kompres"
27
+ APP_TAGLINE = "Kompresi Video Profesional"
28
+
29
+ SUPPORTED_FORMATS = ["mp4", "mov", "mkv", "avi", "webm"]
30
+ OUTPUT_FORMATS = {"MP4 (H.264)": "mp4", "WebM (VP9)": "webm", "GIF Animasi": "gif"}
31
+ FFMPEG_THREADS = 0
32
+ SESSION_DIR = "/tmp/kompres_sessions"
33
+ SESSION_MAX_AGE = 3600
34
+
35
+ _temp_files = []
36
+
37
+ RESOLUTION_MAP = {
38
+ "1080p": 1080,
39
+ "720p": 720,
40
+ "480p": 480,
41
+ "360p": 360,
42
+ }
43
+
44
+ SPEED_OPTIONS = ["ultrafast", "fast", "medium", "slow", "veryslow"]
45
+
46
+ FRAMERATE_OPTIONS = {
47
+ "Bawaan": None,
48
+ "60 FPS": 60,
49
+ "30 FPS": 30,
50
+ "24 FPS": 24,
51
+ }
52
+
53
+ ASPECT_RATIOS = {
54
+ "Bawaan": None,
55
+ "16:9 Landscape": "16:9",
56
+ "9:16 Portrait": "9:16",
57
+ "1:1 Square": "1:1",
58
+ "4:3 Klasik": "4:3",
59
+ }
60
+
61
+ PLATFORM_PRESETS = {
62
+ "Custom": {
63
+ "crf": 28,
64
+ "preset": "medium",
65
+ "resolution": "720p",
66
+ "max_bitrate": None,
67
+ "fps": None,
68
+ "aspect": None,
69
+ "description": "Atur semua parameter secara manual.",
70
+ },
71
+ "WhatsApp": {
72
+ "crf": 28,
73
+ "preset": "medium",
74
+ "resolution": "720p",
75
+ "max_bitrate": "2M",
76
+ "fps": 30,
77
+ "aspect": None,
78
+ "description": "Optimal untuk pengiriman via WhatsApp.",
79
+ },
80
+ "Instagram Feed": {
81
+ "crf": 23,
82
+ "preset": "slow",
83
+ "resolution": "1080p",
84
+ "max_bitrate": "3.5M",
85
+ "fps": 30,
86
+ "aspect": "1:1",
87
+ "description": "Square format untuk feed Instagram.",
88
+ },
89
+ "Instagram Story": {
90
+ "crf": 23,
91
+ "preset": "slow",
92
+ "resolution": "1080p",
93
+ "max_bitrate": "4M",
94
+ "fps": 30,
95
+ "aspect": "9:16",
96
+ "description": "Format vertikal untuk Story dan Reels.",
97
+ },
98
+ "Telegram": {
99
+ "crf": 26,
100
+ "preset": "medium",
101
+ "resolution": "720p",
102
+ "max_bitrate": None,
103
+ "fps": None,
104
+ "aspect": None,
105
+ "description": "Kualitas dan ukuran seimbang untuk Telegram.",
106
+ },
107
+ "Email": {
108
+ "crf": 32,
109
+ "preset": "slow",
110
+ "resolution": "480p",
111
+ "max_bitrate": "1M",
112
+ "fps": 24,
113
+ "aspect": None,
114
+ "description": "Ukuran file minimal untuk lampiran email.",
115
+ },
116
+ }
117
+
118
+ COLOR_PROFILE = {
119
+ "pix_fmt": "yuv420p",
120
+ "colorspace": "bt709",
121
+ "color_primaries": "bt709",
122
+ "color_trc": "bt709",
123
+ "color_range": "tv",
124
+ }
125
+
126
+ PAGE_STYLES = """
127
+ <style>
128
+ @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap');
129
+
130
+ html, body, [class*="st-"] {
131
+ font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
132
+ }
133
+
134
+ .main .block-container {
135
+ max-width: 780px;
136
+ padding-top: 2rem;
137
+ padding-bottom: 4rem;
138
+ }
139
+
140
+ header[data-testid="stHeader"] {
141
+ background: rgba(14, 17, 23, 0.94);
142
+ backdrop-filter: blur(16px);
143
+ -webkit-backdrop-filter: blur(16px);
144
+ }
145
+
146
+ .app-hero {
147
+ text-align: center;
148
+ padding: 2rem 0 1.5rem;
149
+ }
150
+
151
+ .app-hero .brand {
152
+ font-size: 2.6rem;
153
+ font-weight: 800;
154
+ letter-spacing: -0.03em;
155
+ background: linear-gradient(135deg, #a78bfa 0%, #7c3aed 40%, #ec4899 100%);
156
+ -webkit-background-clip: text;
157
+ -webkit-text-fill-color: transparent;
158
+ background-clip: text;
159
+ margin-bottom: 0.2rem;
160
+ }
161
+
162
+ .app-hero .tagline {
163
+ color: #94a3b8;
164
+ font-size: 0.95rem;
165
+ font-weight: 400;
166
+ margin: 0;
167
+ }
168
+
169
+ .app-hero .version-badge {
170
+ display: inline-block;
171
+ background: rgba(124, 58, 237, 0.15);
172
+ color: #a78bfa;
173
+ font-size: 0.7rem;
174
+ font-weight: 600;
175
+ padding: 0.2rem 0.6rem;
176
+ border-radius: 20px;
177
+ margin-top: 0.5rem;
178
+ letter-spacing: 0.04em;
179
+ }
180
+
181
+ .preset-info {
182
+ background: rgba(99, 102, 241, 0.08);
183
+ border-left: 3px solid #7c3aed;
184
+ padding: 0.7rem 1rem;
185
+ border-radius: 0 8px 8px 0;
186
+ margin: 0.5rem 0;
187
+ font-size: 0.85rem;
188
+ color: #cbd5e1;
189
+ }
190
+
191
+ .result-panel {
192
+ background: linear-gradient(145deg, rgba(16, 185, 129, 0.1), rgba(5, 150, 105, 0.03));
193
+ border: 1px solid rgba(16, 185, 129, 0.2);
194
+ border-radius: 14px;
195
+ padding: 1.4rem;
196
+ margin: 1rem 0;
197
+ }
198
+
199
+ .result-panel h3 {
200
+ color: #34d399;
201
+ font-weight: 700;
202
+ margin-bottom: 0.3rem;
203
+ font-size: 1.15rem;
204
+ }
205
+
206
+ .result-panel .result-stats {
207
+ color: #cbd5e1;
208
+ font-size: 0.92rem;
209
+ }
210
+
211
+ .reduction-badge {
212
+ display: inline-block;
213
+ background: rgba(16, 185, 129, 0.2);
214
+ color: #34d399;
215
+ font-weight: 700;
216
+ padding: 0.2rem 0.7rem;
217
+ border-radius: 20px;
218
+ font-size: 0.85rem;
219
+ }
220
+
221
+ .section-title {
222
+ font-size: 0.85rem;
223
+ font-weight: 700;
224
+ color: #94a3b8;
225
+ text-transform: uppercase;
226
+ letter-spacing: 0.06em;
227
+ margin: 1.2rem 0 0.6rem;
228
+ padding-bottom: 0.4rem;
229
+ border-bottom: 1px solid rgba(148, 163, 184, 0.1);
230
+ }
231
+
232
+ .footer-section {
233
+ text-align: center;
234
+ padding: 2rem 0 1rem;
235
+ color: #64748b;
236
+ font-size: 0.82rem;
237
+ border-top: 1px solid rgba(148, 163, 184, 0.08);
238
+ margin-top: 3rem;
239
+ }
240
+
241
+ .footer-section a {
242
+ color: #a78bfa;
243
+ text-decoration: none;
244
+ font-weight: 500;
245
+ }
246
+
247
+ .footer-section a:hover {
248
+ text-decoration: underline;
249
+ }
250
+
251
+ div[data-testid="stFileUploader"] {
252
+ border: 2px dashed rgba(124, 58, 237, 0.35);
253
+ border-radius: 16px;
254
+ padding: 1.5rem 1rem;
255
+ transition: all 0.3s ease;
256
+ background: rgba(124, 58, 237, 0.04);
257
+ min-height: 120px;
258
+ }
259
+
260
+ div[data-testid="stFileUploader"]:hover {
261
+ border-color: rgba(124, 58, 237, 0.6);
262
+ background: rgba(124, 58, 237, 0.08);
263
+ box-shadow: 0 0 24px rgba(124, 58, 237, 0.12);
264
+ }
265
+
266
+ div[data-testid="stFileUploader"] section > button {
267
+ background: linear-gradient(135deg, #7c3aed, #a78bfa) !important;
268
+ color: white !important;
269
+ border: none !important;
270
+ border-radius: 8px !important;
271
+ font-weight: 600 !important;
272
+ }
273
+
274
+ .stButton > button {
275
+ width: 100%;
276
+ background: linear-gradient(135deg, #7c3aed, #6d28d9);
277
+ color: white;
278
+ border: none;
279
+ border-radius: 10px;
280
+ padding: 0.8rem 1.5rem;
281
+ font-weight: 600;
282
+ font-size: 1rem;
283
+ letter-spacing: 0.01em;
284
+ transition: all 0.25s ease;
285
+ box-shadow: 0 4px 16px rgba(109, 40, 217, 0.3);
286
+ }
287
+
288
+ .stButton > button:hover {
289
+ transform: translateY(-2px);
290
+ box-shadow: 0 8px 24px rgba(109, 40, 217, 0.45);
291
+ }
292
+
293
+ .stButton > button:active {
294
+ transform: translateY(0);
295
+ }
296
+
297
+ div[data-testid="stDownloadButton"] > button {
298
+ width: 100%;
299
+ background: linear-gradient(135deg, #059669, #047857);
300
+ color: white;
301
+ border: none;
302
+ border-radius: 10px;
303
+ padding: 0.75rem;
304
+ font-weight: 600;
305
+ transition: all 0.25s ease;
306
+ box-shadow: 0 4px 14px rgba(5, 150, 105, 0.25);
307
+ }
308
+
309
+ div[data-testid="stDownloadButton"] > button:hover {
310
+ transform: translateY(-2px);
311
+ box-shadow: 0 8px 20px rgba(5, 150, 105, 0.4);
312
+ }
313
+
314
+ </style>
315
+ """
316
+
317
+
318
+ def format_filesize(size_bytes):
319
+ if size_bytes == 0:
320
+ return "0 B"
321
+ units = ["B", "KB", "MB", "GB"]
322
+ exp = min(int(math.log(size_bytes, 1024)), len(units) - 1)
323
+ value = size_bytes / (1024 ** exp)
324
+ return f"{value:.2f} {units[exp]}"
325
+
326
+
327
+ def format_duration(seconds):
328
+ total = int(seconds)
329
+ hours, remainder = divmod(total, 3600)
330
+ minutes, secs = divmod(remainder, 60)
331
+ if hours > 0:
332
+ return f"{hours:02d}:{minutes:02d}:{secs:02d}"
333
+ return f"{minutes:02d}:{secs:02d}"
334
+
335
+
336
+ def calculate_reduction(original, compressed):
337
+ if original == 0:
338
+ return 0.0
339
+ return ((original - compressed) / original) * 100
340
+
341
+
342
+ def get_clean_filename(uploaded_name, out_format="mp4"):
343
+ p = pathlib.Path(uploaded_name)
344
+ return "kompres_" + p.stem + "." + out_format
345
+
346
+
347
+ def estimate_output_size(duration, crf, resolution, has_audio, out_format="mp4"):
348
+ """Estimasi kasar ukuran output berdasarkan parameter."""
349
+ res_bitrate = {"1080p": 4000, "720p": 2000, "480p": 1000, "360p": 600}
350
+ base_kbps = res_bitrate.get(resolution, 2500)
351
+ crf_factor = 2.0 ** ((28 - crf) / 6.0)
352
+ video_kbps = base_kbps * crf_factor
353
+ if out_format == "gif":
354
+ video_kbps = video_kbps * 3
355
+ elif out_format == "webm":
356
+ video_kbps = video_kbps * 0.85
357
+ audio_kbps = 96 if has_audio and out_format != "gif" else 0
358
+ total_kbps = video_kbps + audio_kbps
359
+ size_bytes = (total_kbps * duration * 1000) / 8
360
+ return max(int(size_bytes), 0)
361
+
362
+
363
+ def calculate_target_bitrate(target_mb, duration, has_audio):
364
+ """Hitung bitrate video untuk mencapai target ukuran file."""
365
+ if duration <= 0:
366
+ return None
367
+ target_bits = target_mb * 8 * 1024 * 1024
368
+ audio_bits = 96 * 1000 * duration if has_audio else 0
369
+ video_bits = target_bits - audio_bits
370
+ if video_bits <= 0:
371
+ return None
372
+ video_kbps = int(video_bits / duration / 1000)
373
+ return str(video_kbps) + "k"
374
+
375
+
376
+ def extract_frame(video_path, timestamp=1.0):
377
+ """Ambil satu frame dari video dan kembalikan sebagai base64 JPEG."""
378
+ try:
379
+ out_path = video_path + "_thumb.jpg"
380
+ _temp_files.append(out_path)
381
+ (
382
+ ffmpeg
383
+ .input(video_path, ss=timestamp)
384
+ .output(out_path, vframes=1, format="image2", **{"q:v": 2})
385
+ .overwrite_output()
386
+ .run(capture_stdout=True, capture_stderr=True)
387
+ )
388
+ if os.path.exists(out_path):
389
+ with open(out_path, "rb") as f:
390
+ return base64.b64encode(f.read()).decode("utf-8")
391
+ except Exception:
392
+ pass
393
+ return None
394
+
395
+
396
+ def probe_video(file_path):
397
+ try:
398
+ info = ffmpeg.probe(file_path, analyzeduration="5000000", probesize="5000000")
399
+ video_stream = next(
400
+ (s for s in info.get("streams", []) if s.get("codec_type") == "video"),
401
+ None,
402
+ )
403
+ audio_stream = next(
404
+ (s for s in info.get("streams", []) if s.get("codec_type") == "audio"),
405
+ None,
406
+ )
407
+
408
+ duration = float(info.get("format", {}).get("duration", 0))
409
+ bitrate = int(info.get("format", {}).get("bit_rate", 0))
410
+
411
+ result = {
412
+ "duration": duration,
413
+ "duration_text": format_duration(duration),
414
+ "bitrate": bitrate,
415
+ "bitrate_text": (str(bitrate // 1000) + " kbps") if bitrate else "N/A",
416
+ "has_audio": audio_stream is not None,
417
+ }
418
+
419
+ if video_stream:
420
+ fps_parts = video_stream.get("r_frame_rate", "0/1").split("/")
421
+ if len(fps_parts) == 2 and int(fps_parts[1]) > 0:
422
+ fps = round(int(fps_parts[0]) / int(fps_parts[1]), 1)
423
+ else:
424
+ fps = 0
425
+ result["width"] = int(video_stream.get("width", 0))
426
+ result["height"] = int(video_stream.get("height", 0))
427
+ result["codec"] = video_stream.get("codec_name", "unknown").upper()
428
+ result["fps"] = fps
429
+ result["resolution_text"] = str(video_stream.get("width", 0)) + "x" + str(video_stream.get("height", 0))
430
+
431
+ if audio_stream:
432
+ result["audio_codec"] = audio_stream.get("codec_name", "unknown").upper()
433
+ ab = audio_stream.get("bit_rate", 0)
434
+ result["audio_bitrate"] = int(ab) // 1000 if ab else 0
435
+
436
+ return result
437
+ except Exception:
438
+ return None
439
+
440
+
441
+ def compress_video(
442
+ input_path,
443
+ output_path,
444
+ crf,
445
+ preset,
446
+ mute_audio,
447
+ resolution,
448
+ trim_start=None,
449
+ trim_end=None,
450
+ target_fps=None,
451
+ aspect_ratio=None,
452
+ max_bitrate=None,
453
+ progress_callback=None,
454
+ duration_seconds=0,
455
+ out_format="mp4",
456
+ ):
457
+ try:
458
+ input_args = {}
459
+ if trim_start is not None and trim_start > 0:
460
+ input_args["ss"] = trim_start
461
+ if trim_end is not None and trim_end > 0:
462
+ input_args["to"] = trim_end
463
+
464
+ source = ffmpeg.input(input_path, **input_args)
465
+ video = source.video
466
+ audio = source.audio
467
+
468
+ if resolution in RESOLUTION_MAP:
469
+ target_h = RESOLUTION_MAP[resolution]
470
+ video = ffmpeg.filter(video, "scale", "trunc(oh*a/2)*2", target_h)
471
+ else:
472
+ video = ffmpeg.filter(video, "scale", "trunc(iw/2)*2", "trunc(ih/2)*2")
473
+
474
+ if aspect_ratio:
475
+ ratio_map = {"16:9": "16/9", "9:16": "9/16", "1:1": "1", "4:3": "4/3"}
476
+ if aspect_ratio in ratio_map:
477
+ r = ratio_map[aspect_ratio]
478
+ video = ffmpeg.filter(
479
+ video, "crop",
480
+ "if(gt(iw/ih," + r + "),ih*" + r + ",iw)",
481
+ "if(gt(iw/ih," + r + "),ih,iw/(" + r + "))",
482
+ )
483
+ video = ffmpeg.filter(video, "scale", "trunc(iw/2)*2", "trunc(ih/2)*2")
484
+
485
+ if target_fps:
486
+ video = ffmpeg.filter(video, "fps", fps=target_fps)
487
+
488
+ # --- GIF output ---
489
+ if out_format == "gif":
490
+ if not target_fps:
491
+ video = ffmpeg.filter(video, "fps", fps=15)
492
+ palette_path = output_path + "_palette.png"
493
+ _temp_files.append(palette_path)
494
+ palette_gen = ffmpeg.output(video, palette_path, vf="palettegen=stats_mode=diff", an=None)
495
+ ffmpeg.run(palette_gen, overwrite_output=True, capture_stdout=True, capture_stderr=True)
496
+ source2 = ffmpeg.input(input_path, **input_args)
497
+ vid2 = source2.video
498
+ if resolution in RESOLUTION_MAP:
499
+ vid2 = ffmpeg.filter(vid2, "scale", "trunc(oh*a/2)*2", RESOLUTION_MAP[resolution])
500
+ if target_fps:
501
+ vid2 = ffmpeg.filter(vid2, "fps", fps=target_fps)
502
+ else:
503
+ vid2 = ffmpeg.filter(vid2, "fps", fps=15)
504
+ palette_in = ffmpeg.input(palette_path)
505
+ gif_out = ffmpeg.filter([vid2, palette_in], "paletteuse", dither="bayer", bayer_scale=3)
506
+ output = ffmpeg.output(gif_out, output_path, an=None, loop=0)
507
+ ffmpeg.run(output, overwrite_output=True, capture_stdout=True, capture_stderr=True)
508
+ return True, None
509
+
510
+ # --- WebM VP9 output ---
511
+ if out_format == "webm":
512
+ encoding_params = {
513
+ "vcodec": "libvpx-vp9",
514
+ "crf": crf,
515
+ "b:v": "0",
516
+ "threads": FFMPEG_THREADS,
517
+ "row-mt": 1,
518
+ }
519
+ if max_bitrate:
520
+ encoding_params["b:v"] = max_bitrate
521
+ if mute_audio:
522
+ output = ffmpeg.output(video, output_path, an=None, **encoding_params)
523
+ else:
524
+ audio_params = {"c:a": "libopus", "b:a": "96k", "ac": 2}
525
+ output = ffmpeg.output(audio, video, output_path, **audio_params, **encoding_params)
526
+ else:
527
+ # --- MP4 H.264 output ---
528
+ encoding_params = {
529
+ "vcodec": "libx264",
530
+ "crf": crf,
531
+ "preset": preset,
532
+ "movflags": "+faststart",
533
+ "profile:v": "high",
534
+ "tune": "film",
535
+ "threads": FFMPEG_THREADS,
536
+ }
537
+ encoding_params.update(COLOR_PROFILE)
538
+ if max_bitrate:
539
+ encoding_params["maxrate"] = max_bitrate
540
+ encoding_params["bufsize"] = max_bitrate
541
+ if mute_audio:
542
+ output = ffmpeg.output(video, output_path, an=None, **encoding_params)
543
+ else:
544
+ audio_params = {"c:a": "aac", "b:a": "96k", "ac": 2}
545
+ output = ffmpeg.output(audio, video, output_path, **audio_params, **encoding_params)
546
+
547
+ cmd = ffmpeg.compile(output, overwrite_output=True)
548
+
549
+ if progress_callback and duration_seconds > 0:
550
+ process = subprocess.Popen(
551
+ cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True
552
+ )
553
+ pattern = re.compile(r"time=(\d+):(\d+):(\d+\.\d+)")
554
+ speed_pattern = re.compile(r"speed=\s*([0-9.]+)x")
555
+ stderr_lines = []
556
+ start_time = time.time()
557
+
558
+ if process.stderr is not None:
559
+ for line in iter(process.stderr.readline, ""):
560
+ stderr_lines.append(line)
561
+ match = pattern.search(line)
562
+ if match:
563
+ h = float(match.group(1))
564
+ m = float(match.group(2))
565
+ s = float(match.group(3))
566
+ elapsed = h * 3600 + m * 60 + s
567
+ pct = min(elapsed / duration_seconds, 1.0)
568
+ wall = time.time() - start_time
569
+ speed_m = speed_pattern.search(line)
570
+ speed_txt = speed_m.group(1) + "x" if speed_m else ""
571
+ eta = ""
572
+ if pct > 0.01 and wall > 2:
573
+ remaining = (wall / pct) * (1 - pct)
574
+ eta = format_duration(remaining)
575
+ progress_callback(pct, speed_txt, eta)
576
+
577
+ process.wait()
578
+ if process.returncode != 0:
579
+ tail = stderr_lines[-50:] if len(stderr_lines) > 50 else stderr_lines
580
+ return False, "".join(tail)
581
+ else:
582
+ ffmpeg.run(output, overwrite_output=True, capture_stdout=True, capture_stderr=True)
583
+
584
+ return True, None
585
+
586
+ except ffmpeg.Error as err:
587
+ error_detail = err.stderr.decode("utf-8") if err.stderr else "Proses encoding gagal"
588
+ return False, error_detail
589
+
590
+
591
+ def save_upload_to_temp(uploaded_file, token):
592
+ """Simpan file upload ke direktori sesi persisten dengan token unik."""
593
+ os.makedirs(SESSION_DIR, exist_ok=True)
594
+ cleanup_old_sessions()
595
+
596
+ suffix = pathlib.Path(uploaded_file.name).suffix or ".mp4"
597
+ session_id = str(int(time.time() * 1000))
598
+ file_path = os.path.join(SESSION_DIR, session_id + suffix)
599
+ meta_path = os.path.join(SESSION_DIR, session_id + ".json")
600
+
601
+ with open(file_path, "wb") as f:
602
+ f.write(uploaded_file.getbuffer())
603
+
604
+ meta = {
605
+ "original_name": uploaded_file.name,
606
+ "file_path": file_path,
607
+ "file_size": uploaded_file.size,
608
+ "timestamp": time.time(),
609
+ "session_id": session_id,
610
+ "token": token,
611
+ }
612
+ with open(meta_path, "w") as f:
613
+ json.dump(meta, f)
614
+
615
+ _temp_files.append(file_path)
616
+ _temp_files.append(meta_path)
617
+ return file_path
618
+
619
+
620
+ def find_recent_session(token):
621
+ """Cari sesi upload terakhir yang cocok dengan token browser ini."""
622
+ if not os.path.isdir(SESSION_DIR):
623
+ return None
624
+ if not token:
625
+ return None
626
+ now = time.time()
627
+ best = None
628
+ for name in os.listdir(SESSION_DIR):
629
+ if not name.endswith(".json"):
630
+ continue
631
+ meta_path = os.path.join(SESSION_DIR, name)
632
+ try:
633
+ with open(meta_path, "r") as f:
634
+ meta = json.load(f)
635
+ if meta.get("token") != token:
636
+ continue
637
+ age = now - meta.get("timestamp", 0)
638
+ if age > SESSION_MAX_AGE:
639
+ continue
640
+ if not os.path.exists(meta.get("file_path", "")):
641
+ continue
642
+ if best is None or meta["timestamp"] > best["timestamp"]:
643
+ best = meta
644
+ except (json.JSONDecodeError, OSError):
645
+ continue
646
+ return best
647
+
648
+
649
+ def cleanup_old_sessions():
650
+ """Hapus file sesi yang lebih dari 1 jam."""
651
+ if not os.path.isdir(SESSION_DIR):
652
+ return
653
+ now = time.time()
654
+ for name in os.listdir(SESSION_DIR):
655
+ full = os.path.join(SESSION_DIR, name)
656
+ try:
657
+ if now - os.path.getmtime(full) > SESSION_MAX_AGE:
658
+ os.unlink(full)
659
+ except OSError:
660
+ pass
661
+
662
+
663
+ def cleanup_temp_files():
664
+ for path in _temp_files:
665
+ try:
666
+ if os.path.exists(path):
667
+ os.unlink(path)
668
+ except OSError:
669
+ pass
670
+ _temp_files.clear()
671
+
672
+
673
+ atexit.register(cleanup_temp_files)
674
+
675
+
676
+ @st.cache_data(show_spinner=False, ttl=600)
677
+ def load_file_bytes(file_path):
678
+ with open(file_path, "rb") as f:
679
+ return f.read()
680
+
681
+
682
+ def render_header():
683
+ # Sembunyikan sidebar toggle arrow
684
+ hide_sidebar = """
685
+ <style>
686
+ [data-testid="collapsedControl"] { display: none !important; }
687
+ section[data-testid="stSidebar"] { display: none !important; }
688
+ </style>
689
+ """
690
+ st.markdown(hide_sidebar, unsafe_allow_html=True)
691
+ st.markdown(PAGE_STYLES, unsafe_allow_html=True)
692
+ st.markdown(
693
+ '<div class="app-hero">'
694
+ '<div class="brand">' + APP_TITLE + '</div>'
695
+ '<p class="tagline">' + APP_TAGLINE + '</p>'
696
+ '<span class="version-badge">v' + APP_VERSION + '</span>'
697
+ '</div>',
698
+ unsafe_allow_html=True,
699
+ )
700
+
701
+
702
+ def render_history():
703
+ """Tampilkan riwayat kompresi di main page."""
704
+ history = st.session_state.get("compression_history", [])
705
+ if history:
706
+ with st.expander("📋 Riwayat Kompresi (" + str(len(history)) + ")", expanded=False):
707
+ for item in reversed(history[-10:]):
708
+ st.caption(
709
+ "**" + item["name"] + "** — "
710
+ + item["original"] + " → " + item["result"]
711
+ + " " + item["reduction"]
712
+ )
713
+
714
+
715
+ def render_video_info(metadata):
716
+ c1, c2, c3 = st.columns(3)
717
+ c1.metric("Durasi", metadata.get("duration_text", "N/A"))
718
+ c2.metric("Resolusi", metadata.get("resolution_text", "N/A"))
719
+ c3.metric("Codec", metadata.get("codec", "N/A"))
720
+
721
+ c4, c5, c6 = st.columns(3)
722
+ c4.metric("FPS", str(metadata.get("fps", 0)))
723
+ c5.metric("Bitrate", metadata.get("bitrate_text", "N/A"))
724
+ c6.metric("Audio", metadata.get("audio_codec", "Tidak ada"))
725
+
726
+
727
+ def render_platform_presets():
728
+ preset_name = st.selectbox(
729
+ "Platform Target",
730
+ list(PLATFORM_PRESETS.keys()),
731
+ index=0,
732
+ help="Pilih platform tujuan untuk mengatur parameter otomatis.",
733
+ )
734
+ preset = PLATFORM_PRESETS[preset_name]
735
+
736
+ if preset_name != "Custom":
737
+ st.markdown(
738
+ '<div class="preset-info">' + preset["description"] + '</div>',
739
+ unsafe_allow_html=True,
740
+ )
741
+
742
+ return {"name": preset_name, **preset}
743
+
744
+
745
+ def render_compression_controls(preset, video_metadata):
746
+ is_custom = preset["name"] == "Custom"
747
+ settings = {}
748
+
749
+ st.markdown('<div class="section-title">Kompresi dan Kualitas</div>', unsafe_allow_html=True)
750
+
751
+ # --- Format Output ---
752
+ fmt_label = st.selectbox("Format Output", list(OUTPUT_FORMATS.keys()), index=0)
753
+ settings["out_format"] = OUTPUT_FORMATS[fmt_label]
754
+
755
+ # --- Smart Compression ---
756
+ smart_mode = st.checkbox("Smart Compression (target ukuran file)", value=False)
757
+ if smart_mode:
758
+ target_mb = st.number_input(
759
+ "Target ukuran (MB)",
760
+ min_value=0.5, max_value=500.0, value=10.0, step=0.5,
761
+ help="Masukkan target ukuran file hasil. Bitrate akan dihitung otomatis.",
762
+ )
763
+ settings["smart_target_mb"] = target_mb
764
+ else:
765
+ settings["smart_target_mb"] = None
766
+
767
+ if is_custom and not smart_mode:
768
+ settings["crf"] = st.slider(
769
+ "Level Kompresi (CRF)",
770
+ min_value=18,
771
+ max_value=36,
772
+ value=preset["crf"],
773
+ help="Nilai lebih tinggi = file lebih kecil. 18-22 hampir lossless, 28-32 ukuran minimal.",
774
+ )
775
+ settings["preset"] = st.select_slider(
776
+ "Kecepatan Encoding",
777
+ options=SPEED_OPTIONS,
778
+ value=preset["preset"],
779
+ help="Encoding lambat menghasilkan kompresi lebih efisien.",
780
+ )
781
+ res_options = ["Resolusi Asli"] + list(RESOLUTION_MAP.keys())
782
+ res_index = 0
783
+ if preset["resolution"] in RESOLUTION_MAP:
784
+ res_index = list(RESOLUTION_MAP.keys()).index(preset["resolution"]) + 1
785
+ selected_res = st.selectbox("Resolusi Output", res_options, index=res_index)
786
+ settings["resolution"] = "original" if selected_res == "Resolusi Asli" else selected_res
787
+ elif not smart_mode:
788
+ settings["crf"] = preset["crf"]
789
+ settings["preset"] = preset["preset"]
790
+ settings["resolution"] = preset["resolution"]
791
+ st.info(
792
+ "CRF: " + str(preset["crf"]) + " | Preset: " + preset["preset"]
793
+ + " | Resolusi: " + preset["resolution"]
794
+ )
795
+ else:
796
+ settings["crf"] = 28
797
+ settings["preset"] = "medium"
798
+ settings["resolution"] = preset.get("resolution", "720p")
799
+
800
+ settings["mute_audio"] = st.checkbox("Nonaktifkan Audio")
801
+
802
+ # --- Estimasi Ukuran ---
803
+ if video_metadata and not smart_mode:
804
+ duration = video_metadata.get("duration", 0)
805
+ has_audio = video_metadata.get("has_audio", False) and not settings["mute_audio"]
806
+ if duration > 0:
807
+ est = estimate_output_size(
808
+ duration, settings["crf"], settings["resolution"],
809
+ has_audio, settings["out_format"],
810
+ )
811
+ st.caption("Estimasi ukuran hasil: **" + format_filesize(est) + "**")
812
+
813
+ return settings
814
+
815
+
816
+ def render_advanced_controls(preset, video_metadata):
817
+ advanced = {}
818
+
819
+ st.markdown('<div class="section-title">Pengaturan Lanjutan</div>', unsafe_allow_html=True)
820
+
821
+ max_duration = video_metadata.get("duration", 600) if video_metadata else 600
822
+
823
+ col_start, col_end = st.columns(2)
824
+ with col_start:
825
+ trim_start = st.number_input(
826
+ "Potong mulai (detik)",
827
+ min_value=0.0,
828
+ max_value=float(max_duration),
829
+ value=0.0,
830
+ step=0.5,
831
+ format="%.1f",
832
+ )
833
+ with col_end:
834
+ trim_end = st.number_input(
835
+ "Potong sampai (detik)",
836
+ min_value=0.0,
837
+ max_value=float(max_duration),
838
+ value=0.0,
839
+ step=0.5,
840
+ format="%.1f",
841
+ help="Isi 0 untuk memproses sampai akhir video.",
842
+ )
843
+
844
+ advanced["trim_start"] = trim_start if trim_start > 0 else None
845
+ advanced["trim_end"] = trim_end if trim_end > 0 else None
846
+
847
+ is_custom = preset["name"] == "Custom"
848
+
849
+ col_fps, col_ratio = st.columns(2)
850
+ with col_fps:
851
+ if is_custom:
852
+ fps_label = st.selectbox("Frame Rate", list(FRAMERATE_OPTIONS.keys()), index=0)
853
+ advanced["target_fps"] = FRAMERATE_OPTIONS[fps_label]
854
+ else:
855
+ advanced["target_fps"] = preset.get("fps")
856
+ fps_display = str(preset["fps"]) + " FPS" if preset.get("fps") else "Bawaan"
857
+ st.text_input("Frame Rate", value=fps_display, disabled=True)
858
+
859
+ with col_ratio:
860
+ if is_custom:
861
+ aspect_label = st.selectbox("Aspect Ratio", list(ASPECT_RATIOS.keys()), index=0)
862
+ advanced["aspect_ratio"] = ASPECT_RATIOS[aspect_label]
863
+ else:
864
+ advanced["aspect_ratio"] = preset.get("aspect")
865
+ aspect_display = preset.get("aspect") or "Bawaan"
866
+ st.text_input("Aspect Ratio", value=aspect_display, disabled=True)
867
+
868
+ advanced["max_bitrate"] = preset.get("max_bitrate")
869
+
870
+ return advanced
871
+
872
+
873
+ def render_comparison_slider(input_path, output_path, duration):
874
+ """Render before/after image comparison slider menggunakan iframe component."""
875
+ import streamlit.components.v1 as components
876
+
877
+ timestamp = min(duration * 0.3, 5.0) if duration > 0 else 1.0
878
+
879
+ before_b64 = extract_frame(input_path, timestamp)
880
+ after_b64 = extract_frame(output_path, timestamp)
881
+
882
+ if not before_b64 or not after_b64:
883
+ col_a, col_b = st.columns(2)
884
+ with col_a:
885
+ st.caption("ASLI")
886
+ st.video(input_path)
887
+ with col_b:
888
+ st.caption("HASIL")
889
+ st.video(output_path)
890
+ return
891
+
892
+ html_code = """<!DOCTYPE html>
893
+ <html>
894
+ <head>
895
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
896
+ <style>
897
+ * { margin: 0; padding: 0; box-sizing: border-box; }
898
+ body { background: transparent; overflow: hidden; font-family: 'Inter', sans-serif; }
899
+ .wrap {
900
+ position: relative;
901
+ width: 100%;
902
+ overflow: hidden;
903
+ border-radius: 12px;
904
+ cursor: col-resize;
905
+ touch-action: none;
906
+ user-select: none;
907
+ -webkit-user-select: none;
908
+ }
909
+ .wrap img.bg {
910
+ display: block;
911
+ width: 100%;
912
+ height: auto;
913
+ }
914
+ .overlay {
915
+ position: absolute;
916
+ top: 0; left: 0;
917
+ width: 50%;
918
+ height: 100%;
919
+ overflow: hidden;
920
+ }
921
+ .overlay img {
922
+ position: absolute;
923
+ top: 0;
924
+ left: 0;
925
+ display: block;
926
+ height: 100%;
927
+ max-width: none;
928
+ }
929
+ .line {
930
+ position: absolute;
931
+ top: 0; left: 50%;
932
+ width: 3px;
933
+ height: 100%;
934
+ background: #fff;
935
+ box-shadow: 0 0 6px rgba(0,0,0,0.6);
936
+ z-index: 10;
937
+ transform: translateX(-50%);
938
+ pointer-events: none;
939
+ }
940
+ .handle {
941
+ position: absolute;
942
+ top: 50%; left: 50%;
943
+ width: 38px; height: 38px;
944
+ background: #fff;
945
+ border-radius: 50%;
946
+ z-index: 11;
947
+ transform: translate(-50%, -50%);
948
+ display: flex;
949
+ align-items: center;
950
+ justify-content: center;
951
+ box-shadow: 0 2px 8px rgba(0,0,0,0.45);
952
+ pointer-events: none;
953
+ }
954
+ .handle svg { width: 18px; height: 18px; }
955
+ .tag {
956
+ position: absolute;
957
+ top: 8px;
958
+ padding: 3px 10px;
959
+ border-radius: 5px;
960
+ font-size: 11px;
961
+ font-weight: 700;
962
+ letter-spacing: 0.05em;
963
+ z-index: 12;
964
+ text-transform: uppercase;
965
+ pointer-events: none;
966
+ }
967
+ .tag-before { right: 8px; background: rgba(239,68,68,0.85); color: #fff; }
968
+ .tag-after { left: 8px; background: rgba(16,185,129,0.85); color: #fff; }
969
+ .hint {
970
+ text-align: center;
971
+ font-size: 12px;
972
+ color: #94a3b8;
973
+ padding: 8px 0 0;
974
+ }
975
+ </style>
976
+ </head>
977
+ <body>
978
+ <div class="wrap" id="wrap">
979
+ <span class="tag tag-before">Asli</span>
980
+ <span class="tag tag-after">Hasil</span>
981
+ <img class="bg" id="bg" src="data:image/jpeg;base64,__BEFORE__" />
982
+ <div class="overlay" id="overlay">
983
+ <img id="afterImg" src="data:image/jpeg;base64,__AFTER__" />
984
+ </div>
985
+ <div class="line" id="line"></div>
986
+ <div class="handle" id="handle">
987
+ <svg viewBox="0 0 24 24" fill="none" stroke="#333" stroke-width="2.5" stroke-linecap="round">
988
+ <path d="M8 4l-6 8 6 8"/><path d="M16 4l6 8-6 8"/>
989
+ </svg>
990
+ </div>
991
+ </div>
992
+ <div class="hint">Geser ke kiri/kanan untuk membandingkan</div>
993
+ <script>
994
+ (function(){
995
+ var wrap = document.getElementById('wrap');
996
+ var overlay = document.getElementById('overlay');
997
+ var afterImg = document.getElementById('afterImg');
998
+ var line = document.getElementById('line');
999
+ var handle = document.getElementById('handle');
1000
+ var bg = document.getElementById('bg');
1001
+ var dragging = false;
1002
+
1003
+ function syncSize() {
1004
+ afterImg.style.width = wrap.offsetWidth + 'px';
1005
+ }
1006
+
1007
+ function getPos(e) {
1008
+ var r = wrap.getBoundingClientRect();
1009
+ var cx = e.touches ? e.touches[0].clientX : e.clientX;
1010
+ var x = cx - r.left;
1011
+ return Math.max(0, Math.min(x / r.width * 100, 100));
1012
+ }
1013
+
1014
+ function moveTo(pct) {
1015
+ overlay.style.width = pct + '%';
1016
+ line.style.left = pct + '%';
1017
+ handle.style.left = pct + '%';
1018
+ }
1019
+
1020
+ function onStart(e) {
1021
+ dragging = true;
1022
+ moveTo(getPos(e));
1023
+ e.preventDefault();
1024
+ }
1025
+ function onMove(e) {
1026
+ if (!dragging) return;
1027
+ moveTo(getPos(e));
1028
+ e.preventDefault();
1029
+ }
1030
+ function onEnd() { dragging = false; }
1031
+
1032
+ wrap.addEventListener('mousedown', onStart);
1033
+ wrap.addEventListener('mousemove', onMove);
1034
+ wrap.addEventListener('mouseup', onEnd);
1035
+ wrap.addEventListener('mouseleave', onEnd);
1036
+ wrap.addEventListener('touchstart', onStart, {passive:false});
1037
+ wrap.addEventListener('touchmove', onMove, {passive:false});
1038
+ wrap.addEventListener('touchend', onEnd);
1039
+
1040
+ bg.onload = function() {
1041
+ syncSize();
1042
+ var h = bg.offsetHeight + 40;
1043
+ window.parent.postMessage({type:'streamlit:setFrameHeight', height: h}, '*');
1044
+ };
1045
+ window.addEventListener('resize', function() {
1046
+ syncSize();
1047
+ var h = bg.offsetHeight + 40;
1048
+ window.parent.postMessage({type:'streamlit:setFrameHeight', height: h}, '*');
1049
+ });
1050
+ function delayedSync() {
1051
+ syncSize();
1052
+ if (bg.offsetHeight > 0) {
1053
+ var h = bg.offsetHeight + 40;
1054
+ window.parent.postMessage({type:'streamlit:setFrameHeight', height: h}, '*');
1055
+ }
1056
+ }
1057
+ setTimeout(delayedSync, 200);
1058
+ setTimeout(delayedSync, 600);
1059
+ setTimeout(delayedSync, 1500);
1060
+ if (window.ResizeObserver) {
1061
+ new ResizeObserver(function() {
1062
+ syncSize();
1063
+ var h = bg.offsetHeight + 40;
1064
+ window.parent.postMessage({type:'streamlit:setFrameHeight', height: h}, '*');
1065
+ }).observe(bg);
1066
+ }
1067
+ })();
1068
+ </script>
1069
+ </body>
1070
+ </html>"""
1071
+
1072
+ html_final = html_code.replace("__BEFORE__", before_b64).replace("__AFTER__", after_b64)
1073
+ components.html(html_final, height=800, scrolling=False)
1074
+
1075
+
1076
+ def render_before_after(input_path, output_path, original_size, uploaded_name, video_metadata, out_format="mp4"):
1077
+ compressed_size = os.path.getsize(output_path)
1078
+ reduction = calculate_reduction(original_size, compressed_size)
1079
+
1080
+ # Simpan ke riwayat
1081
+ history = st.session_state.get("compression_history", [])
1082
+ history.append({
1083
+ "name": uploaded_name,
1084
+ "original": format_filesize(original_size),
1085
+ "result": format_filesize(compressed_size),
1086
+ "reduction": f"-{reduction:.1f}%",
1087
+ })
1088
+ st.session_state["compression_history"] = history
1089
+
1090
+ st.markdown(
1091
+ '<div class="result-panel">'
1092
+ '<h3>Kompresi Berhasil</h3>'
1093
+ '<div class="result-stats">'
1094
+ + format_filesize(original_size) + ' menjadi '
1095
+ '<strong>' + format_filesize(compressed_size) + '</strong>'
1096
+ ' &nbsp; '
1097
+ '<span class="reduction-badge">Hemat ' + f"{reduction:.1f}" + '%</span>'
1098
+ '</div>'
1099
+ '</div>',
1100
+ unsafe_allow_html=True,
1101
+ )
1102
+
1103
+ duration = video_metadata.get("duration", 0) if video_metadata else 0
1104
+ if out_format != "gif":
1105
+ render_comparison_slider(input_path, output_path, duration)
1106
+
1107
+ st.markdown('<div class="section-title">Ukuran File</div>', unsafe_allow_html=True)
1108
+ col_s1, col_s2 = st.columns(2)
1109
+ col_s1.metric("Asli", format_filesize(original_size))
1110
+ col_s2.metric("Hasil", format_filesize(compressed_size), delta="-" + f"{reduction:.1f}" + "%", delta_color="normal")
1111
+
1112
+ if out_format != "gif":
1113
+ output_meta = probe_video(output_path)
1114
+ if video_metadata and output_meta:
1115
+ st.markdown('<div class="section-title">Detail Teknis</div>', unsafe_allow_html=True)
1116
+ col_h1, col_h2, col_h3 = st.columns(3)
1117
+ col_h1.write("**Parameter**")
1118
+ col_h2.write("**Asli**")
1119
+ col_h3.write("**Hasil**")
1120
+ params = [
1121
+ ("Resolusi", video_metadata.get("resolution_text", "-"), output_meta.get("resolution_text", "-")),
1122
+ ("Codec", video_metadata.get("codec", "-"), output_meta.get("codec", "-")),
1123
+ ("FPS", str(video_metadata.get("fps", "-")), str(output_meta.get("fps", "-"))),
1124
+ ("Bitrate", video_metadata.get("bitrate_text", "-"), output_meta.get("bitrate_text", "-")),
1125
+ ]
1126
+ for label, val_before, val_after in params:
1127
+ c1, c2, c3 = st.columns(3)
1128
+ c1.write(label)
1129
+ c2.write(val_before)
1130
+ c3.write(val_after)
1131
+
1132
+ st.write("")
1133
+
1134
+ if out_format == "gif":
1135
+ st.image(output_path, caption="Hasil GIF")
1136
+ else:
1137
+ st.video(output_path)
1138
+
1139
+ mime_map = {"mp4": "video/mp4", "webm": "video/webm", "gif": "image/gif"}
1140
+ download_name = get_clean_filename(uploaded_name, out_format)
1141
+ file_data = load_file_bytes(output_path)
1142
+ st.download_button(
1143
+ label="Download Hasil",
1144
+ data=file_data,
1145
+ file_name=download_name,
1146
+ mime=mime_map.get(out_format, "video/mp4"),
1147
+ )
1148
+
1149
+
1150
+ def render_features():
1151
+ c1, c2, c3 = st.columns(3)
1152
+ with c1:
1153
+ st.markdown("**Aman**")
1154
+ st.caption("Video tidak disimpan permanen di server.")
1155
+ with c2:
1156
+ st.markdown("**Tanpa Watermark**")
1157
+ st.caption("Hasil kompresi bersih tanpa tanda air.")
1158
+ with c3:
1159
+ st.markdown("**Gratis**")
1160
+ st.caption("Gunakan tanpa batas, tanpa biaya.")
1161
+
1162
+
1163
+ def render_footer():
1164
+ st.markdown(
1165
+ '<div class="footer-section">'
1166
+ 'Dibuat oleh <a href="#">Garden</a> &middot; ' + APP_TITLE + ' v' + APP_VERSION + '<br>'
1167
+ '<span style="font-size: 0.75rem; color: #475569;">'
1168
+ 'Dilisensikan di bawah GNU General Public License v3.0'
1169
+ '</span>'
1170
+ '</div>',
1171
+ unsafe_allow_html=True,
1172
+ )
1173
+
1174
+
1175
+ def main():
1176
+ st.set_page_config(
1177
+ page_title=APP_TITLE + " - " + APP_TAGLINE,
1178
+ page_icon="https://em-content.zobj.net/source/twitter/408/film-frames_1f39e-fe0f.png",
1179
+ layout="centered",
1180
+ initial_sidebar_state="collapsed",
1181
+ )
1182
+
1183
+ render_header()
1184
+ render_features()
1185
+ st.divider()
1186
+
1187
+ uploaded_file = st.file_uploader(
1188
+ "Pilih file video",
1189
+ type=SUPPORTED_FORMATS,
1190
+ help="Format: MP4, MOV, MKV, AVI, WebM. Maks 500MB.",
1191
+ )
1192
+
1193
+ # --- Session token: unik per browser/tab ---
1194
+ params = st.query_params
1195
+ session_token = params.get("sid", "")
1196
+ if not session_token:
1197
+ session_token = uuid.uuid4().hex[:16]
1198
+ st.query_params["sid"] = session_token
1199
+
1200
+ if uploaded_file is None:
1201
+ has_session = (
1202
+ "input_path" in st.session_state
1203
+ and os.path.exists(st.session_state["input_path"])
1204
+ )
1205
+
1206
+ if has_session:
1207
+ input_path = st.session_state["input_path"]
1208
+ original_size = st.session_state["input_size"]
1209
+ else:
1210
+ recent = find_recent_session(session_token)
1211
+ if recent and os.path.exists(recent.get("file_path", "")):
1212
+ st.info("Kami menemukan sesi sebelumnya.")
1213
+ col_info, col_btn = st.columns([3, 1])
1214
+ with col_info:
1215
+ st.markdown(
1216
+ "**" + recent["original_name"] + "** ("
1217
+ + format_filesize(recent["file_size"]) + ")"
1218
+ )
1219
+ age_min = int((time.time() - recent["timestamp"]) / 60)
1220
+ st.caption(str(age_min) + " menit yang lalu")
1221
+ with col_btn:
1222
+ if st.button("Lanjutkan", use_container_width=True):
1223
+ st.session_state["input_path"] = recent["file_path"]
1224
+ st.session_state["input_name"] = recent["original_name"]
1225
+ st.session_state["input_size"] = recent["file_size"]
1226
+ st.session_state["input_size_raw"] = recent["file_size"]
1227
+ st.session_state.pop("video_metadata", None)
1228
+ st.rerun()
1229
+ else:
1230
+ st.info("Upload video untuk memulai kompresi.")
1231
+
1232
+ render_footer()
1233
+ return
1234
+ else:
1235
+ file_changed = (
1236
+ "input_name" not in st.session_state
1237
+ or st.session_state["input_name"] != uploaded_file.name
1238
+ or st.session_state.get("input_size_raw") != uploaded_file.size
1239
+ )
1240
+
1241
+ if file_changed:
1242
+ with st.spinner("Menyimpan video..."):
1243
+ input_path = save_upload_to_temp(uploaded_file, session_token)
1244
+ original_size = os.path.getsize(input_path)
1245
+
1246
+ st.session_state["input_path"] = input_path
1247
+ st.session_state["input_name"] = uploaded_file.name
1248
+ st.session_state["input_size"] = original_size
1249
+ st.session_state["input_size_raw"] = uploaded_file.size
1250
+ st.session_state.pop("video_metadata", None)
1251
+ else:
1252
+ input_path = st.session_state["input_path"]
1253
+ original_size = st.session_state["input_size"]
1254
+
1255
+ uploaded_name = st.session_state.get("input_name", "video.mp4")
1256
+
1257
+ st.success("File terpilih: **" + uploaded_name + "** (**" + format_filesize(original_size) + "**)")
1258
+
1259
+ video_metadata = st.session_state.get("video_metadata")
1260
+
1261
+ show_info = st.checkbox("Tampilkan info video", value=False)
1262
+ if show_info:
1263
+ if video_metadata is None:
1264
+ with st.spinner("Membaca metadata..."):
1265
+ video_metadata = probe_video(input_path)
1266
+ st.session_state["video_metadata"] = video_metadata
1267
+ if video_metadata:
1268
+ render_video_info(video_metadata)
1269
+
1270
+ preset = render_platform_presets()
1271
+ settings = render_compression_controls(preset, video_metadata)
1272
+
1273
+ show_advanced = st.checkbox("Tampilkan pengaturan lanjutan", value=False)
1274
+ if show_advanced:
1275
+ advanced = render_advanced_controls(preset, video_metadata)
1276
+ else:
1277
+ advanced = {
1278
+ "trim_start": None,
1279
+ "trim_end": None,
1280
+ "target_fps": preset.get("fps"),
1281
+ "aspect_ratio": preset.get("aspect"),
1282
+ "max_bitrate": preset.get("max_bitrate"),
1283
+ }
1284
+
1285
+ st.write("")
1286
+
1287
+ if st.button("Mulai Kompresi", use_container_width=True):
1288
+ out_fmt = settings.get("out_format", "mp4")
1289
+ output_path = input_path + "_out." + out_fmt
1290
+ _temp_files.append(output_path)
1291
+
1292
+ if video_metadata is None:
1293
+ with st.spinner("Membaca metadata..."):
1294
+ video_metadata = probe_video(input_path)
1295
+ st.session_state["video_metadata"] = video_metadata
1296
+
1297
+ total_duration = 0
1298
+ if video_metadata:
1299
+ total_duration = video_metadata.get("duration", 0)
1300
+ if advanced.get("trim_start") or advanced.get("trim_end"):
1301
+ start = advanced.get("trim_start") or 0
1302
+ end = advanced.get("trim_end") or total_duration
1303
+ total_duration = max(end - start, 0)
1304
+
1305
+ # Smart compression: hitung bitrate dari target ukuran
1306
+ effective_max_bitrate = advanced.get("max_bitrate")
1307
+ if settings.get("smart_target_mb") and total_duration > 0:
1308
+ has_audio = video_metadata.get("has_audio", False) if video_metadata else False
1309
+ smart_br = calculate_target_bitrate(
1310
+ settings["smart_target_mb"], total_duration,
1311
+ has_audio and not settings["mute_audio"],
1312
+ )
1313
+ if smart_br:
1314
+ effective_max_bitrate = smart_br
1315
+
1316
+ progress_bar = st.progress(0, text="Mempersiapkan encoding...")
1317
+ status_text = st.empty()
1318
+
1319
+ def on_progress(pct, speed="", eta=""):
1320
+ progress_bar.progress(
1321
+ min(int(pct * 100), 99),
1322
+ text="Encoding: " + str(int(pct * 100)) + "%",
1323
+ )
1324
+ info_parts = []
1325
+ if speed:
1326
+ info_parts.append("Kecepatan: " + speed)
1327
+ if eta:
1328
+ info_parts.append("Sisa: ~" + eta)
1329
+ if info_parts:
1330
+ status_text.caption(" · ".join(info_parts))
1331
+
1332
+ success, error_msg = compress_video(
1333
+ input_path=input_path,
1334
+ output_path=output_path,
1335
+ crf=settings["crf"],
1336
+ preset=settings["preset"],
1337
+ mute_audio=settings["mute_audio"],
1338
+ resolution=settings["resolution"],
1339
+ trim_start=advanced.get("trim_start"),
1340
+ trim_end=advanced.get("trim_end"),
1341
+ target_fps=advanced.get("target_fps"),
1342
+ aspect_ratio=advanced.get("aspect_ratio"),
1343
+ max_bitrate=effective_max_bitrate,
1344
+ progress_callback=on_progress,
1345
+ duration_seconds=total_duration,
1346
+ out_format=out_fmt,
1347
+ )
1348
+
1349
+ if success:
1350
+ progress_bar.progress(100, text="Selesai!")
1351
+ status_text.empty()
1352
+ render_before_after(input_path, output_path, original_size, uploaded_name, video_metadata, out_fmt)
1353
+ else:
1354
+ progress_bar.empty()
1355
+ status_text.empty()
1356
+ st.error("Terjadi kesalahan saat memproses video.")
1357
+ with st.container():
1358
+ st.code(error_msg, language="text")
1359
+
1360
+ render_history()
1361
+ render_footer()
1362
+
1363
+
1364
+ if __name__ == "__main__":
1365
+ main()
requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ streamlit>=1.31.0,<2.0.0
2
+ ffmpeg-python>=0.2.0,<1.0.0