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

Publish bird images in mqtt events #219

Merged
merged 4 commits into from
Jun 18, 2024

Conversation

isZumpo
Copy link
Contributor

@isZumpo isZumpo commented Jun 18, 2024

Based on request #218

  • Moves the imageprovider package out of httpcontroller to its own package
  • BirdImageCache is now created in internal/analysis/realtime.go and injected into httpcontroller and processor where it is being used by the MqttAction when publishing detections to mqtt.

The new mqtt message which contains the bird image information should be backwards compatible with the old one. Since the old message is simply extended to also contain the filed BirdImage. See example below:

{
   "ID":0,
   "SourceNode":"BirdNET-Go",
   "Date":"2024-06-18",
   "Time":"10:32:48",
   "Source":"malgo",
   "BeginTime":"2024-06-18T10:32:44.38933357Z",
   "EndTime":"0001-01-01T00:00:00Z",
   "SpeciesCode":"blutit",
   "ScientificName":"Cyanistes caeruleus",
   "CommonName":"Eurasian Blue Tit",
   "Confidence":0.9980936050415039,
   "Latitude":0,
   "Longitude":0,
   "Threshold":0.8,
   "Sensitivity":1,
   "ClipName":"clips/2024/06/cyanistes_caeruleus_100p_20240618T103250Z.wav",
   "Comment":"",
   "ProcessingTime":136674686,
   "Results":null,
   "BirdImage":{
      "Url":"https://upload.wikimedia.org/wikipedia/commons/thumb/8/86/Eurasian_blue_tit_Lancashire.jpg/400px-Eurasian_blue_tit_Lancashire.jpg",
      "LicenseName":"CC BY-SA 3.0",
      "LicenseUrl":"https://creativecommons.org/licenses/by-sa/3.0",
      "AuthorName":"Francis Franklin",
      "AuthorUrl":"//commons.wikimedia.org/wiki/User:Baresi_franco"
   }
}

Copy link
Contributor

coderabbitai bot commented Jun 18, 2024

Walkthrough

This update integrates a bird image caching mechanism into various components of the system. The core additions involve modifying the Processor and MqttAction components to utilize the new BirdImageCache. Functions and initializations across components have been updated to accommodate this cache, ensuring that bird images are efficiently fetched and displayed, enhancing the overall functionality.

Changes

File(s) Description
internal/analysis/processor/actions.go Added imports and fields related to BirdImageCache; modified Execute method to fetch and wrap bird image with note.
internal/analysis/processor/processor.go Added BirdImageCache field to Processor struct; updated New function signature; included global BirdImageCache variable.
internal/analysis/processor/workers.go Updated getDefaultActions method to include BirdImageCache.
internal/analysis/realtime.go Added import and initialization of birdImageCache, and passed it to processor.New and httpcontroller.New. Added initBirdImageCache function.
internal/httpcontroller/init.go Updated import statements and New function signature to include birdImageCache parameter; removed initBirdImageCache function.
views/fragments/birdsTableHTML.html Removed a TODO comment about adding credits for the bird thumbnail.

Poem

In code we weave a cache so grand,
With bird images at our hand.
From HTTP to MQTT,
Feathered friends for all to see.
Coding paths now intertwined,
In a nest of logic finely lined. 🐇✨


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 Configration 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: 1

Outside diff range and nitpick comments (2)
internal/analysis/processor/processor.go (2)

16-16: Consider grouping imports logically for better readability.


28-28: Consider adding more detailed comments in complex sections of the code, such as dynamic threshold management and detection processing, to enhance maintainability.

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 7ce09d5 and a8cb297.

Files selected for processing (6)
  • internal/analysis/processor/actions.go (3 hunks)
  • internal/analysis/processor/processor.go (3 hunks)
  • internal/analysis/processor/workers.go (1 hunks)
  • internal/analysis/realtime.go (3 hunks)
  • internal/httpcontroller/init.go (4 hunks)
  • views/fragments/birdsTableHTML.html (1 hunks)
Files skipped from review due to trivial changes (1)
  • views/fragments/birdsTableHTML.html
Additional comments not posted (9)
internal/analysis/processor/workers.go (1)

114-114: Integration of BirdImageCache into MqttAction looks correct.

#!/bin/bash
# Description: Verify that `BirdImageCache` is properly initialized and passed to `MqttAction`.

# Test: Search for initialization and usage of `BirdImageCache`.
rg --type go $'BirdImageCache'
internal/httpcontroller/init.go (2)

47-47: Correct injection of BirdImageCache into the Server struct.


39-39: Proper modification to accept birdImageCache as a parameter in the New function, ensuring it's available throughout the HTTP controller.

#!/bin/bash
# Description: Verify the complete initialization flow of `birdImageCache` in the HTTP controller.

# Test: Search for usages of `birdImageCache` in the initialization sequence.
rg --type go $'birdImageCache'
internal/analysis/processor/actions.go (2)

61-61: Integration of BirdImageCache in MqttAction is implemented correctly.

#!/bin/bash
# Description: Ensure that `BirdImageCache` is properly integrated with the MQTT client configuration.

# Test: Search for configuration and usage of `BirdImageCache` with MQTT.
rg --type go $'BirdImageCache'

156-176: Creation of NoteWithBirdImage struct and its usage in MqttAction.Execute are well-implemented for the new MQTT message format.

#!/bin/bash
# Description: Test the new MQTT message format with `NoteWithBirdImage`.

# Test: Simulate MQTT publish and verify the message format.
echo 'Simulating MQTT publish...'
# Example simulation command (pseudo-code)
# simulate_mqtt_publish --data "$(json_note_with_bird_image)"
internal/analysis/processor/processor.go (4)

28-28: Addition of BirdImageCache to Processor struct supports the new feature of caching bird images. Ensure this field is properly initialized and used across methods.


81-81: Proper initialization of BirdImageCache within the New function ensures it's available for use in the Processor.


28-28: The struct Processor is well-organized and modular, effectively handling various aspects of bird detection processing.


76-76: Update to New function signature to include birdImageCache is appropriate. Ensure that all callers of this function are updated to pass the correct birdImageCache instance.

#!/bin/bash
# Description: Verify all function calls to `New` match the new signature.

# Test: Search for the function usage. Expect: Only occurances of the new signature.
rg --type go $'New'

Also applies to: 81-81

Comment on lines 263 to 296
func initBirdImageCache(ds datastore.Interface) *imageprovider.BirdImageCache {

birdImageCache, err := imageprovider.CreateDefaultCache()
if err != nil {
log.Fatalf("Failed to create image cache: %v", err)
}

// Initialize the image cache by fetching all detectes species in database
go func() error {
speciesList, err := ds.GetAllDetectedSpecies()
if err != nil {
return fmt.Errorf("failed to get detected species: %v", err)
}

var wg sync.WaitGroup

for _, species := range speciesList {
wg.Add(1)

go func(speciesName string) {
defer wg.Done()
_, err := birdImageCache.Get(speciesName)
if err != nil {
fmt.Printf("Failed to get image for species %s: %v\n", speciesName, err)
}
}(species.ScientificName)
}

wg.Wait()
return nil
}()

return birdImageCache
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Initialization and pre-loading of BirdImageCache are correctly implemented. Consider enhancing error handling within the goroutine to prevent silent failures.

// Improved error handling in goroutine
go func() error {
    speciesList, err := ds.GetAllDetectedSpecies()
    if err != nil {
        log.Printf("Failed to get detected species: %v", err)
        return err
    }

    var wg sync.WaitGroup
    for _, species := range speciesList {
        wg.Add(1)
        go func(speciesName string) {
            defer wg.Done()
            _, err := birdImageCache.Get(speciesName)
            if err != nil {
                log.Printf("Failed to get image for species %s: %v\n", speciesName, err)
            }
        }(species.ScientificName)
    }
    wg.Wait()
    return nil
}()

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: 0

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between a8cb297 and 6aef105.

Files selected for processing (1)
  • internal/analysis/realtime.go (3 hunks)
Files skipped from review as they are similar to previous changes (1)
  • internal/analysis/realtime.go

@tphakala tphakala merged commit 4b2b917 into tphakala:main Jun 18, 2024
6 checks passed
@isZumpo isZumpo deleted the birdimages_in_mqtt branch June 18, 2024 17:23
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.

2 participants