main 28bba6cae2ce cached
6 files
33.8 KB
8.0k tokens
7 symbols
1 requests
Download .txt
Repository: win4r/VideoFinder-Llama3.2-vision-Ollama
Branch: main
Commit: 28bba6cae2ce
Files: 6
Total size: 33.8 KB

Directory structure:
gitextract_jcwsfxlv/

├── LICENSE
├── README.md
├── app.py
├── main.py
├── requirements.txt
└── templates/
    └── index.html

================================================
FILE CONTENTS
================================================

================================================
FILE: LICENSE
================================================
                                 Apache License
                           Version 2.0, January 2004
                        http://www.apache.org/licenses/

   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

   1. Definitions.

      "License" shall mean the terms and conditions for use, reproduction,
      and distribution as defined by Sections 1 through 9 of this document.

      "Licensor" shall mean the copyright owner or entity authorized by
      the copyright owner that is granting the License.

      "Legal Entity" shall mean the union of the acting entity and all
      other entities that control, are controlled by, or are under common
      control with that entity. For the purposes of this definition,
      "control" means (i) the power, direct or indirect, to cause the
      direction or management of such entity, whether by contract or
      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      outstanding shares, or (iii) beneficial ownership of such entity.

      "You" (or "Your") shall mean an individual or Legal Entity
      exercising permissions granted by this License.

      "Source" form shall mean the preferred form for making modifications,
      including but not limited to software source code, documentation
      source, and configuration files.

      "Object" form shall mean any form resulting from mechanical
      transformation or translation of a Source form, including but
      not limited to compiled object code, generated documentation,
      and conversions to other media types.

      "Work" shall mean the work of authorship, whether in Source or
      Object form, made available under the License, as indicated by a
      copyright notice that is included in or attached to the work
      (an example is provided in the Appendix below).

      "Derivative Works" shall mean any work, whether in Source or Object
      form, that is based on (or derived from) the Work and for which the
      editorial revisions, annotations, elaborations, or other modifications
      represent, as a whole, an original work of authorship. For the purposes
      of this License, Derivative Works shall not include works that remain
      separable from, or merely link (or bind by name) to the interfaces of,
      the Work and Derivative Works thereof.

      "Contribution" shall mean any work of authorship, including
      the original version of the Work and any modifications or additions
      to that Work or Derivative Works thereof, that is intentionally
      submitted to Licensor for inclusion in the Work by the copyright owner
      or by an individual or Legal Entity authorized to submit on behalf of
      the copyright owner. For the purposes of this definition, "submitted"
      means any form of electronic, verbal, or written communication sent
      to the Licensor or its representatives, including but not limited to
      communication on electronic mailing lists, source code control systems,
      and issue tracking systems that are managed by, or on behalf of, the
      Licensor for the purpose of discussing and improving the Work, but
      excluding communication that is conspicuously marked or otherwise
      designated in writing by the copyright owner as "Not a Contribution."

      "Contributor" shall mean Licensor and any individual or Legal Entity
      on behalf of whom a Contribution has been received by Licensor and
      subsequently incorporated within the Work.

   2. Grant of Copyright License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      copyright license to reproduce, prepare Derivative Works of,
      publicly display, publicly perform, sublicense, and distribute the
      Work and such Derivative Works in Source or Object form.

   3. Grant of Patent License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      (except as stated in this section) patent license to make, have made,
      use, offer to sell, sell, import, and otherwise transfer the Work,
      where such license applies only to those patent claims licensable
      by such Contributor that are necessarily infringed by their
      Contribution(s) alone or by combination of their Contribution(s)
      with the Work to which such Contribution(s) was submitted. If You
      institute patent litigation against any entity (including a
      cross-claim or counterclaim in a lawsuit) alleging that the Work
      or a Contribution incorporated within the Work constitutes direct
      or contributory patent infringement, then any patent licenses
      granted to You under this License for that Work shall terminate
      as of the date such litigation is filed.

   4. Redistribution. You may reproduce and distribute copies of the
      Work or Derivative Works thereof in any medium, with or without
      modifications, and in Source or Object form, provided that You
      meet the following conditions:

      (a) You must give any other recipients of the Work or
          Derivative Works a copy of this License; and

      (b) You must cause any modified files to carry prominent notices
          stating that You changed the files; and

      (c) You must retain, in the Source form of any Derivative Works
          that You distribute, all copyright, patent, trademark, and
          attribution notices from the Source form of the Work,
          excluding those notices that do not pertain to any part of
          the Derivative Works; and

      (d) If the Work includes a "NOTICE" text file as part of its
          distribution, then any Derivative Works that You distribute must
          include a readable copy of the attribution notices contained
          within such NOTICE file, excluding those notices that do not
          pertain to any part of the Derivative Works, in at least one
          of the following places: within a NOTICE text file distributed
          as part of the Derivative Works; within the Source form or
          documentation, if provided along with the Derivative Works; or,
          within a display generated by the Derivative Works, if and
          wherever such third-party notices normally appear. The contents
          of the NOTICE file are for informational purposes only and
          do not modify the License. You may add Your own attribution
          notices within Derivative Works that You distribute, alongside
          or as an addendum to the NOTICE text from the Work, provided
          that such additional attribution notices cannot be construed
          as modifying the License.

      You may add Your own copyright statement to Your modifications and
      may provide additional or different license terms and conditions
      for use, reproduction, or distribution of Your modifications, or
      for any such Derivative Works as a whole, provided Your use,
      reproduction, and distribution of the Work otherwise complies with
      the conditions stated in this License.

   5. Submission of Contributions. Unless You explicitly state otherwise,
      any Contribution intentionally submitted for inclusion in the Work
      by You to the Licensor shall be under the terms and conditions of
      this License, without any additional terms or conditions.
      Notwithstanding the above, nothing herein shall supersede or modify
      the terms of any separate license agreement you may have executed
      with Licensor regarding such Contributions.

   6. Trademarks. This License does not grant permission to use the trade
      names, trademarks, service marks, or product names of the Licensor,
      except as required for reasonable and customary use in describing the
      origin of the Work and reproducing the content of the NOTICE file.

   7. Disclaimer of Warranty. Unless required by applicable law or
      agreed to in writing, Licensor provides the Work (and each
      Contributor provides its Contributions) on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      implied, including, without limitation, any warranties or conditions
      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      PARTICULAR PURPOSE. You are solely responsible for determining the
      appropriateness of using or redistributing the Work and assume any
      risks associated with Your exercise of permissions under this License.

   8. Limitation of Liability. In no event and under no legal theory,
      whether in tort (including negligence), contract, or otherwise,
      unless required by applicable law (such as deliberate and grossly
      negligent acts) or agreed to in writing, shall any Contributor be
      liable to You for damages, including any direct, indirect, special,
      incidental, or consequential damages of any character arising as a
      result of this License or out of the use or inability to use the
      Work (including but not limited to damages for loss of goodwill,
      work stoppage, computer failure or malfunction, or any and all
      other commercial damages or losses), even if such Contributor
      has been advised of the possibility of such damages.

   9. Accepting Warranty or Additional Liability. While redistributing
      the Work or Derivative Works thereof, You may choose to offer,
      and charge a fee for, acceptance of support, warranty, indemnity,
      or other liability obligations and/or rights consistent with this
      License. However, in accepting such obligations, You may act only
      on Your own behalf and on Your sole responsibility, not on behalf
      of any other Contributor, and only if You agree to indemnify,
      defend, and hold each Contributor harmless for any liability
      incurred by, or claims asserted against, such Contributor by reason
      of your accepting any such warranty or additional liability.

   END OF TERMS AND CONDITIONS

   APPENDIX: How to apply the Apache License to your work.

      To apply the Apache License to your work, attach the following
      boilerplate notice, with the fields enclosed by brackets "[]"
      replaced with your own identifying information. (Don't include
      the brackets!)  The text should be enclosed in the appropriate
      comment syntax for the file format. We also recommend that a
      file or class name and description of purpose be included on the
      same "printed page" as the copyright notice for easier
      identification within third-party archives.

   Copyright [yyyy] [name of copyright owner]

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.


