← Back to Pull requests

fix(video): stop the capture thread at end of file for Path sources #35

Merged
mangeshraut712 merged 2 files (160 lines) on Nov 27, 2026 18:24 UTC
View on GitHub
mangeshraut712 mangeshraut712 commented on Nov 25, 2026 10:26 UTC
Author

VideoCapture's docstring says source can be a video file path, but _capture_loop only treats str sources as files. A pathlib.Path source never stops at end of file: read() keeps returning False, the loop takes the camera continue branch, and it spins at 100% CPU with no sleep.

Fix: os.PathLike sources are normalised to str in __init__, so the existing end-of-file check applies and OpenCV gets the str filename it expects. The type annotation now matches the docstring.

Tests (tests/unit/test_video_capture.py, using a fake cv2.VideoCapture):

  • the capture thread exits at end of file for a Path source;

  • a Path reaches OpenCV as str, while an int camera index is unchanged;

  • read() returns a defensive copy;

  • read() and read_queue() handle the empty cases;

  • the 30fps fallback.
  • Results: 7 pass with the fix. On main, the two Path tests fail. ruff check src/ is clean, and mypy reports the same errors as before.

    The bug and tests were drafted with AI help (Z.ai GLM), then verified against main and run locally.

    <!-- devin-review-badge-begin -->

    ---

    <a href="https://app.devin.ai/review/mangeshraut712/real-time-face-emotion-recognition-system/pull/35" target="_blank"><picture><source media="(prefers-color-scheme: dark)" srcset="https://static.devin.ai/assets/gh-devin-review-dark.svg?v=4"><img src="https://static.devin.ai/assets/gh-devin-review-light.svg?v=4" alt="Devin Review"></picture></a>
    <!-- devin-review-badge-end -->

    <!-- CURSOR_SUMMARY -->
    ---

    [!NOTE]

    Low Risk

    Small, guarded change in VideoCapture initialization plus new unit tests; no auth or critical infrastructure impact.

    > Overview

    Fixes a bug where VideoCapture with a pathlib.Path (or other os.PathLike) video source never exited at end-of-file because _capture_loop only breaks on isinstance(self.source, str), leaving a tight CPU spin.

    > __init__ now normalises path-like sources to str via os.fspath behind an isinstance(..., os.PathLike) guard so camera indices stay int; the source type hint and docstring match that behaviour.

    > Adds tests/unit/test_video_capture.py with a fake cv2.VideoCapture, covering the Path EOF regression, str handoff to OpenCV, camera index preservation, read / read_queue edge cases, and the 30fps fallback.

    > <sup>Reviewed by Cursor Bugbot for commit 4197504cda722d73ee96300c62e375be399e20d2. Bugbot is set up for automated code reviews on this repo. Configure here.</sup>

    <!-- /CURSOR_SUMMARY -->

    Diff: 160 lines (+157 / -3) across 2 files Reviewer: mangeshraut712 Review duration: 3357m
    All Vouch review confidence checks passed
    Residual risk 0.08 = Change Risk (0.49) × (1 − Review Confidence (0.84)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.49 · 160 lines diff across 2 files
    0.49
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.91 · 5 substantive comment(s)
    0.91
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    83%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.304
    Self Review self_review
    0.140
    Real PR Conversation Timeline
    11 items
    chatgpt-codex-connector[bot] chatgpt-codex-connector[bot] commented on Nov 25, 2026 10:26 UTC
    Bot

    <!-- codex-pull-request-review-summary -->
    <!-- codex-review-state:v1 {"code_review":{"commit_sha":"4197504cda722d73ee96300c62e375be399e20d2","has_any_findings":true,"has_unresolved_findings":true,"status":"failed"},"security_review":{"commit_sha":"2a0339f69e574e0b9126a4a79ff9252544c79e9d","has_any_findings":null,"has_unresolved_findings":null,"status":"completed"}} -->
    <!-- codex-security-review:v1 {"blockingSeverityThreshold":"P0","headSha":"2a0339f69e574e0b9126a4a79ff9252544c79e9d","mergeGateEnabled":false,"pullRequestNumber":35,"repository":"mangeshraut712/Real-Time-Face-Emotion-Recognition-System","status":"completed"} -->
    <details>
    <summary><strong>Codex Review Summary</strong>: ❌ Failed</summary>

    This comment shows the latest Codex review activity on this pull request.

    | Review | Status | Commit | Review trigger |
    | --- | --- | --- | --- |
    | 📝 Code Review | ❌ Failed <relative-time datetime="2026-11-27T17:53:16.991826Z">2026-11-27T17:53:16.991826Z</relative-time><br/>We couldn’t complete this review. Comment @codex review to try again. | 4197504 | New commits |
    | 🔒 Security Review | ✅ Completed <relative-time datetime="2026-11-25T10:28:47.901306Z">2026-11-25T10:28:47.901306Z</relative-time> | 2a0339f | PR opened |

    <details> <summary>ℹ️ About Codex in GitHub</summary>
    <br/>

    Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review

  • Mark a draft as ready

  • Comment "@codex review" or "@codex security review".
  • Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

    </details>

    </details>

    devin-ai-integration[bot] devin-ai-integration[bot] commented on Nov 25, 2026 10:27 UTC
    Reviewer

    ✅ Devin Review: No Issues Found

    Devin Review analyzed this PR and found no bugs or issues to report.

    <!-- devin-review-badge-begin -->
    <a href="https://app.devin.ai/review/mangeshraut712/real-time-face-emotion-recognition-system/pull/35" target="_blank"><picture><source media="(prefers-color-scheme: dark)" srcset="https://static.devin.ai/assets/gh-devin-review-dark.svg?v=4"><img src="https://static.devin.ai/assets/gh-devin-review-light.svg?v=4" alt="Devin Review"></picture></a>
    <!-- devin-review-badge-end -->

    <!-- devin-review-summary -->

    codacy-production[bot] codacy-production[bot] commented on Nov 25, 2026 10:27 UTC
    Bot

    Up to standards :white_check_mark:


    <details><summary><strong>🟢 Issues</strong> <code>0 issues</code></summary>

    <br/>

    >

    > Results:

    0 new issues

    >

    > View in Codacy

    <br/>

    </details>

    <details><summary><strong>🟢 Metrics</strong> <code>19 complexity · 0 duplication</code></summary>

    <br/>

    > | Metric | Results |

    | ------------- | ------------- |

    | Complexity | 19 |

    > | Duplication | 0 |
    >

    View in Codacy

    <br/>

    </details>

    <sub>NEW Get contextual insights on your PRs based on Codacy's metrics, along with PR and Jira context, without leaving GitHub. Enable AI reviewer</sub>
    <sub>TIP This summary will be updated as you push new changes.</sub>

    <!-- a1b2c3d4-e5f6-7890-abcd-ef1234567890 -->

    kilo-code-bot[bot] kilo-code-bot[bot] commented on code on Nov 25, 2026 12:05 UTC
    Code Review
    src/utils/video.py:1
    @@ -33,7 +34,7 @@ class VideoCapture:
     
         def __init__(
             self,
    -        source: int = 0,
    +        source: int | str | os.PathLike[str] = 0,

    🔥 The Roast: The type annotation now accepts os.PathLike[str] but the docstring two lines down still says "Camera index or video file path". A pathlib.Path is neither an index nor a string — it's a path object. The docstring got left behind like a forgotten TODO comment.

    🩹 The Fix: Update the docstring on line 47 to mention os.PathLike / pathlib.Path support.

    📏 Severity: nitpick

    kilo-code-bot[bot] kilo-code-bot[bot] commented on code on Nov 25, 2026 12:05 UTC
    Code Review
    src/utils/video.py:1
    @@ -49,7 +50,10 @@ def __init__(
                 fps: Desired frames per second
                 buffer_size: Frame buffer size
             """
    -        self.source = source
    +        # Normalise path objects to str: OpenCV expects a str filename, and the
    +        # capture loop relies on a str source to stop at end of file instead of
    +        # retrying forever as it does for cameras.
    +        self.source = os.fspath(source) if isinstance(source, os.PathLike) else source

    🔥 The Roast: os.fspath(source) already handles strings gracefully (returns them unchanged). The isinstance(source, os.PathLike) check is redundant — you could just always call os.fspath(source) and let it do its job. It's like checking if someone's human before asking them to breathe.

    🩹 The Fix:

            self.source = os.fspath(source)
    

    📏 Severity: suggestion

    kilo-code-bot[bot] kilo-code-bot[bot] commented on Nov 25, 2026 12:10 UTC
    Bot

    <!-- kilo-review -->

    Code Review Roast 🔥

    Verdict: No Issues Found | Recommendation: Merge

    Oh wait, this PR is actually clean. I need to sit down. I had my flamethrower warmed up and everything.

    📊 Overall: Like finding a unicorn in production — I didn't think clean PRs existed anymore, but here we are.

    <details>
    <summary><b>Files Reviewed (2 files)</b></summary>

  • src/utils/video.py

  • tests/unit/test_video_capture.py
  • </details>

    <!-- kilo-review-history -->
    <details>
    <summary><b>Previous Review Summary</b> (commit 2a0339f)</summary>

    _Current summary above is authoritative. Previous snapshots are kept for context only._
    <!-- kilo-review-history-entry -->

    Previous review (commit 2a0339f)

    Verdict: 2 Issues Found | Recommendation: Address before merge

    Overview


    | Severity | Count |
    |----------|-------|
    | 🚨 critical | 0 |
    | ⚠️ warning | 0 |
    | 💡 suggestion | 1 |
    | 🤏 nitpick | 1 |

    <details>
    <summary><b>Issue Details (click to expand)</b></summary>

    | File | Line | Roast |
    |------|------|-------|
    | src/utils/video.py | 37 | Type annotation accepts os.PathLike but docstring still says "Camera index or video file path" — a Path object is neither |
    | src/utils/video.py | 56 | os.fspath() already handles strings; the isinstance check is redundant — like checking if someone's human before asking them to breathe |

    </details>

    ---

    🏆 Best part: The fix is surgically precise — normalizing Path to str in __init__ lets the existing EOF check work without touching the capture loop. Tests are thorough: EOF exit, str passthrough, defensive copies, empty reads, 30fps fallback. Someone actually thought about edge cases.

    💀 Worst part: The docstring didn't get the memo about Path support. Also, os.fspath() has been doing this exact job since Python 3.6 — the explicit isinstance check is just ceremony.

    📊 Overall: Like a PR that fixed the bug and wrote great tests, then forgot to proofread the label on the box. Merge after the docstring touch-up and the os.fspath() simplification.

    <details>
    <summary><b>Files Reviewed (2 files)</b></summary>

  • src/utils/video.py - 2 issues

  • tests/unit/test_video_capture.py - 0 issues (solid test coverage)
  • </details>

    Fix these issues in Kilo Cloud
    </details>
    <!-- /kilo-review-history -->

    ---
    <!-- kilo-usage -->
    <sub>Reviewed by free · Input: 47.5K · Output: 2.4K · Cached: 184.1K</sub>

    cursor[bot] cursor[bot] commented on Nov 27, 2026 17:53 UTC
    Bot

    <h3>Bugbot couldn't run - usage limit reached</h3>

    Bugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit.

    A user or team admin can review and increase usage limits in the Cursor dashboard.

    (requestId: 88ce27b1-7c5c-4642-9bf2-181afd60038a)

    chatgpt-codex-connector[bot] chatgpt-codex-connector[bot] commented on Nov 27, 2026 17:53 UTC
    Bot

    You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

    mangeshraut712 mangeshraut712 commented on code on Nov 27, 2026 17:53 UTC
    Code Review
    src/utils/video.py:1
    @@ -33,7 +34,7 @@ class VideoCapture:
     
         def __init__(
             self,
    -        source: int = 0,
    +        source: int | str | os.PathLike[str] = 0,

    Fixed in 4197504. The docstring now names all three accepted forms and says what happens to a path:

    source: Camera index (int, default 0) or a video file path (str,
        pathlib.Path, or any os.PathLike[str]). A path is stored as str.
    

    mangeshraut712 mangeshraut712 commented on code on Nov 27, 2026 17:53 UTC
    Code Review
    src/utils/video.py:1
    @@ -49,7 +50,10 @@ def __init__(
                 fps: Desired frames per second
                 buffer_size: Frame buffer size
             """
    -        self.source = source
    +        # Normalise path objects to str: OpenCV expects a str filename, and the
    +        # capture loop relies on a str source to stop at end of file instead of
    +        # retrying forever as it does for cameras.
    +        self.source = os.fspath(source) if isinstance(source, os.PathLike) else source

    Not applying this one: the isinstance guard is required, and self.source = os.fspath(source) unconditionally breaks every camera source.

    os.fspath only accepts str, bytes and os.PathLike. The default value of source is the camera index 0, an int:

    >>> os.fspath(0)
    TypeError: expected str, bytes or os.PathLike object, not int
    

    So with the suggestion, VideoCapture() raises in the constructor. It also matters beyond the constructor: _capture_loop tells a file from a camera with isinstance(self.source, str), which relies on a camera index staying an int.

    I checked it rather than reasoning about it. With the one-liner applied, tests/unit/test_video_capture.py gives 9 failed, 1 passed, all TypeError on an int source, including the existing test_path_source_is_passed_to_opencv_as_str. With the guard, 10 of 10 pass.

    In 4197504 I added three regression tests that pin this (VideoCapture() and VideoCapture(source=1) keep source as an int; the default source is camera 0) and a comment next to the guard stating the reason, so the simplification is not suggested again. tests/unit: 30 passed; ruff check src/ and mypy src/utils/video.py are clean.

    Assignees
    mangeshraut712 mangeshraut712
    Labels
    risk: low confidence: 83.8% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 48.9% (MEDIUM) · Higher = larger blast radius
    48.9%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 83.8% · Lower = rushed or shallow review
    83.8%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 7.9% · Safe to merge
    7.9%