File size: 2,265 Bytes
4b32b65
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import uuid
import pandas as pd
import gradio as gr

from faster_whisper import WhisperModel
from huggingface_hub import HfApi, upload_file

# =========================
# ENV
# =========================
HF_TOKEN = os.getenv("HF_TOKEN")
DATASET_REPO = os.getenv("DATASET_REPO")

# =========================
# LOAD MODEL
# =========================
model = WhisperModel("base")

# =========================
# TRANSCRIBE FUNCTION
# =========================
def transcribe_video(video_file):

    if video_file is None:
        return "No file uploaded.", None

    file_id = str(uuid.uuid4())[:8]

    segments, info = model.transcribe(
        video_file,
        beam_size=5
    )

    transcript = ""

    for segment in segments:
        transcript += f"[{segment.start:.2f} - {segment.end:.2f}] {segment.text}\n"

    # =========================
    # SAVE LOCAL TXT
    # =========================
    txt_name = f"transcript_{file_id}.txt"

    with open(txt_name, "w", encoding="utf-8") as f:
        f.write(transcript)

    # =========================
    # SAVE CSV METADATA
    # =========================
    csv_name = f"metadata_{file_id}.csv"

    df = pd.DataFrame([
        {
            "file_id": file_id,
            "original_file": os.path.basename(video_file),
            "transcript": transcript
        }
    ])

    df.to_csv(csv_name, index=False)

    # =========================
    # UPLOAD TO DATASET
    # =========================
    api = HfApi(token=HF_TOKEN)

    upload_file(
        path_or_fileobj=txt_name,
        path_in_repo=f"transcripts/{txt_name}",
        repo_id=DATASET_REPO,
        repo_type="dataset",
        token=HF_TOKEN,
    )

    upload_file(
        path_or_fileobj=csv_name,
        path_in_repo=f"metadata/{csv_name}",
        repo_id=DATASET_REPO,
        repo_type="dataset",
        token=HF_TOKEN,
    )

    return transcript, txt_name

# =========================
# UI
# =========================
app = gr.Interface(
    fn=transcribe_video,
    inputs=gr.Video(label="Upload Video"),
    outputs=[
        gr.Textbox(label="Transcript"),
        gr.File(label="Download TXT")
    ],
    title="AI Video Transcriber",
    description="Chinese + English AI transcription"
)

app.launch()