================================================
FILE: README.md
================================================
# VideoFinder

# 作者微信:stoeng

[English](#english) | [中文](#中文)



# English

## video:https://youtu.be/t5q4fT4rKK4

## 🔍 About VideoFinder
VideoFinder is an intelligent video analysis tool that leverages multimodal AI models to detect and locate specific objects or people in videos. Built with FastAPI and integrated with the Llama Vision model, it provides a user-friendly web interface for video analysis tasks.

## ✨ Features
- Upload and analyze videos through an intuitive web interface
- Real-time frame-by-frame analysis using multimodal AI
- Natural language object description support
- Visual results display with confidence scores
- Image preprocessing for better detection accuracy
- Streaming response for real-time analysis feedback

## 🚀 Getting Started

### Prerequisites
- Python 3.8+
- Ollama with Llama Vision model installed
- OpenCV

### Installation

1. Clone the repository
```bash
git clone https://github.com/win4r/VideoFinder-Llama3.2-vision-Ollama.git
cd VideoFinder
```

2. Install dependencies
```bash
pip install -r requirements.txt
```

3. Make sure Ollama is running with Llama Vision model
```bash
ollama run llama3.2-vision
```

4. Start the application
```bash
python main.py
```

5. Access the web interface at `http://localhost:8000`

## 🛠️ Usage
1. Open the web interface
2. Upload a video file
3. Enter a description of the object/person you want to find
4. Click "Start Analysis"
5. View results as they appear in real-time

## 📦 Dependencies
- FastAPI
- OpenCV
- Ollama
- Jinja2
- uvicorn

# 中文

## 演示视频:https://youtu.be/t5q4fT4rKK4

## 🔍 关于 VideoFinder
VideoFinder 是一个智能视频分析工具,利用多模态AI模型来检测和定位视频中的特定物体或人物。该工具基于 FastAPI 构建,集成了 Llama Vision 模型,提供了友好的 Web 界面进行视频分析任务。

## ✨ 特性
- 通过直观的网页界面上传和分析视频
- 使用多模态 AI 进行实时逐帧分析
- 支持自然语言目标描述
- 可视化结果显示与置信度评分
- 图像预处理以提高检测准确率
- 流式响应实现实时分析反馈

## 🚀 快速开始

### 环境要求
- Python 3.8+
- 安装了 Llama Vision 模型的 Ollama
- OpenCV

### 安装步骤

1. 克隆仓库
```bash
git clone https://github.com/win4r/VideoFinder-Llama3.2-vision-Ollama.git
cd VideoFinder
```

2. 安装依赖
```bash
pip install -r requirements.txt
```

3. 确保 Ollama 已运行并加载 Llama Vision 模型
```bash
ollama run llama3.2-vision
```

4. 启动应用
```bash
python main.py
```

5. 访问 `http://localhost:8000` 打开 Web 界面

## 🛠️ 使用方法
1. 打开 Web 界面
2. 上传视频文件
3. 输入要查找的目标描述
4. 点击"开始分析"
5. 实时查看分析结果

## 📦 依赖项
- FastAPI
- OpenCV
- Ollama
- Jinja2
- uvicorn


================================================
FILE: app.py
================================================
import cv2
import os
import ollama
import time


def analyze_image(image_path, object_str):
    """
    分析单张图像,检测是否存在目标对象
    Args:
        image_path: 图像文件路径
        object_str: 要检测的目标对象描述

    Returns:
        tuple: (是否匹配, 描述文本, 置信度)
    """
    prompt_str = f"""Please analyze the image and answer the following questions:

1. Is there a {object_str} in the image?
2. If yes, describe its appearance and location in the image in detail.
3. If no, describe what you see in the image instead.
4. On a scale of 1-10, how confident are you in your answer?

Please structure your response as follows:
Answer: [YES/NO]
Description: [Your detailed description]
Confidence: [1-10]"""

    try:
        # 调用llama模型分析图像
        response = ollama.chat(
            model='llama3.2-vision',
            messages=[
                {
                    'role': 'user',
                    'content': prompt_str,
                    'images': [image_path]
                }
            ]
        )

        print(f"等待模型分析中...")
        time.sleep(1)  # 短暂延迟确保响应完整

        # 获取并打印原始响应
        response_text = response['message']['content']
        print(f"Raw response: {response_text}")

        # 处理响应文本,移除Markdown格式符号
        response_text = response_text.replace('**', '')
        response_lines = response_text.strip().split('\n')

        # 从响应中提取关键信息
        answer = None
        description = None
        confidence = 10  # 默认置信度为10,因为模型没有明确返回置信度

        # 逐行解析响应内容
        for line in response_lines:
            line = line.strip()
            if line.lower().startswith('answer:'):
                answer = line.split(':', 1)[1].strip().upper()
            # 同时匹配Description、Reasoning和Alternative Description
            elif any(line.lower().startswith(prefix) for prefix in
                     ['description:', 'reasoning:', 'alternative description:']):
                description = line.split(':', 1)[1].strip()
            elif line.lower().startswith('confidence:'):
                try:
                    confidence = int(line.split(':', 1)[1].strip())
                except ValueError:
                    confidence = 10  # 如果无法解析置信度,使用默认值

        # 检查是否获取到必要的信息
        if answer is None or description is None:
            raise ValueError("Response format is incomplete")

        print(f"解析结果 - 答案: {answer}, 描述: {description}, 置信度: {confidence}")

        # 返回分析结果
        return answer == "YES" and confidence >= 7, description, confidence
    except Exception as e:
        print(f"Error during image analysis: {e}")
        import traceback
        print(traceback.format_exc())
        return False, "Error occurred", 0


def preprocess_image(image_path):
    """
    图像预处理函数,增强图像质量
    Args:
        image_path: 图像文件路径
    """
    # 读取图像
    img = cv2.imread(image_path)
    if img is None:
        print(f"Error: Could not read image at {image_path}")
        return

    # 转换颜色空间并进行对比度增强
    lab = cv2.cvtColor(img, cv2.COLOR_BGR2LAB)
    l, a, b = cv2.split(lab)
    clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
    cl = clahe.apply(l)
    limg = cv2.merge((cl, a, b))
    final = cv2.cvtColor(limg, cv2.COLOR_LAB2BGR)

    # 保存处理后的图像
    cv2.imwrite(image_path, final, [cv2.IMWRITE_JPEG_QUALITY, 100])


def extract_and_analyze_frames(video_path, output_folder, object_str):
    """
    从视频中提取帧并分析是否包含目标对象
    Args:
        video_path: 视频文件路径
        output_folder: 帧图像保存文件夹
        object_str: 要检测的目标对象描述

    Returns:
        int or None: 找到目标的时间点(秒),未找到返回None
    """
    # 创建输出目录
    if not os.path.exists(output_folder):
        os.makedirs(output_folder)

    # 打开视频文件
    video = cv2.VideoCapture(video_path)
    if not video.isOpened():
        print(f"Error: Could not open video at {video_path}")
        return None

    # 获取视频FPS
    fps = int(video.get(cv2.CAP_PROP_FPS))
    frame_count = 0
    consecutive_matches = 0
    match_threshold = 1  # 连续匹配阈值
    cool_down_time = 2  # 每帧分析后的冷却时间(秒)

    print(f"开始分析视频,FPS: {fps}")

    try:
        while True:
            # 读取视频帧
            success, frame = video.read()
            if not success:
                break

            # 每秒处理一帧
            if frame_count % fps == 0:
                print(f"\n处理第 {frame_count // fps} 秒的帧")

                # 保存当前帧
                output_filename = os.path.join(output_folder, f"frame_{frame_count // fps}.jpg")
                output_filename = os.path.abspath(output_filename)

                cv2.imwrite(output_filename, frame)
                print(f"已保存帧到: {output_filename}")

                # 预处理图像
                preprocess_image(output_filename)
                print("已完成图像预处理")

                print("开始分析图像...")
                print(f"使用图像路径: {output_filename}")

                # 检查文件是否存在
                if not os.path.exists(output_filename):
                    print(f"警告: 文件不存在: {output_filename}")
                    continue

                # 分析图像
                is_match, description, confidence = analyze_image(output_filename, object_str)
                print(f"分析完成 - 匹配: {is_match}, 置信度: {confidence}")
                print(f"描述: {description}")

                # 处理匹配结果
                if is_match:
                    consecutive_matches += 1
                    print(f"潜在匹配 - 时间: 第 {frame_count // fps} 秒")
                    print(f"描述: {description}")
                    print(f"置信度: {confidence}")

                    # 如果连续匹配次数达到阈值,返回结果并退出
                    if consecutive_matches >= match_threshold:
                        match_time = frame_count // fps - match_threshold + 1
                        print(f"找到连续匹配!时间: 第 {match_time} 秒到第 {frame_count // fps} 秒")
                        video.release()  # 释放视频资源
                        return match_time  # 直接返回结果
                else:
                    consecutive_matches = 0

                # 分析完一帧后的冷却时间
                print(f"等待 {cool_down_time} 秒进行显卡冷却...")
                time.sleep(cool_down_time)

            frame_count += 1

    finally:
        # 确保视频资源被释放
        video.release()

    print(f"未找到匹配的图像。共分析了 {frame_count // fps} 张图像。")
    return None


# 主程序入口
if __name__ == "__main__":
    # 设置参数
    video_path = "./a.mp4"
    output_folder = "output_frames"
    object_to_find = "A man riding a bicycle"

    print("开始运行视频分析程序...")
    # 运行分析
    result = extract_and_analyze_frames(video_path, output_folder, object_to_find)

    # 输出结果
    if result is not None:
        print(f"目标对象在视频的第 {result} 秒被找到。")
    else:
        print("在整个视频中未找到目标对象。")

================================================
FILE: main.py
================================================
# main.py
from fastapi import FastAPI, UploadFile, File, Form, Request
from fastapi.templating import Jinja2Templates
from fastapi.staticfiles import StaticFiles
from fastapi.responses import JSONResponse, StreamingResponse
import shutil
import os
import cv2
import ollama
import time
from pathlib import Path
import asyncio
import json

app = FastAPI()

# 创建必要的目录
UPLOAD_DIR = Path("uploads")
FRAMES_DIR = Path("frames")
UPLOAD_DIR.mkdir(exist_ok=True)
FRAMES_DIR.mkdir(exist_ok=True)

# 设置模板和上传/帧目录的静态文件服务
templates = Jinja2Templates(directory="templates")
app.mount("/uploads", StaticFiles(directory="uploads"), name="uploads")
app.mount("/frames", StaticFiles(directory="frames"), name="frames")


async def analyze_image(image_path: str, object_str: str):
    """异步版本的图像分析函数"""
    prompt_str = f"""Please analyze the image and answer the following questions:
    1. Is there a {object_str} in the image?
    2. If yes, describe its appearance and location in the image in detail.
    3. If no, describe what you see in the image instead.
    4. On a scale of 1-10, how confident are you in your answer?

    Please structure your response as follows:
    Answer: [YES/NO]
    Description: [Your detailed description]
    Confidence: [1-10]"""

    try:
        response = await asyncio.to_thread(
            ollama.chat,
            model='llama3.2-vision',
            messages=[{
                'role': 'user',
                'content': prompt_str,
                'images': [image_path]
            }]
        )

        response_text = response['message']['content']
        response_lines = response_text.strip().split('\n')

        answer = None
        description = None
        confidence = 10

        for line in response_lines:
            line = line.strip()
            if line.lower().startswith('answer:'):
                answer = line.split(':', 1)[1].strip().upper()
            elif any(line.lower().startswith(prefix) for prefix in
                     ['description:', 'reasoning:', 'alternative description:']):
                description = line.split(':', 1)[1].strip()
            elif line.lower().startswith('confidence:'):
                try:
                    confidence = int(line.split(':', 1)[1].strip())
                except ValueError:
                    confidence = 10

        return answer == "YES" and confidence >= 7, description, confidence
    except Exception as e:
        print(f"Error during image analysis: {str(e)}")
        return False, "Error occurred", 0


def preprocess_image(image_path):
    """图像预处理函数"""
    img = cv2.imread(image_path)
    if img is None:
        return False

    lab = cv2.cvtColor(img, cv2.COLOR_BGR2LAB)
    l, a, b = cv2.split(lab)
    clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
    cl = clahe.apply(l)
    limg = cv2.merge((cl, a, b))
    final = cv2.cvtColor(limg, cv2.COLOR_LAB2BGR)
    cv2.imwrite(image_path, final, [cv2.IMWRITE_JPEG_QUALITY, 100])
    return True


@app.get("/")
async def home(request: Request):
    return templates.TemplateResponse("index.html", {"request": request})


@app.post("/analyze")
async def analyze_video(
        video: UploadFile = File(...),
        object_str: str = Form(...)
):
    try:
        # 保存上传的视频
        video_path = UPLOAD_DIR / video.filename
        with open(video_path, "wb") as buffer:
            shutil.copyfileobj(video.file, buffer)

        # 为当前任务创建专门的帧目录
        task_frames_dir = FRAMES_DIR / video.filename.split('.')[0]
        task_frames_dir.mkdir(exist_ok=True)

        # 异步生成分析结果
        async def generate_results():
            cap = cv2.VideoCapture(str(video_path))
            fps = int(cap.get(cv2.CAP_PROP_FPS))
            frame_count = 0

            try:
                while True:
                    success, frame = cap.read()
                    if not success:
                        break

                    if frame_count % fps == 0:  # 每秒处理一帧
                        current_second = frame_count // fps
                        frame_path = os.path.join(task_frames_dir, f"frame_{current_second}.jpg")
                        cv2.imwrite(frame_path, frame)

                        if preprocess_image(frame_path):
                            is_match, description, confidence = await analyze_image(frame_path, object_str)

                            result = {
                                "status": "success",
                                "frame": {
                                    "second": current_second,
                                    "is_match": is_match,
                                    "description": description,
                                    "confidence": confidence,
                                    "frame_path": f"/frames/{video.filename.split('.')[0]}/frame_{current_second}.jpg"
                                }
                            }

                            yield json.dumps(result) + "\n"

                    frame_count += 1

            finally:
                cap.release()

        return StreamingResponse(generate_results(), media_type="application/json")

    except Exception as e:
        return JSONResponse(
            status_code=500,
            content={"status": "error", "message": str(e)}
        )


if __name__ == "__main__":
    import uvicorn

    uvicorn.run(app, host="0.0.0.0", port=8000)

================================================
FILE: requirements.txt
================================================
annotated-types==0.7.0
anyio==4.6.2.post1
certifi==2024.8.30
click==8.1.7
fastapi==0.115.4
h11==0.14.0
httpcore==1.0.6
httpx==0.27.2
idna==3.10
Jinja2==3.1.4
MarkupSafe==3.0.2
numpy==2.1.3
ollama==0.3.3
opencv-python==4.10.0.84
pydantic==2.9.2
pydantic_core==2.23.4
python-multipart==0.0.17
sniffio==1.3.1
starlette==0.41.2
typing_extensions==4.12.2
uvicorn==0.32.0


================================================
FILE: templates/index.html
================================================
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Video Analysis</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        .upload-area {
            border: 2px dashed #ccc;
            border-radius: 5px;
            padding: 20px;
            text-align: center;
            background: #f8f9fa;
            cursor: pointer;
            margin-bottom: 10px;
        }
        .upload-area:hover {
            border-color: #0d6efd;
            background: #f1f3f5;
        }
        .results-container {
            max-height: 600px;
            overflow-y: auto;
        }
        .frame-image {
            max-width: 100%;
            height: auto;
            border-radius: 5px;
            margin-bottom: 10px;
        }
        .analyzing {
            animation: pulse 2s infinite;
        }
        @keyframes pulse {
            0% { opacity: 1; }
            50% { opacity: 0.5; }
            100% { opacity: 1; }
        }
    </style>
</head>
<body>
    <div class="container py-5">
        <div class="row justify-content-center">
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title mb-0">Video Object Detection</h3>
                    </div>
                    <div class="card-body">
                        <form id="uploadForm">
                            <div class="mb-3">
                                <label class="form-label">Upload Video</label>
                                <div class="upload-area" id="uploadArea">
                                    <div id="uploadText">
                                        <p class="mb-0">Click or drag video to upload</p>
                                    </div>
                                    <input type="file" id="videoInput" accept="video/*" class="d-none">
                                </div>
                                <small class="text-muted" id="fileInfo"></small>
                            </div>

                            <div class="mb-3">
                                <label for="objectInput" class="form-label">Object to Find</label>
                                <input type="text" class="form-control" id="objectInput"
                                       placeholder="e.g., 'a person wearing red shirt'">
                            </div>

                            <div class="alert alert-danger d-none" id="errorAlert"></div>

                            <button type="submit" class="btn btn-primary w-100" id="analyzeBtn">
                                Start Analysis
                            </button>
                        </form>

                        <div id="statusText" class="text-center mt-3 d-none">
                            <p class="analyzing">Analyzing video...</p>
                        </div>

                        <div class="results-container mt-4" id="resultsContainer"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const uploadArea = document.getElementById('uploadArea');
            const videoInput = document.getElementById('videoInput');
            const uploadForm = document.getElementById('uploadForm');
            const analyzeBtn = document.getElementById('analyzeBtn');
            const statusText = document.getElementById('statusText');
            const errorAlert = document.getElementById('errorAlert');
            const resultsContainer = document.getElementById('resultsContainer');
            const fileInfo = document.getElementById('fileInfo');

            uploadArea.addEventListener('dragover', (e) => {
                e.preventDefault();
                uploadArea.style.borderColor = '#0d6efd';
            });

            uploadArea.addEventListener('dragleave', (e) => {
                e.preventDefault();
                uploadArea.style.borderColor = '#ccc';
            });

            uploadArea.addEventListener('drop', (e) => {
                e.preventDefault();
                uploadArea.style.borderColor = '#ccc';
                const files = e.dataTransfer.files;
                if (files.length) {
                    videoInput.files = files;
                    updateFileInfo(files[0]);
                }
            });

            uploadArea.addEventListener('click', () => {
                videoInput.click();
            });

            videoInput.addEventListener('change', (e) => {
                if (e.target.files.length) {
                    updateFileInfo(e.target.files[0]);
                }
            });

            function updateFileInfo(file) {
                fileInfo.textContent = `Selected file: ${file.name}`;
            }

            function showError(message) {
                errorAlert.textContent = message;
                errorAlert.classList.remove('d-none');
            }

            function displayFrame(frame) {
                const frameCard = document.createElement('div');
                frameCard.className = 'card mb-3';
                frameCard.innerHTML = `
                    <div class="card-header">
                        <h5 class="card-title mb-0">Frame at ${frame.second} seconds</h5>
                    </div>
                    <div class="card-body">
                        <img src="${frame.frame_path}" alt="Frame ${frame.second}" class="frame-image">
                        <p class="card-text">${frame.description || 'No description available'}</p>
                        <p class="card-text">
                            <small class="text-muted">Confidence: ${frame.confidence}/10</small>
                            <small class="text-muted float-end">Match: ${frame.is_match ? 'Yes' : 'No'}</small>
                        </p>
                    </div>
                `;
                resultsContainer.insertBefore(frameCard, resultsContainer.firstChild);
            }

            uploadForm.addEventListener('submit', async (e) => {
                e.preventDefault();

                const video = videoInput.files[0];
                const objectStr = document.getElementById('objectInput').value;

                if (!video || !objectStr) {
                    showError('Please provide both video file and object description');
                    return;
                }

                try {
                    errorAlert.classList.add('d-none');
                    statusText.classList.remove('d-none');
                    analyzeBtn.disabled = true;
                    resultsContainer.innerHTML = '';

                    const formData = new FormData();
                    formData.append('video', video);
                    formData.append('object_str', objectStr);

                    const response = await fetch('/analyze', {
                        method: 'POST',
                        body: formData
                    });

                    const reader = response.body.getReader();
                    const decoder = new TextDecoder();

                    while (true) {
                        const {value, done} = await reader.read();
                        if (done) break;

                        const text = decoder.decode(value);
                        const results = text.split('\n').filter(line => line.trim());

                        for (const result of results) {
                            try {
                                const data = JSON.parse(result);
                                if (data.status === 'success' && data.frame) {
                                    displayFrame(data.frame);
                                }
                            } catch (e) {
                                console.error('Error parsing result:', e);
                            }
                        }
                    }
                } catch (error) {
                    showError('An error occurred during analysis');
                    console.error('Error:', error);
                } finally {
                    statusText.classList.add('d-none');
                    analyzeBtn.disabled = false;
                }
            });
        });
    </script>
