[
  {
    "path": "LICENSE",
    "content": "                                 Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licenses/\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. Definitions.\n\n      \"License\" shall mean the terms and conditions for use, reproduction,\n      and distribution as defined by Sections 1 through 9 of this document.\n\n      \"Licensor\" shall mean the copyright owner or entity authorized by\n      the copyright owner that is granting the License.\n\n      \"Legal Entity\" shall mean the union of the acting entity and all\n      other entities that control, are controlled by, or are under common\n      control with that entity. For the purposes of this definition,\n      \"control\" means (i) the power, direct or indirect, to cause the\n      direction or management of such entity, whether by contract or\n      otherwise, or (ii) ownership of fifty percent (50%) or more of the\n      outstanding shares, or (iii) beneficial ownership of such entity.\n\n      \"You\" (or \"Your\") shall mean an individual or Legal Entity\n      exercising permissions granted by this License.\n\n      \"Source\" form shall mean the preferred form for making modifications,\n      including but not limited to software source code, documentation\n      source, and configuration files.\n\n      \"Object\" form shall mean any form resulting from mechanical\n      transformation or translation of a Source form, including but\n      not limited to compiled object code, generated documentation,\n      and conversions to other media types.\n\n      \"Work\" shall mean the work of authorship, whether in Source or\n      Object form, made available under the License, as indicated by a\n      copyright notice that is included in or attached to the work\n      (an example is provided in the Appendix below).\n\n      \"Derivative Works\" shall mean any work, whether in Source or Object\n      form, that is based on (or derived from) the Work and for which the\n      editorial revisions, annotations, elaborations, or other modifications\n      represent, as a whole, an original work of authorship. For the purposes\n      of this License, Derivative Works shall not include works that remain\n      separable from, or merely link (or bind by name) to the interfaces of,\n      the Work and Derivative Works thereof.\n\n      \"Contribution\" shall mean any work of authorship, including\n      the original version of the Work and any modifications or additions\n      to that Work or Derivative Works thereof, that is intentionally\n      submitted to Licensor for inclusion in the Work by the copyright owner\n      or by an individual or Legal Entity authorized to submit on behalf of\n      the copyright owner. For the purposes of this definition, \"submitted\"\n      means any form of electronic, verbal, or written communication sent\n      to the Licensor or its representatives, including but not limited to\n      communication on electronic mailing lists, source code control systems,\n      and issue tracking systems that are managed by, or on behalf of, the\n      Licensor for the purpose of discussing and improving the Work, but\n      excluding communication that is conspicuously marked or otherwise\n      designated in writing by the copyright owner as \"Not a Contribution.\"\n\n      \"Contributor\" shall mean Licensor and any individual or Legal Entity\n      on behalf of whom a Contribution has been received by Licensor and\n      subsequently incorporated within the Work.\n\n   2. Grant of Copyright License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      copyright license to reproduce, prepare Derivative Works of,\n      publicly display, publicly perform, sublicense, and distribute the\n      Work and such Derivative Works in Source or Object form.\n\n   3. Grant of Patent License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      (except as stated in this section) patent license to make, have made,\n      use, offer to sell, sell, import, and otherwise transfer the Work,\n      where such license applies only to those patent claims licensable\n      by such Contributor that are necessarily infringed by their\n      Contribution(s) alone or by combination of their Contribution(s)\n      with the Work to which such Contribution(s) was submitted. If You\n      institute patent litigation against any entity (including a\n      cross-claim or counterclaim in a lawsuit) alleging that the Work\n      or a Contribution incorporated within the Work constitutes direct\n      or contributory patent infringement, then any patent licenses\n      granted to You under this License for that Work shall terminate\n      as of the date such litigation is filed.\n\n   4. Redistribution. You may reproduce and distribute copies of the\n      Work or Derivative Works thereof in any medium, with or without\n      modifications, and in Source or Object form, provided that You\n      meet the following conditions:\n\n      (a) You must give any other recipients of the Work or\n          Derivative Works a copy of this License; and\n\n      (b) You must cause any modified files to carry prominent notices\n          stating that You changed the files; and\n\n      (c) You must retain, in the Source form of any Derivative Works\n          that You distribute, all copyright, patent, trademark, and\n          attribution notices from the Source form of the Work,\n          excluding those notices that do not pertain to any part of\n          the Derivative Works; and\n\n      (d) If the Work includes a \"NOTICE\" text file as part of its\n          distribution, then any Derivative Works that You distribute must\n          include a readable copy of the attribution notices contained\n          within such NOTICE file, excluding those notices that do not\n          pertain to any part of the Derivative Works, in at least one\n          of the following places: within a NOTICE text file distributed\n          as part of the Derivative Works; within the Source form or\n          documentation, if provided along with the Derivative Works; or,\n          within a display generated by the Derivative Works, if and\n          wherever such third-party notices normally appear. The contents\n          of the NOTICE file are for informational purposes only and\n          do not modify the License. You may add Your own attribution\n          notices within Derivative Works that You distribute, alongside\n          or as an addendum to the NOTICE text from the Work, provided\n          that such additional attribution notices cannot be construed\n          as modifying the License.\n\n      You may add Your own copyright statement to Your modifications and\n      may provide additional or different license terms and conditions\n      for use, reproduction, or distribution of Your modifications, or\n      for any such Derivative Works as a whole, provided Your use,\n      reproduction, and distribution of the Work otherwise complies with\n      the conditions stated in this License.\n\n   5. Submission of Contributions. Unless You explicitly state otherwise,\n      any Contribution intentionally submitted for inclusion in the Work\n      by You to the Licensor shall be under the terms and conditions of\n      this License, without any additional terms or conditions.\n      Notwithstanding the above, nothing herein shall supersede or modify\n      the terms of any separate license agreement you may have executed\n      with Licensor regarding such Contributions.\n\n   6. Trademarks. This License does not grant permission to use the trade\n      names, trademarks, service marks, or product names of the Licensor,\n      except as required for reasonable and customary use in describing the\n      origin of the Work and reproducing the content of the NOTICE file.\n\n   7. Disclaimer of Warranty. Unless required by applicable law or\n      agreed to in writing, Licensor provides the Work (and each\n      Contributor provides its Contributions) on an \"AS IS\" BASIS,\n      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n      implied, including, without limitation, any warranties or conditions\n      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n      PARTICULAR PURPOSE. You are solely responsible for determining the\n      appropriateness of using or redistributing the Work and assume any\n      risks associated with Your exercise of permissions under this License.\n\n   8. Limitation of Liability. In no event and under no legal theory,\n      whether in tort (including negligence), contract, or otherwise,\n      unless required by applicable law (such as deliberate and grossly\n      negligent acts) or agreed to in writing, shall any Contributor be\n      liable to You for damages, including any direct, indirect, special,\n      incidental, or consequential damages of any character arising as a\n      result of this License or out of the use or inability to use the\n      Work (including but not limited to damages for loss of goodwill,\n      work stoppage, computer failure or malfunction, or any and all\n      other commercial damages or losses), even if such Contributor\n      has been advised of the possibility of such damages.\n\n   9. Accepting Warranty or Additional Liability. While redistributing\n      the Work or Derivative Works thereof, You may choose to offer,\n      and charge a fee for, acceptance of support, warranty, indemnity,\n      or other liability obligations and/or rights consistent with this\n      License. However, in accepting such obligations, You may act only\n      on Your own behalf and on Your sole responsibility, not on behalf\n      of any other Contributor, and only if You agree to indemnify,\n      defend, and hold each Contributor harmless for any liability\n      incurred by, or claims asserted against, such Contributor by reason\n      of your accepting any such warranty or additional liability.\n\n   END OF TERMS AND CONDITIONS\n\n   APPENDIX: How to apply the Apache License to your work.\n\n      To apply the Apache License to your work, attach the following\n      boilerplate notice, with the fields enclosed by brackets \"[]\"\n      replaced with your own identifying information. (Don't include\n      the brackets!)  The text should be enclosed in the appropriate\n      comment syntax for the file format. We also recommend that a\n      file or class name and description of purpose be included on the\n      same \"printed page\" as the copyright notice for easier\n      identification within third-party archives.\n\n   Copyright [yyyy] [name of copyright owner]\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n"
  },
  {
    "path": "README.md",
    "content": "# VideoFinder\n\n# 作者微信：stoeng\n\n[English](#english) | [中文](#中文)\n\n\n\n# English\n\n## video:https://youtu.be/t5q4fT4rKK4\n\n## 🔍 About VideoFinder\nVideoFinder 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.\n\n## ✨ Features\n- Upload and analyze videos through an intuitive web interface\n- Real-time frame-by-frame analysis using multimodal AI\n- Natural language object description support\n- Visual results display with confidence scores\n- Image preprocessing for better detection accuracy\n- Streaming response for real-time analysis feedback\n\n## 🚀 Getting Started\n\n### Prerequisites\n- Python 3.8+\n- Ollama with Llama Vision model installed\n- OpenCV\n\n### Installation\n\n1. Clone the repository\n```bash\ngit clone https://github.com/win4r/VideoFinder-Llama3.2-vision-Ollama.git\ncd VideoFinder\n```\n\n2. Install dependencies\n```bash\npip install -r requirements.txt\n```\n\n3. Make sure Ollama is running with Llama Vision model\n```bash\nollama run llama3.2-vision\n```\n\n4. Start the application\n```bash\npython main.py\n```\n\n5. Access the web interface at `http://localhost:8000`\n\n## 🛠️ Usage\n1. Open the web interface\n2. Upload a video file\n3. Enter a description of the object/person you want to find\n4. Click \"Start Analysis\"\n5. View results as they appear in real-time\n\n## 📦 Dependencies\n- FastAPI\n- OpenCV\n- Ollama\n- Jinja2\n- uvicorn\n\n# 中文\n\n## 演示视频:https://youtu.be/t5q4fT4rKK4\n\n## 🔍 关于 VideoFinder\nVideoFinder 是一个智能视频分析工具，利用多模态AI模型来检测和定位视频中的特定物体或人物。该工具基于 FastAPI 构建，集成了 Llama Vision 模型，提供了友好的 Web 界面进行视频分析任务。\n\n## ✨ 特性\n- 通过直观的网页界面上传和分析视频\n- 使用多模态 AI 进行实时逐帧分析\n- 支持自然语言目标描述\n- 可视化结果显示与置信度评分\n- 图像预处理以提高检测准确率\n- 流式响应实现实时分析反馈\n\n## 🚀 快速开始\n\n### 环境要求\n- Python 3.8+\n- 安装了 Llama Vision 模型的 Ollama\n- OpenCV\n\n### 安装步骤\n\n1. 克隆仓库\n```bash\ngit clone https://github.com/win4r/VideoFinder-Llama3.2-vision-Ollama.git\ncd VideoFinder\n```\n\n2. 安装依赖\n```bash\npip install -r requirements.txt\n```\n\n3. 确保 Ollama 已运行并加载 Llama Vision 模型\n```bash\nollama run llama3.2-vision\n```\n\n4. 启动应用\n```bash\npython main.py\n```\n\n5. 访问 `http://localhost:8000` 打开 Web 界面\n\n## 🛠️ 使用方法\n1. 打开 Web 界面\n2. 上传视频文件\n3. 输入要查找的目标描述\n4. 点击\"开始分析\"\n5. 实时查看分析结果\n\n## 📦 依赖项\n- FastAPI\n- OpenCV\n- Ollama\n- Jinja2\n- uvicorn\n"
  },
  {
    "path": "app.py",
    "content": "import cv2\nimport os\nimport ollama\nimport time\n\n\ndef analyze_image(image_path, object_str):\n    \"\"\"\n    分析单张图像，检测是否存在目标对象\n    Args:\n        image_path: 图像文件路径\n        object_str: 要检测的目标对象描述\n\n    Returns:\n        tuple: (是否匹配, 描述文本, 置信度)\n    \"\"\"\n    prompt_str = f\"\"\"Please analyze the image and answer the following questions:\n\n1. Is there a {object_str} in the image?\n2. If yes, describe its appearance and location in the image in detail.\n3. If no, describe what you see in the image instead.\n4. On a scale of 1-10, how confident are you in your answer?\n\nPlease structure your response as follows:\nAnswer: [YES/NO]\nDescription: [Your detailed description]\nConfidence: [1-10]\"\"\"\n\n    try:\n        # 调用llama模型分析图像\n        response = ollama.chat(\n            model='llama3.2-vision',\n            messages=[\n                {\n                    'role': 'user',\n                    'content': prompt_str,\n                    'images': [image_path]\n                }\n            ]\n        )\n\n        print(f\"等待模型分析中...\")\n        time.sleep(1)  # 短暂延迟确保响应完整\n\n        # 获取并打印原始响应\n        response_text = response['message']['content']\n        print(f\"Raw response: {response_text}\")\n\n        # 处理响应文本，移除Markdown格式符号\n        response_text = response_text.replace('**', '')\n        response_lines = response_text.strip().split('\\n')\n\n        # 从响应中提取关键信息\n        answer = None\n        description = None\n        confidence = 10  # 默认置信度为10，因为模型没有明确返回置信度\n\n        # 逐行解析响应内容\n        for line in response_lines:\n            line = line.strip()\n            if line.lower().startswith('answer:'):\n                answer = line.split(':', 1)[1].strip().upper()\n            # 同时匹配Description、Reasoning和Alternative Description\n            elif any(line.lower().startswith(prefix) for prefix in\n                     ['description:', 'reasoning:', 'alternative description:']):\n                description = line.split(':', 1)[1].strip()\n            elif line.lower().startswith('confidence:'):\n                try:\n                    confidence = int(line.split(':', 1)[1].strip())\n                except ValueError:\n                    confidence = 10  # 如果无法解析置信度，使用默认值\n\n        # 检查是否获取到必要的信息\n        if answer is None or description is None:\n            raise ValueError(\"Response format is incomplete\")\n\n        print(f\"解析结果 - 答案: {answer}, 描述: {description}, 置信度: {confidence}\")\n\n        # 返回分析结果\n        return answer == \"YES\" and confidence >= 7, description, confidence\n    except Exception as e:\n        print(f\"Error during image analysis: {e}\")\n        import traceback\n        print(traceback.format_exc())\n        return False, \"Error occurred\", 0\n\n\ndef preprocess_image(image_path):\n    \"\"\"\n    图像预处理函数，增强图像质量\n    Args:\n        image_path: 图像文件路径\n    \"\"\"\n    # 读取图像\n    img = cv2.imread(image_path)\n    if img is None:\n        print(f\"Error: Could not read image at {image_path}\")\n        return\n\n    # 转换颜色空间并进行对比度增强\n    lab = cv2.cvtColor(img, cv2.COLOR_BGR2LAB)\n    l, a, b = cv2.split(lab)\n    clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))\n    cl = clahe.apply(l)\n    limg = cv2.merge((cl, a, b))\n    final = cv2.cvtColor(limg, cv2.COLOR_LAB2BGR)\n\n    # 保存处理后的图像\n    cv2.imwrite(image_path, final, [cv2.IMWRITE_JPEG_QUALITY, 100])\n\n\ndef extract_and_analyze_frames(video_path, output_folder, object_str):\n    \"\"\"\n    从视频中提取帧并分析是否包含目标对象\n    Args:\n        video_path: 视频文件路径\n        output_folder: 帧图像保存文件夹\n        object_str: 要检测的目标对象描述\n\n    Returns:\n        int or None: 找到目标的时间点（秒），未找到返回None\n    \"\"\"\n    # 创建输出目录\n    if not os.path.exists(output_folder):\n        os.makedirs(output_folder)\n\n    # 打开视频文件\n    video = cv2.VideoCapture(video_path)\n    if not video.isOpened():\n        print(f\"Error: Could not open video at {video_path}\")\n        return None\n\n    # 获取视频FPS\n    fps = int(video.get(cv2.CAP_PROP_FPS))\n    frame_count = 0\n    consecutive_matches = 0\n    match_threshold = 1  # 连续匹配阈值\n    cool_down_time = 2  # 每帧分析后的冷却时间（秒）\n\n    print(f\"开始分析视频，FPS: {fps}\")\n\n    try:\n        while True:\n            # 读取视频帧\n            success, frame = video.read()\n            if not success:\n                break\n\n            # 每秒处理一帧\n            if frame_count % fps == 0:\n                print(f\"\\n处理第 {frame_count // fps} 秒的帧\")\n\n                # 保存当前帧\n                output_filename = os.path.join(output_folder, f\"frame_{frame_count // fps}.jpg\")\n                output_filename = os.path.abspath(output_filename)\n\n                cv2.imwrite(output_filename, frame)\n                print(f\"已保存帧到: {output_filename}\")\n\n                # 预处理图像\n                preprocess_image(output_filename)\n                print(\"已完成图像预处理\")\n\n                print(\"开始分析图像...\")\n                print(f\"使用图像路径: {output_filename}\")\n\n                # 检查文件是否存在\n                if not os.path.exists(output_filename):\n                    print(f\"警告: 文件不存在: {output_filename}\")\n                    continue\n\n                # 分析图像\n                is_match, description, confidence = analyze_image(output_filename, object_str)\n                print(f\"分析完成 - 匹配: {is_match}, 置信度: {confidence}\")\n                print(f\"描述: {description}\")\n\n                # 处理匹配结果\n                if is_match:\n                    consecutive_matches += 1\n                    print(f\"潜在匹配 - 时间: 第 {frame_count // fps} 秒\")\n                    print(f\"描述: {description}\")\n                    print(f\"置信度: {confidence}\")\n\n                    # 如果连续匹配次数达到阈值，返回结果并退出\n                    if consecutive_matches >= match_threshold:\n                        match_time = frame_count // fps - match_threshold + 1\n                        print(f\"找到连续匹配！时间: 第 {match_time} 秒到第 {frame_count // fps} 秒\")\n                        video.release()  # 释放视频资源\n                        return match_time  # 直接返回结果\n                else:\n                    consecutive_matches = 0\n\n                # 分析完一帧后的冷却时间\n                print(f\"等待 {cool_down_time} 秒进行显卡冷却...\")\n                time.sleep(cool_down_time)\n\n            frame_count += 1\n\n    finally:\n        # 确保视频资源被释放\n        video.release()\n\n    print(f\"未找到匹配的图像。共分析了 {frame_count // fps} 张图像。\")\n    return None\n\n\n# 主程序入口\nif __name__ == \"__main__\":\n    # 设置参数\n    video_path = \"./a.mp4\"\n    output_folder = \"output_frames\"\n    object_to_find = \"A man riding a bicycle\"\n\n    print(\"开始运行视频分析程序...\")\n    # 运行分析\n    result = extract_and_analyze_frames(video_path, output_folder, object_to_find)\n\n    # 输出结果\n    if result is not None:\n        print(f\"目标对象在视频的第 {result} 秒被找到。\")\n    else:\n        print(\"在整个视频中未找到目标对象。\")"
  },
  {
    "path": "main.py",
    "content": "# main.py\nfrom fastapi import FastAPI, UploadFile, File, Form, Request\nfrom fastapi.templating import Jinja2Templates\nfrom fastapi.staticfiles import StaticFiles\nfrom fastapi.responses import JSONResponse, StreamingResponse\nimport shutil\nimport os\nimport cv2\nimport ollama\nimport time\nfrom pathlib import Path\nimport asyncio\nimport json\n\napp = FastAPI()\n\n# 创建必要的目录\nUPLOAD_DIR = Path(\"uploads\")\nFRAMES_DIR = Path(\"frames\")\nUPLOAD_DIR.mkdir(exist_ok=True)\nFRAMES_DIR.mkdir(exist_ok=True)\n\n# 设置模板和上传/帧目录的静态文件服务\ntemplates = Jinja2Templates(directory=\"templates\")\napp.mount(\"/uploads\", StaticFiles(directory=\"uploads\"), name=\"uploads\")\napp.mount(\"/frames\", StaticFiles(directory=\"frames\"), name=\"frames\")\n\n\nasync def analyze_image(image_path: str, object_str: str):\n    \"\"\"异步版本的图像分析函数\"\"\"\n    prompt_str = f\"\"\"Please analyze the image and answer the following questions:\n    1. Is there a {object_str} in the image?\n    2. If yes, describe its appearance and location in the image in detail.\n    3. If no, describe what you see in the image instead.\n    4. On a scale of 1-10, how confident are you in your answer?\n\n    Please structure your response as follows:\n    Answer: [YES/NO]\n    Description: [Your detailed description]\n    Confidence: [1-10]\"\"\"\n\n    try:\n        response = await asyncio.to_thread(\n            ollama.chat,\n            model='llama3.2-vision',\n            messages=[{\n                'role': 'user',\n                'content': prompt_str,\n                'images': [image_path]\n            }]\n        )\n\n        response_text = response['message']['content']\n        response_lines = response_text.strip().split('\\n')\n\n        answer = None\n        description = None\n        confidence = 10\n\n        for line in response_lines:\n            line = line.strip()\n            if line.lower().startswith('answer:'):\n                answer = line.split(':', 1)[1].strip().upper()\n            elif any(line.lower().startswith(prefix) for prefix in\n                     ['description:', 'reasoning:', 'alternative description:']):\n                description = line.split(':', 1)[1].strip()\n            elif line.lower().startswith('confidence:'):\n                try:\n                    confidence = int(line.split(':', 1)[1].strip())\n                except ValueError:\n                    confidence = 10\n\n        return answer == \"YES\" and confidence >= 7, description, confidence\n    except Exception as e:\n        print(f\"Error during image analysis: {str(e)}\")\n        return False, \"Error occurred\", 0\n\n\ndef preprocess_image(image_path):\n    \"\"\"图像预处理函数\"\"\"\n    img = cv2.imread(image_path)\n    if img is None:\n        return False\n\n    lab = cv2.cvtColor(img, cv2.COLOR_BGR2LAB)\n    l, a, b = cv2.split(lab)\n    clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))\n    cl = clahe.apply(l)\n    limg = cv2.merge((cl, a, b))\n    final = cv2.cvtColor(limg, cv2.COLOR_LAB2BGR)\n    cv2.imwrite(image_path, final, [cv2.IMWRITE_JPEG_QUALITY, 100])\n    return True\n\n\n@app.get(\"/\")\nasync def home(request: Request):\n    return templates.TemplateResponse(\"index.html\", {\"request\": request})\n\n\n@app.post(\"/analyze\")\nasync def analyze_video(\n        video: UploadFile = File(...),\n        object_str: str = Form(...)\n):\n    try:\n        # 保存上传的视频\n        video_path = UPLOAD_DIR / video.filename\n        with open(video_path, \"wb\") as buffer:\n            shutil.copyfileobj(video.file, buffer)\n\n        # 为当前任务创建专门的帧目录\n        task_frames_dir = FRAMES_DIR / video.filename.split('.')[0]\n        task_frames_dir.mkdir(exist_ok=True)\n\n        # 异步生成分析结果\n        async def generate_results():\n            cap = cv2.VideoCapture(str(video_path))\n            fps = int(cap.get(cv2.CAP_PROP_FPS))\n            frame_count = 0\n\n            try:\n                while True:\n                    success, frame = cap.read()\n                    if not success:\n                        break\n\n                    if frame_count % fps == 0:  # 每秒处理一帧\n                        current_second = frame_count // fps\n                        frame_path = os.path.join(task_frames_dir, f\"frame_{current_second}.jpg\")\n                        cv2.imwrite(frame_path, frame)\n\n                        if preprocess_image(frame_path):\n                            is_match, description, confidence = await analyze_image(frame_path, object_str)\n\n                            result = {\n                                \"status\": \"success\",\n                                \"frame\": {\n                                    \"second\": current_second,\n                                    \"is_match\": is_match,\n                                    \"description\": description,\n                                    \"confidence\": confidence,\n                                    \"frame_path\": f\"/frames/{video.filename.split('.')[0]}/frame_{current_second}.jpg\"\n                                }\n                            }\n\n                            yield json.dumps(result) + \"\\n\"\n\n                    frame_count += 1\n\n            finally:\n                cap.release()\n\n        return StreamingResponse(generate_results(), media_type=\"application/json\")\n\n    except Exception as e:\n        return JSONResponse(\n            status_code=500,\n            content={\"status\": \"error\", \"message\": str(e)}\n        )\n\n\nif __name__ == \"__main__\":\n    import uvicorn\n\n    uvicorn.run(app, host=\"0.0.0.0\", port=8000)"
  },
  {
    "path": "requirements.txt",
    "content": "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\nhttpx==0.27.2\nidna==3.10\nJinja2==3.1.4\nMarkupSafe==3.0.2\nnumpy==2.1.3\nollama==0.3.3\nopencv-python==4.10.0.84\npydantic==2.9.2\npydantic_core==2.23.4\npython-multipart==0.0.17\nsniffio==1.3.1\nstarlette==0.41.2\ntyping_extensions==4.12.2\nuvicorn==0.32.0\n"
  },
  {
    "path": "templates/index.html",
    "content": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n    <meta charset=\"UTF-8\">\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n    <title>Video Analysis</title>\n    <link href=\"https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css\" rel=\"stylesheet\">\n    <style>\n        .upload-area {\n            border: 2px dashed #ccc;\n            border-radius: 5px;\n            padding: 20px;\n            text-align: center;\n            background: #f8f9fa;\n            cursor: pointer;\n            margin-bottom: 10px;\n        }\n        .upload-area:hover {\n            border-color: #0d6efd;\n            background: #f1f3f5;\n        }\n        .results-container {\n            max-height: 600px;\n            overflow-y: auto;\n        }\n        .frame-image {\n            max-width: 100%;\n            height: auto;\n            border-radius: 5px;\n            margin-bottom: 10px;\n        }\n        .analyzing {\n            animation: pulse 2s infinite;\n        }\n        @keyframes pulse {\n            0% { opacity: 1; }\n            50% { opacity: 0.5; }\n            100% { opacity: 1; }\n        }\n    </style>\n</head>\n<body>\n    <div class=\"container py-5\">\n        <div class=\"row justify-content-center\">\n            <div class=\"col-md-8\">\n                <div class=\"card\">\n                    <div class=\"card-header\">\n                        <h3 class=\"card-title mb-0\">Video Object Detection</h3>\n                    </div>\n                    <div class=\"card-body\">\n                        <form id=\"uploadForm\">\n                            <div class=\"mb-3\">\n                                <label class=\"form-label\">Upload Video</label>\n                                <div class=\"upload-area\" id=\"uploadArea\">\n                                    <div id=\"uploadText\">\n                                        <p class=\"mb-0\">Click or drag video to upload</p>\n                                    </div>\n                                    <input type=\"file\" id=\"videoInput\" accept=\"video/*\" class=\"d-none\">\n                                </div>\n                                <small class=\"text-muted\" id=\"fileInfo\"></small>\n                            </div>\n\n                            <div class=\"mb-3\">\n                                <label for=\"objectInput\" class=\"form-label\">Object to Find</label>\n                                <input type=\"text\" class=\"form-control\" id=\"objectInput\"\n                                       placeholder=\"e.g., 'a person wearing red shirt'\">\n                            </div>\n\n                            <div class=\"alert alert-danger d-none\" id=\"errorAlert\"></div>\n\n                            <button type=\"submit\" class=\"btn btn-primary w-100\" id=\"analyzeBtn\">\n                                Start Analysis\n                            </button>\n                        </form>\n\n                        <div id=\"statusText\" class=\"text-center mt-3 d-none\">\n                            <p class=\"analyzing\">Analyzing video...</p>\n                        </div>\n\n                        <div class=\"results-container mt-4\" id=\"resultsContainer\"></div>\n                    </div>\n                </div>\n            </div>\n        </div>\n    </div>\n\n    <script src=\"https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js\"></script>\n    <script>\n        document.addEventListener('DOMContentLoaded', function() {\n            const uploadArea = document.getElementById('uploadArea');\n            const videoInput = document.getElementById('videoInput');\n            const uploadForm = document.getElementById('uploadForm');\n            const analyzeBtn = document.getElementById('analyzeBtn');\n            const statusText = document.getElementById('statusText');\n            const errorAlert = document.getElementById('errorAlert');\n            const resultsContainer = document.getElementById('resultsContainer');\n            const fileInfo = document.getElementById('fileInfo');\n\n            uploadArea.addEventListener('dragover', (e) => {\n                e.preventDefault();\n                uploadArea.style.borderColor = '#0d6efd';\n            });\n\n            uploadArea.addEventListener('dragleave', (e) => {\n                e.preventDefault();\n                uploadArea.style.borderColor = '#ccc';\n            });\n\n            uploadArea.addEventListener('drop', (e) => {\n                e.preventDefault();\n                uploadArea.style.borderColor = '#ccc';\n                const files = e.dataTransfer.files;\n                if (files.length) {\n                    videoInput.files = files;\n                    updateFileInfo(files[0]);\n                }\n            });\n\n            uploadArea.addEventListener('click', () => {\n                videoInput.click();\n            });\n\n            videoInput.addEventListener('change', (e) => {\n                if (e.target.files.length) {\n                    updateFileInfo(e.target.files[0]);\n                }\n            });\n\n            function updateFileInfo(file) {\n                fileInfo.textContent = `Selected file: ${file.name}`;\n            }\n\n            function showError(message) {\n                errorAlert.textContent = message;\n                errorAlert.classList.remove('d-none');\n            }\n\n            function displayFrame(frame) {\n                const frameCard = document.createElement('div');\n                frameCard.className = 'card mb-3';\n                frameCard.innerHTML = `\n                    <div class=\"card-header\">\n                        <h5 class=\"card-title mb-0\">Frame at ${frame.second} seconds</h5>\n                    </div>\n                    <div class=\"card-body\">\n                        <img src=\"${frame.frame_path}\" alt=\"Frame ${frame.second}\" class=\"frame-image\">\n                        <p class=\"card-text\">${frame.description || 'No description available'}</p>\n                        <p class=\"card-text\">\n                            <small class=\"text-muted\">Confidence: ${frame.confidence}/10</small>\n                            <small class=\"text-muted float-end\">Match: ${frame.is_match ? 'Yes' : 'No'}</small>\n                        </p>\n                    </div>\n                `;\n                resultsContainer.insertBefore(frameCard, resultsContainer.firstChild);\n            }\n\n            uploadForm.addEventListener('submit', async (e) => {\n                e.preventDefault();\n\n                const video = videoInput.files[0];\n                const objectStr = document.getElementById('objectInput').value;\n\n                if (!video || !objectStr) {\n                    showError('Please provide both video file and object description');\n                    return;\n                }\n\n                try {\n                    errorAlert.classList.add('d-none');\n                    statusText.classList.remove('d-none');\n                    analyzeBtn.disabled = true;\n                    resultsContainer.innerHTML = '';\n\n                    const formData = new FormData();\n                    formData.append('video', video);\n                    formData.append('object_str', objectStr);\n\n                    const response = await fetch('/analyze', {\n                        method: 'POST',\n                        body: formData\n                    });\n\n                    const reader = response.body.getReader();\n                    const decoder = new TextDecoder();\n\n                    while (true) {\n                        const {value, done} = await reader.read();\n                        if (done) break;\n\n                        const text = decoder.decode(value);\n                        const results = text.split('\\n').filter(line => line.trim());\n\n                        for (const result of results) {\n                            try {\n                                const data = JSON.parse(result);\n                                if (data.status === 'success' && data.frame) {\n                                    displayFrame(data.frame);\n                                }\n                            } catch (e) {\n                                console.error('Error parsing result:', e);\n                            }\n                        }\n                    }\n                } catch (error) {\n                    showError('An error occurred during analysis');\n                    console.error('Error:', error);\n                } finally {\n                    statusText.classList.add('d-none');\n                    analyzeBtn.disabled = false;\n                }\n            });\n        });\n    </script>\n</body>\n</html>"
  }
]