cyber88 commited on
Commit
5e9be4e
·
verified ·
1 Parent(s): 2a93eb9

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -99
app.py DELETED
@@ -1,99 +0,0 @@
1
- # @title Beat Identifier (auto-detect CPU/GPU, queue & parallel, expose file URLs)
2
-
3
- import os
4
- import gradio as gr
5
- import librosa
6
- import numpy as np
7
- import tempfile
8
- import requests
9
- import shutil
10
- import torch
11
- from concurrent.futures import ThreadPoolExecutor
12
-
13
- # --- Patch SciPy so librosa.beat_track can find hann() ---
14
- import scipy.signal
15
- from scipy.signal.windows import hann as _hann
16
- scipy.signal.hann = _hann
17
-
18
- # Detect device
19
- use_cuda = torch.cuda.is_available()
20
- device = torch.device('cuda' if use_cuda else 'cpu')
21
- print(f"Using device: {device}")
22
-
23
- notes = ['C','C#','D','D#','E','F','F#','G','G#','A','A#','B']
24
-
25
- def download_from_gdrive(url):
26
- if "drive.google.com" not in url:
27
- raise ValueError("Not a valid Google Drive URL.")
28
- if "id=" in url:
29
- file_id = url.split("id=")[1].split("&")[0]
30
- else:
31
- file_id = url.split("/d/")[1].split("/")[0]
32
- download_url = f"https://drive.google.com/uc?export=download&id={file_id}"
33
- resp = requests.get(download_url, stream=True)
34
- if resp.status_code != 200:
35
- raise ValueError("Failed to download.")
36
- path = tempfile.NamedTemporaryFile(delete=False, suffix=".mp3").name
37
- with open(path, "wb") as f:
38
- shutil.copyfileobj(resp.raw, f)
39
- return path
40
-
41
- def analyze_single(path):
42
- # load audio
43
- y, sr = librosa.load(path, sr=None)
44
- # optionally use GPU tensor
45
- if use_cuda:
46
- y = torch.from_numpy(y).to(device).cpu().numpy()
47
- # compute duration
48
- duration = librosa.get_duration(y=y, sr=sr)
49
- m, s = divmod(int(duration), 60)
50
- # BPM
51
- onset_env = librosa.onset.onset_strength(y=y, sr=sr)
52
- tempo, _ = librosa.beat.beat_track(onset_envelope=onset_env, sr=sr)
53
- bpm = int(round(float(tempo)))
54
- # key detection
55
- chroma = librosa.feature.chroma_cqt(y=y, sr=sr)
56
- main_note = notes[int(np.mean(chroma, axis=1).argmax())]
57
- # tuning
58
- tuning = librosa.estimate_tuning(y=y, sr=sr)
59
- summary = (
60
- f"**{os.path.basename(path)}**\n\n"
61
- f"- Duration: {m}m{s}s ({duration:.2f}s)\n"
62
- f"- BPM: {bpm}\n"
63
- f"- Key: {main_note}\n"
64
- f"- Tuning offset: {tuning:.3f} semitones"
65
- )
66
- return summary, path
67
-
68
- def analyze_batch(files, gdrive_url):
69
- if files:
70
- paths = files
71
- elif gdrive_url.strip():
72
- paths = [download_from_gdrive(gdrive_url.strip())]
73
- else:
74
- return "⚠️ No input provided.", []
75
- # parallel analysis using all CPU cores
76
- with ThreadPoolExecutor(max_workers=os.cpu_count()) as exe:
77
- results = list(exe.map(analyze_single, paths))
78
- summaries, out_paths = zip(*results)
79
- return "\n\n---\n\n".join(summaries), list(out_paths)
80
-
81
- # Gradio UI
82
- with gr.Blocks(title="Beat Identifier", theme=gr.themes.Soft()) as demo:
83
- gr.Markdown("# Beat Identifier")
84
- gr.Markdown("Upload audio file(s) or paste a Google Drive share URL.")
85
- with gr.Row():
86
- with gr.Column():
87
- upload = gr.File(label="Upload Audio File(s)", file_count="multiple", file_types=["audio"])
88
- gdrive = gr.Textbox(label="Google Drive URL", placeholder="https://drive.google.com/...")
89
- btn = gr.Button("Analyze", variant="primary")
90
- with gr.Column():
91
- out_md = gr.Markdown("", label="Analysis Results")
92
- out_files = gr.File(label="Download / Play Files", file_count="multiple")
93
- btn.click(analyze_batch, inputs=[upload, gdrive], outputs=[out_md, out_files])
94
-
95
- # enable queue to avoid timeouts
96
- demo.queue(max_size=16)
97
-
98
- if __name__ == "__main__":
99
- demo.launch(server_name="0.0.0.0", server_port=7860)