</body>
</html>
Download .txt
gitextract_jcwsfxlv/

├── LICENSE
├── README.md
├── app.py
├── main.py
├── requirements.txt
└── templates/
    └── index.html
Download .txt
SYMBOL INDEX (7 symbols across 2 files)

FILE: app.py
  function analyze_image (line 7) | def analyze_image(image_path, object_str):
  function preprocess_image (line 88) | def preprocess_image(image_path):
  function extract_and_analyze_frames (line 112) | def extract_and_analyze_frames(video_path, output_folder, object_str):

FILE: main.py
  function analyze_image (line 29) | async def analyze_image(image_path: str, object_str: str):
  function preprocess_image (line 79) | def preprocess_image(image_path):
  function home (line 96) | async def home(request: Request):
  function analyze_video (line 101) | async def analyze_video(
Condensed preview — 6 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (38K chars).
[
  {
    "path": "LICENSE",
    "chars": 11357,
    "preview": "                                 Apache License\n                           Version 2.0, January 2004\n                   "
  },
  {
    "path": "README.md",
    "chars": 2344,
    "preview": "# VideoFinder\n\n# 作者微信:stoeng\n\n[English](#english) | [中文](#中文)\n\n\n\n# English\n\n## video:https://youtu.be/t5q4fT4rKK4\n\n## 🔍 "
  },
  {
    "path": "app.py",
    "chars": 6534,
    "preview": "import cv2\nimport os\nimport ollama\nimport time\n\n\ndef analyze_image(image_path, object_str):\n    \"\"\"\n    分析单张图像,检测是否存在目标对"
  },
  {
    "path": "main.py",
    "chars": 5383,
    "preview": "# main.py\nfrom fastapi import FastAPI, UploadFile, File, Form, Request\nfrom fastapi.templating import Jinja2Templates\nfr"
  },
  {
    "path": "requirements.txt",
    "chars": 366,
    "preview": "annotated-types==0.7.0\nanyio==4.6.2.post1\ncertifi==2024.8.30\nclick==8.1.7\nfastapi==0.115.4\nh11==0.14.0\nhttpcore==1.0.6\nh"
  },
  {
    "path": "templates/index.html",
    "chars": 8607,
    "preview": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n    <meta charset=\"UTF-8\">\n    <meta name=\"viewport\" content=\"width=device-width"
  }
]

About this extraction

This page contains the full source code of the win4r/VideoFinder-Llama3.2-vision-Ollama GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 6 files (33.8 KB), approximately 8.0k tokens, and a symbol index with 7 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!