Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added ability to copy/paste annotation guide with assets #7989

Merged
merged 25 commits into from
Jul 24, 2024

Conversation

bsekachev
Copy link
Member

@bsekachev bsekachev commented Jun 5, 2024

Motivation and context

Related #6536

How has this been tested?

Checklist

  • I submit my changes into the develop branch
  • I have created a changelog fragment
  • I have updated the documentation accordingly
  • I have added tests to cover my changes
  • I have linked related issues (see GitHub docs)
  • I have increased versions of npm packages if it is necessary
    (cvat-canvas,
    cvat-core,
    cvat-data and
    cvat-ui)

License

  • I submit my code changes under the same MIT License that covers the project.
    Feel free to contact the maintainers if that's a concern.

Summary by CodeRabbit

  • Bug Fixes

    • Resolved an issue where copying/pasting annotation guides with assets between different resources failed due to an error message.
  • Refactor

    • Renamed GuidePage component to AnnotationGuidePage and refactored logic for fetching and saving guides.
    • Updated component structure and behavior in the annotation guide editor.
  • Style

    • Adjusted the height property in the annotation guide editor for better layout consistency.
  • New Features

    • Added a method to handle updating related assets in the annotation guides.

Copy link
Contributor

coderabbitai bot commented Jun 5, 2024

Important

Review skipped

Auto incremental reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

The recent changes address a bug related to copying/pasting annotation guides with assets, refine the GuidePage component by renaming it to AnnotationGuidePage and adjusting its logic, and modify asset handling in the backend by introducing a new method to update related assets. These updates aim to improve the user experience and streamline the backend processes for managing annotation guides and their associated assets.

Changes

File(s) Change Summary
changelog.d/20240605_154324_boris_fix_anno_guide.md Added a new changelog entry detailing the fix for the annotation guide asset issue.
cvat-ui/src/components/md-guide/guide-page.tsx Renamed GuidePage to AnnotationGuidePage, refactored guide fetching/saving logic, updated file insertion handling, and adjusted component structure.
cvat-ui/src/components/md-guide/styles.scss Updated .cvat-guide-page-editor-wrapper to set height to calc(100% - $grid-unit-size * 16).
cvat/apps/engine/permissions.py Simplified the create method in the Scopes class by removing unnecessary reassignment and logic.
cvat/apps/engine/serializers.py Removed the _update_assets call from the save method in the create method.
cvat/apps/engine/views.py Added _update_related_assets method to AnnotationGuidesViewSet and modified perform_create, perform_update, and perform_destroy methods to call _update_related_assets. Added imports for re, shutil, and contextlib.suppress.

Poem

In fields where code and bugs reside,
A rabbit hops with joy and pride.
Guides now copy, assets stay,
No more errors in our way.
With pages named and styles set,
Our work improved, no more regret.
So cheers to code both swift and bright,
We hop ahead, our future's light! 🐇✨


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

