Spaces:
Sleeping
Sleeping
Download app.py from devil001115/craftiq-studio: direct link, hf CLI and curl.
- Browser
- Download file 8.38 kB
-
https://huggingface.co/spaces/devil001115/craftiq-studio/resolve/main/app.py
- Command line
-
hf download hf://spaces/devil001115/craftiq-studio/app.py
-
curl -L -o app.py https://huggingface.co/spaces/devil001115/craftiq-studio/resolve/main/app.py
8.38 kB
| import os | |
| import re | |
| import subprocess | |
| import numpy as np | |
| import spaces | |
| import gradio as gr | |
| from faster_whisper import WhisperModel | |
| # 1. PRE-DOWNLOAD MODEL WEIGHTS AT STARTUP | |
| print("Loading Craftiq Lab 24/7 Cloud Engine...") | |
| _warmup = WhisperModel("small", device="cpu", compute_type="int8") | |
| del _warmup | |
| print("CRAFTIQ 24/7 ENGINE READY!") | |
| # 2. UNIVERSAL AUDIO LOADER | |
| def load_audio_official(file_path: str) -> np.ndarray: | |
| try: | |
| cmd = [ | |
| "ffmpeg", "-nostdin", "-threads", "0", "-i", file_path, | |
| "-f", "s16le", "-ac", "1", "-acodec", "pcm_s16le", "-ar", "16000", "-" | |
| ] | |
| out = subprocess.run(cmd, capture_output=True, check=True).stdout | |
| return np.frombuffer(out, np.int16).flatten().astype(np.float32) / 32768.0 | |
| except Exception: | |
| from faster_whisper.audio import decode_audio | |
| return decode_audio(file_path, sampling_rate=16000) | |
| # 3. DEVANAGARI TO CLEAN ROMAN HINGLISH CONVERTER | |
| VOWELS = { | |
| 'अ': 'a', 'आ': 'aa', 'इ': 'i', 'ई': 'ee', 'उ': 'u', 'ऊ': 'oo', | |
| 'ऋ': 'ri', 'ए': 'e', 'ऐ': 'ai', 'ओ': 'o', 'औ': 'au', 'अं': 'an', 'अः': 'ah' | |
| } | |
| MATRAS = { | |
| 'ा': 'a', 'ि': 'i', 'ी': 'ee', 'ु': 'u', 'ू': 'oo', 'ृ': 'ri', | |
| 'े': 'e', 'ै': 'ai', 'ो': 'o', 'ौ': 'au', 'ं': 'n', 'ँ': 'n', 'ः': 'h' | |
| } | |
| CONSONANTS = { | |
| 'क': 'k', 'ख': 'kh', 'ग': 'g', 'घ': 'gh', 'ङ': 'ng', | |
| 'च': 'ch', 'छ': 'chh', 'ज': 'j', 'झ': 'jh', 'ञ': 'ny', | |
| 'ट': 't', 'ठ': 'th', 'ड': 'd', 'ढ': 'dh', 'ण': 'n', | |
| 'त': 't', 'थ': 'th', 'द': 'd', 'ध': 'dh', 'न': 'n', | |
| 'प': 'p', 'फ': 'f', 'ब': 'b', 'भ': 'bh', 'म': 'm', | |
| 'य': 'y', 'र': 'r', 'ल': 'l', 'व': 'v', 'श': 'sh', 'ष': 'sh', 'स': 's', 'ह': 'h', | |
| 'ड़': 'r', 'ढ़': 'rh', 'ज़': 'z', 'फ़': 'f', 'क़': 'q', 'ख़': 'kh', 'ग़': 'gh' | |
| } | |
| def to_hinglish(text): | |
| if not any('\u0900' <= ch <= '\u097f' for ch in text): | |
| return text | |
| words = text.split() | |
| out = [] | |
| for word in words: | |
| cw = "" | |
| i = 0 | |
| n = len(word) | |
| while i < n: | |
| ch = word[i] | |
| if ch in VOWELS: | |
| cw += VOWELS[ch] | |
| i += 1 | |
| elif ch in CONSONANTS: | |
| base = CONSONANTS[ch] | |
| if i + 1 < n and word[i + 1] in MATRAS: | |
| cw += base + MATRAS[word[i + 1]] | |
| i += 2 | |
| elif i + 1 < n and word[i + 1] == '्': | |
| cw += base | |
| i += 2 | |
| else: | |
| cw += base if i + 1 == n else base + 'a' | |
| i += 1 | |
| elif ch in MATRAS: | |
| cw += MATRAS[ch] | |
| i += 1 | |
| else: | |
| cw += ch | |
| i += 1 | |
| out.append(cw) | |
| res = " ".join(out) | |
| res = re.sub(r'\bkae\b', 'ke', res) | |
| res = re.sub(r'\bhae\b', 'hai', res) | |
| res = re.sub(r'\bhaen\b', 'hain', res) | |
| res = re.sub(r'\bme\b', 'mein', res) | |
| return res | |
| def format_srt_time(seconds): | |
| seconds = max(0.0, float(seconds)) | |
| hours = int(seconds // 3600) | |
| minutes = int((seconds % 3600) // 60) | |
| secs = int(seconds % 60) | |
| millis = int(round((seconds - int(seconds)) * 1000)) | |
| if millis >= 1000: | |
| millis = 999 | |
| return f"{hours:02d}:{minutes:02d}:{secs:02d},{millis:03d}" | |
| # 4. SUBTITLE GENERATION PIPELINE (WITH @spaces.GPU) | |
| def process_craftiq_audio(media_file, target_lang, pacing_seconds): | |
| if not media_file: | |
| return "❌ Kripya pehle audio ya video file upload karein.", None | |
| try: | |
| try: | |
| craftiq_model = WhisperModel("small", device="cuda", compute_type="float16") | |
| except Exception: | |
| craftiq_model = WhisperModel("small", device="cpu", compute_type="int8", cpu_threads=4) | |
| is_hindi = (target_lang == "Hindi") | |
| lang_code = "hi" if is_hindi else "en" | |
| prompt = "Aap kaise ho? Main theek hoon. Ye video subtitles ke liye hai." if is_hindi else None | |
| audio_data = load_audio_official(media_file) | |
| segments, info = craftiq_model.transcribe( | |
| audio_data, | |
| language=lang_code, | |
| task="transcribe", | |
| initial_prompt=prompt, | |
| word_timestamps=True, | |
| beam_size=1, | |
| vad_filter=True | |
| ) | |
| words_data = [] | |
| for segment in segments: | |
| seg_s = segment.start if segment.start is not None else 0.0 | |
| seg_e = segment.end if segment.end is not None else (seg_s + 2.0) | |
| if segment.words: | |
| for w in segment.words: | |
| ws = w.start if (w.start is not None) else seg_s | |
| we = w.end if (w.end is not None) else seg_e | |
| wt = w.word.strip() if w.word else "" | |
| if wt: | |
| words_data.append({"start": ws, "end": we, "word": wt}) | |
| else: | |
| raw_words = segment.text.strip().split() | |
| if raw_words: | |
| dur = max(0.1, seg_e - seg_s) | |
| step = dur / len(raw_words) | |
| for idx, rw in enumerate(raw_words): | |
| words_data.append({ | |
| "start": seg_s + idx * step, | |
| "end": seg_s + (idx + 1) * step, | |
| "word": rw | |
| }) | |
| if not words_data: | |
| return "❌ Audio me koi aawaz detect nahi hui.", None | |
| chunks = [] | |
| cur_words = [] | |
| cur_s = None | |
| cur_e = None | |
| target_dur = float(pacing_seconds) | |
| for w in words_data: | |
| if cur_s is None: | |
| cur_s = w["start"] | |
| cur_words.append(w["word"]) | |
| cur_e = w["end"] | |
| dur = cur_e - cur_s | |
| ends_punct = any(w["word"].endswith(p) for p in ['.', '?', '!', '।', '॥', ',']) | |
| if dur >= target_dur or (ends_punct and dur >= target_dur * 0.7): | |
| line = " ".join(cur_words).strip() | |
| if is_hindi: | |
| line = to_hinglish(line) | |
| if line: | |
| chunks.append({"start": cur_s, "end": cur_e, "text": line}) | |
| cur_words = [] | |
| cur_s = None | |
| cur_e = None | |
| if cur_words and cur_s is not None: | |
| line = " ".join(cur_words).strip() | |
| if is_hindi: | |
| line = to_hinglish(line) | |
| if line: | |
| chunks.append({"start": cur_s, "end": cur_e or (cur_s + 1.0), "text": line}) | |
| srt_lines = [] | |
| for idx, chunk in enumerate(chunks, 1): | |
| srt_lines.append( | |
| f"{idx}\n{format_srt_time(chunk['start'])} --> {format_srt_time(chunk['end'])}\n{chunk['text']}\n" | |
| ) | |
| full_srt = "\n".join(srt_lines) | |
| output_path = os.path.abspath("CraftiqLab_Subtitles.srt") | |
| with open(output_path, "w", encoding="utf-8") as f: | |
| f.write(full_srt) | |
| return full_srt, output_path | |
| except Exception as e: | |
| return f"❌ Error: {str(e)}", None | |
| # 5. GRADIO 6 COMPATIBLE UI | |
| with gr.Blocks(title="Craftiq Lab") as demo: | |
| gr.Markdown("# 🎙️ Craftiq Lab - 24/7 AI Subtitle Studio") | |
| gr.Markdown("Audio upload karein, language chunein aur 1-click me .SRT file download karein.") | |
| with gr.Row(): | |
| with gr.Column(): | |
| audio_input = gr.Audio(type="filepath", label="📂 Upload Audio / Video") | |
| lang_choice = gr.Radio( | |
| ["Hindi", "English"], | |
| value="Hindi", | |
| label="🌐 Audio Language" | |
| ) | |
| pacing_slider = gr.Slider( | |
| minimum=3, | |
| maximum=15, | |
| step=1, | |
| value=5, | |
| label="⏱️ Subtitle Cut Pacing (Seconds per line)" | |
| ) | |
| generate_btn = gr.Button("✨ Generate Subtitles", variant="primary") | |
| with gr.Column(): | |
| srt_preview = gr.Textbox(lines=14, label="📝 Subtitle Preview (.SRT)") | |
| download_file = gr.File(label="⬇️ Download .SRT File") | |
| generate_btn.click( | |
| fn=process_craftiq_audio, | |
| inputs=[audio_input, lang_choice, pacing_slider], | |
| outputs=[srt_preview, download_file] | |
| ) | |
| demo.launch() |