File size: 12,470 Bytes
0d862c9
 
 
beb1ab3
debd89e
0d862c9
 
 
 
 
 
 
 
a762f5a
0d862c9
 
 
 
 
 
 
 
 
 
 
 
 
 
a762f5a
0d862c9
53d8b6c
debd89e
0d862c9
 
 
 
 
5f1729b
0f36c12
 
 
 
 
 
 
 
 
b2e977e
0f36c12
 
 
 
 
 
 
 
0d862c9
a762f5a
0d862c9
36a1678
0d862c9
4947e5d
debd89e
0d862c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4947e5d
debd89e
0d862c9
 
 
 
 
 
 
 
 
 
36a1678
0d862c9
 
 
36a1678
0d862c9
 
 
 
 
 
 
 
 
 
 
36a1678
0d862c9
 
 
 
 
 
debd89e
f57efa9
 
0d862c9
 
 
 
f57efa9
 
0d862c9
 
 
 
 
 
f57efa9
0d862c9
 
 
f57efa9
 
 
 
0d862c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4947e5d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d5c54d1
 
 
 
 
 
 
 
 
 
1abd69d
 
d5c54d1
 
 
4947e5d
 
 
 
744c110
cdb5967
 
 
 
4947e5d
 
 
 
0d862c9
4947e5d
 
0d862c9
 
 
 
 
 
 
 
 
 
3dfd9b3
 
 
 
 
0d862c9
 
 
 
 
 
 
 
 
 
 
 
 
 
f57efa9
0d862c9
beb1ab3
f57efa9
 
0d862c9
f57efa9
 
0d862c9
 
 
f57efa9
0d862c9
beb1ab3
0d862c9
 
beb1ab3
0d862c9
 
7da7f34
0d862c9
 
beb1ab3
4947e5d
1abd69d
4947e5d
beb1ab3
 
0d862c9
f57efa9
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
import tempfile
from pathlib import Path

import gradio as gr
import spaces
from llama_cookbook.inference.model_utils import load_model as load_model_llamarecipes
from llama_cookbook.inference.model_utils import load_peft_model
from transformers import AutoTokenizer

from src.data.single_video import SingleVideo
from src.data.utils_asr import PromptASR
from src.models.llama_inference import inference
from src.test.vidchapters import get_chapters
from tools.download.models import download_base_model, download_model

# Set up proxies
# from urllib.request import getproxies
# proxies = getproxies()
# os.environ["HTTP_PROXY"] = os.environ["http_proxy"] = proxies["http"]
# os.environ["HTTPS_PROXY"] = os.environ["https_proxy"] = proxies["https"]
# os.environ["NO_PROXY"] = os.environ["no_proxy"] = "localhost, 127.0.0.1/8, ::1"

# Global variables to store loaded models
base_model = None
tokenizer = None
current_peft_model = None
inference_model = None

LLAMA_CKPT_PATH = "meta-llama/Meta-Llama-3.1-8B-Instruct"


@spaces.GPU
def load_base_model():
    """Load the base Llama model and tokenizer once at startup."""
    global base_model, tokenizer

    if base_model is None:
        print(f"Loading base model: {LLAMA_CKPT_PATH}")
        # base_model = load_model_llamarecipes(
        #     model_name=LLAMA_CKPT_PATH,
        #     device_map="auto",
        #     quantization=None,
        #     use_fast_kernels=True,
        # )
        # tokenizer = AutoTokenizer.from_pretrained(LLAMA_CKPT_PATH)
        # Try to get the local path using the download function
        model_path = download_base_model("lucas-ventura/chapter-llama", local_dir=".")
        model_path = f"/home/user/app/{LLAMA_CKPT_PATH}"
        print(f"Model path: {model_path}")
        base_model = load_model_llamarecipes(
            model_name=model_path,
            device_map="auto",
            quantization=None,
            use_fast_kernels=True,
        )
        tokenizer = AutoTokenizer.from_pretrained(model_path)

        base_model.eval()
        tokenizer.pad_token = tokenizer.eos_token
        print("Base model loaded successfully")


@spaces.GPU
class FastLlamaInference:
    def __init__(
        self,
        model,
        add_special_tokens: bool = True,
        temperature: float = 1.0,
        max_new_tokens: int = 1024,
        top_p: float = 1.0,
        top_k: int = 50,
        use_cache: bool = True,
        max_padding_length: int = None,
        do_sample: bool = False,
        min_length: int = None,
        repetition_penalty: float = 1.0,
        length_penalty: int = 1,
        max_prompt_tokens: int = 35_000,
    ):
        self.model = model
        self.tokenizer = tokenizer
        self.add_special_tokens = add_special_tokens
        self.temperature = temperature
        self.max_new_tokens = max_new_tokens
        self.top_p = top_p
        self.top_k = top_k
        self.use_cache = use_cache
        self.max_padding_length = max_padding_length
        self.do_sample = do_sample
        self.min_length = min_length
        self.repetition_penalty = repetition_penalty
        self.length_penalty = length_penalty
        self.max_prompt_tokens = max_prompt_tokens

    def __call__(self, prompt: str, **kwargs):
        # Create a dict of default parameters from instance attributes
        params = {
            "model": self.model,
            "tokenizer": self.tokenizer,
            "prompt": prompt,
            "add_special_tokens": self.add_special_tokens,
            "temperature": self.temperature,
            "max_new_tokens": self.max_new_tokens,
            "top_p": self.top_p,
            "top_k": self.top_k,
            "use_cache": self.use_cache,
            "max_padding_length": self.max_padding_length,
            "do_sample": self.do_sample,
            "min_length": self.min_length,
            "repetition_penalty": self.repetition_penalty,
            "length_penalty": self.length_penalty,
            "max_prompt_tokens": self.max_prompt_tokens,
        }

        # Update with any overrides passed in kwargs
        params.update(kwargs)

        return inference(**params)


@spaces.GPU
def load_peft(model_name: str = "asr-10k"):
    """Load or switch PEFT model while reusing the base model."""
    global base_model, current_peft_model, inference_model

    # First make sure the base model is loaded
    if base_model is None:
        load_base_model()

    # Only load a new PEFT model if it's different from the current one
    if current_peft_model != model_name:
        print(f"Loading PEFT model: {model_name}")
        model_path = download_model(model_name)

        if not Path(model_path).exists():
            print(f"PEFT model does not exist at {model_path}")
            return False

        # Apply the PEFT model to the base model
        peft_model = load_peft_model(base_model, model_path)

        peft_model.eval()

        # Create the inference wrapper
        inference_model = FastLlamaInference(model=peft_model)
        current_peft_model = model_name

        print(f"PEFT model {model_name} loaded successfully")
        return True

    # Model already loaded
    return True


@spaces.GPU
def process_video(video_file, model_name: str = "asr-10k", do_sample: bool = False):
    """Process a video file and generate chapters."""
    progress = gr.Progress()
    progress(0, desc="Starting...")

    # Check if we have a valid input
    if video_file is None:
        return "Please upload a video file."

    # Load the PEFT model
    progress(0.1, desc=f"Loading LoRA parameters from {model_name}...")
    if not load_peft(model_name):
        return "Failed to load model. Please try again."

    # Create a temporary directory to save the uploaded video
    with tempfile.TemporaryDirectory() as temp_dir:
        temp_video_path = Path(temp_dir) / "temp_video.mp4"

        # Using uploaded file
        progress(0.2, desc="Processing uploaded video...")
        with open(temp_video_path, "wb") as f:
            f.write(video_file)

        # Process the video
        progress(0.3, desc="Extracting ASR transcript...")
        single_video = SingleVideo(temp_video_path)
        progress(0.4, desc="Creating prompt...")
        prompt = PromptASR(chapters=single_video)

        vid_id = single_video.video_ids[0]
        progress(0.5, desc="Creating prompt...")
        prompt = prompt.get_prompt_test(vid_id)

        transcript = single_video.get_asr(vid_id)
        prompt = prompt + transcript

        progress(0.6, desc="Generating chapters with Chapter-Llama...")
        _, chapters = get_chapters(
            inference_model,
            prompt,
            max_new_tokens=1024,
            do_sample=do_sample,
            vid_id=vid_id,
        )

        # Format the output
        progress(0.9, desc="Formatting results...")
        output = ""
        for timestamp, text in chapters.items():
            output += f"{timestamp}: {text}\n"

        progress(1.0, desc="Complete!")
        return output


# CSS for the submit button color
head = """
<head>
    <title>Chapter-Llama - VidChapters</title>
    <link rel="icon" type="image/x-icon" href="./favicon.ico">
</head>
"""

title_markdown = """
<div style="display: flex; justify-content: space-between; align-items: center; background: linear-gradient(90deg, rgba(72,219,251,0.1), rgba(29,209,161,0.1)); border-radius: 20px; box-shadow: 0 4px 6px rgba(0,0,0,0.1); padding: 20px; margin-bottom: 20px;">
    <div style="display: flex; align-items: center;">
        <a href="https://github.com/lucas-ventura/chapter-llama" style="margin-right: 20px; text-decoration: none; display: flex; align-items: center;">
            <img src="https://imagine.enpc.fr/~lucas.ventura/chapter-llama/images/chapter-llama.png" alt="Chapter-Llama" style="max-width: 100px; height: auto; border-radius: 15px; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
        </a>
        <div>
            <h1 style="margin: 0; background: linear-gradient(90deg, #8F68C3, #477EF4); -webkit-background-clip: text; -webkit-text-fill-color: transparent; font-size: 2.5em; font-weight: 700;">Chapter-Llama</h1>
            <h2 style="margin: 10px 0; background: linear-gradient(90deg, #8F68C3, #477EF4); -webkit-background-clip: text; -webkit-text-fill-color: transparent; font-size: 1.8em; font-weight: 600;">Efficient Chaptering in Hour-Long Videos with LLMs</h2>           
            <div style="display: flex; gap: 15px; margin-top: 10px;">
                <a href="https://github.com/lucas-ventura/chapter-llama" style="text-decoration: none; color: #8F68C3; font-weight: 500; transition: color 0.3s;">GitHub</a> |
                <a href="https://imagine.enpc.fr/~lucas.ventura/chapter-llama/" style="text-decoration: none; color: #8F68C3; font-weight: 500; transition: color 0.3s;">Project Page</a> |
                <a href="https://arxiv.org/abs/2504.00072" style="text-decoration: none; color: #8F68C3; font-weight: 500; transition: color 0.3s;">Paper</a>
            </div>
        </div>
    </div>
    <div style="text-align: right; margin-left: 20px;">
        <h2 style="margin: 10px 0; color: #24467C; font-weight: 700; font-size: 2.5em;">CVPR 2025</h2>
    </div>
</div>
"""

note_html = """
<div style="background-color: #f9f9f9; border-left: 5px solid #48dbfb; padding: 20px; margin-top: 20px; border-radius: 10px; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);">
    <p style="font-size: 1.1em; color: #ff9933; margin-bottom: 10px; font-weight: bold;">Note: If you encounter any errors with this demo, you can run the code locally using the following commands:</p>
    <pre style="background-color: #f1f1f1; padding: 15px; border-radius: 5px; overflow-x: auto;">
# Clone the repository
git clone https://github.com/lucas-ventura/chapter-llama.git
cd chapter-llama
# Install demo dependencies
python -m pip install -e ".[demo]"
# Launch the demo
python demo.py</pre>
<p style="font-size: 1.1em; color: #555; margin-bottom: 10px;">If you find any issues, please report them on our <a href="https://github.com/lucas-ventura/chapter-llama/issues" style="color: #8F68C3; text-decoration: none;">GitHub repository</a>.</p>
</div>
"""

# Citation from demo_sample.py
bibtext = """
### Citation
```
@InProceedings{ventura25chapter,
  title     = {{Chapter-Llama}: Efficient Chaptering in Hour-Long Videos with {LLM}s},
  author    = {Lucas Ventura and Antoine Yang and Cordelia Schmid and G{\"u}l Varol},
  booktitle = {CVPR},
  year      = {2025}
}
```
"""

# Create the Gradio interface
with gr.Blocks(title="Chapter-Llama", head=head) as demo:
    gr.HTML(title_markdown)
    gr.Markdown(
        """
        This demo is currently using only the audio data (ASR), without frame information. 
        We will add audio+captions functionality in the near future, which will improve 
        chapter generation by incorporating visual content.
        """
    )

    with gr.Row():
        with gr.Column():
            video_input = gr.File(
                label="Upload Video or Audio File",
                file_types=["video", "audio"],
                type="binary",
            )

            model_dropdown = gr.Dropdown(
                choices=["asr-10k", "asr-1k"],
                value="asr-10k",
                label="Select Model",
            )
            do_sample = gr.Checkbox(
                label="Use random sampling", value=False, interactive=True
            )
            submit_btn = gr.Button("Generate Chapters")

        with gr.Column():
            status_area = gr.Markdown("**Status:** Ready to process video")
            output_text = gr.Textbox(
                label="Generated Chapters", lines=10, interactive=False
            )

    def update_status_and_process(video_file, model_name, do_sample):
        if video_file is None:
            return (
                "**Status:** No video uploaded",
                "Please upload a video file.",
            )
        else:
            return "**Status:** Processing video...", process_video(
                video_file, model_name, do_sample
            )

    # Load the base model at startup
    load_base_model()

    submit_btn.click(
        fn=update_status_and_process,
        inputs=[video_input, model_dropdown, do_sample],
        outputs=[status_area, output_text],
    )

    gr.Markdown(bibtext)
    gr.HTML(note_html)


if __name__ == "__main__":
    # Launch the Gradio app
    demo.launch()