Share
Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (invoked as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

Outside diff range and nitpick comments (3)
cvat-ui/src/components/md-guide/guide-page.tsx (1)

Line range hint 77-128: Refactor file handling to improve error handling and readability.

The handleInsertFiles function is quite complex and handles multiple responsibilities. Consider breaking it down into smaller functions, each handling a specific part of the file processing workflow. This will improve readability and maintainability.

+ async function processFile(file: File, guideId: number): Promise<[File, string]> {
+     const { uuid } = await core.assets.create(file, guideId);
+     return [file, uuid];
+ }
+
+ function updateTextAreaValue(addedAssets: [File, string][], textAreaValue: string, selectionStart: number, selectionEnd: number): string {
+     // Implementation goes here
+ }
+
- // Original complex function
+ // Simplified function using the above helpers
cvat/apps/engine/serializers.py (2)

Line range hint 14-14: Consider using a more specific import for re and shutil to improve code clarity and maintainability.


[!TIP]
Codebase Verification

Ensure the deletion of the temporary file created by NamedTemporaryFile.

  • The temporary file created with NamedTemporaryFile is not deleted after its use, which could lead to potential security vulnerabilities.
  • Consider adding code to delete the temporary file using os.remove(temporary_file) after it is no longer needed.
Analysis chain

Line range hint 14-14: Ensure that NamedTemporaryFile is used securely, especially in a web application context, to avoid potential security vulnerabilities.

Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify the secure usage of `NamedTemporaryFile`.

# Test: Search for `NamedTemporaryFile` usage in the file. Expect: Secure usage patterns.
rg "NamedTemporaryFile" cvat/apps/engine/serializers.py

Length of output: 273



Script:

#!/bin/bash
# Description: Extract surrounding lines of `NamedTemporaryFile` usage to verify secure handling.

# Extract 5 lines before and after each occurrence of `NamedTemporaryFile`.
rg -C 5 "NamedTemporaryFile" cvat/apps/engine/serializers.py

Length of output: 1224



Script:

#!/bin/bash
# Description: Verify the deletion of the temporary file created by `NamedTemporaryFile`.

# Search for the deletion of the temporary file.
rg "os.remove\|shutil.rmtree" cvat/apps/engine/serializers.py

Length of output: 63

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between c66bbfc and 57904d4.

Files selected for processing (6)
  • changelog.d/20240605_154324_boris_fix_anno_guide.md (1 hunks)
  • cvat-ui/src/components/md-guide/guide-page.tsx (6 hunks)
  • cvat-ui/src/components/md-guide/styles.scss (1 hunks)
  • cvat/apps/engine/permissions.py (2 hunks)
  • cvat/apps/engine/serializers.py (1 hunks)
  • cvat/apps/engine/views.py (3 hunks)
Files skipped from review due to trivial changes (1)
  • cvat-ui/src/components/md-guide/styles.scss
Additional comments not posted (12)
cvat/apps/engine/serializers.py (10)

Line range hint 14-14: Check if string is used in the file, as it is imported but not visible in the provided code.

Verification successful

The string module is used in the file cvat/apps/engine/serializers.py in the expression string.ascii_lowercase + string.digits + "-".

  • Line: string.ascii_lowercase + string.digits + "-"
Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify the usage of `string` module in the file.

# Test: Search for `string` usage in the file. Expect: Usage instances or none.
rg "string\." cvat/apps/engine/serializers.py

Length of output: 104


Line range hint 14-14: Ensure that Union is used in the file, as it is imported but not visible in the provided code.

Verification successful

The Union type is indeed used multiple times in the file cvat/apps/engine/serializers.py. Therefore, the import of Union is necessary and correctly utilized.

  • Lines where Union is used:
    • parent_instance: Union[models.Project, models.Task]
    • def _get_parent_info(cls, parent_instance: Union[models.Project, models.Task])
    • instance: Union[models.Project, models.Task]
Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify the usage of `Union` in the file.

# Test: Search for `Union` usage in the file. Expect: Usage instances or none.
rg "Union" cvat/apps/engine/serializers.py

Length of output: 428


Line range hint 14-14: Check if textwrap is necessary since it is imported but not visible in the provided code.

Verification successful

The textwrap module is used multiple times in the cvat/apps/engine/serializers.py file, specifically for the dedent function. Therefore, the import is necessary.

  • Instances of textwrap.dedent usage are found throughout the file.
Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify the usage of `textwrap` module in the file.

# Test: Search for `textwrap` usage in the file. Expect: Usage instances or none.
rg "textwrap\." cvat/apps/engine/serializers.py

Length of output: 781


Line range hint 14-14: Confirm the usage of OrderedDict as it is imported but not visible in the provided code.

Verification successful

The OrderedDict is indeed used in the file cvat/apps/engine/serializers.py at multiple locations:

  • Line 14: from typing import Any, Dict, Iterable, Optional, OrderedDict, Union
  • Line 2159: errors = OrderedDict()
  • Line 2161: return OrderedDict([(key, obj[key]) for key in keys])
  • Line 2163: OrderedDict([(key, attr[key]) for key in attr_keys]) for attr in attr_set
Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify the usage of `OrderedDict` in the file.

# Test: Search for `OrderedDict` usage in the file. Expect: Usage instances or none.
rg "OrderedDict" cvat/apps/engine/serializers.py

Length of output: 288


Line range hint 14-14: Check if Optional is necessary since it is imported but not visible in the provided code.

Verification successful

The Optional import is necessary as it is used in multiple type annotations within the file.

  • Lines where Optional is used:
    • parent_label: Optional[models.Label] = None
    • ) -> Optional[models.Label]:
    • def _configure_related_storages(validated_data: Dict[str, Any]) -> Dict[str, Optional[models.Storage]]:
Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify the usage of `Optional` in the file.

