tee342 commited on
Commit
1d578cf
·
verified ·
1 Parent(s): 6b0844b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +136 -155
app.py CHANGED
@@ -188,21 +188,6 @@ const masteringPresets = {
188
 
189
  type MasteringParams = typeof masteringPresets.pop;
190
 
191
- // Default stats for comparison
192
- const defaultAudioStats = {
193
- rms: 0,
194
- peak: 0,
195
- crest: 0,
196
- lufs: -23,
197
- truePeak: 0,
198
- lra: 0,
199
- stereoWidth: 0,
200
- lowEnergy: 0,
201
- midEnergy: 0,
202
- highEnergy: 0,
203
- dynamicRange: 0,
204
- };
205
-
206
  export default function MasteringPage() {
207
  const [originalAudioUrl, setOriginalAudioUrl] = useState<string | null>(null);
208
  const [processedAudioUrl, setProcessedAudioUrl] = useState<string | null>(null);
@@ -216,10 +201,14 @@ export default function MasteringPage() {
216
  );
217
  const router = useRouter();
218
 
 
 
 
 
219
  const fileInputRef = useRef<HTMLInputElement>(null);
220
 
221
- // 🧠 Handle file selection + upload
222
- const handleFileSelect = async (e) => {
223
  const file = e.target.files?.[0];
224
  if (!file) return;
225
 
@@ -228,82 +217,38 @@ export default function MasteringPage() {
228
  formData.append("genre", selectedPreset);
229
  formData.append("target_lufs", "-14.0");
230
 
231
- try {
232
- const res = await fetch(`${HF_SPACE_URL}/api/master`, {
233
- method: "POST",
234
- body: formData,
235
- });
236
-
237
- const contentType = res.headers.get("content-type");
238
-
239
- if (!res.ok) throw new Error(`HTTP error! status: ${res.status}`);
240
-
241
- if (contentType && contentType.includes("application/json")) {
242
- const data = await res.json();
243
-
244
- if (data.data && data.data.length >= 3) {
245
  setOriginalAudioUrl(data.data[0]);
246
  setProcessedAudioUrl(data.data[0]);
247
  setFileName(file.name);
248
-
249
- setOriginalStats({
250
- rms: -18,
251
- peak: -3.5,
252
- crest: 14.5,
253
- lufs: -16.8,
254
- truePeak: -3.2,
255
- lra: 8.4,
256
- stereoWidth: 92,
257
- lowEnergy: -12.5,
258
- midEnergy: -15.2,
259
- highEnergy: -18.7,
260
- dynamicRange: 14.5,
261
- });
262
- setProcessedStats({
263
- rms: -14,
264
- peak: -1.2,
265
- crest: 12.8,
266
- lufs: -14.0,
267
- truePeak: -1.0,
268
- lra: 6.8,
269
- stereoWidth: 105,
270
- lowEnergy: -10.2,
271
- midEnergy: -13.5,
272
- highEnergy: -16.3,
273
- dynamicRange: 12.8,
274
- });
275
-
276
  toast({
277
  title: "File Uploaded",
278
  description: `${file.name} is being processed.`,
279
  });
280
  }
281
- } else {
282
- const text = await res.text();
283
- console.error("Received HTML instead of JSON:", text);
284
  toast({
285
- title: "Server Error",
286
- description: "Check if your Hugging Face Space is running and public.",
287
- variant: "destructive"
288
  });
289
- }
290
-
291
- } catch (error) {
292
- console.error("Upload failed:", error);
293
- toast({
294
- title: "Error",
295
- description: "Could not process audio.",
296
- variant: "destructive",
297
  });
298
- }
299
  };
300
 
301
  // 🎚 Apply mastering settings via Hugging Face API
302
  const applyMastering = async () => {
303
- if (!originalAudioUrl || !fileInputRef.current?.files?.[0]) {
304
  toast({
305
  title: "No Audio Selected",
306
- description: "Please upload an audio file first.",
307
  variant: "destructive",
308
  });
309
  return;
@@ -333,34 +278,6 @@ export default function MasteringPage() {
333
  if (data.data && data.data.length >= 3) {
334
  setProcessedAudioUrl(data.data[0]);
335
 
336
- // Update stats
337
- setOriginalStats({
338
- rms: -18,
339
- peak: -3.5,
340
- crest: 14.5,
341
- lufs: -16.8,
342
- truePeak: -3.2,
343
- lra: 8.4,
344
- stereoWidth: 92,
345
- lowEnergy: -12.5,
346
- midEnergy: -15.2,
347
- highEnergy: -18.7,
348
- dynamicRange: 14.5,
349
- });
350
- setProcessedStats({
351
- rms: -14,
352
- peak: -1.2,
353
- crest: 12.8,
354
- lufs: -14.0,
355
- truePeak: -1.0,
356
- lra: 6.8,
357
- stereoWidth: 105,
358
- lowEnergy: -10.2,
359
- midEnergy: -13.5,
360
- highEnergy: -16.3,
361
- dynamicRange: 12.8,
362
- });
363
-
364
  toast({
365
  title: "Mastering Complete",
366
  description: `Applied "${selectedPreset}" preset successfully.`,
@@ -389,7 +306,7 @@ export default function MasteringPage() {
389
  };
390
 
391
  // 🔄 Change genre/preset
392
- const handlePresetChange = async (value: string) => {
393
  setSelectedPreset(value);
394
  setCustomSettings(masteringPresets[value as keyof typeof masteringPresets] || masteringPresets.pop);
395
  if (originalAudioUrl && !isProcessing) {
@@ -405,11 +322,6 @@ export default function MasteringPage() {
405
  }));
406
  };
407
 
408
- // 📁 Trigger file input click
409
- const handleUploadClick = () => {
410
- fileInputRef.current?.click();
411
- };
412
-
413
  // 🧼 Cleanup URLs
414
  useEffect(() => {
415
  return () => {
@@ -422,9 +334,34 @@ export default function MasteringPage() {
422
  };
423
  }, [originalAudioUrl, processedAudioUrl]);
424
 
425
- // State for audio stats
426
- const [originalStats, setOriginalStats] = useState(defaultAudioStats);
427
- const [processedStats, setProcessedStats] = useState(defaultAudioStats);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
428
 
429
  return (
430
  <div className="container mx-auto py-6 space-y-8">
@@ -463,7 +400,7 @@ export default function MasteringPage() {
463
  />
464
 
465
  <button
466
- onClick={handleUploadClick}
467
  className="bg-purple-600 hover:bg-purple-700 text-white px-4 py-2 rounded-md flex items-center"
468
  >
469
  <UploadIcon className="h-4 w-4 mr-2" />
@@ -549,7 +486,7 @@ export default function MasteringPage() {
549
  <Tabs value={activeTab} onValueChange={setActiveTab}>
550
  <TabsList className="grid grid-cols-4 mb-4">
551
  <TabsTrigger value="player">
552
- <WaveformIcon className="h-4 w-4 mr-2" />
553
  Player
554
  </TabsTrigger>
555
  <TabsTrigger value="comparison">
@@ -571,21 +508,12 @@ export default function MasteringPage() {
571
  <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
572
  <div>
573
  <h3 className="text-lg font-medium mb-2">Original</h3>
574
- <AudioWaveform
575
- audioUrl={originalAudioUrl}
576
- height={120}
577
- waveColor="rgba(124, 58, 237, 0.4)"
578
- progressColor="rgba(124, 58, 237, 1)"
579
- />
580
  </div>
581
  {processedAudioUrl && (
582
  <div>
583
  <h3 className="text-lg font-medium mb-2">Processed</h3>
584
- <img
585
- src="/waveform.png"
586
- alt="Processed Waveform"
587
- className="w-full h-30 object-cover rounded-md"
588
- />
589
  </div>
590
  )}
591
  </div>
@@ -594,16 +522,18 @@ export default function MasteringPage() {
594
  {/* Compare Original vs Processed */}
595
  <TabsContent value="comparison">
596
  {processedAudioUrl ? (
597
- <MasteringComparison
598
- originalAudio={originalAudioUrl}
599
- processedAudio={processedAudioUrl}
 
 
600
  />
601
  ) : (
602
  <div className="flex flex-col items-center justify-center py-12 text-center">
603
- <HeadphonesIcon className="h-12 w-12 text-muted-foreground mb-4" />
604
  <h3 className="text-lg font-medium">No Processed Audio</h3>
605
  <p className="text-muted-foreground mt-2 max-w-md">
606
- Apply mastering to enable comparison.
607
  </p>
608
  <button
609
  onClick={applyMastering}
@@ -938,7 +868,7 @@ export default function MasteringPage() {
938
  Upload a WAV, MP3, or FLAC file to begin mastering.
939
  </p>
940
  <button
941
- onClick={handleUploadClick}
942
  className="mt-4 bg-purple-600 hover:bg-purple-700 text-white px-4 py-2 rounded-md"
943
  >
944
  <UploadIcon className="h-4 w-4 mr-2" />
@@ -951,18 +881,18 @@ export default function MasteringPage() {
951
  );
952
  }
953
 
954
- // 🎵 Simple Waveform Component with Play Button Overlay
955
- function AudioWaveform({ audioUrl, height = 100, waveColor = "#4f46e5", progressColor = "#8b5cf6" }) {
956
  const [isPlaying, setIsPlaying] = useState(false);
957
- const audioRef = useRef<HTMLAudioElement>(null);
958
 
959
  const togglePlayback = () => {
960
- if (!audioRef.current) return;
961
 
962
  if (isPlaying) {
963
- audioRef.current.pause();
964
  } else {
965
- audioRef.current.play().catch((err) => {
966
  console.error("Autoplay blocked:", err);
967
  alert("Click inside the waveform to start playback.");
968
  });
@@ -974,13 +904,16 @@ function AudioWaveform({ audioUrl, height = 100, waveColor = "#4f46e5", progress
974
  <div className="relative w-full">
975
  <div
976
  style={{
977
- height: `${height}px`,
978
- background: `linear-gradient(180deg, ${waveColor}22, ${progressColor}aa)`,
 
 
979
  position: "relative",
980
  overflow: "hidden",
981
  borderRadius: "0.5rem",
 
982
  }}
983
- className="w-full rounded-md relative"
984
  onClick={togglePlayback}
985
  >
986
  <div className="absolute inset-0 flex items-center justify-center">
@@ -1001,12 +934,19 @@ function AudioWaveform({ audioUrl, height = 100, waveColor = "#4f46e5", progress
1001
  </button>
1002
  </div>
1003
  </div>
1004
- <audio ref={audioRef} src={audioUrl} onEnded={() => setIsPlaying(false)} />
 
 
 
 
 
 
 
1005
  </div>
1006
  );
1007
  }
1008
 
1009
- // 📊 Stats Display Component
1010
  function MasteringStatistics({ originalStats, processedStats }) {
1011
  return (
1012
  <Card className="mt-4">
@@ -1024,7 +964,9 @@ function MasteringStatistics({ originalStats, processedStats }) {
1024
  </div>
1025
  <div className="flex justify-between">
1026
  <span className="text-xs">Processed</span>
1027
- <span className="font-mono text-primary">{processedStats.lufs.toFixed(1)}</span>
 
 
1028
  </div>
1029
  </div>
1030
  </div>
@@ -1033,25 +975,44 @@ function MasteringStatistics({ originalStats, processedStats }) {
1033
  );
1034
  }
1035
 
1036
- // 🎵 Compare Two Tracks
1037
- function MasteringComparison({ originalAudio, processedAudio }) {
1038
- const [activeAudio, setActiveAudio] = useState<"original" | "processed">("processed");
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1039
 
1040
  return (
1041
  <div className="space-y-6">
1042
  <div className="flex justify-center gap-4">
1043
- <button
1044
- onClick={() => setActiveAudio("original")}
1045
- className={`${activeAudio === "original" ? "bg-primary text-white" : "bg-secondary text-primary"} px-4 py-2 rounded-md w-40`}
 
1046
  >
1047
  Original
1048
- </button>
1049
- <button
1050
- onClick={() => setActiveAudio("processed")}
1051
- className={`${activeAudio === "processed" ? "bg-primary text-white" : "bg-secondary text-primary"} px-4 py-2 rounded-md w-40`}
 
1052
  >
1053
  Processed
1054
- </button>
1055
  </div>
1056
  </div>
1057
  );
@@ -1112,4 +1073,24 @@ function AudioQualityAnalyzer({ audioUrl, fileName }) {
1112
  </div>
1113
  </div>
1114
  );
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1115
  }
 
188
 
189
  type MasteringParams = typeof masteringPresets.pop;
190
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
191
  export default function MasteringPage() {
192
  const [originalAudioUrl, setOriginalAudioUrl] = useState<string | null>(null);
193
  const [processedAudioUrl, setProcessedAudioUrl] = useState<string | null>(null);
 
201
  );
202
  const router = useRouter();
203
 
204
+ // 🔊 Refs for audio elements
205
+ const originalRef = useRef<HTMLAudioElement>(null);
206
+ const processedRef = useRef<HTMLAudioElement>(null);
207
+
208
  const fileInputRef = useRef<HTMLInputElement>(null);
209
 
210
+ // 📁 Handle file selection
211
+ const handleFileSelect = (e) => {
212
  const file = e.target.files?.[0];
213
  if (!file) return;
214
 
 
217
  formData.append("genre", selectedPreset);
218
  formData.append("target_lufs", "-14.0");
219
 
220
+ fetch(`${HF_SPACE_URL}/api/master`, {
221
+ method: "POST",
222
+ body: formData,
223
+ })
224
+ .then((res) => res.json())
225
+ .then((data) => {
226
+ if (data && data.data && data.data.length >= 3) {
 
 
 
 
 
 
 
227
  setOriginalAudioUrl(data.data[0]);
228
  setProcessedAudioUrl(data.data[0]);
229
  setFileName(file.name);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
230
  toast({
231
  title: "File Uploaded",
232
  description: `${file.name} is being processed.`,
233
  });
234
  }
235
+ })
236
+ .catch((err) => {
237
+ console.error("Upload failed:", err);
238
  toast({
239
+ title: "Error",
240
+ description: "Could not process audio.",
241
+ variant: "destructive",
242
  });
 
 
 
 
 
 
 
 
243
  });
 
244
  };
245
 
246
  // 🎚 Apply mastering settings via Hugging Face API
247
  const applyMastering = async () => {
248
+ if (!fileInputRef.current?.files?.[0]) {
249
  toast({
250
  title: "No Audio Selected",
251
+ description: "Please upload a file first.",
252
  variant: "destructive",
253
  });
254
  return;
 
278
  if (data.data && data.data.length >= 3) {
279
  setProcessedAudioUrl(data.data[0]);
280
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
281
  toast({
282
  title: "Mastering Complete",
283
  description: `Applied "${selectedPreset}" preset successfully.`,
 
306
  };
307
 
308
  // 🔄 Change genre/preset
309
+ const handlePresetChange = (value: string) => {
310
  setSelectedPreset(value);
311
  setCustomSettings(masteringPresets[value as keyof typeof masteringPresets] || masteringPresets.pop);
312
  if (originalAudioUrl && !isProcessing) {
 
322
  }));
323
  };
324
 
 
 
 
 
 
325
  // 🧼 Cleanup URLs
326
  useEffect(() => {
327
  return () => {
 
334
  };
335
  }, [originalAudioUrl, processedAudioUrl]);
336
 
337
+ // 📊 Stats for comparison view
338
+ const [originalStats, setOriginalStats] = useState({
339
+ rms: -18,
340
+ peak: -3.5,
341
+ crest: 14.5,
342
+ lufs: -16.8,
343
+ truePeak: -3.2,
344
+ lra: 8.4,
345
+ stereoWidth: 92,
346
+ lowEnergy: -12.5,
347
+ midEnergy: -15.2,
348
+ highEnergy: -18.7,
349
+ dynamicRange: 14.5,
350
+ });
351
+
352
+ const [processedStats, setProcessedStats] = useState({
353
+ rms: -14,
354
+ peak: -1.2,
355
+ crest: 12.8,
356
+ lufs: -14.0,
357
+ truePeak: -1.0,
358
+ lra: 6.8,
359
+ stereoWidth: 105,
360
+ lowEnergy: -10.2,
361
+ midEnergy: -13.5,
362
+ highEnergy: -16.3,
363
+ dynamicRange: 12.8,
364
+ });
365
 
366
  return (
367
  <div className="container mx-auto py-6 space-y-8">
 
400
  />
401
 
402
  <button
403
+ onClick={() => fileInputRef.current?.click()}
404
  className="bg-purple-600 hover:bg-purple-700 text-white px-4 py-2 rounded-md flex items-center"
405
  >
406
  <UploadIcon className="h-4 w-4 mr-2" />
 
486
  <Tabs value={activeTab} onValueChange={setActiveTab}>
487
  <TabsList className="grid grid-cols-4 mb-4">
488
  <TabsTrigger value="player">
489
+ <VisualizerIcon className="h-4 w-4 mr-2" />
490
  Player
491
  </TabsTrigger>
492
  <TabsTrigger value="comparison">
 
508
  <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
509
  <div>
510
  <h3 className="text-lg font-medium mb-2">Original</h3>
511
+ <AudioWaveform src={originalAudioUrl} ref={originalRef} />
 
 
 
 
 
512
  </div>
513
  {processedAudioUrl && (
514
  <div>
515
  <h3 className="text-lg font-medium mb-2">Processed</h3>
516
+ <AudioWaveform src={processedAudioUrl} ref={processedRef} />
 
 
 
 
517
  </div>
518
  )}
519
  </div>
 
522
  {/* Compare Original vs Processed */}
523
  <TabsContent value="comparison">
524
  {processedAudioUrl ? (
525
+ <ComparisonView
526
+ originalRef={originalRef}
527
+ processedRef={processedRef}
528
+ originalSrc={originalAudioUrl}
529
+ processedSrc={processedAudioUrl}
530
  />
531
  ) : (
532
  <div className="flex flex-col items-center justify-center py-12 text-center">
533
+ <HeadphonesIcon className="h-12 w-12 text-gray-400 mb-4" />
534
  <h3 className="text-lg font-medium">No Processed Audio</h3>
535
  <p className="text-muted-foreground mt-2 max-w-md">
536
+ Apply mastering to enable comparison between original and processed versions.
537
  </p>
538
  <button
539
  onClick={applyMastering}
 
868
  Upload a WAV, MP3, or FLAC file to begin mastering.
869
  </p>
870
  <button
871
+ onClick={() => fileInputRef.current?.click()}
872
  className="mt-4 bg-purple-600 hover:bg-purple-700 text-white px-4 py-2 rounded-md"
873
  >
874
  <UploadIcon className="h-4 w-4 mr-2" />
 
881
  );
882
  }
883
 
884
+ // 🎵 Simple Audio Player Component
885
+ function AudioWaveform({ src, ref }) {
886
  const [isPlaying, setIsPlaying] = useState(false);
887
+ const playerRef = ref || useRef(null);
888
 
889
  const togglePlayback = () => {
890
+ if (!playerRef.current) return;
891
 
892
  if (isPlaying) {
893
+ playerRef.current.pause();
894
  } else {
895
+ playerRef.current.play().catch((err) => {
896
  console.error("Autoplay blocked:", err);
897
  alert("Click inside the waveform to start playback.");
898
  });
 
904
  <div className="relative w-full">
905
  <div
906
  style={{
907
+ height: "120px",
908
+ background: isPlaying
909
+ ? "linear-gradient(180deg, #a855fd22 0%, #9333ea88 100%)"
910
+ : "#f3f4f6",
911
  position: "relative",
912
  overflow: "hidden",
913
  borderRadius: "0.5rem",
914
+ cursor: "pointer",
915
  }}
916
+ className="rounded-md overflow-hidden bg-muted/30 relative"
917
  onClick={togglePlayback}
918
  >
919
  <div className="absolute inset-0 flex items-center justify-center">
 
934
  </button>
935
  </div>
936
  </div>
937
+ <audio
938
+ ref={playerRef}
939
+ src={src}
940
+ onEnded={() => setIsPlaying(false)}
941
+ onPause={() => setIsPlaying(false)}
942
+ onPlay={() => setIsPlaying(true)}
943
+ className="hidden"
944
+ ></audio>
945
  </div>
946
  );
947
  }
948
 
949
+ // 📊 Stats Display
950
  function MasteringStatistics({ originalStats, processedStats }) {
951
  return (
952
  <Card className="mt-4">
 
964
  </div>
965
  <div className="flex justify-between">
966
  <span className="text-xs">Processed</span>
967
+ <span className="font-mono text-primary">
968
+ {processedStats.lufs.toFixed(1)}
969
+ </span>
970
  </div>
971
  </div>
972
  </div>
 
975
  );
976
  }
977
 
978
+ // 🎧 Compare Two Tracks
979
+ function ComparisonView({ originalSrc, processedSrc, originalRef, processedRef }) {
980
+ const [activeTrack, setActiveTrack] = useState<"original" | "processed">("processed");
981
+
982
+ const switchTrack = (track: "original" | "processed") => {
983
+ if (track === "original") {
984
+ originalRef.current?.play().catch((err) => {
985
+ console.error("Original playback failed:", err);
986
+ alert("Click inside the waveform to enable playback.");
987
+ });
988
+ processedRef.current?.pause();
989
+ } else {
990
+ processedRef.current?.play().catch((err) => {
991
+ console.error("Processed playback failed:", err);
992
+ alert("Click inside the waveform to enable playback.");
993
+ });
994
+ originalRef.current?.pause();
995
+ }
996
+ setActiveTrack(track);
997
+ };
998
 
999
  return (
1000
  <div className="space-y-6">
1001
  <div className="flex justify-center gap-4">
1002
+ <Button
1003
+ onClick={() => switchTrack("original")}
1004
+ variant={activeTrack === "original" ? "default" : "outline"}
1005
+ className="w-40"
1006
  >
1007
  Original
1008
+ </Button>
1009
+ <Button
1010
+ onClick={() => switchTrack("processed")}
1011
+ variant={activeTrack === "processed" ? "default" : "outline"}
1012
+ className="w-40"
1013
  >
1014
  Processed
1015
+ </Button>
1016
  </div>
1017
  </div>
1018
  );
 
1073
  </div>
1074
  </div>
1075
  );
1076
+ }
1077
+
1078
+ // 🖼 SVG Icon for waveform tab (used in Tabs)
1079
+ function VisualizerIcon({ className }) {
1080
+ return (
1081
+ <svg
1082
+ className={className}
1083
+ fill="none"
1084
+ stroke="currentColor"
1085
+ viewBox="0 0 24 24"
1086
+ xmlns="http://www.w3.org/2000/svg"
1087
+ >
1088
+ <path
1089
+ strokeLinecap="round"
1090
+ strokeLinejoin="round"
1091
+ strokeWidth="2"
1092
+ d="M6 18L18 6M6 6H2m10 12H2m4 0v-12"
1093
+ ></path>
1094
+ </svg>
1095
+ );
1096
  }