# Test: Search for `Optional` usage in the file. Expect: Usage instances or none.
rg "Optional" cvat/apps/engine/serializers.py

Length of output: 407


Line range hint 14-14: Verify the necessity of importing os as it is not explicitly used in the visible code.


Line range hint 14-14: Ensure that Iterable is used in the file, as it is imported but not visible in the provided code.

Verification successful

The Iterable type is indeed used in the file cvat/apps/engine/serializers.py at multiple locations.

  • Line 14: from typing import Any, Dict, Iterable, Optional, OrderedDict, Union
  • Line 2159: sublabels: Iterable[Dict[str, Any]],
  • Line 2160: labels: Iterable[Dict[str, Any]],
  • Line 2164: labels: Iterable[Dict[str, Any]],
Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify the usage of `Iterable` in the file.

# Test: Search for `Iterable` usage in the file. Expect: Usage instances or none.
rg "Iterable" cvat/apps/engine/serializers.py

Length of output: 243


Line range hint 14-14: Verify the necessity of importing Any as it is not explicitly used in the visible code.

Verification successful

The import of Any from the typing module is necessary as it is used in type annotations throughout the file.

  • validated_data: Dict[str, Any]
  • sublabels: Iterable[Dict[str, Any]]
  • labels: Iterable[Dict[str, Any]]
  • Function _configure_related_storages(validated_data: Dict[str, Any]) -> Dict[str, Optional[models.Storage]]
Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify the usage of `Any` module in the file.

# Test: Search for `Any` usage in the file. Expect: Usage instances or none.
rg "Any" cvat/apps/engine/serializers.py

Length of output: 418


Line range hint 14-14: Check if Dict is used in the file, as it is imported but not visible in the provided code.

Verification successful

The Dict type from the typing module is indeed used in the file cvat/apps/engine/serializers.py. Here are the specific instances:

  • Line 14: from typing import Any, Dict, Iterable, Optional, OrderedDict, Union
  • Line 2159: validated_data: Dict[str, Any],
  • Line 2160: sublabels: Iterable[Dict[str, Any]],
  • Line 2161: labels: Iterable[Dict[str, Any]],
  • Line 2162: labels: Iterable[Dict[str, Any]],
  • Line 2163: errors = OrderedDict()
  • Line 2164: return OrderedDict([(key, obj[key]) for key in keys])
  • Line 2165: OrderedDict([(key, attr[key]) for key in attr_keys]) for attr in attr_set
  • Line 2166: validated_data: Dict[str, Any],
  • Line 2167: def _configure_related_storages(validated_data: Dict[str, Any]) -> Dict[str, Optional[models.Storage]]:

The Dict type is used in type annotations for various functions and variables, confirming its necessity in the file.

Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify the usage of `Dict` module in the file.

# Test: Search for `Dict` usage in the file. Expect: Usage instances or none.
rg "Dict" cvat/apps/engine/serializers.py

Length of output: 590


Line range hint 1-1: Ensure the copyright notice is up-to-date.

cvat/apps/engine/views.py (2)

2795-2847: Ensure proper handling of asset copying in _update_related_assets.

Verification successful

The _update_related_assets method is called in both perform_create and perform_update methods. These methods are responsible for creating and updating instances, respectively. The context provided shows that _update_related_assets is used to handle assets related to an AnnotationGuide during these operations.

  • perform_create and perform_update both call _update_related_assets after the main operation (create/update) is performed.
  • The perform_destroy method does not call _update_related_assets, which is expected since it deals with deletion.

Given this context, the asset copying logic in _update_related_assets appears to be properly integrated into the create and update workflows.

Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify asset copying logic in `_update_related_assets`.

# Test: Search for the method usage. Expect: Proper handling of asset copying.
rg --type python $'_update_related_assets'

Length of output: 72



Script:

#!/bin/bash
# Description: Verify asset copying logic in `_update_related_assets`.

# Test: Search for the method usage. Expect: Proper handling of asset copying.
rg --type py $'_update_related_assets'

Length of output: 328



Script:

#!/bin/bash
# Extract lines around the calls to `_update_related_assets` to understand the context.
rg --type py -A 5 -B 5 $'_update_related_assets' cvat/apps/engine/views.py

Length of output: 1101


2856-2857: Verify that target.touch() is called appropriately after updating related assets.

Also applies to: 2861-2862

Verification successful

The search results show that target.touch() is called twice in cvat/apps/engine/views.py. However, to ensure it is called appropriately after updating related assets, we need to verify the context around these calls.


The context around the target.touch() calls confirms that they are appropriately called after updating related assets in both perform_create and perform_update methods.

  • perform_create method:

    def perform_create(self, serializer):
        super().perform_create(serializer)
        self._update_related_assets(self.request, serializer.instance)
        serializer.instance.target.touch()
  • perform_update method:

    def perform_update(self, serializer):
        super().perform_update(serializer)
        self._update_related_assets(self.request, serializer.instance)
        serializer.instance.target.touch()

This ensures that target.touch() is called after _update_related_assets in both cases.

Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify that `target.touch()` is called after updating related assets.

# Test: Search for the method usage. Expect: Proper invocation of `target.touch()`.
rg --type python $'target.touch()'

Length of output: 66



Script:

#!/bin/bash
# Description: Verify that `target.touch()` is called after updating related assets.

# Test: Search for the method usage. Expect: Proper invocation of `target.touch()`.
rg --type py 'target.touch()'

Length of output: 169



Script:

#!/bin/bash
# Description: Verify the context around `target.touch()` calls to ensure they follow `_update_related_assets`.

# Extract 5 lines before and after each occurrence of `target.touch()`
rg --type py 'target.touch()' -A 5 -B 5

Length of output: 1017

changelog.d/20240605_154324_boris_fix_anno_guide.md Outdated Show resolved Hide resolved
cvat/apps/engine/views.py Outdated Show resolved Hide resolved
cvat/apps/engine/permissions.py Show resolved Hide resolved
@codecov-commenter
Copy link

codecov-commenter commented Jun 5, 2024

Codecov Report

Attention: Patch coverage is 9.61538% with 47 lines in your changes missing coverage. Please review.

Project coverage is 83.33%. Comparing base (b4cc2ff) to head (3102a29).

Additional details and impacted files
@@             Coverage Diff             @@
##           develop    #7989      +/-   ##
===========================================
- Coverage    83.36%   83.33%   -0.04%     
===========================================
  Files          388      388              
  Lines        41315    41339      +24     
  Branches      3855     3855              
===========================================
+ Hits         34443    34450       +7     
- Misses        6872     6889      +17     
Components Coverage Δ
cvat-ui 79.67% <ø> (+0.03%) ⬆️
cvat-server 86.61% <9.61%> (-0.10%) ⬇️

Copy link

sonarcloud bot commented Jun 7, 2024

Quality Gate Passed Quality Gate passed

Issues
1 New issue
0 Accepted issues

Measures
0 Security Hotspots
No data about Coverage
0.0% Duplication on New Code

See analysis details on SonarCloud

@@ -2788,6 +2793,67 @@ class AnnotationGuidesViewSet(
ordering = "-id"
iam_organization_field = None

def _update_related_assets(self, request, guide: AnnotationGuide):
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There are many db objects being modified here, so I suggest wrapping this function as an atomic transaction

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I added transaction.atomic where we copy existing assets

cvat/apps/engine/views.py Outdated Show resolved Hide resolved
cvat/apps/engine/views.py Outdated Show resolved Hide resolved
cvat/apps/engine/views.py Outdated Show resolved Hide resolved
Copy link

sonarcloud bot commented Jul 24, 2024

@azhavoro azhavoro merged commit e981718 into develop Jul 24, 2024
33 checks passed
@bsekachev bsekachev deleted the bs/fix_anno_guide branch July 31, 2024 13:12
@cvat-bot cvat-bot bot mentioned this pull request Aug 6, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants