id
stringlengths 6
6
| text
stringlengths 20
17.2k
| title
stringclasses 1
value |
|---|---|---|
244072
|
Laravel's pagination feature allows you to query a subset of data and provides your users with the ability to navigate between *pages* of those results.
Because Laravel's paginator was designed for static applications, in a non-Livewire app, each page navigation triggers a full browser visit to a new URL containing the desired page (`?page=2`).
However, when you use pagination inside a Livewire component, users can navigate between pages while remaining on the same page. Livewire will handle everything behind the scenes, including updating the URL query string with the current page.
## Basic usage
Below is the most basic example of using pagination inside a `ShowPosts` component to only show ten posts at a time:
> [!warning] You must use the `WithPagination` trait
> To take advantage of Livewire's pagination features, each component containing pagination must use the `Livewire\WithPagination` trait.
```php
<?php
namespace App\Livewire;
use Livewire\WithPagination;
use Livewire\Component;
use App\Models\Post;
class ShowPosts extends Component
{
use WithPagination;
public function render()
{
return view('show-posts', [
'posts' => Post::paginate(10),
]);
}
}
```
```blade
<div>
<div>
@foreach ($posts as $post)
<!-- ... -->
@endforeach
</div>
{{ $posts->links() }}
</div>
```
As you can see, in addition to limiting the number of posts shown via the `Post::paginate()` method, we will also use `$posts->links()` to render page navigation links.
For more information on pagination using Laravel, check out [Laravel's comprehensive pagination documentation](https://laravel.com/docs/pagination).
## Disabling URL query string tracking
By default, Livewire's paginator tracks the current page in the browser URL's query string like so: `?page=2`.
If you wish to still use Livewire's pagination utility, but disable query string tracking, you can do so using the `WithoutUrlPagination` trait:
```php
use Livewire\WithoutUrlPagination;
use Livewire\WithPagination;
use Livewire\Component;
class ShowPosts extends Component
{
use WithPagination, WithoutUrlPagination; // [tl! highlight]
// ...
}
```
Now, pagination will work as expected, but the current page won't show up in the query string. This also means the current page won't be persisted across page changes.
## Customizing scroll behavior
By default, Livewire's paginator scrolls to the top of the page after every page change.
You can disable this behavior by passing `false` to the `scrollTo` parameter of the `links()` method like so:
```blade
{{ $posts->links(data: ['scrollTo' => false]) }}
```
Alternatively, you can provide any CSS selector to the `scrollTo` parameter, and Livewire will find the nearest element matching that selector and scroll to it after each navigation:
```blade
{{ $posts->links(data: ['scrollTo' => '#paginated-posts']) }}
```
## Resetting the page
When sorting or filtering results, it is common to want to reset the page number back to `1`.
For this reason, Livewire provides the `$this->resetPage()` method, allowing you to reset the page number from anywhere in your component.
The following component demonstrates using this method to reset the page after the search form is submitted:
```php
<?php
namespace App\Livewire;
use Livewire\WithPagination;
use Livewire\Component;
use App\Models\Post;
class SearchPosts extends Component
{
use WithPagination;
public $query = '';
public function search()
{
$this->resetPage();
}
public function render()
{
return view('show-posts', [
'posts' => Post::where('title', 'like', '%'.$this->query.'%')->paginate(10),
]);
}
}
```
```blade
<div>
<form wire:submit="search">
<input type="text" wire:model="query">
<button type="submit">Search posts</button>
</form>
<div>
@foreach ($posts as $post)
<!-- ... -->
@endforeach
</div>
{{ $posts->links() }}
</div>
```
Now, if a user was on page `5` of the results and then filtered the results further by pressing "Search posts", the page would be reset back to `1`.
### Available page navigation methods
In addition to `$this->resetPage()`, Livewire provides other useful methods for navigating between pages programmatically from your component:
| Method | Description |
|-----------------|-------------------------------------------|
| `$this->setPage($page)` | Set the paginator to a specific page number |
| `$this->resetPage()` | Reset the page back to 1 |
| `$this->nextPage()` | Go to the next page |
| `$this->previousPage()` | Go to the previous page |
## Multiple paginators
Because both Laravel and Livewire use URL query string parameters to store and track the current page number, if a single page contains multiple paginators, it's important to assign them different names.
To demonstrate the problem more clearly, consider the following `ShowClients` component:
```php
use Livewire\WithPagination;
use Livewire\Component;
use App\Models\Client;
class ShowClients extends Component
{
use WithPagination;
public function render()
{
return view('show-clients', [
'clients' => Client::paginate(10),
]);
}
}
```
As you can see, the above component contains a paginated set of *clients*. If a user were to navigate to page `2` of this result set, the URL might look like the following:
```
http://application.test/?page=2
```
Suppose the page also contains a `ShowInvoices` component that also uses pagination. To independently track each paginator's current page, you need to specify a name for the second paginator like so:
```php
use Livewire\WithPagination;
use Livewire\Component;
use App\Models\Invoices;
class ShowInvoices extends Component
{
use WithPagination;
public function render()
{
return view('show-invoices', [
'invoices' => Invoice::paginate(10, pageName: 'invoices-page'),
]);
}
}
```
Now, because of the `pageName` parameter that has been added to the `paginate` method, when a user visits page `2` of the *invoices*, the URL will contain the following:
```
https://application.test/customers?page=2&invoices-page=2
```
When using Livewire's page navigation methods on a named paginator, you must provide the page name as an additional parameter:
```php
$this->setPage(2, pageName: 'invoices-page');
$this->resetPage(pageName: 'invoices-page');
$this->nextPage(pageName: 'invoices-page');
$this->previousPage(pageName: 'invoices-page');
```
## Hooking into page updates
Livewire allows you to execute code before and after a page is updated by defining either of the following methods inside your component:
```php
use Livewire\WithPagination;
class ShowPosts extends Component
{
use WithPagination;
public function updatingPage($page)
{
// Runs before the page is updated for this component...
}
public function updatedPage($page)
{
// Runs after the page is updated for this component...
}
public function render()
{
return view('show-posts', [
'posts' => Post::paginate(10),
]);
}
}
```
### Named paginator hooks
The previous hooks only apply to the default paginator. If you are using a named paginator, you must define the methods using the paginator's name.
For example, below is an example of what a hook for a paginator named `invoices-page` would look like:
```php
public function updatingInvoicesPage($page)
{
//
}
```
### General paginator hooks
If you prefer to not reference the paginator name in the hook method name, you can use the more generic alternatives and simply receive the `$pageName` as a second argument to the hook method:
```php
public function updatingPaginators($page, $pageName)
{
// Runs before the page is updated for this component...
}
public function updatedPaginators($page, $pageName)
{
// Runs after the page is updated for this component...
}
```
## Using the simple theme
You can use Laravel's `simplePaginate()` method instead of `paginate()` for added speed and simplicity.
When paginating results using this method, only *next* and *previous* navigation links will be shown to the user instead of individual links for each page number:
```php
public function render()
{
return view('show-posts', [
'posts' => Post::simplePaginate(10),
]);
}
```
For more information on simple pagination, check out [Laravel's "simplePaginator" documentation](https://laravel.com/docs/pagination#simple-pagination).
| |
244073
|
## Using cursor pagination
Livewire also supports using Laravel's cursor pagination — a faster pagination method useful in large datasets:
```php
public function render()
{
return view('show-posts', [
'posts' => Post::cursorPaginate(10),
]);
}
```
By using `cursorPaginate()` instead of `paginate()` or `simplePaginate()`, the query string in your application's URL will store an encoded *cursor* instead of a standard page number. For example:
```
https://example.com/posts?cursor=eyJpZCI6MTUsIl9wb2ludHNUb05leHRJdGVtcyI6dHJ1ZX0
```
For more information on cursor pagination, check out [Laravel's cursor pagination documentation](https://laravel.com/docs/pagination#cursor-pagination).
## Using Bootstrap instead of Tailwind
If you are using [Bootstrap](https://getbootstrap.com/) instead of [Tailwind](https://tailwindcss.com/) as your application's CSS framework, you can configure Livewire to use Bootstrap styled pagination views instead of the default Tailwind views.
To accomplish this, set the `pagination_theme` configuration value in your application's `config/livewire.php` file:
```php
'pagination_theme' => 'bootstrap',
```
> [!info] Publishing Livewire's configuration file
> Before customizing the pagination theme, you must first publish Livewire's configuration file to your application's `/config` directory by running the following command:
> ```shell
> php artisan livewire:publish --config
> ```
## Modifying the default pagination views
If you want to modify Livewire's pagination views to fit your application's style, you can do so by *publishing* them using the following command:
```shell
php artisan livewire:publish --pagination
```
After running this command, the following four files will be inserted into the `resources/views/vendor/livewire` directory:
| View file name | Description |
|-----------------|-------------------------------------------|
| `tailwind.blade.php` | The standard Tailwind pagination theme |
| `tailwind-simple.blade.php` | The *simple* Tailwind pagination theme |
| `bootstrap.blade.php` | The standard Bootstrap pagination theme |
| `bootstrap-simple.blade.php` | The *simple* Bootstrap pagination theme |
Once the files have been published, you have complete control over them. When rendering pagination links using the paginated result's `->links()` method inside your template, Livewire will use these files instead of its own.
## Using custom pagination views
If you wish to bypass Livewire's pagination views entirely, you can render your own in one of two ways:
1. The `->links()` method in your Blade view
2. The `paginationView()` or `paginationSimpleView()` method in your component
### Via `->links()`
The first approach is to simply pass your custom pagination Blade view name to the `->links()` method directly:
```blade
{{ $posts->links('custom-pagination-links') }}
```
When rendering the pagination links, Livewire will now look for a view at `resources/views/custom-pagination-links.blade.php`.
### Via `paginationView()` or `paginationSimpleView()`
The second approach is to declare a `paginationView` or `paginationSimpleView` method inside your component which returns the name of the view you would like to use:
```php
public function paginationView()
{
return 'custom-pagination-links-view';
}
public function paginationSimpleView()
{
return 'custom-simple-pagination-links-view';
}
```
### Sample pagination view
Below is an unstyled sample of a simple Livewire pagination view for your reference.
As you can see, you can use Livewire's page navigation helpers like `$this->nextPage()` directly inside your template by adding `wire:click="nextPage"` to buttons:
```blade
<div>
@if ($paginator->hasPages())
<nav role="navigation" aria-label="Pagination Navigation">
<span>
@if ($paginator->onFirstPage())
<span>Previous</span>
@else
<button wire:click="previousPage" wire:loading.attr="disabled" rel="prev">Previous</button>
@endif
</span>
<span>
@if ($paginator->onLastPage())
<span>Next</span>
@else
<button wire:click="nextPage" wire:loading.attr="disabled" rel="next">Next</button>
@endif
</span>
</nav>
@endif
</div>
```
| |
244076
|
Livewire offers powerful support for uploading files within your components.
First, add the `WithFileUploads` trait to your component. Once this trait has been added to your component, you can use `wire:model` on file inputs as if they were any other input type and Livewire will take care of the rest.
Here's an example of a simple component that handles uploading a photo:
```php
<?php
namespace App\Livewire;
use Livewire\Component;
use Livewire\WithFileUploads;
use Livewire\Attributes\Validate;
class UploadPhoto extends Component
{
use WithFileUploads;
#[Validate('image|max:1024')] // 1MB Max
public $photo;
public function save()
{
$this->photo->store(path: 'photos');
}
}
```
```blade
<form wire:submit="save">
<input type="file" wire:model="photo">
@error('photo') <span class="error">{{ $message }}</span> @enderror
<button type="submit">Save photo</button>
</form>
```
> [!warning] The "upload" method is reserved
> Notice the above example uses a "save" method instead of an "upload" method. This is a common "gotcha". The term "upload" is reserved by Livewire. You cannot use it as a method or property name in your component.
From the developer's perspective, handling file inputs is no different than handling any other input type: Add `wire:model` to the `<input>` tag and everything else is taken care of for you.
However, more is happening under the hood to make file uploads work in Livewire. Here's a glimpse at what goes on when a user selects a file to upload:
1. When a new file is selected, Livewire's JavaScript makes an initial request to the component on the server to get a temporary "signed" upload URL.
2. Once the URL is received, JavaScript does the actual "upload" to the signed URL, storing the upload in a temporary directory designated by Livewire and returning the new temporary file's unique hash ID.
3. Once the file is uploaded and the unique hash ID is generated, Livewire's JavaScript makes a final request to the component on the server, telling it to "set" the desired public property to the new temporary file.
4. Now, the public property (in this case, `$photo`) is set to the temporary file upload and is ready to be stored or validated at any point.
## Storing uploaded files
The previous example demonstrates the most basic storage scenario: moving the temporarily uploaded file to the "photos" directory on the application's default filesystem disk.
However, you may want to customize the file name of the stored file or even specify a specific storage "disk" to keep the file on (such as S3).
> [!tip] Original file names
> You can access the original file name of a temporary upload, by calling its `->getClientOriginalName()` method.
Livewire honors the same APIs Laravel uses for storing uploaded files, so feel free to consult [Laravel's file upload documentation](https://laravel.com/docs/filesystem#file-uploads). However, below are a few common storage scenarios and examples:
```php
public function save()
{
// Store the file in the "photos" directory of the default filesystem disk
$this->photo->store(path: 'photos');
// Store the file in the "photos" directory in a configured "s3" disk
$this->photo->store(path: 'photos', 's3');
// Store the file in the "photos" directory with the filename "avatar.png"
$this->photo->storeAs(path: 'photos', name: 'avatar');
// Store the file in the "photos" directory in a configured "s3" disk with the filename "avatar.png"
$this->photo->storeAs(path: 'photos', name: 'avatar', 's3');
// Store the file in the "photos" directory, with "public" visibility in a configured "s3" disk
$this->photo->storePublicly(path: 'photos', 's3');
// Store the file in the "photos" directory, with the name "avatar.png", with "public" visibility in a configured "s3" disk
$this->photo->storePubliclyAs(path: 'photos', name: 'avatar', 's3');
}
```
## Handling multiple files
Livewire automatically handles multiple file uploads by detecting the `multiple` attribute on the `<input>` tag.
For example, below is a component with an array property named `$photos`. By adding `multiple` to the form's file input, Livewire will automatically append new files to this array:
```php
use Livewire\Component;
use Livewire\WithFileUploads;
use Livewire\Attributes\Validate;
class UploadPhotos extends Component
{
use WithFileUploads;
#[Validate(['photos.*' => 'image|max:1024'])]
public $photos = [];
public function save()
{
foreach ($this->photos as $photo) {
$photo->store(path: 'photos');
}
}
}
```
```blade
<form wire:submit="save">
<input type="file" wire:model="photos" multiple>
@error('photos.*') <span class="error">{{ $message }}</span> @enderror
<button type="submit">Save photo</button>
</form>
```
## File validation
Like we've discussed, validating file uploads with Livewire is the same as handling file uploads from a standard Laravel controller.
> [!warning] Ensure S3 is properly configured
> Many of the validation rules relating to files require access to the file. When [uploading directly to S3](#uploading-directly-to-amazon-s3), these validation rules will fail if the S3 file object is not publicly accessible.
For more information on file validation, consult [Laravel's file validation documentation](https://laravel.com/docs/validation#available-validation-rules).
## Temporary preview URLs
After a user chooses a file, you should typically show them a preview of that file before they submit the form and store the file.
Livewire makes this trivial by using the `->temporaryUrl()` method on uploaded files.
> [!info] Temporary URLs are restricted to images
> For security reasons, temporary preview URLs are only supported on files with image MIME types.
Let's explore an example of a file upload with an image preview:
```php
use Livewire\Component;
use Livewire\WithFileUploads;
use Livewire\Attributes\Validate;
class UploadPhoto extends Component
{
use WithFileUploads;
#[Validate('image|max:1024')]
public $photo;
// ...
}
```
```blade
<form wire:submit="save">
@if ($photo) <!-- [tl! highlight:2] -->
<img src="{{ $photo->temporaryUrl() }}">
@endif
<input type="file" wire:model="photo">
@error('photo') <span class="error">{{ $message }}</span> @enderror
<button type="submit">Save photo</button>
</form>
```
As previously discussed, Livewire stores temporary files in a non-public directory; therefore, typically there's no simple way to expose a temporary, public URL to your users for image previewing.
However, Livewire solves this issue by providing a temporary, signed URL that pretends to be the uploaded image so your page can show an image preview to your users.
This URL is protected against showing files in directories above the temporary directory. And, because it's signed, users can't abuse this URL to preview other files on your system.
> [!tip] S3 temporary signed URLs
> If you've configured Livewire to use S3 for temporary file storage, calling `->temporaryUrl()` will generate a temporary, signed URL to S3 directly so that image previews aren't loaded from your Laravel application server.
| |
244077
|
## Testing file uploads
You can use Laravel's existing file upload testing helpers to test file uploads.
Below is a complete example of testing the `UploadPhoto` component with Livewire:
```php
<?php
namespace Tests\Feature\Livewire;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
use App\Livewire\UploadPhoto;
use Livewire\Livewire;
use Tests\TestCase;
class UploadPhotoTest extends TestCase
{
/** @test */
public function can_upload_photo()
{
Storage::fake('avatars');
$file = UploadedFile::fake()->image('avatar.png');
Livewire::test(UploadPhoto::class)
->set('photo', $file)
->call('upload', 'uploaded-avatar.png');
Storage::disk('avatars')->assertExists('uploaded-avatar.png');
}
}
```
Below is an example of the `UploadPhoto` component required to make the previous test pass:
```php
use Livewire\Component;
use Livewire\WithFileUploads;
class UploadPhoto extends Component
{
use WithFileUploads;
public $photo;
public function upload($name)
{
$this->photo->storeAs('/', $name, disk: 'avatars');
}
// ...
}
```
For more information on testing file uploads, please consult [Laravel's file upload testing documentation](https://laravel.com/docs/http-tests#testing-file-uploads).
## Uploading directly to Amazon S3
As previously discussed, Livewire stores all file uploads in a temporary directory until the developer permanently stores the file.
By default, Livewire uses the default filesystem disk configuration (usually `local`) and stores the files within a `livewire-tmp/` directory.
Consequently, file uploads are always utilizing your application server, even if you choose to store the uploaded files in an S3 bucket later.
If you wish to bypass your application server and instead store Livewire's temporary uploads in an S3 bucket, you can configure that behavior in your application's `config/livewire.php` configuration file. First, set `livewire.temporary_file_upload.disk` to `s3` (or another custom disk that uses the `s3` driver):
```php
return [
// ...
'temporary_file_upload' => [
'disk' => 's3',
// ...
],
];
```
Now, when a user uploads a file, the file will never actually be stored on your server. Instead, it will be uploaded directly to your S3 bucket within the `livewire-tmp/` sub-directory.
> [!info] Publishing Livewire's configuration file
> Before customizing the file upload disk, you must first publish Livewire's configuration file to your application's `/config` directory by running the following command:
> ```shell
> php artisan livewire:publish --config
> ```
### Configuring automatic file cleanup
Livewire's temporary upload directory will fill up with files quickly; therefore, it's essential to configure S3 to clean up files older than 24 hours.
To configure this behavior, run the following Artisan command from the environment that is utilizing an S3 bucket for file uploads:
```shell
php artisan livewire:configure-s3-upload-cleanup
```
Now, any temporary files older than 24 hours will be cleaned up by S3 automatically.
> [!info]
> If you are not using S3 for file storage, Livewire will handle file cleanup automatically and there is no need to run the command above.
## Loading indicators
Although `wire:model` for file uploads works differently than other `wire:model` input types under the hood, the interface for showing loading indicators remains the same.
You can display a loading indicator scoped to the file upload like so:
```blade
<input type="file" wire:model="photo">
<div wire:loading wire:target="photo">Uploading...</div>
```
Now, while the file is uploading, the "Uploading..." message will be shown and then hidden when the upload is finished.
For more information on loading states, check out our comprehensive [loading state documentation](/docs/wire-loading).
## Progress indicators
Every Livewire file upload operation dispatches JavaScript events on the corresponding `<input>` element, allowing custom JavaScript to intercept the events:
Event | Description
--- | ---
`livewire-upload-start` | Dispatched when the upload starts
`livewire-upload-finish` | Dispatched if the upload is successfully finished
`livewire-upload-cancel` | Dispatched if the upload was cancelled prematurely
`livewire-upload-error` | Dispatched if the upload fails
`livewire-upload-progress` | An event containing the upload progress percentage as the upload progresses
Below is an example of wrapping a Livewire file upload in an Alpine component to display an upload progress bar:
```blade
<form wire:submit="save">
<div
x-data="{ uploading: false, progress: 0 }"
x-on:livewire-upload-start="uploading = true"
x-on:livewire-upload-finish="uploading = false"
x-on:livewire-upload-cancel="uploading = false"
x-on:livewire-upload-error="uploading = false"
x-on:livewire-upload-progress="progress = $event.detail.progress"
>
<!-- File Input -->
<input type="file" wire:model="photo">
<!-- Progress Bar -->
<div x-show="uploading">
<progress max="100" x-bind:value="progress"></progress>
</div>
</div>
<!-- ... -->
</form>
```
## Cancelling an upload
If an upload is taking a long time, a user may want to cancel it. You can provide this functionality with Livewire's `$cancelUpload()` function in JavaScript.
Here's an example of creating a "Cancel Upload" button in a Livewire component using `wire:click` to handle the click event:
```blade
<form wire:submit="save">
<!-- File Input -->
<input type="file" wire:model="photo">
<!-- Cancel upload button -->
<button type="button" wire:click="$cancelUpload('photo')">Cancel Upload</button>
<!-- ... -->
</form>
```
When "Cancel upload" is pressed, the file upload will request will be aborted and the file input will be cleared. The user can now attempt another upload with a different file.
Alternatively, you can call `cancelUpload(...)` from Alpine like so:
```blade
<button type="button" x-on:click="$wire.cancelUpload('photo')">Cancel Upload</button>
```
## JavaScript upload API
Integrating with third-party file-uploading libraries often requires more control than a simple `<input type="file" wire:model="...">` element.
For these scenarios, Livewire exposes dedicated JavaScript functions.
These functions exist on a JavaScript component object, which can be accessed using Livewire's convenient `$wire` object from within your Livewire component's template:
```blade
@script
<script>
let file = $wire.el.querySelector('input[type="file"]').files[0]
// Upload a file...
$wire.upload('photo', file, (uploadedFilename) => {
// Success callback...
}, () => {
// Error callback...
}, (event) => {
// Progress callback...
// event.detail.progress contains a number between 1 and 100 as the upload progresses
}, () => {
// Cancelled callback...
})
// Upload multiple files...
$wire.uploadMultiple('photos', [file], successCallback, errorCallback, progressCallback, cancelledCallback)
// Remove single file from multiple uploaded files...
$wire.removeUpload('photos', uploadedFilename, successCallback)
// Cancel an upload...
$wire.cancelUpload('photos')
</script>
@endscript
```
## Configuration
Because Livewire stores all file uploads temporarily before the developer can validate or store them, it assumes some default handling behavior for all file uploads.
### Global validation
By default, Livewire will validate all temporary file uploads with the following rules: `file|max:12288` (Must be a file less than 12MB).
If you wish to customize these rules, you can do so inside your application's `config/livewire.php` file:
```php
'temporary_file_upload' => [
// ...
'rules' => 'file|mimes:png,jpg,pdf|max:102400', // (100MB max, and only accept PNGs, JPEGs, and PDFs)
],
```
### Global middleware
The temporary file upload endpoint is assigned a throttling middleware by default. You can customize exactly what middleware this endpoint uses via the following configuration option:
```php
'temporary_file_upload' => [
// ...
'middleware' => 'throttle:5,1', // Only allow 5 uploads per user per minute
],
```
### Temporary upload directory
Temporary files are uploaded to the specified disk's `livewire-tmp/` directory. You can customize this directory via the following configuration option:
```php
'temporary_file_upload' => [
// ...
'directory' => 'tmp',
],
```
| |
244080
|
## Object schemas
When extending Livewire's JavaScript system, it's important to understand the different objects you might encounter.
Here is an exhaustive reference of each of Livewire's relevant internal properties.
As a reminder, the average Livewire user may never interact with these. Most of these objects are available for Livewire's internal system or advanced users.
### The `$wire` object
Given the following generic `Counter` component:
```php
<?php
namespace App\Livewire;
use Livewire\Component;
class Counter extends Component
{
public $count = 1;
public function increment()
{
$this->count++;
}
public function render()
{
return view('livewire.counter');
}
}
```
Livewire exposes a JavaScript representation of the server-side component in the form of an object that is commonly referred to as `$wire`:
```js
let $wire = {
// All component public properties are directly accessible on $wire...
count: 0,
// All public methods are exposed and callable on $wire...
increment() { ... },
// Access the `$wire` object of the parent component if one exists...
$parent,
// Access the root DOM element of the Livewire component...
$el,
// Access the ID of the current Livewire component...
$id,
// Get the value of a property by name...
// Usage: $wire.$get('count')
$get(name) { ... },
// Set a property on the component by name...
// Usage: $wire.$set('count', 5)
$set(name, value, live = true) { ... },
// Toggle the value of a boolean property...
$toggle(name, live = true) { ... },
// Call the method
// Usage: $wire.$call('increment')
$call(method, ...params) { ... },
// Entangle the value of a Livewire property with a different,
// arbitrary, Alpine property...
// Usage: <div x-data="{ count: $wire.$entangle('count') }">
$entangle(name, live = false) { ... },
// Watch the value of a property for changes...
// Usage: Alpine.$watch('count', (value, old) => { ... })
$watch(name, callback) { ... },
// Refresh a component by sending a commit to the server
// to re-render the HTML and swap it into the page...
$refresh() { ... },
// Identical to the above `$refresh`. Just a more technical name...
$commit() { ... },
// Listen for a an event dispatched from this component or its children...
// Usage: $wire.$on('post-created', () => { ... })
$on(event, callback) { ... },
// Dispatch an event from this component...
// Usage: $wire.$dispatch('post-created', { postId: 2 })
$dispatch(event, params = {}) { ... },
// Dispatch an event onto another component...
// Usage: $wire.$dispatchTo('dashboard', 'post-created', { postId: 2 })
$dispatchTo(otherComponentName, event, params = {}) { ... },
// Dispatch an event onto this component and no others...
$dispatchSelf(event, params = {}) { ... },
// A JS API to upload a file directly to component
// rather than through `wire:model`...
$upload(
name, // The property name
file, // The File JavaScript object
finish = () => { ... }, // Runs when the upload is finished...
error = () => { ... }, // Runs if an error is triggered mid-upload...
progress = (event) => { // Runs as the upload progresses...
event.detail.progress // An integer from 1-100...
},
) { ... },
// API to upload multiple files at the same time...
$uploadMultiple(name, files, finish, error, progress) { },
// Remove an upload after it's been temporarily uploaded but not saved...
$removeUpload(name, tmpFilename, finish, error) { ... },
// Retrieve the underlying "component" object...
__instance() { ... },
}
```
You can learn more about `$wire` in [Livewire's documentation on accessing properties in JavaScript](/docs/properties#accessing-properties-from-javascript).
### The `snapshot` object
Between each network request, Livewire serializes the PHP component into an object that can be consumed in JavaScript. This snapshot is used to unserialize the component back into a PHP object and therefore has mechanisms built in to prevent tampering:
```js
let snapshot = {
// The serialized state of the component (public properties)...
data: { count: 0 },
// Long-standing information about the component...
memo: {
// The component's unique ID...
id: '0qCY3ri9pzSSMIXPGg8F',
// The component's name. Ex. <livewire:[name] />
name: 'counter',
// The URI, method, and locale of the web page that the
// component was originally loaded on. This is used
// to re-apply any middleware from the original request
// to subsequent component update requests (commits)...
path: '/',
method: 'GET',
locale: 'en',
// A list of any nested "child" components. Keyed by
// internal template ID with the component ID as the values...
children: [],
// Weather or not this component was "lazy loaded"...
lazyLoaded: false,
// A list of any validation errors thrown during the
// last request...
errors: [],
},
// A securely encrypted hash of this snapshot. This way,
// if a malicious user tampers with the snapshot with
// the goal of accessing un-owned resources on the server,
// the checksum validation will fail and an error will
// be thrown...
checksum: '1bc274eea17a434e33d26bcaba4a247a4a7768bd286456a83ea6e9be2d18c1e7',
}
```
### The `component` object
Every component on a page has a corresponding component object behind the scenes keeping track of its state and exposing its underlying functionality. This is one layer deeper than `$wire`. It is only meant for advanced usage.
Here's an actual component object for the above `Counter` component with descriptions of relevant properties in JS comments:
```js
let component = {
// The root HTML element of the component...
el: HTMLElement,
// The unique ID of the component...
id: '0qCY3ri9pzSSMIXPGg8F',
// The component's "name" (<livewire:[name] />)...
name: 'counter',
// The latest "effects" object. Effects are "side-effects" from server
// round-trips. These include redirects, file downloads, etc...
effects: {},
// The component's last-known server-side state...
canonical: { count: 0 },
// The component's mutable data object representing its
// live client-side state...
ephemeral: { count: 0 },
// A reactive version of `this.ephemeral`. Changes to
// this object will be picked up by AlpineJS expressions...
reactive: Proxy,
// A Proxy object that is typically used inside Alpine
// expressions as `$wire`. This is meant to provide a
// friendly JS object interface for Livewire components...
$wire: Proxy,
// A list of any nested "child" components. Keyed by
// internal template ID with the component ID as the values...
children: [],
// The last-known "snapshot" representation of this component.
// Snapshots are taken from the server-side component and used
// to re-create the PHP object on the backend...
snapshot: {...},
// The un-parsed version of the above snapshot. This is used to send back to the
// server on the next roundtrip because JS parsing messes with PHP encoding
// which often results in checksum mis-matches.
snapshotEncoded: '{"data":{"count":0},"memo":{"id":"0qCY3ri9pzSSMIXPGg8F","name":"counter","path":"\/","method":"GET","children":[],"lazyLoaded":true,"errors":[],"locale":"en"},"checksum":"1bc274eea17a434e33d26bcaba4a247a4a7768bd286456a83ea6e9be2d18c1e7"}',
}
```
| |
244091
|
Properties store and manage data inside your Livewire components. They are defined as public properties on component classes and can be accessed and modified on both the server and client-side.
## Initializing properties
You can set initial values for properties within your component's `mount()` method.
Consider the following example:
```php
<?php
namespace App\Livewire;
use Illuminate\Support\Facades\Auth;
use Livewire\Component;
class TodoList extends Component
{
public $todos = [];
public $todo = '';
public function mount()
{
$this->todos = Auth::user()->todos; // [tl! highlight]
}
// ...
}
```
In this example, we've defined an empty `todos` array and initialized it with existing todos from the authenticated user. Now, when the component renders for the first time, all the existing todos in the database are shown to the user.
## Bulk assignment
Sometimes initializing many properties in the `mount()` method can feel verbose. To help with this, Livewire provides a convenient way to assign multiple properties at once via the `fill()` method. By passing an associative array of property names and their respective values, you can set several properties simultaneously and cut down on repetitive lines of code in `mount()`.
For example:
```php
<?php
namespace App\Livewire;
use Livewire\Component;
use App\Models\Post;
class UpdatePost extends Component
{
public $post;
public $title;
public $description;
public function mount(Post $post)
{
$this->post = $post;
$this->fill( // [tl! highlight]
$post->only('title', 'description'), // [tl! highlight]
); // [tl! highlight]
}
// ...
}
```
Because `$post->only(...)` returns an associative array of model attributes and values based on the names you pass into it, the `$title` and `$description` properties will be initially set to the `title` and `description` of the `$post` model from the database without having to set each one individually.
## Data binding
Livewire supports two-way data binding through the `wire:model` HTML attribute. This allows you to easily synchronize data between component properties and HTML inputs, keeping your user interface and component state in sync.
Let's use the `wire:model` directive to bind the `$todo` property in a `TodoList` component to a basic input element:
```php
<?php
namespace App\Livewire;
use Livewire\Component;
class TodoList extends Component
{
public $todos = [];
public $todo = '';
public function add()
{
$this->todos[] = $this->todo;
$this->todo = '';
}
// ...
}
```
```blade
<div>
<input type="text" wire:model="todo" placeholder="Todo..."> <!-- [tl! highlight] -->
<button wire:click="add">Add Todo</button>
<ul>
@foreach ($todos as $todo)
<li>{{ $todo }}</li>
@endforeach
</ul>
</div>
```
In the above example, the text input's value will synchronize with the `$todo` property on the server when the "Add Todo" button is clicked.
This is just scratching the surface of `wire:model`. For deeper information on data binding, check out our [documentation on forms](/docs/forms).
## Resetting properties
Sometimes, you may need to reset your properties back to their initial state after an action is performed by the user. In these cases, Livewire provides a `reset()` method that accepts one or more property names and resets their values to their initial state.
In the example below, we can avoid code duplication by using `$this->reset()` to reset the `todo` field after the "Add Todo" button is clicked:
```php
<?php
namespace App\Livewire;
use Livewire\Component;
class ManageTodos extends Component
{
public $todos = [];
public $todo = '';
public function addTodo()
{
$this->todos[] = $this->todo;
$this->reset('todo'); // [tl! highlight]
}
// ...
}
```
In the above example, after a user clicks "Add Todo", the input field holding the todo that has just been added will clear, allowing the user to write a new todo.
> [!warning] `reset()` won't work on values set in `mount()`
> `reset()` will reset a property to its state before the `mount()` method was called. If you initialized the property in `mount()` to a different value, you will need to reset the property manually.
## Pulling properties
Alternatively, you can use the `pull()` method to both reset and retrieve the value in one operation.
Here's the same example from above, but simplified with `pull()`:
```php
<?php
namespace App\Livewire;
use Livewire\Component;
class ManageTodos extends Component
{
public $todos = [];
public $todo = '';
public function addTodo()
{
$this->todos[] = $this->pull('todo'); // [tl! highlight]
}
// ...
}
```
The above example is pulling a single value, but `pull()` can also be used to reset and retrieve (as a key-value pair) all or some properties:
```php
// The same as $this->all() and $this->reset();
$this->pull();
// The same as $this->only(...) and $this->reset(...);
$this->pull(['title', 'content']);
```
| |
244092
|
## Supported property types
Livewire supports a limited set of property types because of its unique approach to managing component data between server requests.
Each property in a Livewire component is serialized or "dehydrated" into JSON between requests, then "hydrated" from JSON back into PHP for the next request.
This two-way conversion process has certain limitations, restricting the types of properties Livewire can work with.
### Primitive types
Livewire supports primitive types such as strings, integers, etc. These types can be easily converted to and from JSON, making them ideal for use as properties in Livewire components.
Livewire supports the following primitive property types: `Array`, `String`, `Integer`, `Float`, `Boolean`, and `Null`.
```php
class TodoList extends Component
{
public $todos = []; // Array
public $todo = ''; // String
public $maxTodos = 10; // Integer
public $showTodos = false; // Boolean
public $todoFilter; // Null
}
```
### Common PHP types
In addition to primitive types, Livewire supports common PHP object types used in Laravel applications. However, it's important to note that these types will be _dehydrated_ into JSON and _hydrated_ back to PHP on each request. This means that the property may not preserve run-time values such as closures. Also, information about the object such as class names may be exposed to JavaScript.
Supported PHP types:
| Type | Full Class Name |
|------|-----------------|
| BackedEnum | `BackedEnum` |
| Collection | `Illuminate\Support\Collection` |
| Eloquent Collection | `Illuminate\Database\Eloquent\Collection` |
| Model | `Illuminate\Database\Eloquent\Model` |
| DateTime | `DateTime` |
| Carbon | `Carbon\Carbon` |
| Stringable | `Illuminate\Support\Stringable` |
> [!warning] Eloquent Collections and Models
> When storing Eloquent Collections and Models in Livewire properties, additional query constraints like select(...) will not be re-applied on subsequent requests.
>
> See [Eloquent constraints aren't preserved between requests](#eloquent-constraints-arent-preserved-between-requests) for more details
Here's a quick example of setting properties as these various types:
```php
public function mount()
{
$this->todos = collect([]); // Collection
$this->todos = Todos::all(); // Eloquent Collection
$this->todo = Todos::first(); // Model
$this->date = new DateTime('now'); // DateTime
$this->date = new Carbon('now'); // Carbon
$this->todo = str(''); // Stringable
}
```
### Supporting custom types
Livewire allows your application to support custom types through two powerful mechanisms:
* Wireables
* Synthesizers
Wireables are simple and easy to use for most applications, so we'll explore them below. If you're an advanced user or package author wanting more flexibility, [Synthesizers are the way to go](/docs/synthesizers).
#### Wireables
Wireables are any class in your application that implements the `Wireable` interface.
For example, let's imagine you have a `Customer` object in your application that contains the primary data about a customer:
```php
class Customer
{
protected $name;
protected $age;
public function __construct($name, $age)
{
$this->name = $name;
$this->age = $age;
}
}
```
Attempting to set an instance of this class to a Livewire component property will result in an error telling you that the `Customer` property type isn't supported:
```php
class ShowCustomer extends Component
{
public Customer $customer;
public function mount()
{
$this->customer = new Customer('Caleb', 29);
}
}
```
However, you can solve this by implementing the `Wireable` interface and adding a `toLivewire()` and `fromLivewire()` method to your class. These methods tell Livewire how to turn properties of this type into JSON and back again:
```php
use Livewire\Wireable;
class Customer implements Wireable
{
protected $name;
protected $age;
public function __construct($name, $age)
{
$this->name = $name;
$this->age = $age;
}
public function toLivewire()
{
return [
'name' => $this->name,
'age' => $this->age,
];
}
public static function fromLivewire($value)
{
$name = $value['name'];
$age = $value['age'];
return new static($name, $age);
}
}
```
Now you can freely set `Customer` objects on your Livewire components and Livewire will know how to convert these objects into JSON and back into PHP.
As mentioned earlier, if you want to support types more globally and powerfully, Livewire offers Synthesizers, its advanced internal mechanism for handling different property types. [Learn more about Synthesizers](/docs/synthesizers).
## Accessing properties from JavaScript
Because Livewire properties are also available in the browser via JavaScript, you can access and manipulate their JavaScript representations from [AlpineJS](https://alpinejs.dev/).
Alpine is a lightweight JavaScript library that is included with Livewire. Alpine provides a way to build lightweight interactions into your Livewire components without making full server roundtrips.
Internally, Livewire's frontend is built on top of Alpine. In fact, every Livewire component is actually an Alpine component under-the-hood. This means that you can freely utilize Alpine inside your Livewire components.
The rest of this page assumes a basic familiarity with Alpine. If you're unfamiliar with Alpine, [take a look at the Alpine documentation](https://alpinejs.dev/docs).
### Accessing properties
Livewire exposes a magic `$wire` object to Alpine. You can access the `$wire` object from any Alpine expression inside your Livewire component.
The `$wire` object can be treated like a JavaScript version of your Livewire component. It has all the same properties and methods as the PHP version of your component, but also contains a few dedicated methods to perform specific functions in your template.
For example, we can use `$wire` to show a live character count of the `todo` input field:
```blade
<div>
<input type="text" wire:model="todo">
Todo character length: <h2 x-text="$wire.todo.length"></h2>
</div>
```
As the user types in the field, the character length of the current todo being written will be shown and live-updated on the page, all without sending a network request to the server.
If you prefer, you can use the more explicit `.get()` method to accomplish the same thing:
```blade
<div>
<input type="text" wire:model="todo">
Todo character length: <h2 x-text="$wire.get('todo').length"></h2>
</div>
```
### Manipulating properties
Similarly, you can manipulate your Livewire component properties in JavaScript using `$wire`.
For example, let's add a "Clear" button to the `TodoList` component to allow the user to reset the input field using only JavaScript:
```blade
<div>
<input type="text" wire:model="todo">
<button x-on:click="$wire.todo = ''">Clear</button>
</div>
```
After the user clicks "Clear", the input will be reset to an empty string, without sending a network request to the server.
On the subsequent request, the server-side value of `$todo` will be updated and synchronized.
If you prefer, you can also use the more explicit `.set()` method for setting properties client-side. However, you should note that using `.set()` by default immediately triggers a network request and synchronizes the state with the server. If that is desired, then this is an excellent API:
```blade
<button x-on:click="$wire.set('todo', '')">Clear</button>
```
In order to update the property without sending a network request to the server, you can pass a third bool parameter. This will defer the network request and on a subsequent request, the state will be synchronized on the server-side:
```blade
<button x-on:click="$wire.set('todo', '', false)">Clear</button>
```
| |
244093
|
## Security concerns
While Livewire properties are a powerful feature, there are a few security considerations that you should be aware of before using them.
In short, always treat public properties as user input — as if they were request input from a traditional endpoint. In light of this, it's essential to validate and authorize properties before persisting them to a database — just like you would do when working with request input in a controller.
### Don't trust property values
To demonstrate how neglecting to authorize and validate properties can introduce security holes in your application, the following `UpdatePost` component is vulnerable to attack:
```php
<?php
namespace App\Livewire;
use Livewire\Component;
use App\Models\Post;
class UpdatePost extends Component
{
public $id;
public $title;
public $content;
public function mount(Post $post)
{
$this->id = $post->id;
$this->title = $post->title;
$this->content = $post->content;
}
public function update()
{
$post = Post::findOrFail($this->id);
$post->update([
'title' => $this->title,
'content' => $this->content,
]);
session()->flash('message', 'Post updated successfully!');
}
public function render()
{
return view('livewire.update-post');
}
}
```
```blade
<form wire:submit="update">
<input type="text" wire:model="title">
<input type="text" wire:model="content">
<button type="submit">Update</button>
</form>
```
At first glance, this component may look completely fine. But, let's walk through how an attacker could use the component to do unauthorized things in your application.
Because we are storing the `id` of the post as a public property on the component, it can be manipulated on the client just the same as the `title` and `content` properties.
It doesn't matter that we didn't write an input with `wire:model="id"`. A malicious user can easily change the view to the following using their browser DevTools:
```blade
<form wire:submit="update">
<input type="text" wire:model="id"> <!-- [tl! highlight] -->
<input type="text" wire:model="title">
<input type="text" wire:model="content">
<button type="submit">Update</button>
</form>
```
Now the malicious user can update the `id` input to the ID of a different post model. When the form is submitted and `update()` is called, `Post::findOrFail()` will return and update a post the user is not the owner of.
To prevent this kind of attack, we can use one or both of the following strategies:
* Authorize the input
* Lock the property from updates
#### Authorizing the input
Because `$id` can be manipulated client-side with something like `wire:model`, just like in a controller, we can use [Laravel's authorization](https://laravel.com/docs/authorization) to make sure the current user can update the post:
```php
public function update()
{
$post = Post::findOrFail($this->id);
$this->authorize('update', $post); // [tl! highlight]
$post->update(...);
}
```
If a malicious user mutates the `$id` property, the added authorization will catch it and throw an error.
#### Locking the property
Livewire also allows you to "lock" properties in order to prevent properties from being modified on the client-side. You can "lock" a property from client-side manipulation using the `#[Locked]` attribute:
```php
use Livewire\Attributes\Locked;
use Livewire\Component;
class UpdatePost extends Component
{
#[Locked] // [tl! highlight]
public $id;
// ...
}
```
Now, if a user tries to modify `$id` on the front end, an error will be thrown.
By using `#[Locked]`, you can assume this property has not been manipulated anywhere outside your component's class.
For more information on locking properties, [consult the Locked properties documentation](/docs/locked).
#### Eloquent models and locking
When an Eloquent model is assigned to a Livewire component property, Livewire will automatically lock the property and ensure the ID isn't changed, so that you are safe from these kinds of attacks:
```php
<?php
namespace App\Livewire;
use Livewire\Component;
use App\Models\Post;
class UpdatePost extends Component
{
public Post $post; // [tl! highlight]
public $title;
public $content;
public function mount(Post $post)
{
$this->post = $post;
$this->title = $post->title;
$this->content = $post->content;
}
public function update()
{
$this->post->update([
'title' => $this->title,
'content' => $this->content,
]);
session()->flash('message', 'Post updated successfully!');
}
public function render()
{
return view('livewire.update-post');
}
}
```
### Properties expose system information to the browser
Another essential thing to remember is that Livewire properties are serialized or "dehydrated" before they are sent to the browser. This means that their values are converted to a format that can be sent over the wire and understood by JavaScript. This format can expose information about your application to the browser, including the names and class names of your properties.
For example, suppose you have a Livewire component that defines a public property named `$post`. This property contains an instance of a `Post` model from your database. In this case, the dehydrated value of this property sent over the wire might look something like this:
```json
{
"type": "model",
"class": "App\Models\Post",
"key": 1,
"relationships": []
}
```
As you can see, the dehydrated value of the `$post` property includes the class name of the model (`App\Models\Post`) as well as the ID and any relationships that have been eager-loaded.
If you don't want to expose the class name of the model, you can use Laravel's "morphMap" functionality from a service provider to assign an alias to a model class name:
```php
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Database\Eloquent\Relations\Relation;
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
Relation::morphMap([
'post' => 'App\Models\Post',
]);
}
}
```
Now, when the Eloquent model is "dehydrated" (serialized), the original class name won't be exposed, only the "post" alias:
```json
{
"type": "model",
"class": "App\Models\Post", // [tl! remove]
"class": "post", // [tl! add]
"key": 1,
"relationships": []
}
```
###
| |
244104
|
Livewire provides a simple `wire:click` directive for calling component methods (aka actions) when a user clicks a specific element on the page.
For example, given the `ShowInvoice` component below:
```php
<?php
namespace App\Livewire;
use Livewire\Component;
use App\Models\Invoice;
class ShowInvoice extends Component
{
public Invoice $invoice;
public function download()
{
return response()->download(
$this->invoice->file_path, 'invoice.pdf'
);
}
}
```
You can trigger the `download()` method from the class above when a user clicks a "Download Invoice" button by adding `wire:click="download"`:
```html
<button type="button" wire:click="download"> <!-- [tl! highlight] -->
Download Invoice
</button>
```
## Using `wire:click` on links
When using `wire:click` on `<a>` tags, you must append `.prevent` to prevent the default handling of a link in the browser. Otherwise, the browser will visit the provided link and update the page's URL.
```html
<a href="#" wire:click.prevent="...">
```
## Going deeper
The `wire:click` directive is just one of many different available event listeners in Livewire. For full documentation on its (and other event listeners) capabilities, visit [the Livewire actions documentation page](/docs/actions).
| |
244105
|
```blade
<form wire:submit="save">
<label>
<span>Title</span>
<input type="text" wire:model="title">
@error('title') <span>{{ $message }}</span> @enderror
</label>
<label>
<span>Title</span>
<input type="text" wire:model="title">
@error('title') <span>{{ $message }}</span> @enderror
</label>
<button type="submit">Save</button>
</form>
```
```blade
<form wire:submit="save">
<x-input-text label="Title" wire:model="title" :error="$error->first('title')" />
<x-input-text label="Content" wire:model="content" :error="$error->first('content')" />
<button type="submit">Save</button>
</form>
```
```blade
@props(['label', 'error'])
<label>
<span>{{ $label }}</span>
<input type="text" {{ $attributes->whereStartsWith('wire:') }}>
@if($error) <span>{{ $error }}</span> @endif
</label>
```
## Injecting and running assets
```blade
@php $key = str()->uuid(); @endphp
<div>
<input type="text" id="{{ $key }}">
</div>
@assets
<script src="https://cdn.jsdelivr.net/npm/pikaday/pikaday.js" defer></script>
<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/pikaday/css/pikaday.css">
@endassets
@script
<script>
new Pikaday({ field: document.getElementById('{{ $key }}') });
</script>
@endscript
```
| |
244106
|
Livewire actions are methods on your component that can be triggered by frontend interactions like clicking a button or submitting a form. They provide the developer experience of being able to call a PHP method directly from the browser, allowing you to focus on the logic of your application without getting bogged down writing boilerplate code connecting your application's frontend and backend.
Let's explore a basic example of calling a `save` action on a `CreatePost` component:
```php
<?php
namespace App\Livewire;
use Livewire\Component;
use App\Models\Post;
class CreatePost extends Component
{
public $title = '';
public $content = '';
public function save()
{
Post::create([
'title' => $this->title,
'content' => $this->content,
]);
return redirect()->to('/posts');
}
public function render()
{
return view('livewire.create-post');
}
}
```
```blade
<form wire:submit="save"> <!-- [tl! highlight] -->
<input type="text" wire:model="title">
<textarea wire:model="content"></textarea>
<button type="submit">Save</button>
</form>
```
In the above example, when a user submits the form by clicking "Save", `wire:submit` intercepts the `submit` event and calls the `save()` action on the server.
In essence, actions are a way to easily map user interactions to server-side functionality without the hassle of submitting and handling AJAX requests manually.
## Refreshing a component
Sometimes you may want to trigger a simple "refresh" of your component. For example, if you have a component checking the status of something in the database, you may want to show a button to your users allowing them to refresh the displayed results.
You can do this using Livewire's simple `$refresh` action anywhere you would normally reference your own component method:
```blade
<button type="button" wire:click="$refresh">...</button>
```
When the `$refresh` action is triggered, Livewire will make a server-roundtrip and re-render your component without calling any methods.
It's important to note that any pending data updates in your component (for example `wire:model` bindings) will be applied on the server when the component is refreshed.
Internally, Livewire uses the name "commit" to refer to any time a Livewire component is updated on the server. If you prefer this terminology, you can use the `$commit` helper instead of `$refresh`. The two are identical.
```blade
<button type="button" wire:click="$commit">...</button>
```
You can also trigger a component refresh using AlpineJS in your Livewire component:
```blade
<button type="button" x-on:click="$wire.$refresh()">...</button>
```
Learn more by reading the [documentation for using Alpine inside Livewire](/docs/alpine).
## Confirming an action
When allowing users to perform dangerous actions—such as deleting a post from the database—you may want to show them a confirmation alert to verify that they wish to perform that action.
Livewire makes this easy by providing a simple directive called `wire:confirm`:
```blade
<button
type="button"
wire:click="delete"
wire:confirm="Are you sure you want to delete this post?"
>
Delete post <!-- [tl! highlight:-2,1] -->
</button>
```
When `wire:confirm` is added to an element containing a Livewire action, when a user tries to trigger that action, they will be presented with a confirmation dialog containing the provided message. They can either press "OK" to confirm the action, or press "Cancel" or hit the escape key.
For more information, visit the [`wire:confirm` documentation page](/docs/wire-confirm).
## E
| |
244107
|
vent listeners
Livewire supports a variety of event listeners, allowing you to respond to various types of user interactions:
| Listener | Description |
|-----------------|-------------------------------------------|
| `wire:click` | Triggered when an element is clicked |
| `wire:submit` | Triggered when a form is submitted |
| `wire:keydown` | Triggered when a key is pressed down |
| `wire:keyup` | Triggered when a key is released
| `wire:mouseenter`| Triggered when the mouse enters an element |
| `wire:*`| Whatever text follows `wire:` will be used as the event name of the listener |
Because the event name after `wire:` can be anything, Livewire supports any browser event you might need to listen for. For example, to listen for `transitionend`, you can use `wire:transitionend`.
### Listening for specific keys
You can use one of Livewire's convenient aliases to narrow down key press event listeners to a specific key or combination of keys.
For example, to perform a search when a user hits `Enter` after typing into a search box, you can use `wire:keydown.enter`:
```blade
<input wire:model="query" wire:keydown.enter="searchPosts">
```
You can chain more key aliases after the first to listen for combinations of keys. For example, if you would like to listen for the `Enter` key only while the `Shift` key is pressed, you may write the following:
```blade
<input wire:keydown.shift.enter="...">
```
Below is a list of all the available key modifiers:
| Modifier | Key |
|---------------|------------------------------|
| `.shift` | Shift |
| `.enter` | Enter |
| `.space` | Space |
| `.ctrl` | Ctrl |
| `.cmd` | Cmd |
| `.meta` | Cmd on Mac, Windows key on Windows |
| `.alt` | Alt |
| `.up` | Up arrow |
| `.down` | Down arrow |
| `.left` | Left arrow |
| `.right` | Right arrow |
| `.escape` | Escape |
| `.tab` | Tab |
| `.caps-lock` | Caps Lock |
| `.equal` | Equal, `=` |
| `.period` | Period, `.` |
| `.slash` | Forward Slash, `/` |
### Event handler modifiers
Livewire also includes helpful modifiers to make common event-handling tasks trivial.
For example, if you need to call `event.preventDefault()` from inside an event listener, you can suffix the event name with `.prevent`:
```blade
<input wire:keydown.prevent="...">
```
Here is a full list of all the available event listener modifiers and their functions:
| Modifier | Key |
|------------------|---------------------------------------------------------|
| `.prevent` | Equivalent of calling `.preventDefault()` |
| `.stop` | Equivalent of calling `.stopPropagation()` |
| `.window` | Listens for event on the `window` object |
| `.outside` | Only listens for clicks "outside" the element |
| `.document` | Listens for events on the `document` object |
| `.once` | Ensures the listener is only called once |
| `.debounce` | Debounce the handler by 250ms as a default |
| `.debounce.100ms`| Debounce the handler for a specific amount of time |
| `.throttle` | Throttle the handler to being called every 250ms at minimum |
| `.throttle.100ms`| Throttle the handler at a custom duration |
| `.self` | Only call listener if event originated on this element, not children |
| `.camel` | Converts event name to camel case (`wire:custom-event` -> "customEvent") |
| `.dot` | Converts event name to dot notation (`wire:custom-event` -> "custom.event") |
| `.passive` | `wire:touchstart.passive` won't block scroll performance |
| `.capture` | Listen for event in the "capturing" phase |
Because `wire:` uses [Alpine's](https://alpinejs.dev) `x-on` directive under the hood, these modifiers are made available to you by Alpine. For more context on when you should use these modifiers, consult the [Alpine Events documentation](https://alpinejs.dev/essentials/events).
### Handling third-party events
Livewire also supports listening for custom events fired by third-party libraries.
For example, let's imagine you're using the [Trix](https://trix-editor.org/) rich text editor in your project and you want to listen for the `trix-change` event to capture the editor's content. You can accomplish this using the `wire:trix-change` directive:
```blade
<form wire:submit="save">
<!-- ... -->
<trix-editor
wire:trix-change="setPostContent($event.target.value)"
></trix-editor>
<!-- ... -->
</form>
```
In this example, the `setPostContent` action is called whenever the `trix-change` event is triggered, updating the `content` property in the Livewire component with the current value of the Trix editor.
> [!info] You can access the event object using `$event`
> Within Livewire event handlers, you can access the event object via `$event`. This is useful for referencing information on the event. For example, you can access the element that triggered the event via `$event.target`.
> [!warning]
> The Trix demo code above is incomplete and only useful as a demonstration of event listeners. If used verbatim, a network request would be fired on every single keystroke. A more performant implementation would be:
>
> ```blade
> <trix-editor
> x-on:trix-change="$wire.content = $event.target.value"
>></trix-editor>
> ```
### Listening for dispatched custom events
If your application dispatches custom events from Alpine, you can also listen for those using Livewire:
```blade
<div wire:custom-event="...">
<!-- Deeply nested within this component: -->
<button x-on:click="$dispatch('custom-event')">...</button>
</div>
```
When the button is clicked in the above example, the `custom-event` event is dispatched and bubbles up to the root of the Livewire component where `wire:custom-event` catches it and invokes a given action.
If you want to listen for an event dispatched somewhere else in your application, you will need to wait instead for the event to bubble up to the `window` object and listen for it there. Fortunately, Livewire makes this easy by allowing you to add a simple `.window` modifier to any event listener:
```blade
<div wire:custom-event.window="...">
<!-- ... -->
</div>
<!-- Dispatched somewhere on the page outside the component: -->
<button x-on:click="$dispatch('custom-event')">...</button>
```
### Disabling inputs while a form is being submitted
Consider the `CreatePost` example we previously discussed:
```blade
<form wire:submit="save">
<input wire:model="title">
<textarea wire:model="content"></textarea>
<button type="submit">Save</button>
</form>
```
When a user clicks "Save", a network request is sent to the server to call the `save()` action on the Livewire component.
But, let's imagine that a user is filling out this form on a slow internet connection. The user clicks "Save" and nothing happens initially because the network request takes longer than usual. They might wonder if the submission failed and attempt to click the "Save" button again while the first request is still being handled.
In this case, there would be two requests for the same action being processed at the same time.
To prevent this scenario, Livewire automatically disables the submit button and all form inputs inside the `<form>` element while a `wire:submit` action is being processed. This ensures that a form isn't accidentally submitted twice.
To further lessen the confusion for users on slower connections, it is often helpful to show some loading indicator such as a subtle background color change or SVG animation.
Livewire provides a `wire:loading` directive that makes it trivial to show and hide loading indicators anywhere on a page. Here's a short example of using `wire:loading` to show a loading message below the "Save" button:
```blade
<form wire:submit="save">
<textarea wire:model="content"></textarea>
<button type="submit">Save</button>
<span wire:loading>Saving...</span> <!-- [tl! highlight] -->
</form>
```
`wire:loading` is a powerful feature with a variety of more powerful features. [Check out the full loading documentation for more information](/docs/wire-loading).
## P
| |
244110
|
ecurity concerns
Remember that any public method in your Livewire component can be called from the client-side, even without an associated `wire:click` handler that invokes it. In these scenarios, users can still trigger the action from the browser's DevTools.
Below are three examples of easy-to-miss vulnerabilities in Livewire components. Each will show the vulnerable component first and the secure component after. As an exercise, try spotting the vulnerabilities in the first example before viewing the solution.
If you are having difficulty spotting the vulnerabilities and that makes you concerned about your ability to keep your own applications secure, remember all these vulnerabilities apply to standard web applications that use requests and controllers. If you use a component method as a proxy for a controller method, and its parameters as a proxy for request input, you should be able to apply your existing application security knowledge to your Livewire code.
### Always authorize action parameters
Just like controller request input, it's imperative to authorize action parameters since they are arbitrary user input.
Below is a `ShowPosts` component where users can view all their posts on one page. They can delete any post they like using one of the post's "Delete" buttons.
Here is a vulnerable version of component:
```php
<?php
namespace App\Livewire;
use Illuminate\Support\Facades\Auth;
use Livewire\Component;
use App\Models\Post;
class ShowPosts extends Component
{
public function delete($id)
{
$post = Post::find($id);
$post->delete();
}
public function render()
{
return view('livewire.show-posts', [
'posts' => Auth::user()->posts,
]);
}
}
```
```blade
<div>
@foreach ($posts as $post)
<div wire:key="{{ $post->id }}">
<h1>{{ $post->title }}</h1>
<span>{{ $post->content }}</span>
<button wire:click="delete({{ $post->id }})">Delete</button>
</div>
@endforeach
</div>
```
Remember that a malicious user can call `delete()` directly from a JavaScript console, passing any parameters they would like to the action. This means that a user viewing one of their posts can delete another user's post by passing the un-owned post ID to `delete()`.
To protect against this, we need to authorize that the user owns the post about to be deleted:
```php
<?php
namespace App\Livewire;
use Illuminate\Support\Facades\Auth;
use Livewire\Component;
use App\Models\Post;
class ShowPosts extends Component
{
public function delete($id)
{
$post = Post::find($id);
$this->authorize('delete', $post); // [tl! highlight]
$post->delete();
}
public function render()
{
return view('livewire.show-posts', [
'posts' => Auth::user()->posts,
]);
}
}
```
### Always authorize server-side
Like standard Laravel controllers, Livewire actions can be called by any user, even if there isn't an affordance for invoking the action in the UI.
Consider the following `BrowsePosts` component where any user can view all the posts in the application, but only administrators can delete a post:
```php
<?php
namespace App\Livewire;
use Livewire\Component;
use App\Models\Post;
class BrowsePosts extends Component
{
public function deletePost($id)
{
$post = Post::find($id);
$post->delete();
}
public function render()
{
return view('livewire.browse-posts', [
'posts' => Post::all(),
]);
}
}
```
```blade
<div>
@foreach ($posts as $post)
<div wire:key="{{ $post->id }}">
<h1>{{ $post->title }}</h1>
<span>{{ $post->content }}</span>
@if (Auth::user()->isAdmin())
<button wire:click="deletePost({{ $post->id }})">Delete</button>
@endif
</div>
@endforeach
</div>
```
As you can see, only administrators can see the "Delete" button; however, any user can call `deletePost()` on the component from the browser's DevTools.
To patch this vulnerability, we need to authorize the action on the server like so:
```php
<?php
namespace App\Livewire;
use Illuminate\Support\Facades\Auth;
use Livewire\Component;
use App\Models\Post;
class BrowsePosts extends Component
{
public function deletePost($id)
{
if (! Auth::user()->isAdmin) { // [tl! highlight:2]
abort(403);
}
$post = Post::find($id);
$post->delete();
}
public function render()
{
return view('livewire.browse-posts', [
'posts' => Post::all(),
]);
}
}
```
With this change, only administrators can delete a post from this component.
### Keep dangerous methods protected or private
Every public method inside your Livewire component is callable from the client. Even methods you haven't referenced inside a `wire:click` handler. To prevent a user from calling a method that isn't intended to be callable client-side, you should mark them as `protected` or `private`. By doing so, you restrict the visibility of that sensitive method to the component's class and its subclasses, ensuring they cannot be called from the client-side.
Consider the `BrowsePosts` example that we previously discussed, where users can view all posts in your application, but only administrators can delete posts. In the [Always authorize server-side](/docs/actions#always-authorize-server-side) section, we made the action secure by adding server-side authorization. Now imagine we refactor the actual deletion of the post into a dedicated method like you might do in order to simplify your code:
```php
// Warning: This snippet demonstrates what NOT to do...
<?php
namespace App\Livewire;
use Illuminate\Support\Facades\Auth;
use Livewire\Component;
use App\Models\Post;
class BrowsePosts extends Component
{
public function deletePost($id)
{
if (! Auth::user()->isAdmin) {
abort(403);
}
$this->delete($id); // [tl! highlight]
}
public function delete($postId) // [tl! highlight:5]
{
$post = Post::find($postId);
$post->delete();
}
public function render()
{
return view('livewire.browse-posts', [
'posts' => Post::all(),
]);
}
}
```
```blade
<div>
@foreach ($posts as $post)
<div wire:key="{{ $post->id }}">
<h1>{{ $post->title }}</h1>
<span>{{ $post->content }}</span>
<button wire:click="deletePost({{ $post->id }})">Delete</button>
</div>
@endforeach
</div>
```
As you can see, we refactored the post deletion logic into a dedicated method named `delete()`. Even though this method isn't referenced anywhere in our template, if a user gained knowledge of its existence, they would be able to call it from the browser's DevTools because it is `public`.
To remedy this, we can mark the method as `protected` or `private`. Once the method is marked as `protected` or `private`, an error will be thrown if a user tries to invoke it:
```php
<?php
namespace App\Livewire;
use Illuminate\Support\Facades\Auth;
use Livewire\Component;
use App\Models\Post;
class BrowsePosts extends Component
{
public function deletePost($id)
{
if (! Auth::user()->isAdmin) {
abort(403);
}
$this->delete($id);
}
protected function delete($postId) // [tl! highlight]
{
$post = Post::find($postId);
$post->delete();
}
public function render()
{
return view('livewire.browse-posts', [
'posts' => Post::all(),
]);
}
}
```
<!--
## Applying middleware
By default, Livewire re-applies authentication and authorization related middleware on subsequent requests if those middleware were applied on the initial page load request.
For example, imagine your component is loaded inside a route that is assigned the `auth` middleware and a user's session ends. When the user triggers another action, the `auth` middleware will be re-applied and the user will receive an error.
If there are specific middleware that you would like to apply to a specific action, you may do so with the `#[Middleware]` attribute. For example, we could apply a `LogPostCreation` middleware to an action that creates posts:
```php
<?php
namespace App\Livewire;
use App\Http\Middleware\LogPostCreation;
use Livewire\Component;
class CreatePost extends Component
{
public $title;
public $content;
#[Middleware(LogPostCreation::class)] // [tl! highlight]
public function save()
{
// Create the post...
}
// ...
}
```
Now, the `LogPostCreation` middleware will be applied only to the `createPost` action, ensuring that the activity is only being logged when users create a new post.
-->
| |
244111
|
Many modern web applications are built as "single page applications" (SPAs). In these applications, each page rendered by the application no longer requires a full browser page reload, avoiding the overhead of re-downloading JavaScript and CSS assets on every request.
The alternative to a *single page application* is a *multi-page application*. In these applications, every time a user clicks a link, an entirely new HTML page is requested and rendered in the browser.
While most PHP applications have traditionally been multi-page applications, Livewire offers a single page application experience via a simple attribute you can add to links in your application: `wire:navigate`.
## Basic usage
Let's explore an example of using `wire:navigate`. Below is a typical Laravel routes file (`routes/web.php`) with three Livewire components defined as routes:
```php
use App\Livewire\Dashboard;
use App\Livewire\ShowPosts;
use App\Livewire\ShowUsers;
Route::get('/', Dashboard::class);
Route::get('/posts', ShowPosts::class);
Route::get('/users', ShowUsers::class);
```
By adding `wire:navigate` to each link in a navigation menu on each page, Livewire will prevent the standard handling of the link click and replace it with its own, faster version:
```blade
<nav>
<a href="/" wire:navigate>Dashboard</a>
<a href="/posts" wire:navigate>Posts</a>
<a href="/users" wire:navigate>Users</a>
</nav>
```
Below is a breakdown of what happens when a `wire:navigate` link is clicked:
* User clicks a link
* Livewire prevents the browser from visiting the new page
* Instead, Livewire requests the page in the background and shows a loading bar at the top of the page
* When the HTML for the new page has been received, Livewire replaces the current page's URL, `<title>` tag and `<body>` contents with the elements from the new page
This technique results in much faster page load times — often twice as fast — and makes the application "feel" like a JavaScript powered single page application.
## Redirects
When one of your Livewire components redirects users to another URL within your application, you can also instruct Livewire to use its `wire:navigate` functionality to load the new page. To accomplish this, provide the `navigate` argument to the `redirect()` method:
```php
return $this->redirect('/posts', navigate: true);
```
Now, instead of a full page request being used to redirect the user to the new URL, Livewire will replace the contents and URL of the current page with the new one.
## Prefetching links
By default, Livewire includes a gentle strategy to _prefetch_ pages before a user clicks on a link:
* A user presses down on their mouse button
* Livewire starts requesting the page
* They lift up on the mouse button to complete the _click_
* Livewire finishes the request and navigates to the new page
Surprisingly, the time between a user pressing down and lifting up on the mouse button is often enough time to load half or even an entire page from the server.
If you want an even more aggressive approach to prefetching, you may use the `.hover` modifier on a link:
```blade
<a href="/posts" wire:navigate.hover>Posts</a>
```
The `.hover` modifier will instruct Livewire to prefetch the page after a user has hovered over the link for `60` milliseconds.
> [!warning] Prefetching on hover increases server usage
> Because not all users will click a link they hover over, adding `.hover` will request pages that may not be needed, though Livewire attempts to mitigate some of this overhead by waiting `60` milliseconds before prefetching the page.
## Persisting elements across page visits
Sometimes, there are parts of a user interface that you need to persist between page loads, such as audio or video players. For example, in a podcasting application, a user may want to keep listening to an episode as they browse other pages.
You can achieve this in Livewire with the `@persist` directive.
By wrapping an element with `@persist` and providing it with a name, when a new page is requested using `wire:navigate`, Livewire will look for an element on the new page that has a matching `@persist`. Instead of replacing the element like normal, Livewire will use the existing DOM element from the previous page in the new page, preserving any state within the element.
Here is an example of an `<audio>` player element being persisted across pages using `@persist`:
```blade
@persist('player')
<audio src="{{ $episode->file }}" controls></audio>
@endpersist
```
If the above HTML appears on both pages — the current page, and the next one — the original element will be re-used on the new page. In the case of an audio player, the audio playback won't be interrupted when navigating from one page to another.
Please be aware that the persisted element must be placed outside your Livewire components. A common practice is to position the persisted element in your main layout, such as `resources/views/components/layouts/app.blade.php`.
```html
<!-- resources/views/components/layouts/app.blade.php -->
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{{ $title ?? 'Page Title' }}</title>
</head>
<body>
<main>
{{ $slot }}
</main>
@persist('player') <!-- [tl! highlight:2] -->
<audio src="{{ $episode->file }}" controls></audio>
@endpersist
</body>
</html>
```
### Preserving scroll position
By default, Livewire will preserve the scroll position of a page when navigating back and forth between pages. However, sometimes you may want to preserve the scroll position of an individual element you are persisting between page loads.
To do this, you must add `wire:scroll` to the element containing a scrollbar like so:
```html
@persist('scrollbar')
<div class="overflow-y-scroll" wire:scroll> <!-- [tl! highlight] -->
<!-- ... -->
</div>
@endpersist
```
## JavaScript hooks
Each page navigation triggers three lifecycle hooks:
* `livewire:navigate`
* `livewire:navigating`
* `livewire:navigated`
It's important to note that these three hooks events are dispatched on navigations of all types. This includes manual navigation using `Livewire.navigate()`, redirecting with navigation enabled, and back and forward button presses in the browser.
Here's an example of registering listeners for each of these events:
```js
document.addEventListener('livewire:navigate', (event) => {
// Triggers when a navigation is triggered.
// Can be "cancelled" (prevent the navigate from actually being performed):
event.preventDefault()
// Contains helpful context about the navigation trigger:
let context = event.detail
// A URL object of the intended destination of the navigation...
context.url
// A boolean [true/false] indicating whether or not this navigation
// was triggered by a back/forward (history state) navigation...
context.history
// A boolean [true/false] indicating whether or not there is
// cached version of this page to be used instead of
// fetching a new one via a network round-trip...
context.cached
})
document.addEventListener('livewire:navigating', () => {
// Triggered when new HTML is about to swapped onto the page...
// This is a good place to mutate any HTML before the page
// is nagivated away from...
})
document.addEventListener('livewire:navigated', () => {
// Triggered as the final step of any page navigation...
// Also triggered on page-load instead of "DOMContentLoaded"...
})
```
> [!warning] Event listeners will persist across pages
>
> When you attach an event listener to the document it will not be removed when you navigate to a different page. This can lead to unexpected behaviour if you need code to run only after navigating to a specific page, or if you add the same event listener on every page. If you do not remove your event listener it may cause exceptions on other pages when it's looking for elements that do not exist, or you may end up with the event listener executing multiple times per navigation.
>
> An easy method to remove an event listener after it runs is to pass the option `{once: true}` as a third parameter to the `addEventListener` function.
> ```js
> document.addEventListener('livewire:navigated', () => {
> // ...
> }, { once: true })
> ```
## Manually visiting a new page
In addition to `wire:navigate`, you can manually call the `Livewire.navigate()` method to trigger a visit to a new page using JavaScript:
```html
<script>
// ...
Livewire.navigate('/new/url')
</script>
```
## Using
| |
244112
|
with analytics software
When navigating pages using `wire:navigate` in your app, any `<script>` tags in the `<head>` only evaluate when the page is initially loaded.
This creates a problem for analytics software such as [Fathom Analytics](https://usefathom.com/). These tools rely on a `<script>` snippet being evaluated on every single page change, not just the first.
Tools like [Google Analytics](https://marketingplatform.google.com/about/analytics/) are smart enough to handle this automatically, however, when using Fathom Analytics, you must add `data-spa="auto"` to your script tag to ensure each page visit is tracked properly:
```blade
<head>
<!-- ... -->
<!-- Fathom Analytics -->
@if (! config('app.debug'))
<script src="https://cdn.usefathom.com/script.js" data-site="ABCDEFG" data-spa="auto" defer></script> <!-- [tl! highlight] -->
@endif
</head>
```
## Script evaluation
When navigating to a new page using `wire:navigate`, it _feels_ like the browser has changed pages; however, from the browser's perspective, you are technically still on the original page.
Because of this, styles and scripts are executed normally on the first page, but on subsequent pages, you may have to tweak the way you normally write JavaScript.
Here are a few caveats and scenarios you should be aware of when using `wire:navigate`.
### Don't rely on `DOMContentLoaded`
It's common practice to place JavaScript inside a `DOMContentLoaded` event listener so that the code you want to run only executes after the page has fully loaded.
When using `wire:navigate`, `DOMContentLoaded` is only fired on the first page visit, not subsequent visits.
To run code on every page visit, swap every instance of `DOMContentLoaded` with `livewire:navigated`:
```js
document.addEventListener('DOMContentLoaded', () => { // [tl! remove]
document.addEventListener('livewire:navigated', () => { // [tl! add]
// ...
})
```
Now, any code placed inside this listener will be run on the initial page visit, and also after Livewire has finished navigating to subsequent pages.
Listening to this event is useful for things like initializing third-party libraries.
### Scripts in `<head>` are loaded once
If two pages include the same `<script>` tag in the `<head>`, that script will only be run on the initial page visit and not on subsequent page visits.
```blade
<!-- Page one -->
<head>
<script src="/app.js"></script>
</head>
<!-- Page two -->
<head>
<script src="/app.js"></script>
</head>
```
### New `<head>` scripts are evaluated
If a subsequent page includes a new `<script>` tag in the `<head>` that was not present in the `<head>` of the initial page visit, Livewire will run the new `<script>` tag.
In the below example, _page two_ includes a new JavaScript library for a third-party tool. When the user navigates to _page two_, that library will be evaluated.
```blade
<!-- Page one -->
<head>
<script src="/app.js"></script>
</head>
<!-- Page two -->
<head>
<script src="/app.js"></script>
<script src="/third-party.js"></script>
</head>
```
> [!info] Head assets are blocking
> If you are navigating to a new page that contains an asset like `<script src="...">` in the head tag. That asset will be fetched and processed before the navigation is complete and the new page is swapped in. This might be surprising behavior, but it ensures any scripts that depend on those assets will have immediate access to them.
### Reloading when assets change
It's common practice to include a version hash in an application's main JavaScript file name. This ensures that after deploying a new version of your application, users will receive the fresh JavaScript asset, and not an old version served from the browser's cache.
But, now that you are using `wire:navigate` and each page visit is no longer a fresh browser page load, your users may still be receiving stale JavaScript after deployments.
To prevent this, you may add `data-navigate-track` to a `<script>` tag in `<head>`:
```blade
<!-- Page one -->
<head>
<script src="/app.js?id=123" data-navigate-track></script>
</head>
<!-- Page two -->
<head>
<script src="/app.js?id=456" data-navigate-track></script>
</head>
```
When a user visits _page two_, Livewire will detect a fresh JavaScript asset and trigger a full browser page reload.
If you are using [Laravel's Vite plug-in](https://laravel.com/docs/vite#loading-your-scripts-and-styles) to bundle and serve your assets, Livewire adds `data-navigate-track` to the rendered HTML asset tags automatically. You can continue referencing your assets and scripts like normal:
```blade
<head>
@vite(['resources/css/app.css', 'resources/js/app.js'])
</head>
```
Livewire will automatically inject `data-navigate-track` onto the rendered HTML tags.
> [!warning] Only query string changes are tracked
> Livewire will only reload a page if a `[data-navigate-track]` element's query string (`?id="456"`) changes, not the URI itself (`/app.js`).
### Scripts in the `<body>` are re-evaluated
Because Livewire replaces the entire contents of the `<body>` on every new page, all `<script>` tags on the new page will be run:
```blade
<!-- Page one -->
<body>
<script>
console.log('Runs on page one')
</script>
</body>
<!-- Page two -->
<body>
<script>
console.log('Runs on page two')
</script>
</body>
```
If you have a `<script>` tag in the body that you only want to be run once, you can add the `data-navigate-once` attribute to the `<script>` tag and Livewire will only run it on the initial page visit:
```blade
<script data-navigate-once>
console.log('Runs only on page one')
</script>
```
## Customizing the progress bar
When a page takes longer than 150ms to load, Livewire will show a progress bar at the top of the page.
You can customize the color of this bar or disable it all together inside Livewire's config file (`config/livewire.php`):
```php
'navigate' => [
'show_progress_bar' => false,
'progress_bar_color' => '#2299dd',
],
```
| |
244113
|
File downloads in Livewire work much the same as in Laravel itself. Typically, you can use any Laravel download utility inside a Livewire component, and it should work as expected.
However, behind the scenes, file downloads are handled differently than in a standard Laravel application. When using Livewire, the file's contents are Base64 encoded, sent to the frontend, and decoded back into binary to be downloaded directly from the client.
## Basic usage
Triggering a file download in Livewire is as simple as returning a standard Laravel download response.
Below is an example of a `ShowInvoice` component that contains a "Download" button to download the invoice PDF:
```php
<?php
namespace App\Livewire;
use Livewire\Component;
use App\Models\Invoice;
class ShowInvoice extends Component
{
public Invoice $invoice;
public function mount(Invoice $invoice)
{
$this->invoice = $invoice;
}
public function download()
{
return response()->download( // [tl! highlight:2]
$this->invoice->file_path, 'invoice.pdf'
);
}
public function render()
{
return view('livewire.show-invoice');
}
}
```
```blade
<div>
<h1>{{ $invoice->title }}</h1>
<span>{{ $invoice->date }}</span>
<span>{{ $invoice->amount }}</span>
<button type="button" wire:click="download">Download</button> <!-- [tl! highlight] -->
</div>
```
Just like in a Laravel controller, you can also use the `Storage` facade to initiate downloads:
```php
public function download()
{
return Storage::disk('invoices')->download('invoice.csv');
}
```
## Streaming downloads
Livewire can also stream downloads; however, they aren't truly streamed. The download isn't triggered until the file's contents are collected and delivered to the browser:
```php
public function download()
{
return response()->streamDownload(function () {
echo '...'; // Echo download contents directly...
}, 'invoice.pdf');
}
```
## Testing file downloads
Livewire also provides a `->assertFileDownloaded()` method to easily test that a file was downloaded with a given name:
```php
use App\Models\Invoice;
/** @test */
public function can_download_invoice()
{
$invoice = Invoice::factory();
Livewire::test(ShowInvoice::class)
->call('download')
->assertFileDownloaded('invoice.pdf');
}
```
You can also test to ensure a file was not downloaded using the `->assertNoFileDownloaded()` method:
```php
use App\Models\Invoice;
/** @test */
public function does_not_download_invoice_if_unauthorised()
{
$invoice = Invoice::factory();
Livewire::test(ShowInvoice::class)
->call('download')
->assertNoFileDownloaded();
}
```
| |
244114
|
When a Livewire component updates the browser's DOM, it does so in an intelligent way we call "morphing". The term _morph_ is in contrast with a word like _replace_.
Instead of _replacing_ a component's HTML with newly rendered HTML every time a component is updated, Livewire dynamically compares the current HTML with the new HTML, identifies differences, and makes surgical changes to the HTML only in the places where changes are needed.
This has the benefit of preserving existing, un-changed elements on a component. For example, event listeners, focus state, and form input values are all preserved between Livewire updates. Of course, morphing also offers increased performance compared to wiping and re-rending new DOM on every update.
## How morphing works
To understand how Livewire determines which elements to update between Livewire requests, consider this simple `Todos` component:
```php
class Todos extends Component
{
public $todo = '';
public $todos = [
'first',
'second',
];
public function add()
{
$this->todos[] = $this->todo;
}
}
```
```blade
<form wire:submit="add">
<ul>
@foreach ($todos as $item)
<li>{{ $item }}</li>
@endforeach
</ul>
<input wire:model="todo">
</form>
```
The initial render of this component will output the following HTML:
```html
<form wire:submit="add">
<ul>
<li>first</li>
<li>second</li>
</ul>
<input wire:model="todo">
</form>
```
Now, imagine you typed "third" into the input field and pressed the `[Enter]` key. The newly rendered HTML would be:
```html
<form wire:submit="add">
<ul>
<li>first</li>
<li>second</li>
<li>third</li> <!-- [tl! add] -->
</ul>
<input wire:model="todo">
</form>
```
When Livewire processes the component update, it _morphs_ the original DOM into the newly rendered HTML. The following visualization should intuitively give you an understanding of how it works:
<div style="padding:56.25% 0 0 0;position:relative;"><iframe src="https://player.vimeo.com/video/844600772?badge=0&autopause=0&player_id=0&app_id=58479" frameborder="0" allow="autoplay; fullscreen; picture-in-picture" allowfullscreen style="position:absolute;top:0;left:0;width:100%;height:100%;" title="morph_basic"></iframe></div><script src="https://player.vimeo.com/api/player.js"></script>
As you can see, Livewire walks both HTML trees simultaneously. As it encounters each element in both trees, it compares them for changes, additions, and removals. If it detects one, it surgically makes the appropriate change.
## Morphing shortcomings
The following are scenarios where morphing algorithms fail to correctly identify the change in HTML trees and therefore cause problems in your application.
### Inserting intermediate elements
Consider the following Livewire Blade template for a fictitious `CreatePost` component:
```blade
<form wire:submit="save">
<div>
<input wire:model="title">
</div>
@if ($errors->has('title'))
<div>{{ $errors->first('title') }}</div>
@endif
<div>
<button>Save</button>
</div>
</form>
```
If a user tries submitting the form, but encounters a validation error, the following problem occurs:
<div style="padding:56.25% 0 0 0;position:relative;"><iframe src="https://player.vimeo.com/video/844600840?badge=0&autopause=0&player_id=0&app_id=58479" frameborder="0" allow="autoplay; fullscreen; picture-in-picture" allowfullscreen style="position:absolute;top:0;left:0;width:100%;height:100%;" title="morph_problem"></iframe></div><script src="https://player.vimeo.com/api/player.js"></script>
As you can see, when Livewire encounters the new `<div>` for the error message, it doesn't know whether to change the existing `<div>` in-place, or insert the new `<div>` in the middle.
To re-iterate what's happening more explicitly:
* Livewire encounters the first `<div>` in both trees. They are the same, so it continues.
* Livewire encounters the second `<div>` in both trees and thinks they are the same `<div>`, just one has changed contents. So instead of inserting the error message as a new element, it changes the `<button>` into an error message.
* Livewire then, after mistakenly modifying the previous element, notices an additional element at the end of the comparison. It then creates and appends the element after the previous one.
* Therefore, destroying, then re-creating an element that otherwise should have been simply moved.
This scenario is at the root of almost all morph-related bugs.
Here are a few specific problematic impacts of these bugs:
* Event listeners and element state are lost between updates
* Event listeners and state are misplaced across the wrong elements
* Entire Livewire components can be reset or duplicated as Livewire components are also simply elements in the DOM tree
* Alpine components and state can be lost or misplaced
Fortunately, Livewire has worked hard to mitigate these problems using the following approaches:
### Internal look-ahead
Livewire has an additional step in its morphing algorithm that checks subsequent elements and their contents before changing an element.
This prevents the above scenario from happening in many cases.
Here is a visualization of the "look-ahead" algorithm in action:
<div style="padding:56.25% 0 0 0;position:relative;"><iframe src="https://player.vimeo.com/video/844600800?badge=0&autopause=0&player_id=0&app_id=58479" frameborder="0" allow="autoplay; fullscreen; picture-in-picture" allowfullscreen style="position:absolute;top:0;left:0;width:100%;height:100%;" title="morph_lookahead"></iframe></div><script src="https://player.vimeo.com/api/player.js"></script>
### Injecting morph markers
On the backend, Livewire automatically detects conditionals inside Blade templates and wraps them in HTML comment markers that Livewire's JavaScript can use as a guide when morphing.
Here's an example of the previous Blade template but with Livewire's injected markers:
```blade
<form wire:submit="save">
<div>
<input wire:model="title">
</div>
<!--[if BLOCK]><![endif]--> <!-- [tl! highlight] -->
@if ($errors->has('title'))
<div>Error: {{ $errors->first('title') }}</div>
@endif
<!--[if ENDBLOCK]><![endif]--> <!-- [tl! highlight] -->
<div>
<button>Save</button>
</div>
</form>
```
With these markers injected into the template, Livewire can now more easily detect the difference between a change and an addition.
This feature is extremely beneficial to Livewire applications, but because it requires parsing templates via regex, it can sometimes fail to properly detect conditionals. If this feature is more of a hindrance than a help to your application, you can disable it with the following configuration in your application's `config/livewire.php` file:
```php
'inject_morph_markers' => false,
```
#### Wrapping conditionals
If the above two solutions don't cover your situation, the most reliable way to avoid morphing problems is to wrap conditionals and loops in their own elements that are always present.
For example, here's the above Blade template rewritten with wrapping `<div>` elements:
```blade
<form wire:submit="save">
<div>
<input wire:model="title">
</div>
<div> <!-- [tl! highlight] -->
@if ($errors->has('title'))
<div>{{ $errors->first('title') }}</div>
@endif
</div> <!-- [tl! highlight] -->
<div>
<button>Save</button>
</div>
</form>
```
Now that the conditional has been wrapped in a persistent element, Livewire will morph the two different HTML trees properly.
#### Bypassing morphing
If you need to bypass morphing entirely for an element, you can use [wire:replace](/docs/wire-replace) to instruct livewire to replace all children of an element instead of attempting to morph the existing elements.
| |
244115
|
## Automated upgrade tool
To save you time upgrading, we've included an Artisan command to automate as many parts of the upgrade process as possible.
After [installing Livewire version 3](/docs/upgrading#update-livewire-to-version-3), run the following command, and you will receive prompts to upgrade each breaking change automatically:
```shell
php artisan livewire:upgrade
```
Although the above command can upgrade much of your application, the only way to ensure a complete upgrade is to follow the step-by-step guide on this page.
> [!tip] Hire us to upgrade your app instead
> If you have a large Livewire application or just don't want to deal with upgrading from version 2 to version 3, you can hire us to handle it for you. [Learn more about our upgrade service here.](/jumpstart)
## Upgrade PHP
Livewire now requires that your application is running on PHP version 8.1 or greater.
## Update Livewire to version 3
Run the following composer command to upgrade your application's Livewire dependency from version 2 to 3:
```shell
composer require livewire/livewire "^3.0"
```
> [!warning] Livewire 3 package compatibility
> Most of the major third-party Livewire packages either currently support Livewire 3 or are working on supporting it soon. However, there will inevitably be packages that take longer to release support for Livewire 3.
## Clear the view cache
Run the following Artisan command from your application's root directory to clear any cached/compiled Blade views and force Livewire to re-compile them to be Livewire 3 compatible:
```shell
php artisan view:clear
```
## Merge new configuration
Livewire 3 has changed multiple configuration options. If your application has a published configuration file (`config/livewire.php`), you will need to update it to account for the following changes.
### New configuration
The following configuration keys have been introduced in version 3:
```php
'legacy_model_binding' => false,
'inject_assets' => true,
'inject_morph_markers' => true,
'navigate' => false,
'pagination_theme' => 'tailwind',
```
You can reference [Livewire's new configuration file on GitHub](https://github.com/livewire/livewire/blob/master/config/livewire.php) for additional option descriptions and copy-pastable code.
### Changed configuration
The following configuration items have been updated with new default values:
#### New class namespace
Livewire's default `class_namespace` has changed from `App\Http\Livewire` to `App\Livewire`. You are welcome to keep the old namespace configuration value; however, if you choose to update your configuration to the new namespace, you will have to move your Livewire components to `app/Livewire`:
```php
'class_namespace' => 'App\\Http\\Livewire', // [tl! remove]
'class_namespace' => 'App\\Livewire', // [tl! add]
```
#### New layout view path
When rendering full-page components in version 2, Livewire would use `resources/views/layouts/app.blade.php` as the default layout Blade component.
Because of a growing community preference for anonymous Blade components, Livewire 3 has changed the default location to: `resources/views/components/layouts/app.blade.php`.
```php
'layout' => 'layouts.app', // [tl! remove]
'layout' => 'components.layouts.app', // [tl! add]
```
### Removed configuration
Livewire no longer recognizes the following configuration items.
#### `app_url`
If your application is served under a non-root URI, in Livewire 2 you could use the `app_url` configuration option to configure the URL Livewire uses to make AJAX requests to.
In this case, we've found a string configuration to be too rigid. Therefore, Livewire 3 has chosen to use runtime configuration instead. You can reference our documentation on [configuring Livewire's update endpoint](/docs/installation#configuring-livewires-update-endpoint) for more information.
#### `asset_url`
In Livewire 2, if your application was served under a non-root URI, you would use the `asset_url` configuration option to configure the base URL that Livewire uses to serve its JavaScript assets.
Livewire 3 has instead chosen a runtime configuration strategy. You can reference our documentation on [configuring Livewire's script asset endpoint](/docs/installation#customizing-the-asset-url) for more information.
#### `middleware_group`
Because Livewire now exposes a more flexible way to customize its update endpoint, the `middleware_group` configuration option has been removed.
You can reference our documentation on [customizing Livewire's update endpoint](/docs/installation#configuring-livewires-update-endpoint) for more information on applying custom middleware to Livewire requests.
#### `manifest_path`
Livewire 3 no longer uses a manifest file for component autoloading. Therefore, the `manifest_path` configuration is no longer necessary.
#### `back_button_cache`
Because Livewire 3 now offers an [SPA experience for your application using `wire:navigate`](/docs/navigate), the `back_button_cache` configuration is no longer necessary.
## Livewire app namespace
In version 2, Livewire components were generated and recognized automatically under the `App\Http\Livewire` namespace.
Livewire 3 has changed this default to: `App\Livewire`.
You can either move all of your components to the new location or add the following configuration to your application's `config/livewire.php` configuration file:
```php
'class_namespace' => 'App\\Http\\Livewire',
```
### Discovery
With Livewire 3, there is no manifest present, and there is therefore nothing to “discover” in relation to Livewire Components, and you can safely remove any livewire:discover references from your build scripts without issue.
## Page component layout view
When rendering Livewire components as full pages using a syntax like the following:
```php
Route::get('/posts', ShowPosts::class);
```
The Blade layout file used by Livewire to render the component has changed from `resources/views/layouts/app.blade.php` to `resources/views/components/layouts/app.blade.php`:
```shell
resources/views/layouts/app.blade.php #[tl! remove]
resources/views/components/layouts/app.blade.php #[tl! add]
```
You can either move your layout file to the new location or apply the following configuration inside your application's `config/livewire.php` configuration file:
```php
'layout' => 'layouts.app',
```
For more information, check out the documentation on [creating and using a page-component layout](/docs/components#layout-files).
## Eloquent model binding
Livewire 2 supported `wire:model` binding directly to Eloquent model properties. For example, the following was a common pattern:
```php
public Post $post;
protected $rules = [
'post.title' => 'required',
'post.description' => 'required',
];
```
```html
<input wire:model="post.title">
<input wire:model="post.description">
```
In Livewire 3, binding directly to Eloquent models has been disabled in favor of using individual properties, or extracting [Form Objects](/docs/forms#extracting-a-form-object).
However, because this behavior is so heavily relied upon in Livewire applications, version 3 maintains support for this behavior via a configuration item in `config/livewire.php`:
```php
'legacy_model_binding' => true,
```
By setting `legacy_model_binding` to `true`, Livewire will handle Eloquent model properties exactly as it did in version 2.
## A
| |
244116
|
lpineJS
Livewire 3 ships with [AlpineJS](https://alpinejs.dev) by default.
If you manually include Alpine in your Livewire application, you will need to remove it, so that Livewire's built-in version doesn't conflict.
### Including Alpine via a script tag
If you include Alpine into your application via a script tag like the following, you can remove it entirely and Livewire will load its internal version instead:
```html
<script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script> <!-- [tl! remove] -->
```
### Including plugins via a script tag
Livewire 3 now ships with the following Alpine plugins out-of-the-box:
* [Anchor](https://alpinejs.dev/plugins/anchor)
* [Collapse](https://alpinejs.dev/plugins/collapse)
* [Focus](https://alpinejs.dev/plugins/focus)
* [Intersect](https://alpinejs.dev/plugins/intersect)
* [Mask](https://alpinejs.dev/plugins/mask)
* [Morph](https://alpinejs.dev/plugins/morph)
* [Persist](https://alpinejs.dev/plugins/persist)
It is worth keeping an eye on changes to the [package.json](https://github.com/livewire/livewire/blob/main/package.json) file, as new Alpine plugins may be added!
If you have previously included any of these in your application via `<script>` tags like below, you should remove them along with Alpine's core:
```html
<script defer src="https://cdn.jsdelivr.net/npm/@alpinejs/intersect@3.x.x/dist/cdn.min.js"></script> <!-- [tl! remove:1] -->
<!-- ... -->
```
### Accessing the Alpine global via a script tag
If you are currently accessing the `Alpine` global object from a script tag like so:
```html
<script>
document.addEventListener('alpine:init', () => {
Alpine.data(...)
})
</script>
```
You may continue to do so, as Livewire internally includes and registers Alpine's global object like before.
### Including via JS bundle
If you have included Alpine or any of the popular core Alpine plugins mentioned above via NPM into your applications JavaScript bundle like so:
```js
// Warning: this is a snippet of the Livewire 2 approach to including Alpine
import Alpine from 'alpinejs'
import intersect from '@alpinejs/intersect'
Alpine.plugin(intersect)
Alpine.start()
```
You can remove them entirely, because Livewire includes Alpine and many popular Alpine plugins by default.
#### Accessing Alpine via JS bundle
If you are registering custom Alpine plugins or components inside your application's JavaScript bundle like so:
```js
// Warning: this is a snippet of the Livewire 2 approach to including Alpine
import Alpine from 'alpinejs'
import customPlugin from './plugins/custom-plugin'
Alpine.plugin(customPlugin)
Alpine.start()
```
You can still accomplish this by importing the Livewire core ESM module into your bundle and accessing `Alpine` from there.
To import Livewire into your bundle, you must first disable Livewire's normal JavaScript injection and provide the necessary configuration to Livewire by replacing `@livewireScripts` with `@livewireScriptConfig` in your application's primary layout:
```blade
<!-- ... -->
@livewireScripts <!-- [tl! remove] -->
@livewireScriptConfig <!-- [tl! add] -->
</body>
```
Now, you can import `Alpine` and `Livewire` into your application's bundle like so:
```js
import { Livewire, Alpine } from '../../vendor/livewire/livewire/dist/livewire.esm';
import customPlugin from './plugins/custom-plugin'
Alpine.plugin(customPlugin)
Livewire.start()
```
Notice you no longer need to call `Alpine.start()`. Livewire will start Alpine automatically.
For more information, please consult our documentation on [manually bundling Livewire's JavaScript](/docs/installation#manually-bundling-livewire-and-alpine).
## `wire:model`
In Livewire 3, `wire:model` is "deferred" by default (instead of by `wire:model.defer`). To achieve the same behavior as `wire:model` from Livewire 2, you must use `wire:model.live`.
Below is a list of the necessary substitutions you will need to make in your templates to keep your application's behavior consistent:
```html
<input wire:model="..."> <!-- [tl! remove] -->
<input wire:model.live="..."> <!-- [tl! add] -->
<input wire:model.defer="..."> <!-- [tl! remove] -->
<input wire:model="..."> <!-- [tl! add] -->
<input wire:model.lazy="..."> <!-- [tl! remove] -->
<input wire:model.blur="..."> <!-- [tl! add] -->
```
## `@entangle`
Similar to the changes to `wire:model`, Livewire 3 defers all data binding by default. To match this behavior, `@entangle` has been updated as well.
To keep your application running as expected, make the following `@entangle` substitutions:
```blade
@entangle(...) <!-- [tl! remove] -->
@entangle(...).live <!-- [tl! add] -->
@entangle(...).defer <!-- [tl! remove] -->
@entangle(...) <!-- [tl! add] -->
```
## E
| |
244120
|
Livewire is a Laravel package, so you will need to have a Laravel application up and running before you can install and use Livewire. If you need help setting up a new Laravel application, please see the [official Laravel documentation](https://laravel.com/docs/installation).
To install Livewire, open your terminal and navigate to your Laravel application directory, then run the following command:
```shell
composer require livewire/livewire
```
That's it — really. If you want more customization options, keep reading. Otherwise, you can jump right into using Livewire.
> [!warning] `/livewire/livewire.js` returning a 404 status code
> By default, Livewire exposes a route in your application to serve its JavaScript assets from: `/livewire/livewire.js`. This is fine for most applications, however, if you are using Nginx with a custom configuration, you may receive a 404 from this endpoint. To fix this issue, you can either [compile Livewire's JavaScript assets yourself](#manually-bundling-livewire-and-alpine), or [configure Nginx to allow for this](https://benjamincrozat.com/livewire-js-404-not-found).
## Publishing the configuration file
Livewire is "zero-config", meaning you can use it by following conventions, without any additional configuration. However, if needed, you can publish and customize Livewire's configuration file by running the following Artisan command:
```shell
php artisan livewire:publish --config
```
This will create a new `livewire.php` file in your Laravel application's `config` directory.
## Manually including Livewire's frontend assets
By default, Livewire injects the JavaScript and CSS assets it needs into each page that includes a Livewire component.
If you want more control over this behavior, you can manually include the assets on a page using the following Blade directives:
```blade
<html>
<head>
...
@livewireStyles
</head>
<body>
...
@livewireScripts
</body>
</html>
```
By including these assets manually on a page, Livewire knows not to inject the assets automatically.
> [!warning] AlpineJS is bundled with Livewire
> Because Alpine is bundled with Livewire's JavaScript assets, you must include @verbatim`@livewireScripts`@endverbatim on every page you wish to use Alpine. Even if you're not using Livewire on that page.
Though rarely required, you may disable Livewire's auto-injecting asset behavior by updating the `inject_assets` [configuration option](#publishing-the-configuration-file) in your application's `config/livewire.php` file:
```php
'inject_assets' => false,
```
If you'd rather force Livewire to inject its assets on a single page or multiple pages, you can call the following global method from the current route or from a service provider.
```php
\Livewire\Livewire::forceAssetInjection();
```
## Configuring Livewire's update endpoint
Every update in a Livewire component sends a network request to the server at the following endpoint: `https://example.com/livewire/update`
This can be a problem for some applications that use localization or multi-tenancy.
In those cases, you can register your own endpoint however you like, and as long as you do it inside `Livewire::setUpdateRoute()`, Livewire will know to use this endpoint for all component updates:
```php
Livewire::setUpdateRoute(function ($handle) {
return Route::post('/custom/livewire/update', $handle);
});
```
Now, instead of using `/livewire/update`, Livewire will send component updates to `/custom/livewire/update`.
Because Livewire allows you to register your own update route, you can declare any additional middleware you want Livewire to use directly inside `setUpdateRoute()`:
```php
Livewire::setUpdateRoute(function ($handle) {
return Route::post('/custom/livewire/update', $handle)
->middleware([...]); // [tl! highlight]
});
```
## Customizing the asset URL
By default, Livewire will serve its JavaScript assets from the following URL: `https://example.com/livewire/livewire.js`. Additionally, Livewire will reference this asset from a script tag like so:
```blade
<script src="/livewire/livewire.js" ...
```
If your application has global route prefixes due to localization or multi-tenancy, you can register your own endpoint that Livewire should use internally when fetching its JavaScript.
To use a custom JavaScript asset endpoint, you can register your own route inside `Livewire::setScriptRoute()`:
```php
Livewire::setScriptRoute(function ($handle) {
return Route::get('/custom/livewire/livewire.js', $handle);
});
```
Now, Livewire will load its JavaScript like so:
```blade
<script src="/custom/livewire/livewire.js" ...
```
## Manually bundling Livewire and Alpine
By default, Alpine and Livewire are loaded using the `<script src="livewire.js">` tag, which means you have no control over the order in which these libraries are loaded. Consequently, importing and registering Alpine plugins, as shown in the example below, will no longer function:
```js
// Warning: This snippet demonstrates what NOT to do...
import Alpine from 'alpinejs'
import Clipboard from '@ryangjchandler/alpine-clipboard'
Alpine.plugin(Clipboard)
Alpine.start()
```
To address this issue, we need to inform Livewire that we want to use the ESM (ECMAScript module) version ourselves and prevent the injection of the `livewire.js` script tag. To achieve this, we must add the `@livewireScriptConfig` directive to our layout file (`resources/views/components/layouts/app.blade.php`):
```blade
<html>
<head>
<!-- ... -->
@livewireStyles
@vite(['resources/js/app.js'])
</head>
<body>
{{ $slot }}
@livewireScriptConfig <!-- [tl! highlight] -->
</body>
</html>
```
When Livewire detects the `@livewireScriptConfig` directive, it will refrain from injecting the Livewire and Alpine scripts. If you are using the `@livewireScripts` directive to manually load Livewire, be sure to remove it. Make sure to add the `@livewireStyles` directive if it is not already present.
The final step is importing Alpine and Livewire in our `app.js` file, allowing us to register any custom resources, and ultimately starting Livewire and Alpine:
```js
import { Livewire, Alpine } from '../../vendor/livewire/livewire/dist/livewire.esm';
import Clipboard from '@ryangjchandler/alpine-clipboard'
Alpine.plugin(Clipboard)
Livewire.start()
```
> [!tip] Rebuild your assets after composer update
> Make sure that if you are manually bundling Livewire and Alpine, that you rebuild your assets whenever you run `composer update`.
> [!warning] Not compatible with Laravel Mix
> Laravel Mix will not work if you are manually bundling Livewire and AlpineJS. Instead, we recommend that you [switch to Vite](https://laravel.com/docs/vite).
## Publishing Livewire's frontend assets
> [!warning] Publishing assets isn't necessary
> Publishing Livewire's assets isn't necessary for Livewire to run. Only do this if you have a specific need for it.
If you prefer the JavaScript assets to be served by your web server not through Laravel, use the `livewire:publish` command:
```bash
php artisan livewire:publish --assets
```
To keep assets up-to-date and avoid issues in future updates, we strongly recommend that you add the following command to your composer.json file:
```json
{
"scripts": {
"post-update-cmd": [
// Other scripts
"@php artisan vendor:publish --tag=livewire:assets --ansi --force"
]
}
}
```
| |
244126
|
It's important to make sure your Livewire apps are secure and don't expose any application vulnerabilities. Livewire has internal security features to handle many cases, however, there are times when it's up to your application code to keep your components secure.
## Authorizing action parameters
Livewire actions are extremely powerful, however, any parameters passed to Livewire actions are mutable on the client and should be treated as un-trusted user input.
Arguably the most common security pitfall in Livewire is failing to validate and authorize Livewire action calls before persisting changes to the database.
Here is an example of an insecurity resulting from a lack of authorization:
```php
<?php
use App\Models\Post;
use Livewire\Component;
class ShowPost extends Component
{
// ...
public function delete($id)
{
// INSECURE!
$post = Post::find($id);
$post->delete();
}
}
```
```html
<button wire:click="delete({{ $post->id }})">Delete Post</button>
```
The reason the above example is insecure is that `wire:click="delete(...)"` can be modified in the browser to pass ANY post ID a malicious user wishes.
Action parameters (like `$id` in this case) should be treated the same as any untrusted input from the browser.
Therefore, to keep this application secure and prevent a user from deleting another user's post, we must add authorization to the `delete()` action.
First, let's create a [Laravel Policy](https://laravel.com/docs/authorization#creating-policies) for the Post model by running the following command:
```bash
php artisan make:policy PostPolicy --model=Post
```
After running the above command, a new Policy will be created inside `app/Policies/PostPolicy.php`. We can then update its contents with a `delete` method like so:
```php
<?php
namespace App\Policies;
use App\Models\Post;
use App\Models\User;
class PostPolicy
{
/**
* Determine if the given post can be deleted by the user.
*/
public function delete(?User $user, Post $post): bool
{
return $user?->id === $post->user_id;
}
}
```
Now, we can use the `$this->authorize()` method from the Livewire component to ensure the user owns the post before deleting it:
```php
public function delete($id)
{
$post = Post::find($id);
// If the user doesn't own the post,
// an AuthorizationException will be thrown...
$this->authorize('delete', $post); // [tl! highlight]
$post->delete();
}
```
Further reading:
* [Laravel Gates](https://laravel.com/docs/authorization#gates)
* [Laravel Policies](https://laravel.com/docs/authorization#creating-policies)
## Authorizing public properties
Similar to action parameters, public properties in Livewire should be treated as un-trusted input from the user.
Here is the same example from above about deleting a post, written insecurely in a different manner:
```php
<?php
use App\Models\Post;
use Livewire\Component;
class ShowPost extends Component
{
public $postId;
public function mount($postId)
{
$this->postId = $postId;
}
public function delete()
{
// INSECURE!
$post = Post::find($this->postId);
$post->delete();
}
}
```
```html
<button wire:click="delete">Delete Post</button>
```
As you can see, instead of passing the `$postId` as a parameter to the `delete` method from `wire:click`, we are storing it as a public property on the Livewire component.
The problem with this approach is that any malicious user can inject a custom element onto the page such as:
```html
<input type="text" wire:model="postId">
```
This would allow them to freely modify the `$postId` before pressing "Delete Post". Because the `delete` action doesn't authorize the value of `$postId`, the user can now delete any post in the database, whether they own it or not.
To protect against this risk, there are two possible solutions:
### Using model properties
When setting public properties, Livewire treats models differently than plain values such as strings and integers. Because of this, if we instead store the entire post model as a property on the component, Livewire will ensure the ID is never tampered with.
Here is an example of storing a `$post` property instead of a simple `$postId` property:
```php
<?php
use App\Models\Post;
use Livewire\Component;
class ShowPost extends Component
{
public Post $post;
public function mount($postId)
{
$this->post = Post::find($postId);
}
public function delete()
{
$this->post->delete();
}
}
```
```html
<button wire:click="delete">Delete Post</button>
```
This component is now secured because there is no way for a malicious user to change the `$post` property to a different Eloquent model.
### Locking the property
Another way to prevent properties from being set to unwanted values is to use [locked properties](https://livewire.laravel.com/docs/locked). Locking properties is done by applying the `#[Locked]` attribute. Now if users attempt to tamper with this value an error will be thrown.
Note that properties with the Locked attribute can still be changed in the back-end, so care still needs to taken that untrusted user input is not passed to the property in your own Livewire functions.
```php
<?php
use App\Models\Post;
use Livewire\Component;
use Livewire\Attributes\Locked;
class ShowPost extends Component
{
#[Locked] // [tl! highlight]
public $postId;
public function mount($postId)
{
$this->postId = $postId;
}
public function delete()
{
$post = Post::find($this->postId);
$post->delete();
}
}
```
### Authorizing the property
If using a model property is undesired in your scenario, you can of course fall-back to manually authorizing the deletion of the post inside the `delete` action:
```php
<?php
use App\Models\Post;
use Livewire\Component;
class ShowPost extends Component
{
public $postId;
public function mount($postId)
{
$this->postId = $postId;
}
public function delete()
{
$post = Post::find($this->postId);
$this->authorize('delete', $post); // [tl! highlight]
$post->delete();
}
}
```
```html
<button wire:click="delete">Delete Post</button>
```
Now, even though a malicious user can still freely modify the value of `$postId`, when the `delete` action is called, `$this->authorize()` will throw an `AuthorizationException` if the user does not own the post.
Further reading:
* [Laravel Gates](https://laravel.com/docs/authorization#gates)
* [Laravel Policies](https://laravel.com/docs/authorization#creating-policies)
| |
244127
|
## Middleware
When a Livewire component is loaded on a page containing route-level [Authorization Middleware](https://laravel.com/docs/authorization#via-middleware), like so:
```php
Route::get('/post/{post}', App\Livewire\UpdatePost::class)
->middleware('can:update,post'); // [tl! highlight]
```
Livewire will ensure those middlewares are re-applied to subsequent Livewire network requests. This is referred to as "Persistent Middleware" in Livewire's core.
Persistent middleware protects you from scenarios where the authorization rules or user permissions have changed after the initial page-load.
Here's a more in-depth example of such a scenario:
```php
Route::get('/post/{post}', App\Livewire\UpdatePost::class)
->middleware('can:update,post'); // [tl! highlight]
```
```php
<?php
use App\Models\Post;
use Livewire\Component;
use Livewire\Attributes\Validate;
class UpdatePost extends Component
{
public Post $post;
#[Validate('required|min:5')]
public $title = '';
public $content = '';
public function mount()
{
$this->title = $this->post->title;
$this->content = $this->post->content;
}
public function update()
{
$this->post->update([
'title' => $this->title,
'content' => $this->content,
]);
}
}
```
As you can see, the `can:update,post` middleware is applied at the route-level. This means that a user who doesn't have permission to update a post cannot view the page.
However, consider a scenario where a user:
* Loads the page
* Loses permission to update after the page loads
* Tries updating the post after losing permission
Because Livewire has already successfully loaded the page you might ask yourself: "When Livewire makes a subsequent request to update the post, will the `can:update,post` middleware be re-applied? Or instead, will the un-authorized user be able to update the post successfully?"
Because Livewire has internal mechanisms to re-apply middleware from the original endpoint, you are protected in this scenario.
### Configuring persistent middleware
By default, Livewire persists the following middleware across network requests:
```php
\Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
\Laravel\Jetstream\Http\Middleware\AuthenticateSession::class,
\Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
\App\Http\Middleware\RedirectIfAuthenticated::class,
\Illuminate\Auth\Middleware\Authenticate::class,
\Illuminate\Auth\Middleware\Authorize::class,
```
If any of the above middlewares are applied to the initial page-load, they will be persisted (re-applied) to any future network requests.
However, if you are applying a custom middleware from your application the initial page-load, and want it persisted between Livewire requests, you will need to add it to this list from a [Service Provider](https://laravel.com/docs/providers#main-content) in your app like so:
```php
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Livewire;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*/
public function boot(): void
{
Livewire::addPersistentMiddleware([ // [tl! highlight:2]
App\Http\Middleware\EnsureUserHasRole::class,
]);
}
}
```
If a Livewire component is loaded on a page that uses the `EnsureUserHasRole` middleware from your application, it will now be persisted and re-applied to any future network requests to that Livewire component.
> [!warning] Middleware arguments are not supported
> Livewire currently doesn't support middleware arguments for persistent middleware definitions.
>
> ```php
> // Bad...
> Livewire::addPersistentMiddleware(AuthorizeResource::class.':admin');
>
> // Good...
> Livewire::addPersistentMiddleware(AuthorizeResource::class);
> ```
### Applying global Livewire middleware
Alternatively, if you wish to apply specific middleware to every single Livewire update network request, you can do so by registering your own Livewire update route with any middleware you wish:
```php
Livewire::setUpdateRoute(function ($handle) {
return Route::post('/livewire/update', $handle)
->middleware(App\Http\Middleware\LocalizeViewPaths::class);
});
```
Any Livewire AJAX/fetch requests made to the server will use the above endpoint and apply the `LocalizeViewPaths` middleware before handling the component update.
Learn more about [customizing the update route on the Installation page](https://livewire.laravel.com/docs/installation#configuring-livewires-update-endpoint).
## Snapshot checksums
Between every Livewire request, a snapshot is taken of the Livewire component and sent to the browser. This snapshot is used to re-build the component during the next server round-trip.
[Learn more about Livewire snapshots in the Hydration documentation.](https://livewire.laravel.com/docs/hydration#the-snapshot)
Because fetch requests can be intercepted and tampered with in a browser, Livewire generates a "checksum" of each snapshot to go along with it.
This checksum is then used on the next network request to verify that the snapshot hasn't changed in any way.
If Livewire finds a checksum mismatch, it will throw a `CorruptComponentPayloadException` and the request will fail.
This protects against any form of malicious tampering that would otherwise result in granting users the ability to execute or modify unrelated code.
| |
244171
|
class HttpKernel extends Kernel
{
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* @var array
*/
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\Illuminate\Foundation\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
];
/**
* The application's route middleware groups.
*
* @var array
*/
protected $middlewareGroups = [
'web' => [
\Illuminate\Cookie\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\Illuminate\Foundation\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'api' => [
'throttle:60,1',
'bindings',
],
];
/**
* The application's route middleware.
*
* These middleware may be assigned to groups or used individually.
*
* @var array
*/
protected $routeMiddleware = [
'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \Orchestra\Testbench\Http\Middleware\RedirectIfAuthenticated::class,
'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
];
/**
* The priority-sorted list of middleware.
*
* This forces non-global middleware to always be in the given order.
*
* @var array
*/
protected $middlewarePriority = [
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\Illuminate\Auth\Middleware\Authenticate::class,
\Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
\Illuminate\Auth\Middleware\Authorize::class,
];
}
class Component extends BaseComponent
{
public static $loggedMiddleware = [];
public $middleware = [];
public $showNested = false;
public $changeProtected = false;
public function mount(Post $post)
{
//
}
public function showNestedComponent()
{
$this->showNested = true;
}
public function toggleProtected()
{
$this->changeProtected = ! $this->changeProtected;
}
public function render()
{
$this->middleware = static::$loggedMiddleware;
return <<<'HTML'
<div>
<span dusk="middleware">@json($middleware)</span>
<button wire:click="$refresh" dusk="refresh">Refresh</button>
<button wire:click="toggleProtected" dusk="changeProtected">Change Protected</button>
<button wire:click="showNestedComponent" dusk="showNested">Show Nested</button>
<h1>
@unless($changeProtected)
Protected Content
@else
Still Secure Content
@endunless
</h1>
@if ($showNested)
@livewire(\Livewire\Mechanisms\PersistentMiddleware\NestedComponent::class)
@endif
</div>
HTML;
}
}
class NestedComponent extends BaseComponent
{
public $middleware = [];
public function render()
{
$this->middleware = Component::$loggedMiddleware;
return <<<'HTML'
<div>
<span dusk="nested-middleware">@json($middleware)</span>
<button wire:click="$refresh" dusk="refreshNested">Refresh</button>
</div>
HTML;
}
}
class AllowListedMiddleware
{
public function handle(Request $request, Closure $next): Response
{
Component::$loggedMiddleware[] = static::class;
return $next($request);
}
}
class BlockListedMiddleware
{
public function handle(Request $request, Closure $next): Response
{
Component::$loggedMiddleware[] = static::class;
return $next($request);
}
}
class User extends AuthUser
{
use Sushi;
protected $fillable = ['banned'];
public function posts()
{
return $this->hasMany(Post::class);
}
protected $rows = [
[
'id' => 1,
'name' => 'First User',
'email' => 'first@laravel-livewire.com',
'password' => '',
'banned' => false,
],
[
'id' => 2,
'name' => 'Second user',
'email' => 'second@laravel-livewire.com',
'password' => '',
'banned' => false,
],
];
}
class Post extends Model
{
use Sushi;
public function user()
{
return $this->belongsTo(User::class);
}
protected $rows = [
['title' => 'First', 'user_id' => 1],
['title' => 'Second', 'user_id' => 2],
];
}
class PostPolicy
{
public function update(User $user, Post $post)
{
return (int) $post->user_id === (int) $user->id;
}
}
class IsBanned
{
public function handle(Request $request, Closure $next): Response
{
if ($request->user()->banned) {
return redirect('/force-logout');
}
return $next($request);
}
}
| |
244234
|
<?php
namespace Livewire\Features\SupportLegacyModels;
use Illuminate\Database\Eloquent\Collection as EloquentCollection;
use Livewire\Mechanisms\HandleComponents\Synthesizers\Synth;
use LogicException;
class EloquentCollectionSynth extends Synth
{
public static $key = 'elcl';
public static function match($target)
{
return $target instanceof EloquentCollection;
}
public function dehydrate(EloquentCollection $target, $dehydrateChild)
{
$class = $target::class;
$modelClass = $target->getQueueableClass();
$meta = [];
$meta['keys'] = $target->modelKeys();
$meta['class'] = $class;
$meta['modelClass'] = $modelClass;
if ($modelClass && ($connection = $this->getConnection($target)) !== $modelClass::make()->getConnectionName()) {
$meta['connection'] = $connection;
}
$relations = $target->getQueueableRelations();
if (count($relations)) {
$meta['relations'] = $relations;
}
$rules = $this->getRules($this->context);
if (empty($rules)) return [[], $meta];
$data = $this->getDataFromCollection($target, $rules);
foreach ($data as $key => $child) {
$data[$key] = $dehydrateChild($key, $child);
}
return [ $data, $meta ];
}
public function hydrate($data, $meta, $hydrateChild)
{
if (isset($meta['__child_from_parent'])) {
$collection = $meta['__child_from_parent'];
unset($meta['__child_from_parent']);
} else {
$collection = $this->loadCollection($meta);
}
if (isset($meta['relations'])) {
$collection->loadMissing($meta['relations']);
}
if (count($data)) {
foreach ($data as $key => $childData) {
$childData[1]['__child_from_parent'] = $collection->get($key);
$data[$key] = $hydrateChild($key, $childData);
}
return $collection::wrap($data);
}
return $collection;
}
public function get(&$target, $key)
{
return $target->get($key);
}
public function set(&$target, $key, $value, $pathThusFar, $fullPath)
{
if (SupportLegacyModels::missingRuleFor($this->context->component, $fullPath)) {
throw new CannotBindToModelDataWithoutValidationRuleException($fullPath, $this->context->component->getName());
}
$target->put($key, $value);
}
public function methods($target)
{
return [];
}
public function call($target, $method, $params, $addEffect)
{
}
protected function getRules($context)
{
$key = $this->path ?? null;
if (is_null($key)) return [];
return SupportLegacyModels::getRulesFor($context->component, $key);
}
protected function getConnection(EloquentCollection $collection)
{
if ($collection->isEmpty()) {
return;
}
$connection = $collection->first()->getConnectionName();
$collection->each(function ($model) use ($connection) {
// If there is no connection name, it must be a new model so continue.
if (is_null($model->getConnectionName())) {
return;
}
if ($model->getConnectionName() !== $connection) {
throw new LogicException('Livewire can\'t dehydrate an Eloquent Collection with models from different connections.');
}
});
return $connection;
}
protected function getDataFromCollection(EloquentCollection $collection, $rules)
{
return $this->filterData($collection->all(), $rules);
}
protected function filterData($data, $rules)
{
return array_filter($data, function ($key) use ($rules) {
return array_key_exists('*', $rules);
}, ARRAY_FILTER_USE_KEY);
}
protected function loadCollection($meta)
{
if (isset($meta['keys']) && count($meta['keys']) >= 0 && ! empty($meta['modelClass'])) {
$model = new $meta['modelClass'];
if (isset($meta['connection'])) {
$model->setConnection($meta['connection']);
}
$query = $model->newQueryForRestoration($meta['keys']);
if (isset($meta['relations'])) {
$query->with($meta['relations']);
}
$query->useWritePdo();
$collection = $query->get();
$collection = $collection->keyBy->getKey();
return new $meta['class'](
collect($meta['keys'])->map(function ($id) use ($collection) {
return $collection[$id] ?? null;
})->filter()
);
}
return new $meta['class']();
}
}
| |
244246
|
public function test_it_serialises_properties_from_model_that_has_not_been_persisted()
{
// @todo: Review this, as it's not quite correct, key "name" should be sent to the front end, even if not set, to match V2 functionality
$model = Author::make();
$rules = [
'model.name' => '',
];
$expected = [
'name' => null,
];
$component = Livewire::test(ModelsComponent::class, ['model' => $model, 'rules' => $rules]);
$results = $component->snapshot['data']['model'][0];
$this->assertEquals($expected['name'], $results['name']);
}
public function test_it_ignores_the_key_if_the_model_does_not_exist()
{
$this->expectNotToPerformAssertions();
$model = Author::make();
$model->id = 123;
Livewire::test(ModelsComponent::class, ['model' => $model])
->call('$refresh');
}
}
class PostComponent extends TestComponent
{
public $post;
public function mount()
{
$this->post = Post::first();
}
}
class ModelsComponent extends TestComponent
{
public $model;
public $models;
public $_rules = [
'model.title' => '',
'model.name' => '',
'model.email' => '',
'model.posts.*.title' => '',
'model.posts.*.description' => '',
'model.posts.*.content' => '',
'model.posts.*.comments.*.comment' => '',
'model.posts.*.comments.*.author.name' => '',
'model.posts.*.otherComments.*.comment' => '',
'model.posts.*.otherComments.*.author.name' => '',
];
protected function rules()
{
return $this->_rules;
}
public function mount($rules = null)
{
if (isset($rules)) {
$this->_rules = $rules;
}
}
}
class Author extends Model
{
protected $connection = 'testbench';
protected $guarded = [];
public function posts()
{
return $this->hasMany(Post::class);
}
public function comments()
{
return $this->hasMany(Comment::class);
}
public function otherComments()
{
return $this->hasMany(Comment::class);
}
}
class Post extends Model
{
protected $connection = 'testbench';
protected $guarded = [];
public function author()
{
return $this->belongsTo(Author::class);
}
public function comments()
{
return $this->hasMany(Comment::class);
}
public function otherComments()
{
return $this->hasMany(OtherComment::class);
}
}
class Comment extends Model
{
protected $connection = 'testbench';
protected $guarded = [];
public function author()
{
return $this->belongsTo(Author::class);
}
public function post()
{
return $this->belongsTo(Post::class);
}
}
class OtherComment extends Model
{
protected $connection = 'testbench';
protected $guarded = [];
public function author()
{
return $this->belongsTo(Author::class);
}
public function post()
{
return $this->belongsTo(Post::class);
}
}
| |
244252
|
class Foo extends Model
{
use Sushi;
protected $casts = ['baz' => 'array', 'bob' => 'array', 'lob' => 'array', 'zap' => 'array'];
protected function getRows()
{
return [[
'bar' => 'rab',
'bar_baz' => 'zab_rab',
'baz' => json_encode(['zab', 'azb']),
'bob' => json_encode(['obb']),
'lob' => json_encode(['law' => []]),
'zap' => json_encode([]),
]];
}
}
class CamelFoo extends Model
{
use Sushi;
protected function getRows()
{
return [[
'bar' => 'baz',
]];
}
}
class ComponentWithCamelCasedModelProperty extends Component
{
public $camelFoo;
protected $rules = [
'camelFoo.bar' => 'required',
];
public function save()
{
$this->validate();
}
public function render()
{
return \view('dump-errors');
}
}
class ComponentForEloquentModelHydrationMiddleware extends Component
{
public $foo;
protected $rules = [
'foo.bar' => 'required',
'foo.bar_baz' => 'required',
'foo.baz' => 'required|array|min:2',
'foo.bob.*' => 'required|min:2',
'foo.lob.law.*' => 'required|array',
'foo.lob.law.*.blog' => 'required|min:5',
'foo.zap.*.*.name' => 'required|min:3',
];
public function save()
{
$this->validate();
$this->foo->save();
}
public function performValidateOnly($field)
{
$this->validateOnly($field);
}
public function render()
{
return \view('dump-errors');
}
}
class ComponentForEloquentModelCollectionHydrationMiddleware extends Component
{
public $foos;
protected $rules = [
'foos' => 'required',
'foos.*' => 'max:20',
'foos.*.bar_baz' => 'required|min:10',
'foos.*.bar' => 'required|min:10',
];
public function performValidateOnly($field)
{
$this->validateOnly($field);
}
public function render()
{
return \view('dump-errors');
}
}
class Items extends Model
{
use Sushi;
protected $rows = [
['title' => 'Lawn Mower', 'price' => '226.99', 'cart_id' => 1],
['title' => 'Leaf Blower', 'price' => '134.99', 'cart_id' => 1],
['title' => 'Rake', 'price' => '9.99', 'cart_id' => 1],
['title' => 'Lawn Mower', 'price' => '226.99', 'cart_id' => 2],
['title' => 'Leaf Blower', 'price' => '134.99', 'cart_id' => 2],
['title' => 'Lawn Mower', 'price' => '226.99', 'cart_id' => 3],
['title' => 'Leaf Blower', 'price' => '134.99', 'cart_id' => 3],
['title' => 'Rake', 'price' => '9.99', 'cart_id' => 3],
];
protected $schema = [
'price' => 'float',
];
}
class Cart extends Model
{
use Sushi;
protected $rows = [
['id' => 1, 'name' => 'Bob'],
['id' => 2, 'name' => 'John'],
['id' => 3, 'name' => 'Mark'],
];
public function items()
{
return $this->hasMany(Items::class, 'cart_id', 'id');
}
}
class ComponentForEloquentModelNestedHydrationMiddleware extends Component
{
public $cart;
protected $rules = [
'cart.items.*.title' => 'required',
];
public function save()
{
$this->validate();
$this->cart->items->each->save();
}
public function render()
{
return \view('dump-errors');
}
}
| |
244256
|
class ModelForAttributeCasting extends \Illuminate\Database\Eloquent\Model
{
use Sushi;
protected $guarded = [];
protected $casts = [
'normal_date' => 'date',
'formatted_date' => 'date:d-m-Y',
'date_with_time' => 'datetime',
'timestamped_date' => 'timestamp',
'integer_number' => 'integer',
'real_number' => 'real',
'float_number' => 'float',
'double_precision_number' => 'double',
'decimal_with_one_digit' => 'decimal:1',
'decimal_with_two_digits' => 'decimal:2',
'string_name' => 'string',
'boolean_value' => 'boolean',
'array_list' => 'array',
'json_list' => 'json',
'collected_list' => 'collection',
'object_value' => 'object',
'custom_caster' => QuizAnswerCaster::class,
'enum' => TestingEnum::class,
];
public function getRows()
{
return [
[
'normal_date' => new \DateTime('2000-08-12'),
'formatted_date' => new \DateTime('2020-03-03'),
'date_with_time' => new \DateTime('2015-10-21'),
'timestamped_date' => new \DateTime('2002-08-30'),
'integer_number' => 1,
'real_number' => 2,
'float_number' => 3,
'double_precision_number' => 4,
'decimal_with_one_digit' => 5,
'decimal_with_two_digits' => 6,
'string_name' => 'Gladys',
'boolean_value' => false,
'array_list' => json_encode([]),
'json_list' => json_encode([1, 2, 3]),
'collected_list' => json_encode([true, false]),
'object_value' => json_encode(['name' => 'Marian', 'email' => 'marian@likes.pizza']),
'custom_caster' => 'dumb answer',
'enum' => null,
]
];
}
}
class QuizAnswer
{
protected $answer;
public static function make(string $answer): self
{
$new = new static();
$new->answer = $answer;
return $new;
}
public function getAnswer(): string
{
return $this->answer;
}
public function matches($givenAnswer): bool
{
return $this->answer === $givenAnswer;
}
public function __toString()
{
return $this->getAnswer();
}
}
class QuizAnswerCaster implements CastsAttributes
{
public function get($model, string $key, $value, array $attributes)
{
return QuizAnswer::make((string) $value);
}
public function set($model, string $key, $value, array $attributes)
{
if ($value instanceof QuizAnswer) {
$value = $value->getAnswer();
}
return $value;
}
}
enum TestingEnum: string
{
case FOO = 'bar';
}
class ComponentForModelAttributeCasting extends TestComponent
{
public $model;
public function rules(): array
{
return [
'model.normal_date' => ['required', 'date'],
'model.formatted_date' => ['required', 'date'],
'model.date_with_time' => ['required', 'date'],
'model.timestamped_date' => ['required', 'integer'],
'model.integer_number' => ['required', 'integer'],
'model.real_number' => ['required', 'numeric'],
'model.float_number' => ['required', 'numeric'],
'model.double_precision_number' => ['required', 'numeric'],
'model.decimal_with_one_digit' => ['required', 'numeric'],
'model.decimal_with_two_digits' => ['required', 'numeric'],
'model.string_name' => ['required', 'string'],
'model.boolean_value' => ['required', 'boolean'],
'model.array_list' => ['required', 'array'],
'model.array_list.*' => ['required', 'string'],
'model.json_list' => ['required', 'array'],
'model.json_list.*' => ['required', 'numeric'],
'model.collected_list' => ['required'],
'model.collected_list.*' => ['required', 'boolean'],
'model.object_value' => ['required'],
'model.object_value.name' => ['required'],
'model.object_value.email' => ['required', 'email'],
'model.custom_caster' => ['required'],
'model.enum' => ['nullable', Rule::enum(TestingEnum::class)]
];
}
public function mount() {
$this->model = ModelForAttributeCasting::first();
}
public function validateAttribute(string $attribute)
{
$this->validateOnly($attribute);
}
}
| |
244260
|
<?php
namespace Livewire\Features\SupportErrorResponses;
use Livewire\Component as BaseComponent;
use Livewire\Livewire;
class BrowserTest extends \Tests\BrowserTestCase
{
public function test_it_shows_page_expired_dialog_when_session_has_expired()
{
Livewire::visit(Component::class)
->waitForLivewire()->click('@regenerateSession')
->click('@refresh')
// Wait for Livewire to respond, but dusk helper won't
// work as dialog box is stopping further execution
->waitForDialog()
->assertDialogOpened("This page has expired.\nWould you like to refresh the page?")
// Dismiss dialog so next tests run
->dismissDialog()
;
}
public function test_it_shows_custom_hook_dialog_using_on_error_response_hook_when_session_has_expired()
{
Livewire::withQueryParams(['useCustomErrorResponseHook' => true])
->visit(Component::class)
->waitForLivewire()->click('@regenerateSession')
->click('@refresh')
// Wait for Livewire to respond, but dusk helper won't
// work as dialog box is stopping further execution
->waitForDialog()
->assertDialogOpened('Page Expired - Error Response')
// Dismiss dialog so next tests run
->dismissDialog()
;
}
}
class Component extends BaseComponent
{
public $useCustomPageExpiredHook = false;
public $useCustomErrorResponseHook = false;
protected $queryString = [
'useCustomPageExpiredHook' => ['except' => false],
'useCustomErrorResponseHook' => ['except' => false],
];
public function regenerateSession()
{
request()->session()->regenerate();
}
public function render()
{
return <<< 'HTML'
<div>
<button type="button" wire:click="regenerateSession" dusk="regenerateSession">Regenerate Session</button>
<button type="button" wire:click="$refresh" dusk="refresh">Refresh</button>
@if($useCustomErrorResponseHook)
<script>
document.addEventListener('livewire:init', () => {
Livewire.hook('request', ({ fail, preventDefault }) => {
fail(({ status }) => {
if (status === 419) {
confirm('Page Expired - Error Response')
preventDefault()
}
})
})
})
</script>
@endif
</div>
HTML;
}
}
| |
244262
|
<?php
namespace Livewire\Features\SupportLocales;
use Illuminate\Support\Facades\App;
use Livewire\Livewire;
use Tests\TestComponent;
class UnitTest extends \Tests\TestCase
{
public function test_a_livewire_component_can_persist_its_locale()
{
// Set locale
App::setLocale('en');
$this->assertEquals(App::getLocale(), 'en');
// Mount component and new ensure locale is set
$component = Livewire::test(ComponentForLocalePersistanceHydrationMiddleware::class);
$this->assertEquals(App::getLocale(), 'es');
// Reset locale to ensure it isn't persisted in the test session
App::setLocale('en');
$this->assertEquals(App::getLocale(), 'en');
// Verify locale is persisted from component mount
$component->call('$refresh');
$this->assertEquals(App::getLocale(), 'es');
}
}
class ComponentForLocalePersistanceHydrationMiddleware extends TestComponent
{
public function mount()
{
App::setLocale('es');
}
}
| |
244295
|
<?php
namespace Livewire\Features\SupportFileUploads;
use Illuminate\Support\Facades\Storage;
use League\Flysystem\WhitespacePathNormalizer;
class FileUploadConfiguration
{
public static function storage()
{
$disk = static::disk();
if (app()->runningUnitTests()) {
// We want to "fake" the first time in a test run, but not again because
// Storage::fake() wipes the storage directory every time its called.
rescue(
// If the storage disk is not found (meaning it's the first time),
// this will throw an error and trip the second callback.
fn() => Storage::disk($disk),
fn() => Storage::fake($disk),
// swallows the error that is thrown on the first try
report: false
);
}
return Storage::disk($disk);
}
public static function disk()
{
if (app()->runningUnitTests()) {
return 'tmp-for-tests';
}
return config('livewire.temporary_file_upload.disk') ?: config('filesystems.default');
}
public static function diskConfig()
{
return config('filesystems.disks.'.static::disk());
}
public static function isUsingS3()
{
$diskBeforeTestFake = config('livewire.temporary_file_upload.disk') ?: config('filesystems.default');
return config('filesystems.disks.'.strtolower($diskBeforeTestFake).'.driver') === 's3';
}
public static function isUsingGCS()
{
$diskBeforeTestFake = config('livewire.temporary_file_upload.disk') ?: config('filesystems.default');
return config('filesystems.disks.'.strtolower($diskBeforeTestFake).'.driver') === 'gcs';
}
public static function normalizeRelativePath($path)
{
return (new WhitespacePathNormalizer)->normalizePath($path);
}
public static function directory()
{
return static::normalizeRelativePath(config('livewire.temporary_file_upload.directory') ?: 'livewire-tmp');
}
protected static function s3Root()
{
if (! static::isUsingS3()) return '';
$diskConfig = static::diskConfig();
if (! is_array($diskConfig)) return '';
$root = $diskConfig['root'] ?? null;
return $root !== null ? static::normalizeRelativePath($root) : '';
}
public static function path($path = '', $withS3Root = true)
{
$prefix = $withS3Root ? static::s3Root() : '';
$directory = static::directory();
$path = static::normalizeRelativePath($path);
return $prefix.($prefix ? '/' : '').$directory.($path ? '/' : '').$path;
}
public static function mimeType($filename)
{
$mimeType = static::storage()->mimeType(static::path($filename));
return $mimeType === 'image/svg' ? 'image/svg+xml' : $mimeType;
}
public static function lastModified($filename)
{
return static::storage()->lastModified($filename);
}
public static function middleware()
{
return config('livewire.temporary_file_upload.middleware') ?: 'throttle:60,1';
}
public static function shouldCleanupOldUploads()
{
return config('livewire.temporary_file_upload.cleanup', true);
}
public static function rules()
{
$rules = config('livewire.temporary_file_upload.rules');
if (is_null($rules)) return ['required', 'file', 'max:12288'];
if (is_array($rules)) return $rules;
return explode('|', $rules);
}
public static function maxUploadTime()
{
return config('livewire.temporary_file_upload.max_upload_time') ?: 5;
}
}
| |
244411
|
<?php
namespace Livewire\Features\SupportNavigate;
use Laravel\Dusk\Browser;
use Livewire\Attributes\On;
use Illuminate\Support\Facades\Blade;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\View;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Url;
use Livewire\Component;
use Livewire\Drawer\Utils;
use Livewire\Livewire;
class BrowserTest extends \Tests\BrowserTestCase
{
public static function tweakApplicationHook()
{
return function () {
View::addNamespace('test-views', __DIR__ . '/test-views');
Livewire::component('query-page', QueryPage::class);
Livewire::component('first-page', FirstPage::class);
Livewire::component('first-page-child', FirstPageChild::class);
Livewire::component('first-page-with-link-outside', FirstPageWithLinkOutside::class);
Livewire::component('second-page', SecondPage::class);
Livewire::component('third-page', ThirdPage::class);
Livewire::component('first-asset-page', FirstAssetPage::class);
Livewire::component('second-asset-page', SecondAssetPage::class);
Livewire::component('third-asset-page', ThirdAssetPage::class);
Livewire::component('first-tracked-asset-page', FirstTrackedAssetPage::class);
Livewire::component('second-tracked-asset-page', SecondTrackedAssetPage::class);
Livewire::component('second-remote-asset', SecondRemoteAsset::class);
Livewire::component('first-scroll-page', FirstScrollPage::class);
Livewire::component('second-scroll-page', SecondScrollPage::class);
Livewire::component('parent-component', ParentComponent::class);
Livewire::component('child-component', ChildComponent::class);
Livewire::component('script-component', ScriptComponent::class);
Livewire::component('nav-bar-component', NavBarComponent::class);
Route::get('/navbar/{page}', NavBarComponent::class)->middleware('web');
Route::get('/query-page', QueryPage::class)->middleware('web');
Route::get('/first', FirstPage::class)->middleware('web');
Route::get('/first-hide-progress', function () {
config(['livewire.navigate.show_progress_bar' => false]);
return (new FirstPage)();
})->middleware('web');
Route::get('/first-outside', FirstPageWithLinkOutside::class)->middleware('web');
Route::get('/redirect-to-second', fn () => redirect()->to('/second'));
Route::get('/second', SecondPage::class)->middleware('web');
Route::get('/third', ThirdPage::class)->middleware('web');
Route::get('/fourth', FourthPage::class)->middleware('web');
Route::get('/first-asset', FirstAssetPage::class)->middleware('web');
Route::get('/second-asset', SecondAssetPage::class)->middleware('web');
Route::get('/third-asset', ThirdAssetPage::class)->middleware('web');
Route::get('/first-scroll', FirstScrollPage::class)->middleware('web');
Route::get('/second-scroll', SecondScrollPage::class)->middleware('web');
Route::get('/second-remote-asset', SecondRemoteAsset::class)->middleware('web');
Route::get('/first-tracked-asset', FirstTrackedAssetPage::class)->middleware('web');
Route::get('/second-tracked-asset', SecondTrackedAssetPage::class)->middleware('web');
Route::get('/test-navigate-asset.js', function () {
return Utils::pretendResponseIsFile(__DIR__ . '/test-views/test-navigate-asset.js');
});
Route::get('/parent', ParentComponent::class)->middleware('web');
Route::get('/page-with-link-to-page-without-livewire', PageWithLinkAway::class);
Route::get('/page-without-livewire-component', fn () => Blade::render(<<<'HTML'
<html>
<head>
<meta name="empty-layout" content>
<script src="/test-navigate-asset.js" data-navigate-track></script>
</head>
<body>
<div dusk="non-livewire-page">This is a page without a livewire component</div>
</body>
</html>
HTML));
Route::get('/page-with-alpine-for-loop', PageWithAlpineForLoop::class);
Route::get('/script-component', ScriptComponent::class);
};
}
public function test_back_button_works_with_teleports()
{
$this->registerComponentTestRoutes([
'/second' => new class extends Component {
public function render(){ return <<<'HTML'
<div>
On second page
</div>
HTML; }
},
]);
Livewire::visit(new class extends Component {
public function render(){
return <<<'HTML'
<div x-data="{ outerScopeCount: 0 }">
Livewire component...
<template x-teleport="body">
<div>
<span x-text="outerScopeCount" dusk="target"></span>
<button x-on:click="outerScopeCount++" dusk="button">inc</button>
</div>
</template>
<a href="/second" wire:navigate dusk="link">Go to second page</a>
</div>
HTML;
}
})
->assertSeeIn('@target', '0')
->click('@button')
->assertSeeIn('@target', '1')
->click('@link')
->waitForText('On second page')
->back()
->assertDontSee('On second page')
->assertSeeIn('@target', '0')
->click('@button')
->assertSeeIn('@target', '1')
->forward()
->back()
->assertSeeIn('@target', '0')
->click('@button')
->assertSeeIn('@target', '1')
;
}
public function test_back_button_works_with_teleports_inside_persist()
{
$this->registerComponentTestRoutes([
'/second' => new class extends Component {
public function render(){ return <<<'HTML'
<div>
<div>
On second page
</div>
@persist('header')
<div x-data="{ outerScopeCount: 0 }">
<template x-teleport="body">
<div>
<span x-text="outerScopeCount" dusk="target"></span>
<button x-on:click="outerScopeCount++" dusk="button">inc</button>
</div>
</template>
</div>
@endpersist
</div>
HTML; }
},
]);
Livewire::visit(new class extends Component {
public function render(){
return <<<'HTML'
<div>
<div>
On first page
</div>
@persist('header')
<div x-data="{ outerScopeCount: 0 }">
<template x-teleport="body">
<div>
<span x-text="outerScopeCount" dusk="target"></span>
<button x-on:click="outerScopeCount++" dusk="button">inc</button>
</div>
</template>
</div>
@endpersist
<a href="/second" wire:navigate dusk="link">Go to second page</a>
</div>
HTML;
}
})
->assertSeeIn('@target', '0')
->click('@button')
->assertSeeIn('@target', '1')
->click('@link')
->waitForText('On second page')
->assertSeeIn('@target', '1')
->click('@button')
->assertSeeIn('@target', '2')
->back()
->assertSeeIn('@target', '2')
->click('@button')
->assertSeeIn('@target', '3')
->forward()
->assertSeeIn('@target', '3')
->click('@button')
->assertSeeIn('@target', '4')
;
}
public function test_can_configure_progress_bar()
{
$this->browse(function ($browser) {
$browser
->visit('/first')
->tap(fn ($b) => $b->script('window._lw_dusk_test = true'))
->assertScript('return window._lw_dusk_test')
->assertSee('On first')
->click('@link.to.third')
->waitFor('#nprogress')
->waitForText('Done loading...');
});
$this->browse(function ($browser) {
$browser
->visit('/first-hide-progress')
->tap(fn ($b) => $b->script('window._lw_dusk_test = true'))
->assertScript('return window._lw_dusk_test')
->assertSee('On first')
->click('@link.to.third')
->pause(500)
->assertMissing('#nprogress')
->waitForText('Done loading...');
});
}
| |
244413
|
public function test_navigate_scrolls_to_top_and_back_preserves_scroll()
{
$this->browse(function ($browser) {
$browser
->visit('/first-scroll')
->assertVisible('@first-target')
->assertNotInViewPort('@first-target')
->scrollTo('@first-target')
->assertInViewPort('@first-target')
->click('@link.to.second')
->waitForText('On second')
->assertNotInViewPort('@second-target')
->scrollTo('@second-target')
->back()
->waitForText('On first')
->assertInViewPort('@first-target')
->forward()
->waitForText('On second')
->assertInViewPort('@second-target')
;
});
}
public function test_navigate_back_works_from_page_without_a_livewire_component_that_has_a_script_with_data_navigate_track()
{
// When using `@vite` on the page without a Livewire component,
// it injects a script tag with `data-navigate-track`,
// which causes Livewire to be unloaded and the back button no longer work.
$this->browse(function ($browser) {
$browser
->visit('/page-with-link-to-page-without-livewire')
->assertSee('Link to page without Livewire component')
->assertDontSee('This is a page without a livewire component')
->click('@link.away')
->waitFor('@non-livewire-page')
->assertSee('This is a page without a livewire component')
->assertDontSee('Link to page without Livewire component')
->back()
->waitFor('@page-with-link-away')
->assertSee('Link to page without Livewire component')
->assertDontSee('This is a page without a livewire component')
;
});
}
public function test_navigate_is_only_triggered_on_left_click()
{
$this->browse(function ($browser) {
$browser
->visit('/first')
->tap(fn ($b) => $b->script('window._lw_dusk_test = true'))
->assertScript('return window._lw_dusk_test')
->assertSee('On first')
->rightClick('@link.to.second')
->pause(500) // Let navigate run if it was going to (it should not)
->assertSee('On first')
->click('@link.to.second')
->waitFor('@link.to.first')
->assertSee('On second')
;
});
}
public function test_livewire_navigated_event_is_fired_on_first_page_load()
{
$this->browse(function ($browser) {
$browser
->visit('/second')
->assertSee('On second')
->assertScript('window.foo_navigated', 'bar');
});
}
public function test_livewire_before_navigate_event_is_fired_when_click()
{
$this->browse(function($browser) {
$browser
->visit('/fourth')
->assertSee('On fourth')
->assertScript('window.foo', 'bar')
->assertSee('On fourth')
->click('@link.to.first') // first attempt bar -> baz
->assertScript('window.foo', 'baz')
->assertSee('On fourth')
->click('@link.to.first') // second attempt baz -> bat
->assertScript('window.foo', 'bat')
->assertSee('On fourth')
->click('@link.to.first') // finally navigate
->assertSee('On first')
;
});
}
public function test_livewire_navigated_event_is_fired_after_redirect_without_reloading()
{
$this->browse(function ($browser) {
$browser
->visit('/first')
->tap(fn ($b) => $b->script('window._lw_dusk_test = true'))
->assertScript('return window._lw_dusk_test')
->assertSee('On first')
->click('@link.to.second')
->waitFor('@link.to.first')
->assertSee('On second')
->assertScript('window.foo_navigated', 'bar');
});
}
public function test_navigate_is_not_triggered_on_cmd_click()
{
$key = PHP_OS_FAMILY === 'Darwin' ? \Facebook\WebDriver\WebDriverKeys::COMMAND : \Facebook\WebDriver\WebDriverKeys::CONTROL;
$this->browse(function (Browser $browser) use ($key) {
$currentWindowHandles = count($browser->driver->getWindowHandles());
$browser
->visit('/first')
->tap(fn ($b) => $b->script('window._lw_dusk_test = true'))
->assertScript('return window._lw_dusk_test')
->assertSee('On first')
->tap(function ($browser) use ($key) {
$browser->driver->getKeyboard()->pressKey($key);
})
->click('@link.to.second')
->tap(function ($browser) use ($key) {
$browser->driver->getKeyboard()->releaseKey($key);
})
->pause(500) // Let navigate run if it was going to (it should not)
->assertSee('On first')
->assertScript('return window._lw_dusk_test')
;
$this->assertCount($currentWindowHandles + 1, $browser->driver->getWindowHandles());
});
}
public function test_events_from_child_components_still_function_after_navigation()
{
$this->browse(function (Browser $browser) {
$browser
->visit('/parent')
->assertSeeNothingIn('@text-child')
->assertSeeNothingIn('@text-parent')
->waitForLivewire()->type('@text-input', 'test')
->waitForTextIn('@text-child', 'test')
->waitForTextIn('@text-parent', 'test')
->waitForNavigate()->click('@home-link')
->assertSeeNothingIn('@text-child')
->assertSeeNothingIn('@text-parent')
->waitForLivewire()->type('@text-input', 'testing')
->waitForTextIn('@text-child', 'testing')
->waitForTextIn('@text-parent', 'testing')
->back()
->waitForTextIn('@text-child', 'test')
->waitForTextIn('@text-parent', 'test')
->waitForLivewire()->type('@text-input', 'testing')
->waitForTextIn('@text-child', 'testing')
->waitForTextIn('@text-parent', 'testing');
});
}
public function test_alpine_for_loop_still_functions_after_navigation()
{
$this->browse(function (Browser $browser) {
$browser
->visit('/page-with-alpine-for-loop')
->assertSeeIn('@text', 'a,b,c')
->assertScript('document.getElementById(\'alpine-for-loop\').querySelectorAll(\'p\').length', 3)
->assertConsoleLogMissingWarning('value is not defined')
->waitForNavigate()->click('@link.to.second')
->assertSee('On second')
->back()
->assertSeeIn('@text', 'a,b,c')
->assertScript('document.getElementById(\'alpine-for-loop\').querySelectorAll(\'p\').length', 3)
->assertConsoleLogMissingWarning('value is not defined')
;
});
}
public function test_injected_assets_such_as_nprogress_styles_are_retained_when_the_page_changes()
{
$this->browse(function ($browser) {
$browser
->visit('/first')
->tap(fn ($b) => $b->script('window._lw_dusk_test = true'))
->assertScript('return window._lw_dusk_test')
->assertSee('On first')
// There should only be two style blocks, livewire styles and nprogress
->assertScript('return document.styleSheets.length', 2)
->click('@link.to.second')
->waitFor('@link.to.first')
->assertSee('On second')
->assertScript('return window._lw_dusk_test')
// There should only be two style blocks, livewire styles and nprogress
->assertScript('return document.styleSheets.length', 2)
->click('@link.to.first')
->waitFor('@link.to.second')
->assertScript('return window._lw_dusk_test')
->assertSee('On first')
// There should only be two style blocks, livewire styles and nprogress
->assertScript('return document.styleSheets.length', 2);
});
}
public function test_remote_assets_loaded_with_the_directive_fully_load_before_component_scripts_and_initialization()
{
$this->browse(function ($browser) {
$browser
->visit('/first')
->assertSee('On first')
// There should only be two style blocks, livewire styles and nprogress
->click('@link.to.asset')
->waitFor('@target')
->waitForTextIn('@target', 'bar')
;
});
}
| |
244420
|
<html>
<head>
<meta name="csrf-token" content="{{ csrf_token() }}">
<script src="/test-navigate-asset.js?v=123" data-navigate-track></script>
</head>
<body>
{{ $slot }}
@stack('scripts')
</body>
</html>
| |
244422
|
<html>
<head>
<meta name="csrf-token" content="{{ csrf_token() }}">
<script src="/test-navigate-asset.js?v=123"></script>
</head>
<body>
{{ $slot }}
@stack('scripts')
</body>
</html>
| |
244423
|
<html>
<head>
<meta name="csrf-token" content="{{ csrf_token() }}">
<script src="/test-navigate-asset.js?v=456" data-navigate-track></script>
</head>
<body>
{{ $slot }}
@stack('scripts')
</body>
</html>
| |
244424
|
<html>
<head>
<meta name="csrf-token" content="{{ csrf_token() }}">
<script src="/test-navigate-asset.js?v=456"></script>
</head>
<body>
{{ $slot }}
@stack('scripts')
</body>
</html>
| |
244447
|
<?php
namespace Livewire\Features\SupportDataBinding;
use Tests\BrowserTestCase;
use Livewire\Livewire;
use Livewire\Component;
use Livewire\Attributes\Computed;
class BrowserTest extends BrowserTestCase
{
function test_can_use_wire_dirty()
{
Livewire::visit(new class extends Component {
public $prop = false;
public function render()
{
return <<<'BLADE'
<div>
<input dusk="checkbox" type="checkbox" wire:model="prop" value="true" />
<div wire:dirty>Unsaved changes...</div>
<div wire:dirty.remove>The data is in-sync...</div>
</div>
BLADE;
}
})
->assertSee('The data is in-sync...')
->check('@checkbox')
->assertDontSee('The data is in-sync')
->assertSee('Unsaved changes...')
->uncheck('@checkbox')
->assertSee('The data is in-sync...')
->assertDontSee('Unsaved changes...')
;
}
function test_can_update_bound_value_from_lifecyle_hook()
{
Livewire::visit(new class extends Component {
public $foo = null;
public $bar = null;
public function updatedFoo(): void
{
$this->bar = null;
}
public function render()
{
return <<<'BLADE'
<div>
<select wire:model.live="foo" dusk="fooSelect">
<option value=""></option>
<option value="one">One</option>
<option value="two">Two</option>
<option value="three">Three</option>
</select>
<select wire:model="bar" dusk="barSelect">
<option value=""></option>
<option value="one">One</option>
<option value="two">Two</option>
<option value="three">Three</option>
</select>
</div>
BLADE;
}
})
->select('@barSelect', 'one')
->waitForLivewire()->select('@fooSelect', 'one')
->assertSelected('@barSelect', '')
;
}
public function updates_dependent_select_options_correctly_when_wire_key_is_applied()
{
Livewire::visit(new class extends Component {
public $parent = 'foo';
public $child = 'bar';
protected $options = [
'foo' => [
'bar',
],
'baz' => [
'qux',
],
];
#[Computed]
public function parentOptions(): array
{
return array_keys($this->options);
}
#[Computed]
public function childOptions(): array
{
return $this->options[$this->parent];
}
public function render(): string
{
return <<<'blade'
<div>
<select wire:model.live="parent" dusk="parent">
@foreach($this->parentOptions as $value)
<option value="{{ $value }}">{{ $value }}</option>
@endforeach
</select>
<select wire:model="child" dusk="child" wire:key="{{ $parent }}">
<option value>Select</option>
@foreach($this->childOptions as $value)
<option value="{{ $value }}">{{ $value }}</option>
@endforeach
</select>
</div>
blade;
}
})
->waitForLivewire()->select('@parent', 'baz')
->assertSelected('@child', '')
->waitForLivewire()->select('@parent', 'foo')
->assertSelected('@child', 'bar');
}
}
| |
244542
|
<?php
namespace Livewire\Tests;
use Livewire\Component;
use Livewire\Livewire;
class AlpineUiBrowserTest extends \Tests\BrowserTestCase
{
public function test_component_with_listbox_and_wire_model_live_should_not_cause_infinite_loop()
{
Livewire::visit(new class extends Component {
public ?array $foo = null;
function render() {
return <<<'HTML'
<div>
<script src="https://unpkg.com/@alpinejs/ui@3.13.4-beta.0/dist/cdn.min.js"></script>
<button wire:click="$refresh">refresh</button>
<div
x-data="{
value: null,
frameworks: [{
id: 1,
name: 'Laravel',
disabled: false,
}],
updates: 0,
}" x-modelable="value" wire:model.live="foo" x-effect="console.log(value); updates++">
<div>updates: <span x-text="updates" dusk="updatesCount"></span></div>
<div x-listbox x-model="value">
<label x-listbox:label>Backend framework</label>
<button x-listbox:button dusk="openListbox">
<span x-text="value ? value.name : 'Select framework'"></span>
</button>
<ul x-listbox:options x-cloak>
<template x-for="framework in frameworks" :key="framework.id">
<li
x-listbox:option
:value="framework"
:disabled="framework.disabled"
dusk="listboxOption">
<span x-text="framework.name"></span>
</li>
</template>
</ul>
</div>
</div>
</div>
HTML;
}
})
->waitForLivewireToLoad()
->click('@openListbox')
->assertSeeIn('@updatesCount', '1')
->pressAndWaitFor('@listboxOption', 250)
->assertSeeIn('@updatesCount', '2')
;
}
public function test_component_with_combobox_and_wire_model_live_should_not_cause_infinite_loop()
{
Livewire::visit(new class extends Component {
public ?array $value = null;
function render() {
return <<<'HTML'
<div>
<script src="https://unpkg.com/@alpinejs/ui@3.13.4-beta.0/dist/cdn.min.js"></script>
<div
x-data="{
query: '',
selected: null,
frameworks: [{
id: 1,
name: 'Laravel',
disabled: false,
}, ],
get filteredFrameworks() {
return this.query === '' ?
this.frameworks :
this.frameworks.filter((framework) => {
return framework.name.toLowerCase().includes(this.query.toLowerCase())
})
},
updates: 0,
}" x-modelable="selected" wire:model.live="value" x-effect="console.log(selected); updates++">
<div>updates: <span x-text="updates" dusk="updatesCount"></span></div>
<div x-combobox x-model="selected">
<div>
<div>
<input
x-combobox:input
:display-value="framework => framework?.name"
@change="query = $event.target.value;"
placeholder="Search..." />
<button x-combobox:button dusk="openCombobox">
open combobox
</button>
</div>
<div x-combobox:options x-cloak>
<ul>
<template
x-for="framework in filteredFrameworks"
:key="framework.id"
hidden>
<li
x-combobox:option
:value="framework"
:disabled="framework.disabled"
dusk="comboboxOption">
<span x-text="framework.name"></span>
</li>
</template>
</ul>
<p x-show="filteredFrameworks.length == 0">No frameworks match your query.</p>
</div>
</div>
</div>
</div>
</div>
HTML;
}
})
->waitForLivewireToLoad()
->click('@openCombobox')
->assertSeeIn('@updatesCount', '1')
->pressAndWaitFor('@comboboxOption', 250)
->assertSeeIn('@updatesCount', '2')
;
}
}
| |
244545
|
<?php
namespace Livewire\Tests;
use Livewire\Component;
use Livewire\Livewire;
class UpdatingTableRowsTest extends \Tests\BrowserTestCase
{
public function test_component_renders_table_rows_and_updates_properly()
{
Livewire::visit([new class extends Component {
public function render() {
return <<<'HTML'
<table>
<tbody>
<livewire:child />
</tbody>
</table>
HTML;
}
},
'child' => new class extends Component {
public int $counter = 0;
public function increment()
{
$this->counter++;
}
public function render()
{
return <<<'HTML'
<tr dusk="table-row">
<td>
<button type="button" wire:click="increment" dusk="increment">+</button>
</td>
<td>
<input wire:model="counter" dusk="counter">
</td>
</tr>
HTML;
}
}])
->assertPresent('@table-row')
->assertPresent('@counter')
->assertInputValue('@counter', '0')
->click('@increment')
->waitForLivewire()
->assertPresent('@table-row')
->assertPresent('@counter')
->assertInputValue('@counter', '1')
;
}
}
| |
244568
|
<?php
namespace Livewire\Exceptions;
use Symfony\Component\HttpKernel\Exception\HttpException;
class LivewirePageExpiredBecauseNewDeploymentHasSignificantEnoughChanges extends HttpException
{
public function __construct()
{
parent::__construct(
419,
'New deployment contains changes to Livewire that have invalidated currently open browser pages.'
);
}
}
| |
244593
|
<p align="center"><a href="https://laravel.com" target="_blank"><img src="https://raw.githubusercontent.com/laravel/art/master/logo-lockup/5%20SVG/2%20CMYK/1%20Full%20Color/laravel-logolockup-cmyk-red.svg" width="400" alt="Laravel Logo"></a></p>
<p align="center">
<a href="https://github.com/laravel/framework/actions"><img src="https://github.com/laravel/framework/workflows/tests/badge.svg" alt="Build Status"></a>
<a href="https://packagist.org/packages/laravel/framework"><img src="https://img.shields.io/packagist/dt/laravel/framework" alt="Total Downloads"></a>
<a href="https://packagist.org/packages/laravel/framework"><img src="https://img.shields.io/packagist/v/laravel/framework" alt="Latest Stable Version"></a>
<a href="https://packagist.org/packages/laravel/framework"><img src="https://img.shields.io/packagist/l/laravel/framework" alt="License"></a>
</p>
## About Laravel
Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experience to be truly fulfilling. Laravel takes the pain out of development by easing common tasks used in many web projects, such as:
- [Simple, fast routing engine](https://laravel.com/docs/routing).
- [Powerful dependency injection container](https://laravel.com/docs/container).
- Multiple back-ends for [session](https://laravel.com/docs/session) and [cache](https://laravel.com/docs/cache) storage.
- Expressive, intuitive [database ORM](https://laravel.com/docs/eloquent).
- Database agnostic [schema migrations](https://laravel.com/docs/migrations).
- [Robust background job processing](https://laravel.com/docs/queues).
- [Real-time event broadcasting](https://laravel.com/docs/broadcasting).
Laravel is accessible, powerful, and provides tools required for large, robust applications.
## Learning Laravel
Laravel has the most extensive and thorough [documentation](https://laravel.com/docs) and video tutorial library of all modern web application frameworks, making it a breeze to get started with the framework.
You may also try the [Laravel Bootcamp](https://bootcamp.laravel.com), where you will be guided through building a modern Laravel application from scratch.
If you don't feel like reading, [Laracasts](https://laracasts.com) can help. Laracasts contains thousands of video tutorials on a range of topics including Laravel, modern PHP, unit testing, and JavaScript. Boost your skills by digging into our comprehensive video library.
## Laravel Sponsors
We would like to extend our thanks to the following sponsors for funding Laravel development. If you are interested in becoming a sponsor, please visit the [Laravel Partners program](https://partners.laravel.com).
### Premium Partners
- **[Vehikl](https://vehikl.com/)**
- **[Tighten Co.](https://tighten.co)**
- **[WebReinvent](https://webreinvent.com/)**
- **[Kirschbaum Development Group](https://kirschbaumdevelopment.com)**
- **[64 Robots](https://64robots.com)**
- **[Curotec](https://www.curotec.com/services/technologies/laravel/)**
- **[Cyber-Duck](https://cyber-duck.co.uk)**
- **[DevSquad](https://devsquad.com/hire-laravel-developers)**
- **[Jump24](https://jump24.co.uk)**
- **[Redberry](https://redberry.international/laravel/)**
- **[Active Logic](https://activelogic.com)**
- **[byte5](https://byte5.de)**
- **[OP.GG](https://op.gg)**
## Contributing
Thank you for considering contributing to the Laravel framework! The contribution guide can be found in the [Laravel documentation](https://laravel.com/docs/contributions).
## Code of Conduct
In order to ensure that the Laravel community is welcoming to all, please review and abide by the [Code of Conduct](https://laravel.com/docs/contributions#code-of-conduct).
## Security Vulnerabilities
If you discover a security vulnerability within Laravel, please send an e-mail to Taylor Otwell via [taylor@laravel.com](mailto:taylor@laravel.com). All security vulnerabilities will be promptly addressed.
## License
The Laravel framework is open-sourced software licensed under the [MIT license](https://opensource.org/licenses/MIT).
| |
244594
|
#!/usr/bin/env php
<?php
use Symfony\Component\Console\Input\ArgvInput;
define('LARAVEL_START', microtime(true));
// Register the Composer autoloader...
require __DIR__.'/vendor/autoload.php';
// Bootstrap Laravel and handle the command...
$status = (require_once __DIR__.'/bootstrap/app.php')
->handleCommand(new ArgvInput);
exit($status);
| |
244601
|
<?php
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
web: __DIR__.'/../routes/web.php',
commands: __DIR__.'/../routes/console.php',
health: '/up',
)
->withMiddleware(function (Middleware $middleware) {
//
})
->withExceptions(function (Exceptions $exceptions) {
//
})->create();
| |
244602
|
<?php
return [
App\Providers\AppServiceProvider::class,
];
| |
244604
|
<?php
namespace App\Models;
// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
/** @use HasFactory<\Database\Factories\UserFactory> */
use HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for serialization.
*
* @var array<int, string>
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* Get the attributes that should be cast.
*
* @return array<string, string>
*/
protected function casts(): array
{
return [
'email_verified_at' => 'datetime',
'password' => 'hashed',
];
}
}
| |
244607
|
<?php
return [
/*
|--------------------------------------------------------------------------
| Application Name
|--------------------------------------------------------------------------
|
| This value is the name of your application, which will be used when the
| framework needs to place the application's name in a notification or
| other UI elements where an application name needs to be displayed.
|
*/
'name' => env('APP_NAME', 'Laravel'),
/*
|--------------------------------------------------------------------------
| Application Environment
|--------------------------------------------------------------------------
|
| This value determines the "environment" your application is currently
| running in. This may determine how you prefer to configure various
| services the application utilizes. Set this in your ".env" file.
|
*/
'env' => env('APP_ENV', 'production'),
/*
|--------------------------------------------------------------------------
| Application Debug Mode
|--------------------------------------------------------------------------
|
| When your application is in debug mode, detailed error messages with
| stack traces will be shown on every error that occurs within your
| application. If disabled, a simple generic error page is shown.
|
*/
'debug' => (bool) env('APP_DEBUG', false),
/*
|--------------------------------------------------------------------------
| Application URL
|--------------------------------------------------------------------------
|
| This URL is used by the console to properly generate URLs when using
| the Artisan command line tool. You should set this to the root of
| the application so that it's available within Artisan commands.
|
*/
'url' => env('APP_URL', 'http://localhost'),
/*
|--------------------------------------------------------------------------
| Application Timezone
|--------------------------------------------------------------------------
|
| Here you may specify the default timezone for your application, which
| will be used by the PHP date and date-time functions. The timezone
| is set to "UTC" by default as it is suitable for most use cases.
|
*/
'timezone' => env('APP_TIMEZONE', 'UTC'),
/*
|--------------------------------------------------------------------------
| Application Locale Configuration
|--------------------------------------------------------------------------
|
| The application locale determines the default locale that will be used
| by Laravel's translation / localization methods. This option can be
| set to any locale for which you plan to have translation strings.
|
*/
'locale' => env('APP_LOCALE', 'en'),
'fallback_locale' => env('APP_FALLBACK_LOCALE', 'en'),
'faker_locale' => env('APP_FAKER_LOCALE', 'en_US'),
/*
|--------------------------------------------------------------------------
| Encryption Key
|--------------------------------------------------------------------------
|
| This key is utilized by Laravel's encryption services and should be set
| to a random, 32 character string to ensure that all encrypted values
| are secure. You should do this prior to deploying the application.
|
*/
'cipher' => 'AES-256-CBC',
'key' => env('APP_KEY'),
'previous_keys' => [
...array_filter(
explode(',', env('APP_PREVIOUS_KEYS', ''))
),
],
/*
|--------------------------------------------------------------------------
| Maintenance Mode Driver
|--------------------------------------------------------------------------
|
| These configuration options determine the driver used to determine and
| manage Laravel's "maintenance mode" status. The "cache" driver will
| allow maintenance mode to be controlled across multiple machines.
|
| Supported drivers: "file", "cache"
|
*/
'maintenance' => [
'driver' => env('APP_MAINTENANCE_DRIVER', 'file'),
'store' => env('APP_MAINTENANCE_STORE', 'database'),
],
];
| |
244612
|
<?php
use Illuminate\Support\Str;
return [
/*
|--------------------------------------------------------------------------
| Default Session Driver
|--------------------------------------------------------------------------
|
| This option determines the default session driver that is utilized for
| incoming requests. Laravel supports a variety of storage options to
| persist session data. Database storage is a great default choice.
|
| Supported: "file", "cookie", "database", "apc",
| "memcached", "redis", "dynamodb", "array"
|
*/
'driver' => env('SESSION_DRIVER', 'database'),
/*
|--------------------------------------------------------------------------
| Session Lifetime
|--------------------------------------------------------------------------
|
| Here you may specify the number of minutes that you wish the session
| to be allowed to remain idle before it expires. If you want them
| to expire immediately when the browser is closed then you may
| indicate that via the expire_on_close configuration option.
|
*/
'lifetime' => env('SESSION_LIFETIME', 120),
'expire_on_close' => env('SESSION_EXPIRE_ON_CLOSE', false),
/*
|--------------------------------------------------------------------------
| Session Encryption
|--------------------------------------------------------------------------
|
| This option allows you to easily specify that all of your session data
| should be encrypted before it's stored. All encryption is performed
| automatically by Laravel and you may use the session like normal.
|
*/
'encrypt' => env('SESSION_ENCRYPT', false),
/*
|--------------------------------------------------------------------------
| Session File Location
|--------------------------------------------------------------------------
|
| When utilizing the "file" session driver, the session files are placed
| on disk. The default storage location is defined here; however, you
| are free to provide another location where they should be stored.
|
*/
'files' => storage_path('framework/sessions'),
/*
|--------------------------------------------------------------------------
| Session Database Connection
|--------------------------------------------------------------------------
|
| When using the "database" or "redis" session drivers, you may specify a
| connection that should be used to manage these sessions. This should
| correspond to a connection in your database configuration options.
|
*/
'connection' => env('SESSION_CONNECTION'),
/*
|--------------------------------------------------------------------------
| Session Database Table
|--------------------------------------------------------------------------
|
| When using the "database" session driver, you may specify the table to
| be used to store sessions. Of course, a sensible default is defined
| for you; however, you're welcome to change this to another table.
|
*/
'table' => env('SESSION_TABLE', 'sessions'),
/*
|--------------------------------------------------------------------------
| Session Cache Store
|--------------------------------------------------------------------------
|
| When using one of the framework's cache driven session backends, you may
| define the cache store which should be used to store the session data
| between requests. This must match one of your defined cache stores.
|
| Affects: "apc", "dynamodb", "memcached", "redis"
|
*/
'store' => env('SESSION_STORE'),
/*
|--------------------------------------------------------------------------
| Session Sweeping Lottery
|--------------------------------------------------------------------------
|
| Some session drivers must manually sweep their storage location to get
| rid of old sessions from storage. Here are the chances that it will
| happen on a given request. By default, the odds are 2 out of 100.
|
*/
'lottery' => [2, 100],
/*
|--------------------------------------------------------------------------
| Session Cookie Name
|--------------------------------------------------------------------------
|
| Here you may change the name of the session cookie that is created by
| the framework. Typically, you should not need to change this value
| since doing so does not grant a meaningful security improvement.
|
*/
'cookie' => env(
'SESSION_COOKIE',
Str::slug(env('APP_NAME', 'laravel'), '_').'_session'
),
/*
|--------------------------------------------------------------------------
| Session Cookie Path
|--------------------------------------------------------------------------
|
| The session cookie path determines the path for which the cookie will
| be regarded as available. Typically, this will be the root path of
| your application, but you're free to change this when necessary.
|
*/
'path' => env('SESSION_PATH', '/'),
/*
|--------------------------------------------------------------------------
| Session Cookie Domain
|--------------------------------------------------------------------------
|
| This value determines the domain and subdomains the session cookie is
| available to. By default, the cookie will be available to the root
| domain and all subdomains. Typically, this shouldn't be changed.
|
*/
'domain' => env('SESSION_DOMAIN'),
/*
|--------------------------------------------------------------------------
| HTTPS Only Cookies
|--------------------------------------------------------------------------
|
| By setting this option to true, session cookies will only be sent back
| to the server if the browser has a HTTPS connection. This will keep
| the cookie from being sent to you when it can't be done securely.
|
*/
'secure' => env('SESSION_SECURE_COOKIE'),
/*
|--------------------------------------------------------------------------
| HTTP Access Only
|--------------------------------------------------------------------------
|
| Setting this value to true will prevent JavaScript from accessing the
| value of the cookie and the cookie will only be accessible through
| the HTTP protocol. It's unlikely you should disable this option.
|
*/
'http_only' => env('SESSION_HTTP_ONLY', true),
/*
|--------------------------------------------------------------------------
| Same-Site Cookies
|--------------------------------------------------------------------------
|
| This option determines how your cookies behave when cross-site requests
| take place, and can be used to mitigate CSRF attacks. By default, we
| will set this value to "lax" to permit secure cross-site requests.
|
| See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#samesitesamesite-value
|
| Supported: "lax", "strict", "none", null
|
*/
'same_site' => env('SESSION_SAME_SITE', 'lax'),
/*
|--------------------------------------------------------------------------
| Partitioned Cookies
|--------------------------------------------------------------------------
|
| Setting this value to true will tie the cookie to the top-level site for
| a cross-site context. Partitioned cookies are accepted by the browser
| when flagged "secure" and the Same-Site attribute is set to "none".
|
*/
'partitioned' => env('SESSION_PARTITIONED_COOKIE', false),
];
| |
244613
|
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Queue Connection Name
|--------------------------------------------------------------------------
|
| Laravel's queue supports a variety of backends via a single, unified
| API, giving you convenient access to each backend using identical
| syntax for each. The default queue connection is defined below.
|
*/
'default' => env('QUEUE_CONNECTION', 'database'),
/*
|--------------------------------------------------------------------------
| Queue Connections
|--------------------------------------------------------------------------
|
| Here you may configure the connection options for every queue backend
| used by your application. An example configuration is provided for
| each backend supported by Laravel. You're also free to add more.
|
| Drivers: "sync", "database", "beanstalkd", "sqs", "redis", "null"
|
*/
'connections' => [
'sync' => [
'driver' => 'sync',
],
'database' => [
'driver' => 'database',
'connection' => env('DB_QUEUE_CONNECTION'),
'table' => env('DB_QUEUE_TABLE', 'jobs'),
'queue' => env('DB_QUEUE', 'default'),
'retry_after' => (int) env('DB_QUEUE_RETRY_AFTER', 90),
'after_commit' => false,
],
'beanstalkd' => [
'driver' => 'beanstalkd',
'host' => env('BEANSTALKD_QUEUE_HOST', 'localhost'),
'queue' => env('BEANSTALKD_QUEUE', 'default'),
'retry_after' => (int) env('BEANSTALKD_QUEUE_RETRY_AFTER', 90),
'block_for' => 0,
'after_commit' => false,
],
'sqs' => [
'driver' => 'sqs',
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'prefix' => env('SQS_PREFIX', 'https://sqs.us-east-1.amazonaws.com/your-account-id'),
'queue' => env('SQS_QUEUE', 'default'),
'suffix' => env('SQS_SUFFIX'),
'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
'after_commit' => false,
],
'redis' => [
'driver' => 'redis',
'connection' => env('REDIS_QUEUE_CONNECTION', 'default'),
'queue' => env('REDIS_QUEUE', 'default'),
'retry_after' => (int) env('REDIS_QUEUE_RETRY_AFTER', 90),
'block_for' => null,
'after_commit' => false,
],
],
/*
|--------------------------------------------------------------------------
| Job Batching
|--------------------------------------------------------------------------
|
| The following options configure the database and table that store job
| batching information. These options can be updated to any database
| connection and table which has been defined by your application.
|
*/
'batching' => [
'database' => env('DB_CONNECTION', 'sqlite'),
'table' => 'job_batches',
],
/*
|--------------------------------------------------------------------------
| Failed Queue Jobs
|--------------------------------------------------------------------------
|
| These options configure the behavior of failed queue job logging so you
| can control how and where failed jobs are stored. Laravel ships with
| support for storing failed jobs in a simple file or in a database.
|
| Supported drivers: "database-uuids", "dynamodb", "file", "null"
|
*/
'failed' => [
'driver' => env('QUEUE_FAILED_DRIVER', 'database-uuids'),
'database' => env('DB_CONNECTION', 'sqlite'),
'table' => 'failed_jobs',
],
];
| |
244614
|
<?php
use Monolog\Handler\NullHandler;
use Monolog\Handler\StreamHandler;
use Monolog\Handler\SyslogUdpHandler;
use Monolog\Processor\PsrLogMessageProcessor;
return [
/*
|--------------------------------------------------------------------------
| Default Log Channel
|--------------------------------------------------------------------------
|
| This option defines the default log channel that is utilized to write
| messages to your logs. The value provided here should match one of
| the channels present in the list of "channels" configured below.
|
*/
'default' => env('LOG_CHANNEL', 'stack'),
/*
|--------------------------------------------------------------------------
| Deprecations Log Channel
|--------------------------------------------------------------------------
|
| This option controls the log channel that should be used to log warnings
| regarding deprecated PHP and library features. This allows you to get
| your application ready for upcoming major versions of dependencies.
|
*/
'deprecations' => [
'channel' => env('LOG_DEPRECATIONS_CHANNEL', 'null'),
'trace' => env('LOG_DEPRECATIONS_TRACE', false),
],
/*
|--------------------------------------------------------------------------
| Log Channels
|--------------------------------------------------------------------------
|
| Here you may configure the log channels for your application. Laravel
| utilizes the Monolog PHP logging library, which includes a variety
| of powerful log handlers and formatters that you're free to use.
|
| Available drivers: "single", "daily", "slack", "syslog",
| "errorlog", "monolog", "custom", "stack"
|
*/
'channels' => [
'stack' => [
'driver' => 'stack',
'channels' => explode(',', env('LOG_STACK', 'single')),
'ignore_exceptions' => false,
],
'single' => [
'driver' => 'single',
'path' => storage_path('logs/laravel.log'),
'level' => env('LOG_LEVEL', 'debug'),
'replace_placeholders' => true,
],
'daily' => [
'driver' => 'daily',
'path' => storage_path('logs/laravel.log'),
'level' => env('LOG_LEVEL', 'debug'),
'days' => env('LOG_DAILY_DAYS', 14),
'replace_placeholders' => true,
],
'slack' => [
'driver' => 'slack',
'url' => env('LOG_SLACK_WEBHOOK_URL'),
'username' => env('LOG_SLACK_USERNAME', 'Laravel Log'),
'emoji' => env('LOG_SLACK_EMOJI', ':boom:'),
'level' => env('LOG_LEVEL', 'critical'),
'replace_placeholders' => true,
],
'papertrail' => [
'driver' => 'monolog',
'level' => env('LOG_LEVEL', 'debug'),
'handler' => env('LOG_PAPERTRAIL_HANDLER', SyslogUdpHandler::class),
'handler_with' => [
'host' => env('PAPERTRAIL_URL'),
'port' => env('PAPERTRAIL_PORT'),
'connectionString' => 'tls://'.env('PAPERTRAIL_URL').':'.env('PAPERTRAIL_PORT'),
],
'processors' => [PsrLogMessageProcessor::class],
],
'stderr' => [
'driver' => 'monolog',
'level' => env('LOG_LEVEL', 'debug'),
'handler' => StreamHandler::class,
'formatter' => env('LOG_STDERR_FORMATTER'),
'with' => [
'stream' => 'php://stderr',
],
'processors' => [PsrLogMessageProcessor::class],
],
'syslog' => [
'driver' => 'syslog',
'level' => env('LOG_LEVEL', 'debug'),
'facility' => env('LOG_SYSLOG_FACILITY', LOG_USER),
'replace_placeholders' => true,
],
'errorlog' => [
'driver' => 'errorlog',
'level' => env('LOG_LEVEL', 'debug'),
'replace_placeholders' => true,
],
'null' => [
'driver' => 'monolog',
'handler' => NullHandler::class,
],
'emergency' => [
'path' => storage_path('logs/laravel.log'),
],
],
];
| |
244615
|
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Filesystem Disk
|--------------------------------------------------------------------------
|
| Here you may specify the default filesystem disk that should be used
| by the framework. The "local" disk, as well as a variety of cloud
| based disks are available to your application for file storage.
|
*/
'default' => env('FILESYSTEM_DISK', 'local'),
/*
|--------------------------------------------------------------------------
| Filesystem Disks
|--------------------------------------------------------------------------
|
| Below you may configure as many filesystem disks as necessary, and you
| may even configure multiple disks for the same driver. Examples for
| most supported storage drivers are configured here for reference.
|
| Supported drivers: "local", "ftp", "sftp", "s3"
|
*/
'disks' => [
'local' => [
'driver' => 'local',
'root' => storage_path('app/private'),
'serve' => true,
'throw' => false,
],
'public' => [
'driver' => 'local',
'root' => storage_path('app/public'),
'url' => env('APP_URL').'/storage',
'visibility' => 'public',
'throw' => false,
],
's3' => [
'driver' => 's3',
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'region' => env('AWS_DEFAULT_REGION'),
'bucket' => env('AWS_BUCKET'),
'url' => env('AWS_URL'),
'endpoint' => env('AWS_ENDPOINT'),
'use_path_style_endpoint' => env('AWS_USE_PATH_STYLE_ENDPOINT', false),
'throw' => false,
],
],
/*
|--------------------------------------------------------------------------
| Symbolic Links
|--------------------------------------------------------------------------
|
| Here you may configure the symbolic links that will be created when the
| `storage:link` Artisan command is executed. The array keys should be
| the locations of the links and the values should be their targets.
|
*/
'links' => [
public_path('storage') => storage_path('app/public'),
],
];
| |
244631
|
<?php
use Illuminate\Http\Request;
define('LARAVEL_START', microtime(true));
// Determine if the application is in maintenance mode...
if (file_exists($maintenance = __DIR__.'/../storage/framework/maintenance.php')) {
require $maintenance;
}
// Register the Composer autoloader...
require __DIR__.'/../vendor/autoload.php';
// Bootstrap Laravel and handle the request...
(require_once __DIR__.'/../bootstrap/app.php')
->handleRequest(Request::capture());
| |
244643
|
import argparse
import sys
import time
import warnings
sys.path.append('./') # to run '$ python *.py' files in subdirectories
import torch
import torch.nn as nn
from torch.utils.mobile_optimizer import optimize_for_mobile
import models
from models.experimental import attempt_load, End2End
from utils.activations import Hardswish, SiLU
from utils.general import set_logging, check_img_size
from utils.torch_utils import select_device
from utils.add_nms import RegisterNMS
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--weights', type=str, default='./yolor-csp-c.pt', help='weights path')
parser.add_argument('--img-size', nargs='+', type=int, default=[640, 640], help='image size') # height, width
parser.add_argument('--batch-size', type=int, default=1, help='batch size')
parser.add_argument('--dynamic', action='store_true', help='dynamic ONNX axes')
parser.add_argument('--dynamic-batch', action='store_true', help='dynamic batch onnx for tensorrt and onnx-runtime')
parser.add_argument('--grid', action='store_true', help='export Detect() layer grid')
parser.add_argument('--end2end', action='store_true', help='export end2end onnx')
parser.add_argument('--max-wh', type=int, default=None, help='None for tensorrt nms, int value for onnx-runtime nms')
parser.add_argument('--topk-all', type=int, default=100, help='topk objects for every images')
parser.add_argument('--iou-thres', type=float, default=0.45, help='iou threshold for NMS')
parser.add_argument('--conf-thres', type=float, default=0.25, help='conf threshold for NMS')
parser.add_argument('--device', default='cpu', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
parser.add_argument('--simplify', action='store_true', help='simplify onnx model')
parser.add_argument('--include-nms', action='store_true', help='export end2end onnx')
parser.add_argument('--fp16', action='store_true', help='CoreML FP16 half-precision export')
parser.add_argument('--int8', action='store_true', help='CoreML INT8 quantization')
opt = parser.parse_args()
opt.img_size *= 2 if len(opt.img_size) == 1 else 1 # expand
opt.dynamic = opt.dynamic and not opt.end2end
opt.dynamic = False if opt.dynamic_batch else opt.dynamic
print(opt)
set_logging()
t = time.time()
# Load PyTorch model
device = select_device(opt.device)
model = attempt_load(opt.weights, map_location=device) # load FP32 model
labels = model.names
# Checks
gs = int(max(model.stride)) # grid size (max stride)
opt.img_size = [check_img_size(x, gs) for x in opt.img_size] # verify img_size are gs-multiples
# Input
img = torch.zeros(opt.batch_size, 3, *opt.img_size).to(device) # image size(1,3,320,192) iDetection
# Update model
for k, m in model.named_modules():
m._non_persistent_buffers_set = set() # pytorch 1.6.0 compatibility
if isinstance(m, models.common.Conv): # assign export-friendly activations
if isinstance(m.act, nn.Hardswish):
m.act = Hardswish()
elif isinstance(m.act, nn.SiLU):
m.act = SiLU()
# elif isinstance(m, models.yolo.Detect):
# m.forward = m.forward_export # assign forward (optional)
model.model[-1].export = not opt.grid # set Detect() layer grid export
y = model(img) # dry run
if opt.include_nms:
model.model[-1].include_nms = True
y = None
# TorchScript export
try:
print('\nStarting TorchScript export with torch %s...' % torch.__version__)
f = opt.weights.replace('.pt', '.torchscript.pt') # filename
ts = torch.jit.trace(model, img, strict=False)
ts.save(f)
print('TorchScript export success, saved as %s' % f)
except Exception as e:
print('TorchScript export failure: %s' % e)
# CoreML export
try:
import coremltools as ct
print('\nStarting CoreML export with coremltools %s...' % ct.__version__)
# convert model from torchscript and apply pixel scaling as per detect.py
ct_model = ct.convert(ts, inputs=[ct.ImageType('image', shape=img.shape, scale=1 / 255.0, bias=[0, 0, 0])])
bits, mode = (8, 'kmeans_lut') if opt.int8 else (16, 'linear') if opt.fp16 else (32, None)
if bits < 32:
if sys.platform.lower() == 'darwin': # quantization only supported on macOS
with warnings.catch_warnings():
warnings.filterwarnings("ignore", category=DeprecationWarning) # suppress numpy==1.20 float warning
ct_model = ct.models.neural_network.quantization_utils.quantize_weights(ct_model, bits, mode)
else:
print('quantization only supported on macOS, skipping...')
f = opt.weights.replace('.pt', '.mlmodel') # filename
ct_model.save(f)
print('CoreML export success, saved as %s' % f)
except Exception as e:
print('CoreML export failure: %s' % e)
# TorchScript-Lite export
try:
print('\nStarting TorchScript-Lite export with torch %s...' % torch.__version__)
f = opt.weights.replace('.pt', '.torchscript.ptl') # filename
tsl = torch.jit.trace(model, img, strict=False)
tsl = optimize_for_mobile(tsl)
tsl._save_for_lite_interpreter(f)
print('TorchScript-Lite export success, saved as %s' % f)
except Exception as e:
print('TorchScript-Lite export failure: %s' % e)
# ONNX export
| |
244644
|
try:
import onnx
print('\nStarting ONNX export with onnx %s...' % onnx.__version__)
f = opt.weights.replace('.pt', '.onnx') # filename
model.eval()
output_names = ['classes', 'boxes'] if y is None else ['output']
dynamic_axes = None
if opt.dynamic:
dynamic_axes = {'images': {0: 'batch', 2: 'height', 3: 'width'}, # size(1,3,640,640)
'output': {0: 'batch', 2: 'y', 3: 'x'}}
if opt.dynamic_batch:
opt.batch_size = 'batch'
dynamic_axes = {
'images': {
0: 'batch',
}, }
if opt.end2end and opt.max_wh is None:
output_axes = {
'num_dets': {0: 'batch'},
'det_boxes': {0: 'batch'},
'det_scores': {0: 'batch'},
'det_classes': {0: 'batch'},
}
else:
output_axes = {
'output': {0: 'batch'},
}
dynamic_axes.update(output_axes)
if opt.grid:
if opt.end2end:
print('\nStarting export end2end onnx model for %s...' % 'TensorRT' if opt.max_wh is None else 'onnxruntime')
model = End2End(model,opt.topk_all,opt.iou_thres,opt.conf_thres,opt.max_wh,device,len(labels))
if opt.end2end and opt.max_wh is None:
output_names = ['num_dets', 'det_boxes', 'det_scores', 'det_classes']
shapes = [opt.batch_size, 1, opt.batch_size, opt.topk_all, 4,
opt.batch_size, opt.topk_all, opt.batch_size, opt.topk_all]
else:
output_names = ['output']
else:
model.model[-1].concat = True
torch.onnx.export(model, img, f, verbose=False, opset_version=12, input_names=['images'],
output_names=output_names,
dynamic_axes=dynamic_axes)
# Checks
onnx_model = onnx.load(f) # load onnx model
onnx.checker.check_model(onnx_model) # check onnx model
if opt.end2end and opt.max_wh is None:
for i in onnx_model.graph.output:
for j in i.type.tensor_type.shape.dim:
j.dim_param = str(shapes.pop(0))
# print(onnx.helper.printable_graph(onnx_model.graph)) # print a human readable model
# # Metadata
# d = {'stride': int(max(model.stride))}
# for k, v in d.items():
# meta = onnx_model.metadata_props.add()
# meta.key, meta.value = k, str(v)
# onnx.save(onnx_model, f)
if opt.simplify:
try:
import onnxsim
print('\nStarting to simplify ONNX...')
onnx_model, check = onnxsim.simplify(onnx_model)
assert check, 'assert check failed'
except Exception as e:
print(f'Simplifier failure: {e}')
# print(onnx.helper.printable_graph(onnx_model.graph)) # print a human readable model
onnx.save(onnx_model,f)
print('ONNX export success, saved as %s' % f)
if opt.include_nms:
print('Registering NMS plugin for ONNX...')
mo = RegisterNMS(f)
mo.register_nms()
mo.save(f)
except Exception as e:
print('ONNX export failure: %s' % e)
# Finish
print('\nExport complete (%.2fs). Visualize with https://github.com/lutzroeder/netron.' % (time.time() - t))
| |
244647
|
olov7_training.pt`](https://github.com/WongKinYiu/yolov7/releases/download/v0.1/yolov7_training.pt) [`yolov7x_training.pt`](https://github.com/WongKinYiu/yolov7/releases/download/v0.1/yolov7x_training.pt) [`yolov7-w6_training.pt`](https://github.com/WongKinYiu/yolov7/releases/download/v0.1/yolov7-w6_training.pt) [`yolov7-e6_training.pt`](https://github.com/WongKinYiu/yolov7/releases/download/v0.1/yolov7-e6_training.pt) [`yolov7-d6_training.pt`](https://github.com/WongKinYiu/yolov7/releases/download/v0.1/yolov7-d6_training.pt) [`yolov7-e6e_training.pt`](https://github.com/WongKinYiu/yolov7/releases/download/v0.1/yolov7-e6e_training.pt)
Single GPU finetuning for custom dataset
``` shell
# finetune p5 models
python train.py --workers 8 --device 0 --batch-size 32 --data data/custom.yaml --img 640 640 --cfg cfg/training/yolov7-custom.yaml --weights 'yolov7_training.pt' --name yolov7-custom --hyp data/hyp.scratch.custom.yaml
# finetune p6 models
python train_aux.py --workers 8 --device 0 --batch-size 16 --data data/custom.yaml --img 1280 1280 --cfg cfg/training/yolov7-w6-custom.yaml --weights 'yolov7-w6_training.pt' --name yolov7-w6-custom --hyp data/hyp.scratch.custom.yaml
```
## Re-parameterization
See [reparameterization.ipynb](tools/reparameterization.ipynb)
## Inference
On video:
``` shell
python detect.py --weights yolov7.pt --conf 0.25 --img-size 640 --source yourvideo.mp4
```
On image:
``` shell
python detect.py --weights yolov7.pt --conf 0.25 --img-size 640 --source inference/images/horses.jpg
```
<div align="center">
<a href="./">
<img src="./figure/horses_prediction.jpg" width="59%"/>
</a>
</div>
## Export
**Pytorch to CoreML (and inference on MacOS/iOS)** <a href="https://colab.research.google.com/github/WongKinYiu/yolov7/blob/main/tools/YOLOv7CoreML.ipynb"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"></a>
**Pytorch to ONNX with NMS (and inference)** <a href="https://colab.research.google.com/github/WongKinYiu/yolov7/blob/main/tools/YOLOv7onnx.ipynb"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"></a>
```shell
python export.py --weights yolov7-tiny.pt --grid --end2end --simplify \
--topk-all 100 --iou-thres 0.65 --conf-thres 0.35 --img-size 640 640 --max-wh 640
```
**Pytorch to TensorRT with NMS (and inference)** <a href="https://colab.research.google.com/github/WongKinYiu/yolov7/blob/main/tools/YOLOv7trt.ipynb"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"></a>
```shell
wget https://github.com/WongKinYiu/yolov7/releases/download/v0.1/yolov7-tiny.pt
python export.py --weights ./yolov7-tiny.pt --grid --end2end --simplify --topk-all 100 --iou-thres 0.65 --conf-thres 0.35 --img-size 640 640
git clone https://github.com/Linaom1214/tensorrt-python.git
python ./tensorrt-python/export.py -o yolov7-tiny.onnx -e yolov7-tiny-nms.trt -p fp16
```
**Pytorch to TensorRT another way** <a href="https://colab.research.google.com/gist/AlexeyAB/fcb47ae544cf284eb24d8ad8e880d45c/yolov7trtlinaom.ipynb"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"></a> <details><summary> <b>Expand</b> </summary>
```shell
wget https://github.com/WongKinYiu/yolov7/releases/download/v0.1/yolov7-tiny.pt
python export.py --weights yolov7-tiny.pt --grid --include-nms
git clone https://github.com/Linaom1214/tensorrt-python.git
python ./tensorrt-python/export.py -o yolov7-tiny.onnx -e yolov7-tiny-nms.trt -p fp16
# Or use trtexec to convert ONNX to TensorRT engine
/usr/src/tensorrt/bin/trtexec --onnx=yolov7-tiny.onnx --saveEngine=yolov7-tiny-nms.trt --fp16
```
</details>
Tested with: Python 3.7.13, Pytorch 1.12.0+cu113
## Pose estimation
[`code`](https://github.com/WongKinYiu/yolov7/tree/pose) [`yolov7-w6-pose.pt`](https://github.com/WongKinYiu/yolov7/releases/download/v0.1/yolov7-w6-pose.pt)
See [keypoint.ipynb](https://github.com/WongKinYiu/yolov7/blob/main/tools/keypoint.ipynb).
<div align="center">
<a href="./">
<img src="./figure/pose.png" width="39%"/>
</a>
</div>
## Instance segmentation (with NTU)
[`code`](https://github.com/WongKinYiu/yolov7/tree/mask) [`yolov7-mask.pt`](https://github.com/WongKinYiu/yolov7/releases/download/v0.1/yolov7-mask.pt)
See [instance.ipynb](https://github.com/WongKinYiu/yolov7/blob/main/tools/instance.ipynb).
<div align="center">
<a href="./">
<img src="./figure/mask.png" width="59%"/>
</a>
</div>
## Instance segmentation
[`code`](https://github.com/WongKinYiu/yolov7/tree/u7/seg) [`yolov7-seg.pt`](https://github.com/WongKinYiu/yolov7/releases/download/v0.1/yolov7-seg.pt)
YOLOv7 for instance segmentation (YOLOR + YOLOv5 + YOLACT)
| Model | Test Size | AP<sup>box</sup> | AP<sub>50</sub><sup>box</sup> | AP<sub>75</sub><sup>box</sup> | AP<sup>mask</sup> | AP<sub>50</sub><sup>mask</sup> | AP<sub>75</sub><sup>mask</sup> |
| :-- | :-: | :-: | :-: | :-: | :-: | :-: | :-: |
| **YOLOv7-seg** | 640 | **51.4%** | **69.4%** | **55.8%** | **41.5%** | **65.5%** | **43.7%** |
## Anchor free detection head
[`code`](https://github.com/WongKinYiu/yolov7/tree/u6) [`yolov7-u6.pt`](https://github.com/WongKinYiu/yolov7/releases/download/v0.1/yolov7-u6.pt)
YOLOv7 with decoupled TAL head (YOLOR + YOLOv5 + YOLOv6)
| Model | Test Size | AP<sup>val</sup> | AP<sub>50</sub><sup>val</sup> | AP<sub>75</sub><sup>val</sup> |
| :-- | :-: | :-: | :-: | :-: |
| **YOLOv7-u6** | 640 | **52.6%** | **69.7%** | **57.3%** |
##
| |
244657
|
def train(hyp, opt, device, tb_writer=None):
logger.info(colorstr('hyperparameters: ') + ', '.join(f'{k}={v}' for k, v in hyp.items()))
save_dir, epochs, batch_size, total_batch_size, weights, rank, freeze = \
Path(opt.save_dir), opt.epochs, opt.batch_size, opt.total_batch_size, opt.weights, opt.global_rank, opt.freeze
# Directories
wdir = save_dir / 'weights'
wdir.mkdir(parents=True, exist_ok=True) # make dir
last = wdir / 'last.pt'
best = wdir / 'best.pt'
results_file = save_dir / 'results.txt'
# Save run settings
with open(save_dir / 'hyp.yaml', 'w') as f:
yaml.dump(hyp, f, sort_keys=False)
with open(save_dir / 'opt.yaml', 'w') as f:
yaml.dump(vars(opt), f, sort_keys=False)
# Configure
plots = not opt.evolve # create plots
cuda = device.type != 'cpu'
init_seeds(2 + rank)
with open(opt.data) as f:
data_dict = yaml.load(f, Loader=yaml.SafeLoader) # data dict
is_coco = opt.data.endswith('coco.yaml')
# Logging- Doing this before checking the dataset. Might update data_dict
loggers = {'wandb': None} # loggers dict
if rank in [-1, 0]:
opt.hyp = hyp # add hyperparameters
run_id = torch.load(weights, map_location=device).get('wandb_id') if weights.endswith('.pt') and os.path.isfile(weights) else None
wandb_logger = WandbLogger(opt, Path(opt.save_dir).stem, run_id, data_dict)
loggers['wandb'] = wandb_logger.wandb
data_dict = wandb_logger.data_dict
if wandb_logger.wandb:
weights, epochs, hyp = opt.weights, opt.epochs, opt.hyp # WandbLogger might update weights, epochs if resuming
nc = 1 if opt.single_cls else int(data_dict['nc']) # number of classes
names = ['item'] if opt.single_cls and len(data_dict['names']) != 1 else data_dict['names'] # class names
assert len(names) == nc, '%g names found for nc=%g dataset in %s' % (len(names), nc, opt.data) # check
# Model
pretrained = weights.endswith('.pt')
if pretrained:
with torch_distributed_zero_first(rank):
attempt_download(weights) # download if not found locally
ckpt = torch.load(weights, map_location=device) # load checkpoint
model = Model(opt.cfg or ckpt['model'].yaml, ch=3, nc=nc, anchors=hyp.get('anchors')).to(device) # create
exclude = ['anchor'] if (opt.cfg or hyp.get('anchors')) and not opt.resume else [] # exclude keys
state_dict = ckpt['model'].float().state_dict() # to FP32
state_dict = intersect_dicts(state_dict, model.state_dict(), exclude=exclude) # intersect
model.load_state_dict(state_dict, strict=False) # load
logger.info('Transferred %g/%g items from %s' % (len(state_dict), len(model.state_dict()), weights)) # report
else:
model = Model(opt.cfg, ch=3, nc=nc, anchors=hyp.get('anchors')).to(device) # create
with torch_distributed_zero_first(rank):
check_dataset(data_dict) # check
train_path = data_dict['train']
test_path = data_dict['val']
# Freeze
freeze = [f'model.{x}.' for x in (freeze if len(freeze) > 1 else range(freeze[0]))] # parameter names to freeze (full or partial)
for k, v in model.named_parameters():
v.requires_grad = True # train all layers
if any(x in k for x in freeze):
print('freezing %s' % k)
v.requires_grad = False
# Optimizer
nbs = 64 # nominal batch size
accumulate = max(round(nbs / total_batch_size), 1) # accumulate loss before optimizing
hyp['weight_decay'] *= total_batch_size * accumulate / nbs # scale weight_decay
logger.info(f"Scaled weight_decay = {hyp['weight_decay']}")
pg0, pg1, pg2 = [], [], [] # optimizer parameter groups
for k, v in model.named_modules():
if hasattr(v, 'bias') and isinstance(v.bias, nn.Parameter):
pg2.append(v.bias) # biases
if isinstance(v, nn.BatchNorm2d):
pg0.append(v.weight) # no decay
elif hasattr(v, 'weight') and isinstance(v.weight, nn.Parameter):
pg1.append(v.weight) # apply decay
if hasattr(v, 'im'):
if hasattr(v.im, 'implicit'):
pg0.append(v.im.implicit)
else:
for iv in v.im:
pg0.append(iv.implicit)
if hasattr(v, 'imc'):
if hasattr(v.imc, 'implicit'):
pg0.append(v.imc.implicit)
else:
for iv in v.imc:
pg0.append(iv.implicit)
if hasattr(v, 'imb'):
if hasattr(v.imb, 'implicit'):
pg0.append(v.imb.implicit)
else:
for iv in v.imb:
pg0.append(iv.implicit)
if hasattr(v, 'imo'):
if hasattr(v.imo, 'implicit'):
pg0.append(v.imo.implicit)
else:
for iv in v.imo:
pg0.append(iv.implicit)
if hasattr(v, 'ia'):
if hasattr(v.ia, 'implicit'):
pg0.append(v.ia.implicit)
else:
for iv in v.ia:
pg0.append(iv.implicit)
if hasattr(v, 'attn'):
if hasattr(v.attn, 'logit_scale'):
pg0.append(v.attn.logit_scale)
if hasattr(v.attn, 'q_bias'):
pg0.append(v.attn.q_bias)
if hasattr(v.attn, 'v_bias'):
pg0.append(v.attn.v_bias)
if hasattr(v.attn, 'relative_position_bias_table'):
pg0.append(v.attn.relative_position_bias_table)
if hasattr(v, 'rbr_dense'):
if hasattr(v.rbr_dense, 'weight_rbr_origin'):
pg0.append(v.rbr_dense.weight_rbr_origin)
if hasattr(v.rbr_dense, 'weight_rbr_avg_conv'):
pg0.append(v.rbr_dense.weight_rbr_avg_conv)
if hasattr(v.rbr_dense, 'weight_rbr_pfir_conv'):
pg0.append(v.rbr_dense.weight_rbr_pfir_conv)
if hasattr(v.rbr_dense, 'weight_rbr_1x1_kxk_idconv1'):
pg0.append(v.rbr_dense.weight_rbr_1x1_kxk_idconv1)
if hasattr(v.rbr_dense, 'weight_rbr_1x1_kxk_conv2'):
pg0.append(v.rbr_dense.weight_rbr_1x1_kxk_conv2)
if hasattr(v.rbr_dense, 'weight_rbr_gconv_dw'):
pg0.append(v.rbr_dense.weight_rbr_gconv_dw)
if hasattr(v.rbr_dense, 'weight_rbr_gconv_pw'):
pg0.append(v.rbr_dense.weight_rbr_gconv_pw)
if hasattr(v.rbr_dense, 'vector'):
pg0.append(v.rbr_dense.vector)
if opt.adam:
optimizer = optim.Adam(pg0, lr=hyp['lr0'], betas=(hyp['momentum'], 0.999)) # adjust beta1 to momentum
else:
optimizer = optim.SGD(pg0, lr=hyp['lr0'], momentum=hyp['momentum'], nesterov=True)
optimizer.add_param_group({'params': pg1, 'weight_decay': hyp['weight_decay']}) # add pg1 with weight_decay
optimizer.add_param_group({'params': pg2}) # add pg2 (biases)
logger.info('Optimizer groups: %g .bias, %g conv.weight, %g other' % (len(pg2), len(pg1), len(pg0)))
del pg0, pg1, pg2
# Scheduler https://arxiv.org/pdf/1812.01187.pdf
# https://pytorch.org/docs/stable/_modules/torch/optim/lr_scheduler.html#OneCycleLR
| |
244663
|
"""PyTorch Hub models
Usage:
import torch
model = torch.hub.load('repo', 'model')
"""
from pathlib import Path
import torch
from models.yolo import Model
from utils.general import check_requirements, set_logging
from utils.google_utils import attempt_download
from utils.torch_utils import select_device
dependencies = ['torch', 'yaml']
check_requirements(Path(__file__).parent / 'requirements.txt', exclude=('pycocotools', 'thop'))
set_logging()
def create(name, pretrained, channels, classes, autoshape):
"""Creates a specified model
Arguments:
name (str): name of model, i.e. 'yolov7'
pretrained (bool): load pretrained weights into the model
channels (int): number of input channels
classes (int): number of model classes
Returns:
pytorch model
"""
try:
cfg = list((Path(__file__).parent / 'cfg').rglob(f'{name}.yaml'))[0] # model.yaml path
model = Model(cfg, channels, classes)
if pretrained:
fname = f'{name}.pt' # checkpoint filename
attempt_download(fname) # download if not found locally
ckpt = torch.load(fname, map_location=torch.device('cpu')) # load
msd = model.state_dict() # model state_dict
csd = ckpt['model'].float().state_dict() # checkpoint state_dict as FP32
csd = {k: v for k, v in csd.items() if msd[k].shape == v.shape} # filter
model.load_state_dict(csd, strict=False) # load
if len(ckpt['model'].names) == classes:
model.names = ckpt['model'].names # set class names attribute
if autoshape:
model = model.autoshape() # for file/URI/PIL/cv2/np inputs and NMS
device = select_device('0' if torch.cuda.is_available() else 'cpu') # default to GPU if available
return model.to(device)
except Exception as e:
s = 'Cache maybe be out of date, try force_reload=True.'
raise Exception(s) from e
def custom(path_or_model='path/to/model.pt', autoshape=True):
"""custom mode
Arguments (3 options):
path_or_model (str): 'path/to/model.pt'
path_or_model (dict): torch.load('path/to/model.pt')
path_or_model (nn.Module): torch.load('path/to/model.pt')['model']
Returns:
pytorch model
"""
model = torch.load(path_or_model, map_location=torch.device('cpu')) if isinstance(path_or_model, str) else path_or_model # load checkpoint
if isinstance(model, dict):
model = model['ema' if model.get('ema') else 'model'] # load model
hub_model = Model(model.yaml).to(next(model.parameters()).device) # create
hub_model.load_state_dict(model.float().state_dict()) # load state_dict
hub_model.names = model.names # class names
if autoshape:
hub_model = hub_model.autoshape() # for file/URI/PIL/cv2/np inputs and NMS
device = select_device('0' if torch.cuda.is_available() else 'cpu') # default to GPU if available
return hub_model.to(device)
def yolov7(pretrained=True, channels=3, classes=80, autoshape=True):
return create('yolov7', pretrained, channels, classes, autoshape)
if __name__ == '__main__':
model = custom(path_or_model='yolov7.pt') # custom example
# model = create(name='yolov7', pretrained=True, channels=3, classes=80, autoshape=True) # pretrained example
# Verify inference
import numpy as np
from PIL import Image
imgs = [np.zeros((640, 480, 3))]
results = model(imgs) # batched inference
results.print()
results.save()
| |
244664
|
import argparse
import time
from pathlib import Path
import cv2
import torch
import torch.backends.cudnn as cudnn
from numpy import random
from models.experimental import attempt_load
from utils.datasets import LoadStreams, LoadImages
from utils.general import check_img_size, check_requirements, check_imshow, non_max_suppression, apply_classifier, \
scale_coords, xyxy2xywh, strip_optimizer, set_logging, increment_path
from utils.plots import plot_one_box
from utils.torch_utils import select_device, load_classifier, time_synchronized, TracedModel
def detect(save_img=False):
source, weights, view_img, save_txt, imgsz, trace = opt.source, opt.weights, opt.view_img, opt.save_txt, opt.img_size, not opt.no_trace
save_img = not opt.nosave and not source.endswith('.txt') # save inference images
webcam = source.isnumeric() or source.endswith('.txt') or source.lower().startswith(
('rtsp://', 'rtmp://', 'http://', 'https://'))
# Directories
save_dir = Path(increment_path(Path(opt.project) / opt.name, exist_ok=opt.exist_ok)) # increment run
(save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir
# Initialize
set_logging()
device = select_device(opt.device)
half = device.type != 'cpu' # half precision only supported on CUDA
# Load model
model = attempt_load(weights, map_location=device) # load FP32 model
stride = int(model.stride.max()) # model stride
imgsz = check_img_size(imgsz, s=stride) # check img_size
if trace:
model = TracedModel(model, device, opt.img_size)
if half:
model.half() # to FP16
# Second-stage classifier
classify = False
if classify:
modelc = load_classifier(name='resnet101', n=2) # initialize
modelc.load_state_dict(torch.load('weights/resnet101.pt', map_location=device)['model']).to(device).eval()
# Set Dataloader
vid_path, vid_writer = None, None
if webcam:
view_img = check_imshow()
cudnn.benchmark = True # set True to speed up constant image size inference
dataset = LoadStreams(source, img_size=imgsz, stride=stride)
else:
dataset = LoadImages(source, img_size=imgsz, stride=stride)
# Get names and colors
names = model.module.names if hasattr(model, 'module') else model.names
colors = [[random.randint(0, 255) for _ in range(3)] for _ in names]
# Run inference
if device.type != 'cpu':
model(torch.zeros(1, 3, imgsz, imgsz).to(device).type_as(next(model.parameters()))) # run once
old_img_w = old_img_h = imgsz
old_img_b = 1
t0 = time.time()
for path, img, im0s, vid_cap in dataset:
img = torch.from_numpy(img).to(device)
img = img.half() if half else img.float() # uint8 to fp16/32
img /= 255.0 # 0 - 255 to 0.0 - 1.0
if img.ndimension() == 3:
img = img.unsqueeze(0)
# Warmup
if device.type != 'cpu' and (old_img_b != img.shape[0] or old_img_h != img.shape[2] or old_img_w != img.shape[3]):
old_img_b = img.shape[0]
old_img_h = img.shape[2]
old_img_w = img.shape[3]
for i in range(3):
model(img, augment=opt.augment)[0]
# Inference
t1 = time_synchronized()
with torch.no_grad(): # Calculating gradients would cause a GPU memory leak
pred = model(img, augment=opt.augment)[0]
t2 = time_synchronized()
# Apply NMS
pred = non_max_suppression(pred, opt.conf_thres, opt.iou_thres, classes=opt.classes, agnostic=opt.agnostic_nms)
t3 = time_synchronized()
# Apply Classifier
if classify:
pred = apply_classifier(pred, modelc, img, im0s)
# Process detections
for i, det in enumerate(pred): # detections per image
if webcam: # batch_size >= 1
p, s, im0, frame = path[i], '%g: ' % i, im0s[i].copy(), dataset.count
else:
p, s, im0, frame = path, '', im0s, getattr(dataset, 'frame', 0)
p = Path(p) # to Path
save_path = str(save_dir / p.name) # img.jpg
txt_path = str(save_dir / 'labels' / p.stem) + ('' if dataset.mode == 'image' else f'_{frame}') # img.txt
gn = torch.tensor(im0.shape)[[1, 0, 1, 0]] # normalization gain whwh
if len(det):
# Rescale boxes from img_size to im0 size
det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape).round()
# Print results
for c in det[:, -1].unique():
n = (det[:, -1] == c).sum() # detections per class
s += f"{n} {names[int(c)]}{'s' * (n > 1)}, " # add to string
# Write results
for *xyxy, conf, cls in reversed(det):
if save_txt: # Write to file
xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh
line = (cls, *xywh, conf) if opt.save_conf else (cls, *xywh) # label format
with open(txt_path + '.txt', 'a') as f:
f.write(('%g ' * len(line)).rstrip() % line + '\n')
if save_img or view_img: # Add bbox to image
label = f'{names[int(cls)]} {conf:.2f}'
plot_one_box(xyxy, im0, label=label, color=colors[int(cls)], line_thickness=1)
# Print time (inference + NMS)
print(f'{s}Done. ({(1E3 * (t2 - t1)):.1f}ms) Inference, ({(1E3 * (t3 - t2)):.1f}ms) NMS')
# Stream results
if view_img:
cv2.imshow(str(p), im0)
cv2.waitKey(1) # 1 millisecond
# Save results (image with detections)
if save_img:
if dataset.mode == 'image':
cv2.imwrite(save_path, im0)
print(f" The image with the result is saved in: {save_path}")
else: # 'video' or 'stream'
if vid_path != save_path: # new video
vid_path = save_path
if isinstance(vid_writer, cv2.VideoWriter):
vid_writer.release() # release previous video writer
if vid_cap: # video
fps = vid_cap.get(cv2.CAP_PROP_FPS)
w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
else: # stream
fps, w, h = 30, im0.shape[1], im0.shape[0]
save_path += '.mp4'
vid_writer = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h))
vid_writer.write(im0)
if save_txt or save_img:
s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else ''
#print(f"Results saved to {save_dir}{s}")
print(f'Done. ({time.time() - t0:.3f}s)')
| |
244665
|
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--weights', nargs='+', type=str, default='yolov7.pt', help='model.pt path(s)')
parser.add_argument('--source', type=str, default='inference/images', help='source') # file/folder, 0 for webcam
parser.add_argument('--img-size', type=int, default=640, help='inference size (pixels)')
parser.add_argument('--conf-thres', type=float, default=0.25, help='object confidence threshold')
parser.add_argument('--iou-thres', type=float, default=0.45, help='IOU threshold for NMS')
parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
parser.add_argument('--view-img', action='store_true', help='display results')
parser.add_argument('--save-txt', action='store_true', help='save results to *.txt')
parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels')
parser.add_argument('--nosave', action='store_true', help='do not save images/videos')
parser.add_argument('--classes', nargs='+', type=int, help='filter by class: --class 0, or --class 0 2 3')
parser.add_argument('--agnostic-nms', action='store_true', help='class-agnostic NMS')
parser.add_argument('--augment', action='store_true', help='augmented inference')
parser.add_argument('--update', action='store_true', help='update all models')
parser.add_argument('--project', default='runs/detect', help='save results to project/name')
parser.add_argument('--name', default='exp', help='save results to project/name')
parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
parser.add_argument('--no-trace', action='store_true', help='don`t trace model')
opt = parser.parse_args()
print(opt)
#check_requirements(exclude=('pycocotools', 'thop'))
with torch.no_grad():
if opt.update: # update all models (to fix SourceChangeWarning)
for opt.weights in ['yolov7.pt']:
detect()
strip_optimizer(opt.weights)
else:
detect()
| |
244680
|
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"id": "0ab662ce",
"metadata": {},
"outputs": [],
"source": [
"import matplotlib.pyplot as plt\n",
"import torch\n",
"import cv2\n",
"from torchvision import transforms\n",
"import numpy as np\n",
"from utils.datasets import letterbox"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "cfd4b844",
"metadata": {},
"outputs": [],
"source": [
"device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n",
"weigths = torch.load('./weights/yolov7-e6e.pt')\n",
"model = weigths['model']\n",
"model = model.half().to(device)\n",
"_ = model.eval()"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "1ee054f1",
"metadata": {},
"outputs": [],
"source": [
"image = cv2.imread('./images/person.jpg') # 504x378 image\n",
"image = letterbox(image, 1280, stride=64, auto=True)[0]\n",
"image_ = image.copy()\n",
"image = transforms.ToTensor()(image)\n",
"image = torch.tensor(np.array([image.numpy()]))\n",
"image = image.to(device)\n",
"image = image.half()\n",
"\n",
"output = model(image)"
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "7ec9e6ab",
"metadata": {},
"outputs": [],
"source": [
"obj1 = output[1][0][0, 0, :, :, 4].sigmoid().cpu().numpy()\n",
"obj2 = output[1][0][0, 1, :, :, 4].sigmoid().cpu().numpy()\n",
"obj3 = output[1][0][0, 2, :, :, 4].sigmoid().cpu().numpy()\n",
"obj4 = output[1][1][0, 0, :, :, 4].sigmoid().cpu().numpy()\n",
"obj5 = output[1][1][0, 1, :, :, 4].sigmoid().cpu().numpy()\n",
"obj6 = output[1][1][0, 2, :, :, 4].sigmoid().cpu().numpy()\n",
"obj7 = output[1][2][0, 0, :, :, 4].sigmoid().cpu().numpy()\n",
"obj8 = output[1][2][0, 1, :, :, 4].sigmoid().cpu().numpy()\n",
"obj9 = output[1][2][0, 2, :, :, 4].sigmoid().cpu().numpy()\n",
"obj10 = output[1][3][0, 0, :, :, 4].sigmoid().cpu().numpy()\n",
"obj11 = output[1][3][0, 1, :, :, 4].sigmoid().cpu().numpy()\n",
"obj12 = output[1][3][0, 2, :, :, 4].sigmoid().cpu().numpy()"
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "38878c81",
"metadata": {},
"outputs": [
{
"data": {
"",
"text/plain": [
"<Figure size 576x576 with 1 Axes>"
]
},
"metadata": {
"needs_background": "light"
},
"output_type": "display_data"
},
{
"data": {
"",
"text/plain": [
"<Figure size 1152x864 with 12 Axes>"
]
},
"metadata": {
"needs_background": "light"
},
"output_type": "display_data"
}
],
"source": [
"%matplotlib inline\n",
"plt.figure(figsize=(8,8))\n",
"plt.axis('off')\n",
"plt.imshow(image_[:,:,[2,1,0]])\n",
"plt.show()\n",
"fig, ax = plt.subplots(4,3,figsize=(16,12))\n",
"#[ax_.axis('off') for ax_ in ax.ravel()]\n",
"[ax_.set_xticklabels([]) for ax_ in ax.ravel()]\n",
"[ax_.set_yticklabels([]) for ax_ in ax.ravel()]\n",
"ax.ravel()[0].imshow(obj1)\n",
"ax.ravel()[1].imshow(obj2)\n",
"ax.ravel()[2].imshow(obj3)\n",
"ax.ravel()[3].imshow(obj4)\n",
"ax.ravel()[4].imshow(obj5)\n",
"ax.ravel()[5].imshow(obj6)\n",
"ax.ravel()[6].imshow(obj7)\n",
"ax.ravel()[7].imshow(obj8)\n",
"ax.ravel()[8].imshow(obj9)\n",
"ax.ravel()[9].imshow(obj10)\n",
"ax.ravel()[10].imshow(obj11)\n",
"ax.ravel()[11].imshow(obj12)\n",
"plt.subplots_adjust(wspace=-0.52, hspace=0)\n",
"plt.show()"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "8536ecc8",
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.8.10"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
| |
244725
|
"\n",
" if shape[::-1] != new_unpad: # resize\n",
" im = cv2.resize(im, new_unpad, interpolation=cv2.INTER_LINEAR)\n",
" top, bottom = int(round(dh - 0.1)), int(round(dh + 0.1))\n",
" left, right = int(round(dw - 0.1)), int(round(dw + 0.1))\n",
" im = cv2.copyMakeBorder(im, top, bottom, left, right, cv2.BORDER_CONSTANT, value=color) # add border\n",
" return im, r, (dw, dh)\n",
"\n",
"def postprocess(boxes,r,dwdh):\n",
" dwdh = torch.tensor(dwdh*2).to(boxes.device)\n",
" boxes -= dwdh\n",
" boxes /= r\n",
" return boxes\n",
"\n",
"names = ['person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', 'truck', 'boat', 'traffic light', \n",
" 'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow', \n",
" 'elephant', 'bear', 'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie', 'suitcase', 'frisbee', \n",
" 'skis', 'snowboard', 'sports ball', 'kite', 'baseball bat', 'baseball glove', 'skateboard', 'surfboard', \n",
" 'tennis racket', 'bottle', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple', \n",
" 'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair', 'couch', \n",
" 'potted plant', 'bed', 'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone', \n",
" 'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors', 'teddy bear', \n",
" 'hair drier', 'toothbrush']\n",
"colors = {name:[random.randint(0, 255) for _ in range(3)] for i,name in enumerate(names)}"
],
"metadata": {
"id": "kRqqsjDcmyNj"
},
"execution_count": 14,
"outputs": []
},
{
"cell_type": "code",
"source": [
"img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n",
"image = img.copy()\n",
"image, ratio, dwdh = letterbox(image, auto=False)\n",
"image = image.transpose((2, 0, 1))\n",
"image = np.expand_dims(image, 0)\n",
"image = np.ascontiguousarray(image)\n",
"\n",
"im = image.astype(np.float32)\n",
"im.shape"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "tzGt5tP9nJs_",
"outputId": "b5e4658f-8b25-4926-bf87-dced1f966fff"
},
"execution_count": 15,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"(1, 3, 640, 640)"
]
},
"metadata": {},
"execution_count": 15
}
]
},
{
"cell_type": "code",
"source": [
"im = torch.from_numpy(im).to(device)\n",
"im/=255\n",
"im.shape\n",
"\n",
"# warmup for 10 times\n",
"for _ in range(10):\n",
" tmp = torch.randn(1,3,640,640).to(device)\n",
" binding_addrs['images'] = int(tmp.data_ptr())\n",
" context.execute_v2(list(binding_addrs.values()))\n",
"\n",
"start = time.perf_counter()\n",
"binding_addrs['images'] = int(im.data_ptr())\n",
"context.execute_v2(list(binding_addrs.values()))\n",
"print(f'Cost {time.perf_counter()-start} s')\n",
"\n",
"nums = bindings['num_dets'].data\n",
"boxes = bindings['det_boxes'].data\n",
"scores = bindings['det_scores'].data\n",
"classes = bindings['det_classes'].data\n",
"nums.shape,boxes.shape,scores.shape,classes.shape\n",
"\n",
"boxes = boxes[0,:nums[0][0]]\n",
"scores = scores[0,:nums[0][0]]\n",
"classes = classes[0,:nums[0][0]]\n",
"\n",
"for box,score,cl in zip(boxes,scores,classes):\n",
" box = postprocess(box,ratio,dwdh).round().int()\n",
" name = names[cl]\n",
" color = colors[name]\n",
" name += ' ' + str(round(float(score),3))\n",
" cv2.rectangle(img,box[:2].tolist(),box[2:].tolist(),color,2)\n",
" cv2.putText(img,name,(int(box[0]), int(box[1]) - 2),cv2.FONT_HERSHEY_SIMPLEX,0.75,color,thickness=2)\n",
"\n",
"Image.fromarray(img)"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/",
"height": 546
},
"id": "xv8UsDWvn9i4",
"outputId": "b960358f-8993-4b84-c8c8-d169676a014a"
},
"execution_count": 16,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Cost 0.00477353700000549 s\n"
]
},
{
"output_type": "execute_result",
"data": {
"text/plain": [
"<PIL.Image.Image image mode=RGB size=773x512 at 0x7FC040337510>"
],
""
},
"metadata": {},
"execution_count": 16
}
]
}
]
}
| |
244727
|
"!git clone https://github.com/WongKinYiu/yolov7\n",
"%cd yolov7\n",
"!ls"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "yfZALjuo-_Md",
"outputId": "88dbe003-898b-48ea-f374-42228d25a3cb"
},
"execution_count": 4,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Cloning into 'yolov7'...\n",
"remote: Enumerating objects: 724, done.\u001b[K\n",
"remote: Counting objects: 100% (724/724), done.\u001b[K\n",
"remote: Compressing objects: 100% (379/379), done.\u001b[K\n",
"remote: Total 724 (delta 366), reused 644 (delta 330), pack-reused 0\u001b[K\n",
"Receiving objects: 100% (724/724), 66.91 MiB | 17.13 MiB/s, done.\n",
"Resolving deltas: 100% (366/366), done.\n",
"/content/yolov7\n",
"cfg\tdetect.py hubconf.py models\t requirements.txt tools\t utils\n",
"data\texport.py inference paper\t scripts\t train_aux.py\n",
"deploy\tfigure\t LICENSE.md README.md test.py\t train.py\n"
]
}
]
},
{
"cell_type": "code",
"source": [
"!# Download trained weights\n",
"!wget https://github.com/WongKinYiu/yolov7/releases/download/v0.1/yolov7-tiny.pt"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "eWlHa1NJ-_Jw",
"outputId": "4e6c08c5-500f-4c3c-d273-bfc8941c37b7"
},
"execution_count": 5,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"--2022-08-12 07:06:10-- https://github.com/WongKinYiu/yolov7/releases/download/v0.1/yolov7-tiny.pt\n",
"Resolving github.com (github.com)... 20.205.243.166\n",
"Connecting to github.com (github.com)|20.205.243.166|:443... connected.\n",
"HTTP request sent, awaiting response... 302 Found\n",
"Location: https://objects.githubusercontent.com/github-production-release-asset-2e65be/511187726/ba7d01ee-125a-4134-8864-fa1abcbf94d5?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAIWNJYAX4CSVEH53A%2F20220812%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20220812T070610Z&X-Amz-Expires=300&X-Amz-Signature=fbe7b2ff90bc6e2262f66d1b321cbddd6f90255ac23ec8bdf17ebe90b888e612&X-Amz-SignedHeaders=host&actor_id=0&key_id=0&repo_id=511187726&response-content-disposition=attachment%3B%20filename%3Dyolov7-tiny.pt&response-content-type=application%2Foctet-stream [following]\n",
"--2022-08-12 07:06:10-- https://objects.githubusercontent.com/github-production-release-asset-2e65be/511187726/ba7d01ee-125a-4134-8864-fa1abcbf94d5?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAIWNJYAX4CSVEH53A%2F20220812%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20220812T070610Z&X-Amz-Expires=300&X-Amz-Signature=fbe7b2ff90bc6e2262f66d1b321cbddd6f90255ac23ec8bdf17ebe90b888e612&X-Amz-SignedHeaders=host&actor_id=0&key_id=0&repo_id=511187726&response-content-disposition=attachment%3B%20filename%3Dyolov7-tiny.pt&response-content-type=application%2Foctet-stream\n",
"Resolving objects.githubusercontent.com (objects.githubusercontent.com)... 185.199.109.133, 185.199.108.133, 185.199.111.133, ...\n",
"Connecting to objects.githubusercontent.com (objects.githubusercontent.com)|185.199.109.133|:443... connected.\n",
"HTTP request sent, awaiting response... 200 OK\n",
"Length: 12639769 (12M) [application/octet-stream]\n",
"Saving to: ‘yolov7-tiny.pt’\n",
"\n",
"yolov7-tiny.pt 100%[===================>] 12.05M 5.85MB/s in 2.1s \n",
"\n",
"2022-08-12 07:06:12 (5.85 MB/s) - ‘yolov7-tiny.pt’ saved [12639769/12639769]\n",
"\n"
]
}
]
},
{
"cell_type": "code",
"source": [
"!python detect.py --weights ./yolov7-tiny.pt --conf 0.25 --img-size 640 --source inference/images/horses.jpg"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "UX7u8eqj-_Hi",
"outputId": "a088cfd4-183a-47a1-d939-3d5afd15ce4c"
},
"execution_count": 6,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Namespace(agnostic_nms=False, augment=False, classes=None, conf_thres=0.25, device='', exist_ok=False, img_size=640, iou_thres=0.45, name='exp', no_trace=False, nosave=False, project='runs/detect', save_conf=False, save_txt=False, source='inference/images/horses.jpg', update=False, view_img=False, weights=['./yolov7-tiny.pt'])\n",
"YOLOR 🚀 v0.1-101-g1b63720 torch 1.12.0+cu113 CUDA:0 (Tesla T4, 15109.75MB)\n",
"\n",
"Fusing layers... \n",
"Model Summary: 200 layers, 6219709 parameters, 229245 gradients\n",
" Convert model to Traced-model... \n",
" traced_script_module saved! \n",
" model is traced! \n",
"\n",
"/usr/local/lib/python3.7/dist-packages/torch/functional.py:478: UserWarning: torch.meshgrid: in an upcoming release, it will be required to pass the indexing argument. (Triggered internally at ../aten/src/ATen/native/TensorShape.cpp:2894.)\n",
" return _VF.meshgrid(tensors, **kwargs) # type: ignore[attr-defined]\n",
"5 horses, Done. (8.0ms) Inference, (44.0ms) NMS\n",
" The image with the result is saved in: runs/detect/exp/horses.jpg\n",
"Done. (0.235s)\n"
]
}
]
},
{
"cell_type": "code",
"source": [
"from PIL import Image\n",
"Image.open('/content/yolov7/runs/detect/exp/horses.jpg')"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/",
"height": 529
},
"id": "wZD-nZXX-_Ez",
"outputId": "b201edb3-fb10-4d7f-f69d-78b4089a0e08"
},
"execution_count": 7,
"outputs": [
{
| |
244744
|
"text": [
" im = (640, 640, 3)\n",
" im = <PIL.Image.Image image mode=RGB size=640x640 at 0x7F8E0F0CD9D0>\n"
]
}
]
},
{
"cell_type": "code",
"source": [
"def xywh2xyxy(x):\n",
" # Convert nx4 boxes from [x, y, w, h] to [x1, y1, x2, y2] where xy1=top-left, xy2=bottom-right\n",
" y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)\n",
" y[:, 0] = x[:, 0] - x[:, 2] / 2 # top left x\n",
" y[:, 1] = x[:, 1] - x[:, 3] / 2 # top left y\n",
" y[:, 2] = x[:, 0] + x[:, 2] / 2 # bottom right x\n",
" y[:, 3] = x[:, 1] + x[:, 3] / 2 # bottom right y\n",
" return y"
],
"metadata": {
"id": "fO3gTcCQrH27"
},
"execution_count": 12,
"outputs": []
},
{
"cell_type": "code",
"source": [
"# Inference only for MacOS and iOS!!!\n",
"\n",
"#y = model.predict({'image': im}) # coordinates are xywh normalized\n",
"#if 'confidence' in y:\n",
"# box = xywh2xyxy(y['coordinates'] * [[w, h, w, h]]) # xyxy pixels\n",
"# conf, cls = y['confidence'].max(1), y['confidence'].argmax(1).astype(np.float)\n",
"# y = np.concatenate((box, conf.reshape(-1, 1), cls.reshape(-1, 1)), 1)\n",
"#else:\n",
"# k = 'var_' + str(sorted(int(k.replace('var_', '')) for k in y)[-1]) # output key\n",
"# y = y[k] # output\n",
"#\n",
"#print(y)"
],
"metadata": {
"id": "dS9iAcSH32A3"
},
"execution_count": null,
"outputs": []
}
]
}
| |
244750
|
" [ 2.0000000e+00, 6.5209000e+01, 2.4051682e+02, 4.7865540e+02,\n",
" 4.9418790e+02, 0.0000000e+00, 5.7698834e-01],\n",
" [ 3.0000000e+00, 5.2892609e+00, 6.2162445e+01, 3.7209552e+02,\n",
" 5.8483594e+02, 0.0000000e+00, 8.7545133e-01],\n",
" [ 3.0000000e+00, 2.6051691e+02, 1.4254585e+02, 6.3040662e+02,\n",
" 5.8132233e+02, 0.0000000e+00, 8.1180179e-01],\n",
" [ 4.0000000e+00, 4.2224957e+02, 1.0267369e+02, 6.3170001e+02,\n",
" 5.5488086e+02, 0.0000000e+00, 9.4197059e-01],\n",
" [ 4.0000000e+00, 4.9545387e+01, 2.7456857e+02, 1.8946579e+02,\n",
" 4.1091318e+02, 3.2000000e+01, 9.3334389e-01],\n",
" [ 4.0000000e+00, 2.6599213e+01, 1.0745810e+02, 4.5867126e+02,\n",
" 5.5153650e+02, 0.0000000e+00, 8.2260609e-01],\n",
" [ 5.0000000e+00, 1.9983047e+02, 3.6107239e+01, 5.2495667e+02,\n",
" 4.8967474e+02, 1.7000000e+01, 8.4681529e-01],\n",
" [ 5.0000000e+00, 1.1123685e+02, 3.1816605e+02, 3.7944864e+02,\n",
" 5.6111890e+02, 1.6000000e+01, 6.9891703e-01]], dtype=float32)]"
]
},
"execution_count": 16,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# batch 6 infer\n",
"im = np.ascontiguousarray(np_batch[0:6,...]/255)\n",
"out = session.run(outname,{'images':im})\n",
"out"
]
},
{
"cell_type": "code",
"execution_count": 17,
"id": "2a72d2fd-14dd-42cf-b807-3e8a82b971d7",
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"# batch 32 infer\n",
"im = np.ascontiguousarray(np_batch/255)\n",
"out = session.run(outname,{'images':im})[0]"
]
},
{
"cell_type": "code",
"execution_count": 18,
"id": "f3ca9301-ba52-4a8c-9ae0-55b28be8a904",
"metadata": {},
"outputs": [],
"source": [
"for i,(batch_id,x0,y0,x1,y1,cls_id,score) in enumerate(out):\n",
" if batch_id >= 6:\n",
" break\n",
" image = origin_RGB[int(batch_id)]\n",
" ratio,dwdh = resize_data[int(batch_id)][1:]\n",
" box = np.array([x0,y0,x1,y1])\n",
" box -= np.array(dwdh*2)\n",
" box /= ratio\n",
" box = box.round().astype(np.int32).tolist()\n",
" cls_id = int(cls_id)\n",
" score = round(float(score),3)\n",
" name = names[cls_id]\n",
" color = colors[name]\n",
" name += ' '+str(score)\n",
" cv2.rectangle(image,box[:2],box[2:],color,2)\n",
" cv2.putText(image,name,(box[0], box[1] - 2),cv2.FONT_HERSHEY_SIMPLEX,0.75,[225, 255, 255],thickness=2)"
]
},
{
"cell_type": "code",
"execution_count": 19,
"id": "ff5ce6a4-4fd9-4804-9afa-e8e8a3e20b41",
"metadata": {},
"outputs": [
{
"data": {
"",
"text/plain": [
"<PIL.Image.Image image mode=RGB size=773x512>"
]
},
"execution_count": 19,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"Image.fromarray(origin_RGB[0])"
]
},
{
"cell_type": "code",
"execution_count": 20,
"id": "d13ed2df-ceb8-46c8-8bfc-aa7ff3750f03",
"metadata": {},
"outputs": [
{
"data": {
"",
"text/plain": [
"<PIL.Image.Image image mode=RGB size=810x1080>"
]
},
"execution_count": 20,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"Image.fromarray(origin_RGB[1])"
]
},
{
"cell_type": "code",
"execution_count": 21,
"id": "b4449198-3c2b-41d6-9a23-de7accf73d82",
"metadata": {},
"outputs": [
{
"data": {
"",
"text/plain": [
"<PIL.Image.Image image mode=RGB size=1280x720>"
]
},
"execution_count": 21,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"Image.fromarray(origin_RGB[2])"
]
},
{
"cell_type": "code",
"execution_count": 22,
"id": "4faf6e6e-afb5-4c97-82c3-aeffdc9aba9e",
"metadata": {},
"outputs": [
{
"data": {
"",
"text/plain": [
"<PIL.Image.Image image mode=RGB size=640x536>"
]
},
"execution_count": 22,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"Image.fromarray(origin_RGB[3])"
]
},
{
"cell_type": "code",
"execution_count": 23,
"id": "27485468-2e69-4aaf-8089-ba0134a1b26f",
"metadata": {},
"outputs": [
{
"data": {
"",
"text/plain": [
"<PIL.Image.Image image mode=RGB size=640x480>"
]
},
"execution_count": 23,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"Image.fromarray(origin_RGB[4])"
]
},
{
"cell_type": "code",
"execution_count": 24,
"id": "ef743cc3-7ae9-495c-ab24-2ac25967ec5c",
"metadata": {},
"outputs": [
{
"data": {
"",
"text/plain": [
"<PIL.Image.Image image mode=RGB size=431x640>"
]
| |
244758
|
"\u001b[?25hRequirement already satisfied: pyparsing!=3.0.5,>=2.0.2 in /usr/local/lib/python3.7/dist-packages (from packaging->onnxruntime) (3.0.9)\n",
"Requirement already satisfied: six>=1.9 in /usr/local/lib/python3.7/dist-packages (from protobuf->onnxruntime) (1.15.0)\n",
"Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.7/dist-packages (from sympy->onnxruntime) (1.2.1)\n",
"Installing collected packages: humanfriendly, coloredlogs, onnxruntime\n",
"Successfully installed coloredlogs-15.0.1 humanfriendly-10.0 onnxruntime-1.12.0\n",
"\u001b[33mWARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv\u001b[0m\u001b[33m\n",
"\u001b[0m/bin/bash: 4.21.3: No such file or directory\n",
"Looking in indexes: https://pypi.org/simple, https://us-python.pkg.dev/colab-wheels/public/simple/\n",
"Collecting onnxruntime-gpu\n",
" Downloading onnxruntime_gpu-1.12.0-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (111.0 MB)\n",
"\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m111.0/111.0 MB\u001b[0m \u001b[31m9.1 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
"\u001b[?25hRequirement already satisfied: packaging in /usr/local/lib/python3.7/dist-packages (from onnxruntime-gpu) (21.3)\n",
"Requirement already satisfied: protobuf in /usr/local/lib/python3.7/dist-packages (from onnxruntime-gpu) (3.17.3)\n",
"Requirement already satisfied: coloredlogs in /usr/local/lib/python3.7/dist-packages (from onnxruntime-gpu) (15.0.1)\n",
"Requirement already satisfied: flatbuffers in /usr/local/lib/python3.7/dist-packages (from onnxruntime-gpu) (2.0)\n",
"Requirement already satisfied: sympy in /usr/local/lib/python3.7/dist-packages (from onnxruntime-gpu) (1.7.1)\n",
"Requirement already satisfied: numpy>=1.21.0 in /usr/local/lib/python3.7/dist-packages (from onnxruntime-gpu) (1.21.6)\n",
"Requirement already satisfied: humanfriendly>=9.1 in /usr/local/lib/python3.7/dist-packages (from coloredlogs->onnxruntime-gpu) (10.0)\n",
"Requirement already satisfied: pyparsing!=3.0.5,>=2.0.2 in /usr/local/lib/python3.7/dist-packages (from packaging->onnxruntime-gpu) (3.0.9)\n",
"Requirement already satisfied: six>=1.9 in /usr/local/lib/python3.7/dist-packages (from protobuf->onnxruntime-gpu) (1.15.0)\n",
"Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.7/dist-packages (from sympy->onnxruntime-gpu) (1.2.1)\n",
"Installing collected packages: onnxruntime-gpu\n",
"Successfully installed onnxruntime-gpu-1.12.0\n",
"\u001b[33mWARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv\u001b[0m\u001b[33m\n",
"\u001b[0m\u001b[33mWARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv\u001b[0m\u001b[33m\n",
"\u001b[0m\u001b[33m WARNING: The script cmark is installed in '/root/.local/bin' which is not on PATH.\n",
" Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.\u001b[0m\u001b[33m\n",
"\u001b[0m\u001b[33m WARNING: The script onnxsim is installed in '/root/.local/bin' which is not on PATH.\n",
" Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.\u001b[0m\u001b[33m\n",
"\u001b[0m\u001b[33mWARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv\u001b[0m\u001b[33m\n",
"\u001b[0m"
]
}
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "hQ5fNost-gZI",
"outputId": "396d7243-b6af-4acf-e555-38a984cd69bb"
},
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Python version: 3.7.13 (default, Apr 24 2022, 01:04:09) \n",
"[GCC 7.5.0], sys.version_info(major=3, minor=7, micro=13, releaselevel='final', serial=0) \n",
"Pytorch version: 1.12.0+cu113 \n"
]
}
],
"source": [
"import sys\n",
"import torch\n",
"print(f\"Python version: {sys.version}, {sys.version_info} \")\n",
"print(f\"Pytorch version: {torch.__version__} \")"
]
},
{
"cell_type": "code",
"source": [
"!nvidia-smi"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "feCaRUEI-_Os",
"outputId": "7a488cf8-f7d7-4366-ce12-442329a9266b"
},
"execution_count": 3,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Mon Jul 25 00:25:03 2022 \n",
"+-----------------------------------------------------------------------------+\n",
"| NVIDIA-SMI 460.32.03 Driver Version: 460.32.03 CUDA Version: 11.2 |\n",
"|-------------------------------+----------------------+----------------------+\n",
"| GPU Name Persistence-M| Bus-Id Disp.A | Volatile Uncorr. ECC |\n",
"| Fan Temp Perf Pwr:Usage/Cap| Memory-Usage | GPU-Util Compute M. |\n",
"| | | MIG M. |\n",
"|===============================+======================+======================|\n",
"| 0 Tesla T4 Off | 00000000:00:04.0 Off | 0 |\n",
"| N/A 38C P8 9W / 70W | 3MiB / 15109MiB | 0% Default |\n",
"| | | N/A |\n",
"+-------------------------------+----------------------+----------------------+\n",
" \n",
"+-----------------------------------------------------------------------------+\n",
"| Processes: |\n",
"| GPU GI CI PID Type Process name GPU Memory |\n",
"| ID ID Usage |\n",
"|=============================================================================|\n",
"| No running processes found |\n",
"+-----------------------------------------------------------------------------+\n"
]
}
]
},
| |
244759
|
{
"cell_type": "code",
"source": [
"!# Download YOLOv7 code\n",
"!git clone https://github.com/WongKinYiu/yolov7\n",
"%cd yolov7\n",
"!ls"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "yfZALjuo-_Md",
"outputId": "ccda5b64-a800-4c4a-bcb9-c7e899280751"
},
"execution_count": 4,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Cloning into 'yolov7'...\n",
"remote: Enumerating objects: 409, done.\u001b[K\n",
"remote: Counting objects: 100% (149/149), done.\u001b[K\n",
"remote: Compressing objects: 100% (67/67), done.\u001b[K\n",
"remote: Total 409 (delta 118), reused 88 (delta 82), pack-reused 260\u001b[K\n",
"Receiving objects: 100% (409/409), 17.46 MiB | 12.55 MiB/s, done.\n",
"Resolving deltas: 100% (190/190), done.\n",
"/content/yolov7\n",
"cfg\t\t\t export.py models\t\t tools\n",
"data\t\t\t figure README.md\t train_aux.py\n",
"detect.py\t\t hubconf.py requirements.txt train.py\n",
"end2end_onnxruntime.ipynb inference scripts\t\t utils\n",
"end2end_tensorrt.ipynb\t LICENSE.md test.py\n"
]
}
]
},
{
"cell_type": "code",
"source": [
"!# Download trained weights\n",
"!wget https://github.com/WongKinYiu/yolov7/releases/download/v0.1/yolov7-tiny.pt"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "eWlHa1NJ-_Jw",
"outputId": "d32d8c3e-1d32-4ec9-bc41-d3e0f9d60497"
},
"execution_count": 5,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"--2022-07-25 00:25:06-- https://github.com/WongKinYiu/yolov7/releases/download/v0.1/yolov7-tiny.pt\n",
"Resolving github.com (github.com)... 20.205.243.166\n",
"Connecting to github.com (github.com)|20.205.243.166|:443... connected.\n",
"HTTP request sent, awaiting response... 302 Found\n",
"Location: https://objects.githubusercontent.com/github-production-release-asset-2e65be/511187726/ba7d01ee-125a-4134-8864-fa1abcbf94d5?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAIWNJYAX4CSVEH53A%2F20220725%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20220725T002506Z&X-Amz-Expires=300&X-Amz-Signature=5f81912326303a5f48f2365a8976dce81a5f5c0aab99c4fff97c50d4626a28e3&X-Amz-SignedHeaders=host&actor_id=0&key_id=0&repo_id=511187726&response-content-disposition=attachment%3B%20filename%3Dyolov7-tiny.pt&response-content-type=application%2Foctet-stream [following]\n",
"--2022-07-25 00:25:06-- https://objects.githubusercontent.com/github-production-release-asset-2e65be/511187726/ba7d01ee-125a-4134-8864-fa1abcbf94d5?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAIWNJYAX4CSVEH53A%2F20220725%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20220725T002506Z&X-Amz-Expires=300&X-Amz-Signature=5f81912326303a5f48f2365a8976dce81a5f5c0aab99c4fff97c50d4626a28e3&X-Amz-SignedHeaders=host&actor_id=0&key_id=0&repo_id=511187726&response-content-disposition=attachment%3B%20filename%3Dyolov7-tiny.pt&response-content-type=application%2Foctet-stream\n",
"Resolving objects.githubusercontent.com (objects.githubusercontent.com)... 185.199.108.133, 185.199.109.133, 185.199.110.133, ...\n",
"Connecting to objects.githubusercontent.com (objects.githubusercontent.com)|185.199.108.133|:443... connected.\n",
"HTTP request sent, awaiting response... 200 OK\n",
"Length: 12639769 (12M) [application/octet-stream]\n",
"Saving to: ‘yolov7-tiny.pt’\n",
"\n",
"yolov7-tiny.pt 100%[===================>] 12.05M 10.4MB/s in 1.2s \n",
"\n",
"2022-07-25 00:25:08 (10.4 MB/s) - ‘yolov7-tiny.pt’ saved [12639769/12639769]\n",
"\n"
]
}
]
},
{
"cell_type": "code",
"source": [
"!python detect.py --weights ./yolov7-tiny.pt --conf 0.25 --img-size 640 --source inference/images/horses.jpg"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "UX7u8eqj-_Hi",
"outputId": "8fc1e981-e105-4c71-e964-bcb3a927ad8d"
},
"execution_count": 6,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Namespace(agnostic_nms=False, augment=False, classes=None, conf_thres=0.25, device='', exist_ok=False, img_size=640, iou_thres=0.45, name='exp', no_trace=False, nosave=False, project='runs/detect', save_conf=False, save_txt=False, source='inference/images/horses.jpg', update=False, view_img=False, weights=['./yolov7-tiny.pt'])\n",
"YOLOR 🚀 v0.1-58-g13458cd torch 1.12.0+cu113 CUDA:0 (Tesla T4, 15109.75MB)\n",
"\n",
"Fusing layers... \n",
"Model Summary: 200 layers, 6219709 parameters, 229245 gradients\n",
" Convert model to Traced-model... \n",
" traced_script_module saved! \n",
" model is traced! \n",
"\n",
"/usr/local/lib/python3.7/dist-packages/torch/functional.py:478: UserWarning: torch.meshgrid: in an upcoming release, it will be required to pass the indexing argument. (Triggered internally at ../aten/src/ATen/native/TensorShape.cpp:2894.)\n",
" return _VF.meshgrid(tensors, **kwargs) # type: ignore[attr-defined]\n",
" The image with the result is saved in: runs/detect/exp/horses.jpg\n",
"Done. (0.216s)\n"
]
}
]
},
{
"cell_type": "code",
"source": [
"from PIL import Image\n",
"Image.open('/content/yolov7/runs/detect/exp/horses.jpg')"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/",
"height": 529
},
"id": "wZD-nZXX-_Ez",
| |
244766
|
class BoundingBox:
def __init__(self, classID, confidence, x1, x2, y1, y2, image_width, image_height):
self.classID = classID
self.confidence = confidence
self.x1 = x1
self.x2 = x2
self.y1 = y1
self.y2 = y2
self.u1 = x1 / image_width
self.u2 = x2 / image_width
self.v1 = y1 / image_height
self.v2 = y2 / image_height
def box(self):
return (self.x1, self.y1, self.x2, self.y2)
def width(self):
return self.x2 - self.x1
def height(self):
return self.y2 - self.y1
def center_absolute(self):
return (0.5 * (self.x1 + self.x2), 0.5 * (self.y1 + self.y2))
def center_normalized(self):
return (0.5 * (self.u1 + self.u2), 0.5 * (self.v1 + self.v2))
def size_absolute(self):
return (self.x2 - self.x1, self.y2 - self.y1)
def size_normalized(self):
return (self.u2 - self.u1, self.v2 - self.v1)
| |
244767
|
# YOLOv7 on Triton Inference Server
Instructions to deploy YOLOv7 as TensorRT engine to [Triton Inference Server](https://github.com/NVIDIA/triton-inference-server).
Triton Inference Server takes care of model deployment with many out-of-the-box benefits, like a GRPC and HTTP interface, automatic scheduling on multiple GPUs, shared memory (even on GPU), dynamic server-side batching, health metrics and memory resource management.
There are no additional dependencies needed to run this deployment, except a working docker daemon with GPU support.
## Export TensorRT
See https://github.com/WongKinYiu/yolov7#export for more info.
```bash
#install onnx-simplifier not listed in general yolov7 requirements.txt
pip3 install onnx-simplifier
# Pytorch Yolov7 -> ONNX with grid, EfficientNMS plugin and dynamic batch size
python export.py --weights ./yolov7.pt --grid --end2end --dynamic-batch --simplify --topk-all 100 --iou-thres 0.65 --conf-thres 0.35 --img-size 640 640
# ONNX -> TensorRT with trtexec and docker
docker run -it --rm --gpus=all nvcr.io/nvidia/tensorrt:22.06-py3
# Copy onnx -> container: docker cp yolov7.onnx <container-id>:/workspace/
# Export with FP16 precision, min batch 1, opt batch 8 and max batch 8
./tensorrt/bin/trtexec --onnx=yolov7.onnx --minShapes=images:1x3x640x640 --optShapes=images:8x3x640x640 --maxShapes=images:8x3x640x640 --fp16 --workspace=4096 --saveEngine=yolov7-fp16-1x8x8.engine --timingCacheFile=timing.cache
# Test engine
./tensorrt/bin/trtexec --loadEngine=yolov7-fp16-1x8x8.engine
# Copy engine -> host: docker cp <container-id>:/workspace/yolov7-fp16-1x8x8.engine .
```
Example output of test with RTX 3090.
```
[I] === Performance summary ===
[I] Throughput: 73.4985 qps
[I] Latency: min = 14.8578 ms, max = 15.8344 ms, mean = 15.07 ms, median = 15.0422 ms, percentile(99%) = 15.7443 ms
[I] End-to-End Host Latency: min = 25.8715 ms, max = 28.4102 ms, mean = 26.672 ms, median = 26.6082 ms, percentile(99%) = 27.8314 ms
[I] Enqueue Time: min = 0.793701 ms, max = 1.47144 ms, mean = 1.2008 ms, median = 1.28644 ms, percentile(99%) = 1.38965 ms
[I] H2D Latency: min = 1.50073 ms, max = 1.52454 ms, mean = 1.51225 ms, median = 1.51404 ms, percentile(99%) = 1.51941 ms
[I] GPU Compute Time: min = 13.3386 ms, max = 14.3186 ms, mean = 13.5448 ms, median = 13.5178 ms, percentile(99%) = 14.2151 ms
[I] D2H Latency: min = 0.00878906 ms, max = 0.0172729 ms, mean = 0.0128844 ms, median = 0.0125732 ms, percentile(99%) = 0.0166016 ms
[I] Total Host Walltime: 3.04768 s
[I] Total GPU Compute Time: 3.03404 s
[I] Explanations of the performance metrics are printed in the verbose logs.
```
Note: 73.5 qps x batch 8 = 588 fps @ ~15ms latency.
## Model Repository
See [Triton Model Repository Documentation](https://github.com/triton-inference-server/server/blob/main/docs/model_repository.md#model-repository) for more info.
```bash
# Create folder structure
mkdir -p triton-deploy/models/yolov7/1/
touch triton-deploy/models/yolov7/config.pbtxt
# Place model
mv yolov7-fp16-1x8x8.engine triton-deploy/models/yolov7/1/model.plan
```
## Model Configuration
See [Triton Model Configuration Documentation](https://github.com/triton-inference-server/server/blob/main/docs/model_configuration.md#model-configuration) for more info.
Minimal configuration for `triton-deploy/models/yolov7/config.pbtxt`:
```
name: "yolov7"
platform: "tensorrt_plan"
max_batch_size: 8
dynamic_batching { }
```
Example repository:
```bash
$ tree triton-deploy/
triton-deploy/
└── models
└── yolov7
├── 1
│ └── model.plan
└── config.pbtxt
3 directories, 2 files
```
## Start Triton Inference Server
```
docker run --gpus all --rm --ipc=host --shm-size=1g --ulimit memlock=-1 --ulimit stack=67108864 -p8000:8000 -p8001:8001 -p8002:8002 -v$(pwd)/triton-deploy/models:/models nvcr.io/nvidia/tritonserver:22.06-py3 tritonserver --model-repository=/models --strict-model-config=false --log-verbose 1
```
In the log you should see:
```
+--------+---------+--------+
| Model | Version | Status |
+--------+---------+--------+
| yolov7 | 1 | READY |
+--------+---------+--------+
```
## Performance with Model Analyzer
See [Triton Model Analyzer Documentation](https://github.com/triton-inference-server/server/blob/main/docs/model_analyzer.md#model-analyzer) for more info.
Performance numbers @ RTX 3090 + AMD Ryzen 9 5950X
Example test for 16 concurrent clients using shared memory, each with batch size 1 requests:
```bash
docker run -it --ipc=host --net=host nvcr.io/nvidia/tritonserver:22.06-py3-sdk /bin/bash
./install/bin/perf_analyzer -m yolov7 -u 127.0.0.1:8001 -i grpc --shared-memory system --concurrency-range 16
# Result (truncated)
Concurrency: 16, throughput: 590.119 infer/sec, latency 27080 usec
```
Throughput for 16 clients with batch size 1 is the same as for a single thread running the engine at 16 batch size locally thanks to Triton [Dynamic Batching Strategy](https://github.com/triton-inference-server/server/blob/main/docs/model_configuration.md#dynamic-batcher). Result without dynamic batching (disable in model configuration) considerably worse:
```bash
# Result (truncated)
Concurrency: 16, throughput: 335.587 infer/sec, latency 47616 usec
```
## How to run model in your code
| |
244769
|
from boundingbox import BoundingBox
import cv2
import numpy as np
def preprocess(img, input_shape, letter_box=True):
if letter_box:
img_h, img_w, _ = img.shape
new_h, new_w = input_shape[0], input_shape[1]
offset_h, offset_w = 0, 0
if (new_w / img_w) <= (new_h / img_h):
new_h = int(img_h * new_w / img_w)
offset_h = (input_shape[0] - new_h) // 2
else:
new_w = int(img_w * new_h / img_h)
offset_w = (input_shape[1] - new_w) // 2
resized = cv2.resize(img, (new_w, new_h))
img = np.full((input_shape[0], input_shape[1], 3), 127, dtype=np.uint8)
img[offset_h:(offset_h + new_h), offset_w:(offset_w + new_w), :] = resized
else:
img = cv2.resize(img, (input_shape[1], input_shape[0]))
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
img = img.transpose((2, 0, 1)).astype(np.float32)
img /= 255.0
return img
def postprocess(num_dets, det_boxes, det_scores, det_classes, img_w, img_h, input_shape, letter_box=True):
boxes = det_boxes[0, :num_dets[0][0]] / np.array([input_shape[0], input_shape[1], input_shape[0], input_shape[1]], dtype=np.float32)
scores = det_scores[0, :num_dets[0][0]]
classes = det_classes[0, :num_dets[0][0]].astype(np.int)
old_h, old_w = img_h, img_w
offset_h, offset_w = 0, 0
if letter_box:
if (img_w / input_shape[1]) >= (img_h / input_shape[0]):
old_h = int(input_shape[0] * img_w / input_shape[1])
offset_h = (old_h - img_h) // 2
else:
old_w = int(input_shape[1] * img_h / input_shape[0])
offset_w = (old_w - img_w) // 2
boxes = boxes * np.array([old_w, old_h, old_w, old_h], dtype=np.float32)
if letter_box:
boxes -= np.array([offset_w, offset_h, offset_w, offset_h], dtype=np.float32)
boxes = boxes.astype(np.int)
detected_objects = []
for box, score, label in zip(boxes, scores, classes):
detected_objects.append(BoundingBox(label, score, box[0], box[2], box[1], box[3], img_w, img_h))
return detected_objects
| |
244777
|
def cache_labels(self, path=Path('./labels.cache'), prefix=''):
# Cache dataset labels, check images and read shapes
x = {} # dict
nm, nf, ne, nc = 0, 0, 0, 0 # number missing, found, empty, duplicate
pbar = tqdm(zip(self.img_files, self.label_files), desc='Scanning images', total=len(self.img_files))
for i, (im_file, lb_file) in enumerate(pbar):
try:
# verify images
im = Image.open(im_file)
im.verify() # PIL verify
shape = exif_size(im) # image size
segments = [] # instance segments
assert (shape[0] > 9) & (shape[1] > 9), f'image size {shape} <10 pixels'
assert im.format.lower() in img_formats, f'invalid image format {im.format}'
# verify labels
if os.path.isfile(lb_file):
nf += 1 # label found
with open(lb_file, 'r') as f:
l = [x.split() for x in f.read().strip().splitlines()]
if any([len(x) > 8 for x in l]): # is segment
classes = np.array([x[0] for x in l], dtype=np.float32)
segments = [np.array(x[1:], dtype=np.float32).reshape(-1, 2) for x in l] # (cls, xy1...)
l = np.concatenate((classes.reshape(-1, 1), segments2boxes(segments)), 1) # (cls, xywh)
l = np.array(l, dtype=np.float32)
if len(l):
assert l.shape[1] == 5, 'labels require 5 columns each'
assert (l >= 0).all(), 'negative labels'
assert (l[:, 1:] <= 1).all(), 'non-normalized or out of bounds coordinate labels'
assert np.unique(l, axis=0).shape[0] == l.shape[0], 'duplicate labels'
else:
ne += 1 # label empty
l = np.zeros((0, 5), dtype=np.float32)
else:
nm += 1 # label missing
l = np.zeros((0, 5), dtype=np.float32)
x[im_file] = [l, shape, segments]
except Exception as e:
nc += 1
print(f'{prefix}WARNING: Ignoring corrupted image and/or label {im_file}: {e}')
pbar.desc = f"{prefix}Scanning '{path.parent / path.stem}' images and labels... " \
f"{nf} found, {nm} missing, {ne} empty, {nc} corrupted"
pbar.close()
if nf == 0:
print(f'{prefix}WARNING: No labels found in {path}. See {help_url}')
x['hash'] = get_hash(self.label_files + self.img_files)
x['results'] = nf, nm, ne, nc, i + 1
x['version'] = 0.1 # cache version
torch.save(x, path) # save for next time
logging.info(f'{prefix}New cache created: {path}')
return x
def __len__(self):
return len(self.img_files)
# def __iter__(self):
# self.count = -1
# print('ran dataset iter')
# #self.shuffled_vector = np.random.permutation(self.nF) if self.augment else np.arange(self.nF)
# return self
def __getitem__(self, index):
index = self.indices[index] # linear, shuffled, or image_weights
hyp = self.hyp
mosaic = self.mosaic and random.random() < hyp['mosaic']
if mosaic:
# Load mosaic
if random.random() < 0.8:
img, labels = load_mosaic(self, index)
else:
img, labels = load_mosaic9(self, index)
shapes = None
# MixUp https://arxiv.org/pdf/1710.09412.pdf
if random.random() < hyp['mixup']:
if random.random() < 0.8:
img2, labels2 = load_mosaic(self, random.randint(0, len(self.labels) - 1))
else:
img2, labels2 = load_mosaic9(self, random.randint(0, len(self.labels) - 1))
r = np.random.beta(8.0, 8.0) # mixup ratio, alpha=beta=8.0
img = (img * r + img2 * (1 - r)).astype(np.uint8)
labels = np.concatenate((labels, labels2), 0)
else:
# Load image
img, (h0, w0), (h, w) = load_image(self, index)
# Letterbox
shape = self.batch_shapes[self.batch[index]] if self.rect else self.img_size # final letterboxed shape
img, ratio, pad = letterbox(img, shape, auto=False, scaleup=self.augment)
shapes = (h0, w0), ((h / h0, w / w0), pad) # for COCO mAP rescaling
labels = self.labels[index].copy()
if labels.size: # normalized xywh to pixel xyxy format
labels[:, 1:] = xywhn2xyxy(labels[:, 1:], ratio[0] * w, ratio[1] * h, padw=pad[0], padh=pad[1])
if self.augment:
# Augment imagespace
if not mosaic:
img, labels = random_perspective(img, labels,
degrees=hyp['degrees'],
translate=hyp['translate'],
scale=hyp['scale'],
shear=hyp['shear'],
perspective=hyp['perspective'])
#img, labels = self.albumentations(img, labels)
# Augment colorspace
augment_hsv(img, hgain=hyp['hsv_h'], sgain=hyp['hsv_s'], vgain=hyp['hsv_v'])
# Apply cutouts
# if random.random() < 0.9:
# labels = cutout(img, labels)
if random.random() < hyp['paste_in']:
sample_labels, sample_images, sample_masks = [], [], []
while len(sample_labels) < 30:
sample_labels_, sample_images_, sample_masks_ = load_samples(self, random.randint(0, len(self.labels) - 1))
sample_labels += sample_labels_
sample_images += sample_images_
sample_masks += sample_masks_
#print(len(sample_labels))
if len(sample_labels) == 0:
break
labels = pastein(img, labels, sample_labels, sample_images, sample_masks)
nL = len(labels) # number of labels
if nL:
labels[:, 1:5] = xyxy2xywh(labels[:, 1:5]) # convert xyxy to xywh
labels[:, [2, 4]] /= img.shape[0] # normalized height 0-1
labels[:, [1, 3]] /= img.shape[1] # normalized width 0-1
if self.augment:
# flip up-down
if random.random() < hyp['flipud']:
img = np.flipud(img)
if nL:
labels[:, 2] = 1 - labels[:, 2]
# flip left-right
if random.random() < hyp['fliplr']:
img = np.fliplr(img)
if nL:
labels[:, 1] = 1 - labels[:, 1]
labels_out = torch.zeros((nL, 6))
if nL:
labels_out[:, 1:] = torch.from_numpy(labels)
# Convert
img = img[:, :, ::-1].transpose(2, 0, 1) # BGR to RGB, to 3x416x416
img = np.ascontiguousarray(img)
return torch.from_numpy(img), labels_out, self.img_files[index], shapes
@staticmethod
def collate_fn(batch):
img, label, path, shapes = zip(*batch) # transposed
for i, l in enumerate(label):
l[:, 0] = i # add target image index for build_targets()
return torch.stack(img, 0), torch.cat(label, 0), path, shapes
| |
244778
|
@staticmethod
def collate_fn4(batch):
img, label, path, shapes = zip(*batch) # transposed
n = len(shapes) // 4
img4, label4, path4, shapes4 = [], [], path[:n], shapes[:n]
ho = torch.tensor([[0., 0, 0, 1, 0, 0]])
wo = torch.tensor([[0., 0, 1, 0, 0, 0]])
s = torch.tensor([[1, 1, .5, .5, .5, .5]]) # scale
for i in range(n): # zidane torch.zeros(16,3,720,1280) # BCHW
i *= 4
if random.random() < 0.5:
im = F.interpolate(img[i].unsqueeze(0).float(), scale_factor=2., mode='bilinear', align_corners=False)[
0].type(img[i].type())
l = label[i]
else:
im = torch.cat((torch.cat((img[i], img[i + 1]), 1), torch.cat((img[i + 2], img[i + 3]), 1)), 2)
l = torch.cat((label[i], label[i + 1] + ho, label[i + 2] + wo, label[i + 3] + ho + wo), 0) * s
img4.append(im)
label4.append(l)
for i, l in enumerate(label4):
l[:, 0] = i # add target image index for build_targets()
return torch.stack(img4, 0), torch.cat(label4, 0), path4, shapes4
# Ancillary functions --------------------------------------------------------------------------------------------------
def load_image(self, index):
# loads 1 image from dataset, returns img, original hw, resized hw
img = self.imgs[index]
if img is None: # not cached
path = self.img_files[index]
img = cv2.imread(path) # BGR
assert img is not None, 'Image Not Found ' + path
h0, w0 = img.shape[:2] # orig hw
r = self.img_size / max(h0, w0) # resize image to img_size
if r != 1: # always resize down, only resize up if training with augmentation
interp = cv2.INTER_AREA if r < 1 and not self.augment else cv2.INTER_LINEAR
img = cv2.resize(img, (int(w0 * r), int(h0 * r)), interpolation=interp)
return img, (h0, w0), img.shape[:2] # img, hw_original, hw_resized
else:
return self.imgs[index], self.img_hw0[index], self.img_hw[index] # img, hw_original, hw_resized
def augment_hsv(img, hgain=0.5, sgain=0.5, vgain=0.5):
r = np.random.uniform(-1, 1, 3) * [hgain, sgain, vgain] + 1 # random gains
hue, sat, val = cv2.split(cv2.cvtColor(img, cv2.COLOR_BGR2HSV))
dtype = img.dtype # uint8
x = np.arange(0, 256, dtype=np.int16)
lut_hue = ((x * r[0]) % 180).astype(dtype)
lut_sat = np.clip(x * r[1], 0, 255).astype(dtype)
lut_val = np.clip(x * r[2], 0, 255).astype(dtype)
img_hsv = cv2.merge((cv2.LUT(hue, lut_hue), cv2.LUT(sat, lut_sat), cv2.LUT(val, lut_val))).astype(dtype)
cv2.cvtColor(img_hsv, cv2.COLOR_HSV2BGR, dst=img) # no return needed
def hist_equalize(img, clahe=True, bgr=False):
# Equalize histogram on BGR image 'img' with img.shape(n,m,3) and range 0-255
yuv = cv2.cvtColor(img, cv2.COLOR_BGR2YUV if bgr else cv2.COLOR_RGB2YUV)
if clahe:
c = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
yuv[:, :, 0] = c.apply(yuv[:, :, 0])
else:
yuv[:, :, 0] = cv2.equalizeHist(yuv[:, :, 0]) # equalize Y channel histogram
return cv2.cvtColor(yuv, cv2.COLOR_YUV2BGR if bgr else cv2.COLOR_YUV2RGB) # convert YUV image to RGB
| |
244782
|
def random_perspective(img, targets=(), segments=(), degrees=10, translate=.1, scale=.1, shear=10, perspective=0.0,
border=(0, 0)):
# torchvision.transforms.RandomAffine(degrees=(-10, 10), translate=(.1, .1), scale=(.9, 1.1), shear=(-10, 10))
# targets = [cls, xyxy]
height = img.shape[0] + border[0] * 2 # shape(h,w,c)
width = img.shape[1] + border[1] * 2
# Center
C = np.eye(3)
C[0, 2] = -img.shape[1] / 2 # x translation (pixels)
C[1, 2] = -img.shape[0] / 2 # y translation (pixels)
# Perspective
P = np.eye(3)
P[2, 0] = random.uniform(-perspective, perspective) # x perspective (about y)
P[2, 1] = random.uniform(-perspective, perspective) # y perspective (about x)
# Rotation and Scale
R = np.eye(3)
a = random.uniform(-degrees, degrees)
# a += random.choice([-180, -90, 0, 90]) # add 90deg rotations to small rotations
s = random.uniform(1 - scale, 1.1 + scale)
# s = 2 ** random.uniform(-scale, scale)
R[:2] = cv2.getRotationMatrix2D(angle=a, center=(0, 0), scale=s)
# Shear
S = np.eye(3)
S[0, 1] = math.tan(random.uniform(-shear, shear) * math.pi / 180) # x shear (deg)
S[1, 0] = math.tan(random.uniform(-shear, shear) * math.pi / 180) # y shear (deg)
# Translation
T = np.eye(3)
T[0, 2] = random.uniform(0.5 - translate, 0.5 + translate) * width # x translation (pixels)
T[1, 2] = random.uniform(0.5 - translate, 0.5 + translate) * height # y translation (pixels)
# Combined rotation matrix
M = T @ S @ R @ P @ C # order of operations (right to left) is IMPORTANT
if (border[0] != 0) or (border[1] != 0) or (M != np.eye(3)).any(): # image changed
if perspective:
img = cv2.warpPerspective(img, M, dsize=(width, height), borderValue=(114, 114, 114))
else: # affine
img = cv2.warpAffine(img, M[:2], dsize=(width, height), borderValue=(114, 114, 114))
# Visualize
# import matplotlib.pyplot as plt
# ax = plt.subplots(1, 2, figsize=(12, 6))[1].ravel()
# ax[0].imshow(img[:, :, ::-1]) # base
# ax[1].imshow(img2[:, :, ::-1]) # warped
# Transform label coordinates
n = len(targets)
if n:
use_segments = any(x.any() for x in segments)
new = np.zeros((n, 4))
if use_segments: # warp segments
segments = resample_segments(segments) # upsample
for i, segment in enumerate(segments):
xy = np.ones((len(segment), 3))
xy[:, :2] = segment
xy = xy @ M.T # transform
xy = xy[:, :2] / xy[:, 2:3] if perspective else xy[:, :2] # perspective rescale or affine
# clip
new[i] = segment2box(xy, width, height)
else: # warp boxes
xy = np.ones((n * 4, 3))
xy[:, :2] = targets[:, [1, 2, 3, 4, 1, 4, 3, 2]].reshape(n * 4, 2) # x1y1, x2y2, x1y2, x2y1
xy = xy @ M.T # transform
xy = (xy[:, :2] / xy[:, 2:3] if perspective else xy[:, :2]).reshape(n, 8) # perspective rescale or affine
# create new boxes
x = xy[:, [0, 2, 4, 6]]
y = xy[:, [1, 3, 5, 7]]
new = np.concatenate((x.min(1), y.min(1), x.max(1), y.max(1))).reshape(4, n).T
# clip
new[:, [0, 2]] = new[:, [0, 2]].clip(0, width)
new[:, [1, 3]] = new[:, [1, 3]].clip(0, height)
# filter candidates
i = box_candidates(box1=targets[:, 1:5].T * s, box2=new.T, area_thr=0.01 if use_segments else 0.10)
targets = targets[i]
targets[:, 1:5] = new[i]
return img, targets
def box_candidates(box1, box2, wh_thr=2, ar_thr=20, area_thr=0.1, eps=1e-16): # box1(4,n), box2(4,n)
# Compute candidate boxes: box1 before augment, box2 after augment, wh_thr (pixels), aspect_ratio_thr, area_ratio
w1, h1 = box1[2] - box1[0], box1[3] - box1[1]
w2, h2 = box2[2] - box2[0], box2[3] - box2[1]
ar = np.maximum(w2 / (h2 + eps), h2 / (w2 + eps)) # aspect ratio
return (w2 > wh_thr) & (h2 > wh_thr) & (w2 * h2 / (w1 * h1 + eps) > area_thr) & (ar < ar_thr) # candidates
def bbox_ioa(box1, box2):
# Returns the intersection over box2 area given box1, box2. box1 is 4, box2 is nx4. boxes are x1y1x2y2
box2 = box2.transpose()
# Get the coordinates of bounding boxes
b1_x1, b1_y1, b1_x2, b1_y2 = box1[0], box1[1], box1[2], box1[3]
b2_x1, b2_y1, b2_x2, b2_y2 = box2[0], box2[1], box2[2], box2[3]
# Intersection area
inter_area = (np.minimum(b1_x2, b2_x2) - np.maximum(b1_x1, b2_x1)).clip(0) * \
(np.minimum(b1_y2, b2_y2) - np.maximum(b1_y1, b2_y1)).clip(0)
# box2 area
box2_area = (b2_x2 - b2_x1) * (b2_y2 - b2_y1) + 1e-16
# Intersection over box2 area
return inter_area / box2_area
| |
244803
|
def plot_results_overlay(start=0, stop=0): # from utils.plots import *; plot_results_overlay()
# Plot training 'results*.txt', overlaying train and val losses
s = ['train', 'train', 'train', 'Precision', 'mAP@0.5', 'val', 'val', 'val', 'Recall', 'mAP@0.5:0.95'] # legends
t = ['Box', 'Objectness', 'Classification', 'P-R', 'mAP-F1'] # titles
for f in sorted(glob.glob('results*.txt') + glob.glob('../../Downloads/results*.txt')):
results = np.loadtxt(f, usecols=[2, 3, 4, 8, 9, 12, 13, 14, 10, 11], ndmin=2).T
n = results.shape[1] # number of rows
x = range(start, min(stop, n) if stop else n)
fig, ax = plt.subplots(1, 5, figsize=(14, 3.5), tight_layout=True)
ax = ax.ravel()
for i in range(5):
for j in [i, i + 5]:
y = results[j, x]
ax[i].plot(x, y, marker='.', label=s[j])
# y_smooth = butter_lowpass_filtfilt(y)
# ax[i].plot(x, np.gradient(y_smooth), marker='.', label=s[j])
ax[i].set_title(t[i])
ax[i].legend()
ax[i].set_ylabel(f) if i == 0 else None # add filename
fig.savefig(f.replace('.txt', '.png'), dpi=200)
def plot_results(start=0, stop=0, bucket='', id=(), labels=(), save_dir=''):
# Plot training 'results*.txt'. from utils.plots import *; plot_results(save_dir='runs/train/exp')
fig, ax = plt.subplots(2, 5, figsize=(12, 6), tight_layout=True)
ax = ax.ravel()
s = ['Box', 'Objectness', 'Classification', 'Precision', 'Recall',
'val Box', 'val Objectness', 'val Classification', 'mAP@0.5', 'mAP@0.5:0.95']
if bucket:
# files = ['https://storage.googleapis.com/%s/results%g.txt' % (bucket, x) for x in id]
files = ['results%g.txt' % x for x in id]
c = ('gsutil cp ' + '%s ' * len(files) + '.') % tuple('gs://%s/results%g.txt' % (bucket, x) for x in id)
os.system(c)
else:
files = list(Path(save_dir).glob('results*.txt'))
assert len(files), 'No results.txt files found in %s, nothing to plot.' % os.path.abspath(save_dir)
for fi, f in enumerate(files):
try:
results = np.loadtxt(f, usecols=[2, 3, 4, 8, 9, 12, 13, 14, 10, 11], ndmin=2).T
n = results.shape[1] # number of rows
x = range(start, min(stop, n) if stop else n)
for i in range(10):
y = results[i, x]
if i in [0, 1, 2, 5, 6, 7]:
y[y == 0] = np.nan # don't show zero loss values
# y /= y[0] # normalize
label = labels[fi] if len(labels) else f.stem
ax[i].plot(x, y, marker='.', label=label, linewidth=2, markersize=8)
ax[i].set_title(s[i])
# if i in [5, 6, 7]: # share train and val loss y axes
# ax[i].get_shared_y_axes().join(ax[i], ax[i - 5])
except Exception as e:
print('Warning: Plotting error for %s; %s' % (f, e))
ax[1].legend()
fig.savefig(Path(save_dir) / 'results.png', dpi=200)
def output_to_keypoint(output):
# Convert model output to target format [batch_id, class_id, x, y, w, h, conf]
targets = []
for i, o in enumerate(output):
kpts = o[:,6:]
o = o[:,:6]
for index, (*box, conf, cls) in enumerate(o.detach().cpu().numpy()):
targets.append([i, cls, *list(*xyxy2xywh(np.array(box)[None])), conf, *list(kpts.detach().cpu().numpy()[index])])
return np.array(targets)
def plot_skeleton_kpts(im, kpts, steps, orig_shape=None):
#Plot the skeleton and keypointsfor coco datatset
palette = np.array([[255, 128, 0], [255, 153, 51], [255, 178, 102],
[230, 230, 0], [255, 153, 255], [153, 204, 255],
[255, 102, 255], [255, 51, 255], [102, 178, 255],
[51, 153, 255], [255, 153, 153], [255, 102, 102],
[255, 51, 51], [153, 255, 153], [102, 255, 102],
[51, 255, 51], [0, 255, 0], [0, 0, 255], [255, 0, 0],
[255, 255, 255]])
skeleton = [[16, 14], [14, 12], [17, 15], [15, 13], [12, 13], [6, 12],
[7, 13], [6, 7], [6, 8], [7, 9], [8, 10], [9, 11], [2, 3],
[1, 2], [1, 3], [2, 4], [3, 5], [4, 6], [5, 7]]
pose_limb_color = palette[[9, 9, 9, 9, 7, 7, 7, 0, 0, 0, 0, 0, 16, 16, 16, 16, 16, 16, 16]]
pose_kpt_color = palette[[16, 16, 16, 16, 16, 0, 0, 0, 0, 0, 0, 9, 9, 9, 9, 9, 9]]
radius = 5
num_kpts = len(kpts) // steps
for kid in range(num_kpts):
r, g, b = pose_kpt_color[kid]
x_coord, y_coord = kpts[steps * kid], kpts[steps * kid + 1]
if not (x_coord % 640 == 0 or y_coord % 640 == 0):
if steps == 3:
conf = kpts[steps * kid + 2]
if conf < 0.5:
continue
cv2.circle(im, (int(x_coord), int(y_coord)), radius, (int(r), int(g), int(b)), -1)
for sk_id, sk in enumerate(skeleton):
r, g, b = pose_limb_color[sk_id]
pos1 = (int(kpts[(sk[0]-1)*steps]), int(kpts[(sk[0]-1)*steps+1]))
pos2 = (int(kpts[(sk[1]-1)*steps]), int(kpts[(sk[1]-1)*steps+1]))
if steps == 3:
conf1 = kpts[(sk[0]-1)*steps+2]
conf2 = kpts[(sk[1]-1)*steps+2]
if conf1<0.5 or conf2<0.5:
continue
if pos1[0]%640 == 0 or pos1[1]%640==0 or pos1[0]<0 or pos1[1]<0:
continue
if pos2[0] % 640 == 0 or pos2[1] % 640 == 0 or pos2[0]<0 or pos2[1]<0:
continue
cv2.line(im, pos1, pos2, (int(r), int(g), int(b)), thickness=2)
| |
244811
|
ut):
# Colors a string https://en.wikipedia.org/wiki/ANSI_escape_code, i.e. colorstr('blue', 'hello world')
*args, string = input if len(input) > 1 else ('blue', 'bold', input[0]) # color arguments, string
colors = {'black': '\033[30m', # basic colors
'red': '\033[31m',
'green': '\033[32m',
'yellow': '\033[33m',
'blue': '\033[34m',
'magenta': '\033[35m',
'cyan': '\033[36m',
'white': '\033[37m',
'bright_black': '\033[90m', # bright colors
'bright_red': '\033[91m',
'bright_green': '\033[92m',
'bright_yellow': '\033[93m',
'bright_blue': '\033[94m',
'bright_magenta': '\033[95m',
'bright_cyan': '\033[96m',
'bright_white': '\033[97m',
'end': '\033[0m', # misc
'bold': '\033[1m',
'underline': '\033[4m'}
return ''.join(colors[x] for x in args) + f'{string}' + colors['end']
def labels_to_class_weights(labels, nc=80):
# Get class weights (inverse frequency) from training labels
if labels[0] is None: # no labels loaded
return torch.Tensor()
labels = np.concatenate(labels, 0) # labels.shape = (866643, 5) for COCO
classes = labels[:, 0].astype(np.int32) # labels = [class xywh]
weights = np.bincount(classes, minlength=nc) # occurrences per class
# Prepend gridpoint count (for uCE training)
# gpi = ((320 / 32 * np.array([1, 2, 4])) ** 2 * 3).sum() # gridpoints per image
# weights = np.hstack([gpi * len(labels) - weights.sum() * 9, weights * 9]) ** 0.5 # prepend gridpoints to start
weights[weights == 0] = 1 # replace empty bins with 1
weights = 1 / weights # number of targets per class
weights /= weights.sum() # normalize
return torch.from_numpy(weights)
def labels_to_image_weights(labels, nc=80, class_weights=np.ones(80)):
# Produces image weights based on class_weights and image contents
class_counts = np.array([np.bincount(x[:, 0].astype(np.int32), minlength=nc) for x in labels])
image_weights = (class_weights.reshape(1, nc) * class_counts).sum(1)
# index = random.choices(range(n), weights=image_weights, k=1) # weight image sample
return image_weights
def coco80_to_coco91_class(): # converts 80-index (val2014) to 91-index (paper)
# https://tech.amikelive.com/node-718/what-object-categories-labels-are-in-coco-dataset/
# a = np.loadtxt('data/coco.names', dtype='str', delimiter='\n')
# b = np.loadtxt('data/coco_paper.names', dtype='str', delimiter='\n')
# x1 = [list(a[i] == b).index(True) + 1 for i in range(80)] # darknet to coco
# x2 = [list(b[i] == a).index(True) if any(b[i] == a) else None for i in range(91)] # coco to darknet
x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 31, 32, 33, 34,
35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63,
64, 65, 67, 70, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 84, 85, 86, 87, 88, 89, 90]
return x
def xyxy2xywh(x):
# Convert nx4 boxes from [x1, y1, x2, y2] to [x, y, w, h] where xy1=top-left, xy2=bottom-right
y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)
y[:, 0] = (x[:, 0] + x[:, 2]) / 2 # x center
y[:, 1] = (x[:, 1] + x[:, 3]) / 2 # y center
y[:, 2] = x[:, 2] - x[:, 0] # width
y[:, 3] = x[:, 3] - x[:, 1] # height
return y
def xywh2xyxy(x):
# Convert nx4 boxes from [x, y, w, h] to [x1, y1, x2, y2] where xy1=top-left, xy2=bottom-right
y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)
y[:, 0] = x[:, 0] - x[:, 2] / 2 # top left x
y[:, 1] = x[:, 1] - x[:, 3] / 2 # top left y
y[:, 2] = x[:, 0] + x[:, 2] / 2 # bottom right x
y[:, 3] = x[:, 1] + x[:, 3] / 2 # bottom right y
return y
def xywhn2xyxy(x, w=640, h=640, padw=0, padh=0):
# Convert nx4 boxes from [x, y, w, h] normalized to [x1, y1, x2, y2] where xy1=top-left, xy2=bottom-right
y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)
y[:, 0] = w * (x[:, 0] - x[:, 2] / 2) + padw # top left x
y[:, 1] = h * (x[:, 1] - x[:, 3] / 2) + padh # top left y
y[:, 2] = w * (x[:, 0] + x[:, 2] / 2) + padw # bottom right x
y[:, 3] = h * (x[:, 1] + x[:, 3] / 2) + padh # bottom right y
return y
def xyn2xy(x, w=640, h=640, padw=0, padh=0):
# Convert normalized segments into pixel segments, shape (n,2)
y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)
y[:, 0] = w * x[:, 0] + padw # top left x
y[:, 1] = h * x[:, 1] + padh # top left y
return y
def segment2box(segment, width=640, height=640):
# Convert 1 segment label to 1 box label, applying inside-image constraint, i.e. (xy1, xy2, ...) to (xyxy)
x, y = segment.T # segment xy
inside = (x >= 0) & (y >= 0) & (x <= width) & (y <= height)
x, y, = x[inside], y[inside]
return np.array([x.min(), y.min(), x.max(), y.max()]) if any(x) else np.zeros((1, 4)) # xyxy
def segments2b
| |
244815
|
ession(prediction, conf_thres=0.25, iou_thres=0.45, classes=None, agnostic=False, multi_label=False,
labels=()):
"""Runs Non-Maximum Suppression (NMS) on inference results
Returns:
list of detections, on (n,6) tensor per image [xyxy, conf, cls]
"""
nc = prediction.shape[2] - 5 # number of classes
xc = prediction[..., 4] > conf_thres # candidates
# Settings
min_wh, max_wh = 2, 4096 # (pixels) minimum and maximum box width and height
max_det = 300 # maximum number of detections per image
max_nms = 30000 # maximum number of boxes into torchvision.ops.nms()
time_limit = 10.0 # seconds to quit after
redundant = True # require redundant detections
multi_label &= nc > 1 # multiple labels per box (adds 0.5ms/img)
merge = False # use merge-NMS
t = time.time()
output = [torch.zeros((0, 6), device=prediction.device)] * prediction.shape[0]
for xi, x in enumerate(prediction): # image index, image inference
# Apply constraints
# x[((x[..., 2:4] < min_wh) | (x[..., 2:4] > max_wh)).any(1), 4] = 0 # width-height
x = x[xc[xi]] # confidence
# Cat apriori labels if autolabelling
if labels and len(labels[xi]):
l = labels[xi]
v = torch.zeros((len(l), nc + 5), device=x.device)
v[:, :4] = l[:, 1:5] # box
v[:, 4] = 1.0 # conf
v[range(len(l)), l[:, 0].long() + 5] = 1.0 # cls
x = torch.cat((x, v), 0)
# If none remain process next image
if not x.shape[0]:
continue
# Compute conf
if nc == 1:
x[:, 5:] = x[:, 4:5] # for models with one class, cls_loss is 0 and cls_conf is always 0.5,
# so there is no need to multiplicate.
else:
x[:, 5:] *= x[:, 4:5] # conf = obj_conf * cls_conf
# Box (center x, center y, width, height) to (x1, y1, x2, y2)
box = xywh2xyxy(x[:, :4])
# Detections matrix nx6 (xyxy, conf, cls)
if multi_label:
i, j = (x[:, 5:] > conf_thres).nonzero(as_tuple=False).T
x = torch.cat((box[i], x[i, j + 5, None], j[:, None].float()), 1)
else: # best class only
conf, j = x[:, 5:].max(1, keepdim=True)
x = torch.cat((box, conf, j.float()), 1)[conf.view(-1) > conf_thres]
# Filter by class
if classes is not None:
x = x[(x[:, 5:6] == torch.tensor(classes, device=x.device)).any(1)]
# Apply finite constraint
# if not torch.isfinite(x).all():
# x = x[torch.isfinite(x).all(1)]
# Check shape
n = x.shape[0] # number of boxes
if not n: # no boxes
continue
elif n > max_nms: # excess boxes
x = x[x[:, 4].argsort(descending=True)[:max_nms]] # sort by confidence
# Batched NMS
c = x[:, 5:6] * (0 if agnostic else max_wh) # classes
boxes, scores = x[:, :4] + c, x[:, 4] # boxes (offset by class), scores
i = torchvision.ops.nms(boxes, scores, iou_thres) # NMS
if i.shape[0] > max_det: # limit detections
i = i[:max_det]
if merge and (1 < n < 3E3): # Merge NMS (boxes merged using weighted mean)
# update boxes as boxes(i,4) = weights(i,n) * boxes(n,4)
iou = box_iou(boxes[i], boxes) > iou_thres # iou matrix
weights = iou * scores[None] # box weights
x[i, :4] = torch.mm(weights, x[:, :4]).float() / weights.sum(1, keepdim=True) # merged boxes
if redundant:
i = i[iou.sum(1) > 1] # require redundancy
output[xi] = x[i]
if (time.time() - t) > time_limit:
print(f'WARNING: NMS time limit {time_limit}s exceeded')
break # time limit exceeded
return output
def non_max_su
| |
244816
|
ession_kpt(prediction, conf_thres=0.25, iou_thres=0.45, classes=None, agnostic=False, multi_label=False,
labels=(), kpt_label=False, nc=None, nkpt=None):
"""Runs Non-Maximum Suppression (NMS) on inference results
Returns:
list of detections, on (n,6) tensor per image [xyxy, conf, cls]
"""
if nc is None:
nc = prediction.shape[2] - 5 if not kpt_label else prediction.shape[2] - 56 # number of classes
xc = prediction[..., 4] > conf_thres # candidates
# Settings
min_wh, max_wh = 2, 4096 # (pixels) minimum and maximum box width and height
max_det = 300 # maximum number of detections per image
max_nms = 30000 # maximum number of boxes into torchvision.ops.nms()
time_limit = 10.0 # seconds to quit after
redundant = True # require redundant detections
multi_label &= nc > 1 # multiple labels per box (adds 0.5ms/img)
merge = False # use merge-NMS
t = time.time()
output = [torch.zeros((0,6), device=prediction.device)] * prediction.shape[0]
for xi, x in enumerate(prediction): # image index, image inference
# Apply constraints
# x[((x[..., 2:4] < min_wh) | (x[..., 2:4] > max_wh)).any(1), 4] = 0 # width-height
x = x[xc[xi]] # confidence
# Cat apriori labels if autolabelling
if labels and len(labels[xi]):
l = labels[xi]
v = torch.zeros((len(l), nc + 5), device=x.device)
v[:, :4] = l[:, 1:5] # box
v[:, 4] = 1.0 # conf
v[range(len(l)), l[:, 0].long() + 5] = 1.0 # cls
x = torch.cat((x, v), 0)
# If none remain process next image
if not x.shape[0]:
continue
# Compute conf
x[:, 5:5+nc] *= x[:, 4:5] # conf = obj_conf * cls_conf
# Box (center x, center y, width, height) to (x1, y1, x2, y2)
box = xywh2xyxy(x[:, :4])
# Detections matrix nx6 (xyxy, conf, cls)
if multi_label:
i, j = (x[:, 5:] > conf_thres).nonzero(as_tuple=False).T
x = torch.cat((box[i], x[i, j + 5, None], j[:, None].float()), 1)
else: # best class only
if not kpt_label:
conf, j = x[:, 5:].max(1, keepdim=True)
x = torch.cat((box, conf, j.float()), 1)[conf.view(-1) > conf_thres]
else:
kpts = x[:, 6:]
conf, j = x[:, 5:6].max(1, keepdim=True)
x = torch.cat((box, conf, j.float(), kpts), 1)[conf.view(-1) > conf_thres]
# Filter by class
if classes is not None:
x = x[(x[:, 5:6] == torch.tensor(classes, device=x.device)).any(1)]
# Apply finite constraint
# if not torch.isfinite(x).all():
# x = x[torch.isfinite(x).all(1)]
# Check shape
n = x.shape[0] # number of boxes
if not n: # no boxes
continue
elif n > max_nms: # excess boxes
x = x[x[:, 4].argsort(descending=True)[:max_nms]] # sort by confidence
# Batched NMS
c = x[:, 5:6] * (0 if agnostic else max_wh) # classes
boxes, scores = x[:, :4] + c, x[:, 4] # boxes (offset by class), scores
i = torchvision.ops.nms(boxes, scores, iou_thres) # NMS
if i.shape[0] > max_det: # limit detections
i = i[:max_det]
if merge and (1 < n < 3E3): # Merge NMS (boxes merged using weighted mean)
# update boxes as boxes(i,4) = weights(i,n) * boxes(n,4)
iou = box_iou(boxes[i], boxes) > iou_thres # iou matrix
weights = iou * scores[None] # box weights
x[i, :4] = torch.mm(weights, x[:, :4]).float() / weights.sum(1, keepdim=True) # merged boxes
if redundant:
i = i[iou.sum(1) > 1] # require redundancy
output[xi] = x[i]
if (time.time() - t) > time_limit:
print(f'WARNING: NMS time limit {time_limit}s exceeded')
break # time limit exceeded
return output
def strip_optimizer(f='best.pt', s=''): # from utils.general import *; strip_optimizer()
# Strip optimizer from 'f' to finalize training, optionally save as 's'
x = torch.load(f, map_location=torch.device('cpu'))
if x.get('ema'):
x['model'] = x['ema'] # replace model with ema
for k in 'optimizer', 'training_results', 'wandb_id', 'ema', 'updates': # keys
x[k] = None
x['epoch'] = -1
x['model'].half() # to FP16
for p in x['model'].parameters():
p.requires_grad = False
torch.save(x, s or f)
mb = os.path.getsize(s or f) / 1E6 # filesize
print(f"Optimizer stripped from {f},{(' saved as %s,' % s) if s else ''} {mb:.1f}MB")
def print_mutation(hyp, results, yaml_file='hyp_evolved.yaml', bucket=''):
# Print mutation results to evolve.txt (for use with train.py --evolve)
a = '%10s' * len(hyp) % tuple(hyp.keys()) # hyperparam keys
b = '%10.3g' * len(hyp) % tuple(hyp.values()) # hyperparam values
c = '%10.4g' * len(results) % results # results (P, R, mAP@0.5, mAP@0.5:0.95, val_losses x 3)
print('\n%s\n%s\nEvolved fitness: %s\n' % (a, b, c))
if bucket:
url = 'gs://%s/evolve.txt' % bucket
if gsutil_getsize(url) > (os.path.getsize('evolve.txt') if os.path.exists('evolve.txt') else 0):
os.system('gsutil cp %s .' % url) # download evolve.txt if larger than local
with open('evolve.txt', 'a') as f: # append result
f.write(c + b + '\n')
x = np.unique(np.loadtxt('evolve.txt', ndmin=2), axis=0) # load unique rows
x = x[np.argsort(-fitness(x))] # sort
np.savetxt('evolve.txt', x, '%10.3g') # save sort by fitness
# Save yaml
for i, k in enumerate(hyp.keys()):
hyp[k] = float(x[0, i + 7])
with open(yaml_file, 'w') as f:
results = tuple(x[0, :7])
c = '%10.4g' * len(results) % results # results (P, R, mAP@0.5, mAP@0.5:0.95, val_losses x 3)
f.write('# Hyperparameter Evolution Results\n# Generations: %g\n# Metrics: ' % len(x) + c + '\n\n')
yaml.dump(hyp, f, sort_keys=False)
if bucket:
os.system('gsutil cp evolve.txt %s gs://%s' % (yaml_file, bucket)) # upload
def apply_clas
| |
244839
|
class Detections:
# detections class for YOLOv5 inference results
def __init__(self, imgs, pred, files, times=None, names=None, shape=None):
super(Detections, self).__init__()
d = pred[0].device # device
gn = [torch.tensor([*[im.shape[i] for i in [1, 0, 1, 0]], 1., 1.], device=d) for im in imgs] # normalizations
self.imgs = imgs # list of images as numpy arrays
self.pred = pred # list of tensors pred[0] = (xyxy, conf, cls)
self.names = names # class names
self.files = files # image filenames
self.xyxy = pred # xyxy pixels
self.xywh = [xyxy2xywh(x) for x in pred] # xywh pixels
self.xyxyn = [x / g for x, g in zip(self.xyxy, gn)] # xyxy normalized
self.xywhn = [x / g for x, g in zip(self.xywh, gn)] # xywh normalized
self.n = len(self.pred) # number of images (batch size)
self.t = tuple((times[i + 1] - times[i]) * 1000 / self.n for i in range(3)) # timestamps (ms)
self.s = shape # inference BCHW shape
def display(self, pprint=False, show=False, save=False, render=False, save_dir=''):
colors = color_list()
for i, (img, pred) in enumerate(zip(self.imgs, self.pred)):
str = f'image {i + 1}/{len(self.pred)}: {img.shape[0]}x{img.shape[1]} '
if pred is not None:
for c in pred[:, -1].unique():
n = (pred[:, -1] == c).sum() # detections per class
str += f"{n} {self.names[int(c)]}{'s' * (n > 1)}, " # add to string
if show or save or render:
for *box, conf, cls in pred: # xyxy, confidence, class
label = f'{self.names[int(cls)]} {conf:.2f}'
plot_one_box(box, img, label=label, color=colors[int(cls) % 10])
img = Image.fromarray(img.astype(np.uint8)) if isinstance(img, np.ndarray) else img # from np
if pprint:
print(str.rstrip(', '))
if show:
img.show(self.files[i]) # show
if save:
f = self.files[i]
img.save(Path(save_dir) / f) # save
print(f"{'Saved' * (i == 0)} {f}", end=',' if i < self.n - 1 else f' to {save_dir}\n')
if render:
self.imgs[i] = np.asarray(img)
def print(self):
self.display(pprint=True) # print results
print(f'Speed: %.1fms pre-process, %.1fms inference, %.1fms NMS per image at shape {tuple(self.s)}' % self.t)
def show(self):
self.display(show=True) # show results
def save(self, save_dir='runs/hub/exp'):
save_dir = increment_path(save_dir, exist_ok=save_dir != 'runs/hub/exp') # increment save_dir
Path(save_dir).mkdir(parents=True, exist_ok=True)
self.display(save=True, save_dir=save_dir) # save results
def render(self):
self.display(render=True) # render results
return self.imgs
def pandas(self):
# return detections as pandas DataFrames, i.e. print(results.pandas().xyxy[0])
new = copy(self) # return copy
ca = 'xmin', 'ymin', 'xmax', 'ymax', 'confidence', 'class', 'name' # xyxy columns
cb = 'xcenter', 'ycenter', 'width', 'height', 'confidence', 'class', 'name' # xywh columns
for k, c in zip(['xyxy', 'xyxyn', 'xywh', 'xywhn'], [ca, ca, cb, cb]):
a = [[x[:5] + [int(x[5]), self.names[int(x[5])]] for x in x.tolist()] for x in getattr(self, k)] # update
setattr(new, k, [pd.DataFrame(x, columns=c) for x in a])
return new
def tolist(self):
# return a list of Detections objects, i.e. 'for result in results.tolist():'
x = [Detections([self.imgs[i]], [self.pred[i]], self.names, self.s) for i in range(self.n)]
for d in x:
for k in ['imgs', 'pred', 'xyxy', 'xyxyn', 'xywh', 'xywhn']:
setattr(d, k, getattr(d, k)[0]) # pop out of list
return x
def __len__(self):
return self.n
class Classify(nn.Module):
# Classification head, i.e. x(b,c1,20,20) to x(b,c2)
def __init__(self, c1, c2, k=1, s=1, p=None, g=1): # ch_in, ch_out, kernel, stride, padding, groups
super(Classify, self).__init__()
self.aap = nn.AdaptiveAvgPool2d(1) # to x(b,c1,1,1)
self.conv = nn.Conv2d(c1, c2, k, s, autopad(k, p), groups=g) # to x(b,c2,1,1)
self.flat = nn.Flatten()
def forward(self, x):
z = torch.cat([self.aap(y) for y in (x if isinstance(x, list) else [x])], 1) # cat if list
return self.flat(self.conv(z)) # flatten to x(b,c2)
##### end of yolov5 ######
##### orepa #####
def transI_fusebn(kernel, bn):
gamma = bn.weight
std = (bn.running_var + bn.eps).sqrt()
return kernel * ((gamma / std).reshape(-1, 1, 1, 1)), bn.bias - bn.running_mean * gamma / std
class ConvBN(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size,
stride=1, padding=0, dilation=1, groups=1, deploy=False, nonlinear=None):
super().__init__()
if nonlinear is None:
self.nonlinear = nn.Identity()
else:
self.nonlinear = nonlinear
if deploy:
self.conv = nn.Conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size,
stride=stride, padding=padding, dilation=dilation, groups=groups, bias=True)
else:
self.conv = nn.Conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size,
stride=stride, padding=padding, dilation=dilation, groups=groups, bias=False)
self.bn = nn.BatchNorm2d(num_features=out_channels)
def forward(self, x):
if hasattr(self, 'bn'):
return self.nonlinear(self.bn(self.conv(x)))
else:
return self.nonlinear(self.conv(x))
def switch_to_deploy(self):
kernel, bias = transI_fusebn(self.conv.weight, self.bn)
conv = nn.Conv2d(in_channels=self.conv.in_channels, out_channels=self.conv.out_channels, kernel_size=self.conv.kernel_size,
stride=self.conv.stride, padding=self.conv.padding, dilation=self.conv.dilation, groups=self.conv.groups, bias=True)
conv.weight.data = kernel
conv.bias.data = bias
for para in self.parameters():
para.detach_()
self.__delattr__('conv')
self.__delattr__('bn')
self.conv = conv
| |
244902
|
# COCO 2017 dataset http://cocodataset.org
# download command/URL (optional)
download: bash ./scripts/get_coco.sh
# train and val data as 1) directory: path/images/, 2) file: path/images.txt, or 3) list: [path1/images/, path2/images/]
train: ./coco/train2017.txt # 118287 images
val: ./coco/val2017.txt # 5000 images
test: ./coco/test-dev2017.txt # 20288 of 40670 images, submit to https://competitions.codalab.org/competitions/20794
# number of classes
nc: 80
# class names
names: [ 'person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', 'truck', 'boat', 'traffic light',
'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow',
'elephant', 'bear', 'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie', 'suitcase', 'frisbee',
'skis', 'snowboard', 'sports ball', 'kite', 'baseball bat', 'baseball glove', 'skateboard', 'surfboard',
'tennis racket', 'bottle', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple',
'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair', 'couch',
'potted plant', 'bed', 'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone',
'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors', 'teddy bear',
'hair drier', 'toothbrush' ]
| |
244903
|
lr0: 0.01 # initial learning rate (SGD=1E-2, Adam=1E-3)
lrf: 0.1 # final OneCycleLR learning rate (lr0 * lrf)
momentum: 0.937 # SGD momentum/Adam beta1
weight_decay: 0.0005 # optimizer weight decay 5e-4
warmup_epochs: 3.0 # warmup epochs (fractions ok)
warmup_momentum: 0.8 # warmup initial momentum
warmup_bias_lr: 0.1 # warmup initial bias lr
box: 0.05 # box loss gain
cls: 0.3 # cls loss gain
cls_pw: 1.0 # cls BCELoss positive_weight
obj: 0.7 # obj loss gain (scale with pixels)
obj_pw: 1.0 # obj BCELoss positive_weight
iou_t: 0.20 # IoU training threshold
anchor_t: 4.0 # anchor-multiple threshold
# anchors: 3 # anchors per output layer (0 to ignore)
fl_gamma: 0.0 # focal loss gamma (efficientDet default gamma=1.5)
hsv_h: 0.015 # image HSV-Hue augmentation (fraction)
hsv_s: 0.7 # image HSV-Saturation augmentation (fraction)
hsv_v: 0.4 # image HSV-Value augmentation (fraction)
degrees: 0.0 # image rotation (+/- deg)
translate: 0.2 # image translation (+/- fraction)
scale: 0.9 # image scale (+/- gain)
shear: 0.0 # image shear (+/- deg)
perspective: 0.0 # image perspective (+/- fraction), range 0-0.001
flipud: 0.0 # image flip up-down (probability)
fliplr: 0.5 # image flip left-right (probability)
mosaic: 1.0 # image mosaic (probability)
mixup: 0.15 # image mixup (probability)
copy_paste: 0.0 # image copy paste (probability)
paste_in: 0.15 # image copy paste (probability), use 0 for faster training
loss_ota: 1 # use ComputeLossOTA, use 0 for faster training
| |
244904
|
lr0: 0.01 # initial learning rate (SGD=1E-2, Adam=1E-3)
lrf: 0.1 # final OneCycleLR learning rate (lr0 * lrf)
momentum: 0.937 # SGD momentum/Adam beta1
weight_decay: 0.0005 # optimizer weight decay 5e-4
warmup_epochs: 3.0 # warmup epochs (fractions ok)
warmup_momentum: 0.8 # warmup initial momentum
warmup_bias_lr: 0.1 # warmup initial bias lr
box: 0.05 # box loss gain
cls: 0.3 # cls loss gain
cls_pw: 1.0 # cls BCELoss positive_weight
obj: 0.7 # obj loss gain (scale with pixels)
obj_pw: 1.0 # obj BCELoss positive_weight
iou_t: 0.20 # IoU training threshold
anchor_t: 4.0 # anchor-multiple threshold
# anchors: 3 # anchors per output layer (0 to ignore)
fl_gamma: 0.0 # focal loss gamma (efficientDet default gamma=1.5)
hsv_h: 0.015 # image HSV-Hue augmentation (fraction)
hsv_s: 0.7 # image HSV-Saturation augmentation (fraction)
hsv_v: 0.4 # image HSV-Value augmentation (fraction)
degrees: 0.0 # image rotation (+/- deg)
translate: 0.2 # image translation (+/- fraction)
scale: 0.5 # image scale (+/- gain)
shear: 0.0 # image shear (+/- deg)
perspective: 0.0 # image perspective (+/- fraction), range 0-0.001
flipud: 0.0 # image flip up-down (probability)
fliplr: 0.5 # image flip left-right (probability)
mosaic: 1.0 # image mosaic (probability)
mixup: 0.0 # image mixup (probability)
copy_paste: 0.0 # image copy paste (probability)
paste_in: 0.0 # image copy paste (probability), use 0 for faster training
loss_ota: 1 # use ComputeLossOTA, use 0 for faster training
| |
244905
|
lr0: 0.01 # initial learning rate (SGD=1E-2, Adam=1E-3)
lrf: 0.01 # final OneCycleLR learning rate (lr0 * lrf)
momentum: 0.937 # SGD momentum/Adam beta1
weight_decay: 0.0005 # optimizer weight decay 5e-4
warmup_epochs: 3.0 # warmup epochs (fractions ok)
warmup_momentum: 0.8 # warmup initial momentum
warmup_bias_lr: 0.1 # warmup initial bias lr
box: 0.05 # box loss gain
cls: 0.5 # cls loss gain
cls_pw: 1.0 # cls BCELoss positive_weight
obj: 1.0 # obj loss gain (scale with pixels)
obj_pw: 1.0 # obj BCELoss positive_weight
iou_t: 0.20 # IoU training threshold
anchor_t: 4.0 # anchor-multiple threshold
# anchors: 3 # anchors per output layer (0 to ignore)
fl_gamma: 0.0 # focal loss gamma (efficientDet default gamma=1.5)
hsv_h: 0.015 # image HSV-Hue augmentation (fraction)
hsv_s: 0.7 # image HSV-Saturation augmentation (fraction)
hsv_v: 0.4 # image HSV-Value augmentation (fraction)
degrees: 0.0 # image rotation (+/- deg)
translate: 0.1 # image translation (+/- fraction)
scale: 0.5 # image scale (+/- gain)
shear: 0.0 # image shear (+/- deg)
perspective: 0.0 # image perspective (+/- fraction), range 0-0.001
flipud: 0.0 # image flip up-down (probability)
fliplr: 0.5 # image flip left-right (probability)
mosaic: 1.0 # image mosaic (probability)
mixup: 0.05 # image mixup (probability)
copy_paste: 0.0 # image copy paste (probability)
paste_in: 0.05 # image copy paste (probability), use 0 for faster training
loss_ota: 1 # use ComputeLossOTA, use 0 for faster training
| |
244906
|
lr0: 0.01 # initial learning rate (SGD=1E-2, Adam=1E-3)
lrf: 0.2 # final OneCycleLR learning rate (lr0 * lrf)
momentum: 0.937 # SGD momentum/Adam beta1
weight_decay: 0.0005 # optimizer weight decay 5e-4
warmup_epochs: 3.0 # warmup epochs (fractions ok)
warmup_momentum: 0.8 # warmup initial momentum
warmup_bias_lr: 0.1 # warmup initial bias lr
box: 0.05 # box loss gain
cls: 0.3 # cls loss gain
cls_pw: 1.0 # cls BCELoss positive_weight
obj: 0.7 # obj loss gain (scale with pixels)
obj_pw: 1.0 # obj BCELoss positive_weight
iou_t: 0.20 # IoU training threshold
anchor_t: 4.0 # anchor-multiple threshold
# anchors: 3 # anchors per output layer (0 to ignore)
fl_gamma: 0.0 # focal loss gamma (efficientDet default gamma=1.5)
hsv_h: 0.015 # image HSV-Hue augmentation (fraction)
hsv_s: 0.7 # image HSV-Saturation augmentation (fraction)
hsv_v: 0.4 # image HSV-Value augmentation (fraction)
degrees: 0.0 # image rotation (+/- deg)
translate: 0.2 # image translation (+/- fraction)
scale: 0.9 # image scale (+/- gain)
shear: 0.0 # image shear (+/- deg)
perspective: 0.0 # image perspective (+/- fraction), range 0-0.001
flipud: 0.0 # image flip up-down (probability)
fliplr: 0.5 # image flip left-right (probability)
mosaic: 1.0 # image mosaic (probability)
mixup: 0.15 # image mixup (probability)
copy_paste: 0.0 # image copy paste (probability)
paste_in: 0.15 # image copy paste (probability), use 0 for faster training
loss_ota: 1 # use ComputeLossOTA, use 0 for faster training
| |
245260
|
#!/usr/bin/env python
'''
face detection using haar cascades
USAGE:
facedetect.py [--cascade <cascade_fn>] [--nested-cascade <cascade_fn>] [<video_source>]
'''
# Python 2/3 compatibility
from __future__ import print_function
import numpy as np
import cv2 as cv
# local modules
from video import create_capture
from common import clock, draw_str
def detect(img, cascade):
rects = cascade.detectMultiScale(img, scaleFactor=1.3, minNeighbors=4, minSize=(30, 30),
flags=cv.CASCADE_SCALE_IMAGE)
if len(rects) == 0:
return []
rects[:,2:] += rects[:,:2]
return rects
def draw_rects(img, rects, color):
for x1, y1, x2, y2 in rects:
cv.rectangle(img, (x1, y1), (x2, y2), color, 2)
def main():
import sys, getopt
args, video_src = getopt.getopt(sys.argv[1:], '', ['cascade=', 'nested-cascade='])
try:
video_src = video_src[0]
except:
video_src = 0
args = dict(args)
cascade_fn = args.get('--cascade', "haarcascades/haarcascade_frontalface_alt.xml")
nested_fn = args.get('--nested-cascade', "haarcascades/haarcascade_eye.xml")
cascade = cv.CascadeClassifier(cv.samples.findFile(cascade_fn))
nested = cv.CascadeClassifier(cv.samples.findFile(nested_fn))
cam = create_capture(video_src, fallback='synth:bg={}:noise=0.05'.format(cv.samples.findFile('lena.jpg')))
while True:
_ret, img = cam.read()
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
gray = cv.equalizeHist(gray)
t = clock()
rects = detect(gray, cascade)
vis = img.copy()
draw_rects(vis, rects, (0, 255, 0))
if not nested.empty():
for x1, y1, x2, y2 in rects:
roi = gray[y1:y2, x1:x2]
vis_roi = vis[y1:y2, x1:x2]
subrects = detect(roi.copy(), nested)
draw_rects(vis_roi, subrects, (255, 0, 0))
dt = clock() - t
draw_str(vis, (20, 20), 'time: %.1f ms' % (dt*1000))
cv.imshow('facedetect', vis)
if cv.waitKey(5) == 27:
break
print('Done')
if __name__ == '__main__':
print(__doc__)
main()
cv.destroyAllWindows()
| |
245267
|
#!/usr/bin/env python
'''
VideoCapture sample showcasing some features of the Video4Linux2 backend
Sample shows how VideoCapture class can be used to control parameters
of a webcam such as focus or framerate.
Also the sample provides an example how to access raw images delivered
by the hardware to get a grayscale image in a very efficient fashion.
Keys:
ESC - exit
g - toggle optimized grayscale conversion
'''
# Python 2/3 compatibility
from __future__ import print_function
import numpy as np
import cv2 as cv
def main():
def decode_fourcc(v):
v = int(v)
return "".join([chr((v >> 8 * i) & 0xFF) for i in range(4)])
font = cv.FONT_HERSHEY_SIMPLEX
color = (0, 255, 0)
cap = cv.VideoCapture(0)
cap.set(cv.CAP_PROP_AUTOFOCUS, 0) # Known bug: https://github.com/opencv/opencv/pull/5474
cv.namedWindow("Video")
convert_rgb = True
fps = int(cap.get(cv.CAP_PROP_FPS))
focus = int(min(cap.get(cv.CAP_PROP_FOCUS) * 100, 2**31-1)) # ceil focus to C_LONG as Python3 int can go to +inf
cv.createTrackbar("FPS", "Video", fps, 30, lambda v: cap.set(cv.CAP_PROP_FPS, v))
cv.createTrackbar("Focus", "Video", focus, 100, lambda v: cap.set(cv.CAP_PROP_FOCUS, v / 100))
while True:
_status, img = cap.read()
fourcc = decode_fourcc(cap.get(cv.CAP_PROP_FOURCC))
fps = cap.get(cv.CAP_PROP_FPS)
if not bool(cap.get(cv.CAP_PROP_CONVERT_RGB)):
if fourcc == "MJPG":
img = cv.imdecode(img, cv.IMREAD_GRAYSCALE)
elif fourcc == "YUYV":
img = cv.cvtColor(img, cv.COLOR_YUV2GRAY_YUYV)
else:
print("unsupported format")
break
cv.putText(img, "Mode: {}".format(fourcc), (15, 40), font, 1.0, color)
cv.putText(img, "FPS: {}".format(fps), (15, 80), font, 1.0, color)
cv.imshow("Video", img)
k = cv.waitKey(1)
if k == 27:
break
elif k == ord('g'):
convert_rgb = not convert_rgb
cap.set(cv.CAP_PROP_CONVERT_RGB, 1 if convert_rgb else 0)
print('Done')
if __name__ == '__main__':
print(__doc__)
main()
cv.destroyAllWindows()
| |
245284
|
#!/usr/bin/env python
'''
MSER detector demo
==================
Usage:
------
mser.py [<video source>]
Keys:
-----
ESC - exit
'''
# Python 2/3 compatibility
from __future__ import print_function
import numpy as np
import cv2 as cv
import video
import sys
def main():
try:
video_src = sys.argv[1]
except:
video_src = 0
cam = video.create_capture(video_src)
mser = cv.MSER_create()
while True:
ret, img = cam.read()
if ret == 0:
break
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
vis = img.copy()
regions, _ = mser.detectRegions(gray)
hulls = [cv.convexHull(p.reshape(-1, 1, 2)) for p in regions]
cv.polylines(vis, hulls, 1, (0, 255, 0))
cv.imshow('img', vis)
if cv.waitKey(5) == 27:
break
print('Done')
if __name__ == '__main__':
print(__doc__)
main()
cv.destroyAllWindows()
| |
245304
|
#!/usr/bin/env python
'''
Multithreaded video processing sample.
Usage:
video_threaded.py {<video device number>|<video file name>}
Shows how python threading capabilities can be used
to organize parallel captured frame processing pipeline
for smoother playback.
Keyboard shortcuts:
ESC - exit
space - switch between multi and single threaded processing
'''
# Python 2/3 compatibility
from __future__ import print_function
import numpy as np
import cv2 as cv
from multiprocessing.pool import ThreadPool
from collections import deque
from common import clock, draw_str, StatValue
import video
class DummyTask:
def __init__(self, data):
self.data = data
def ready(self):
return True
def get(self):
return self.data
def main():
import sys
try:
fn = sys.argv[1]
except:
fn = 0
cap = video.create_capture(fn)
def process_frame(frame, t0):
# some intensive computation...
frame = cv.medianBlur(frame, 19)
frame = cv.medianBlur(frame, 19)
return frame, t0
threadn = cv.getNumberOfCPUs()
pool = ThreadPool(processes = threadn)
pending = deque()
threaded_mode = True
latency = StatValue()
frame_interval = StatValue()
last_frame_time = clock()
while True:
while len(pending) > 0 and pending[0].ready():
res, t0 = pending.popleft().get()
latency.update(clock() - t0)
draw_str(res, (20, 20), "threaded : " + str(threaded_mode))
draw_str(res, (20, 40), "latency : %.1f ms" % (latency.value*1000))
draw_str(res, (20, 60), "frame interval : %.1f ms" % (frame_interval.value*1000))
cv.imshow('threaded video', res)
if len(pending) < threadn:
_ret, frame = cap.read()
t = clock()
frame_interval.update(t - last_frame_time)
last_frame_time = t
if threaded_mode:
task = pool.apply_async(process_frame, (frame.copy(), t))
else:
task = DummyTask(process_frame(frame, t))
pending.append(task)
ch = cv.waitKey(1)
if ch == ord(' '):
threaded_mode = not threaded_mode
if ch == 27:
break
print('Done')
if __name__ == '__main__':
print(__doc__)
main()
cv.destroyAllWindows()
| |
245332
|
if __name__ == '__main__':
import sys
import getopt
print(__doc__)
args, sources = getopt.getopt(sys.argv[1:], '', 'shotdir=')
args = dict(args)
shotdir = args.get('--shotdir', '.')
if len(sources) == 0:
sources = [ 0 ]
caps = list(map(create_capture, sources))
shot_idx = 0
while True:
imgs = []
for i, cap in enumerate(caps):
ret, img = cap.read()
imgs.append(img)
cv.imshow('capture %d' % i, img)
ch = cv.waitKey(1)
if ch == 27:
break
if ch == ord(' '):
for i, img in enumerate(imgs):
fn = '%s/shot_%d_%03d.bmp' % (shotdir, i, shot_idx)
cv.imwrite(fn, img)
print(fn, 'saved')
shot_idx += 1
cv.destroyAllWindows()
| |
245338
|
#!/usr/bin/env python
'''
Video histogram sample to show live histogram of video
Keys:
ESC - exit
'''
# Python 2/3 compatibility
from __future__ import print_function
import numpy as np
import cv2 as cv
# built-in modules
import sys
# local modules
import video
class App():
def set_scale(self, val):
self.hist_scale = val
def run(self):
hsv_map = np.zeros((180, 256, 3), np.uint8)
h, s = np.indices(hsv_map.shape[:2])
hsv_map[:,:,0] = h
hsv_map[:,:,1] = s
hsv_map[:,:,2] = 255
hsv_map = cv.cvtColor(hsv_map, cv.COLOR_HSV2BGR)
cv.imshow('hsv_map', hsv_map)
cv.namedWindow('hist', 0)
self.hist_scale = 10
cv.createTrackbar('scale', 'hist', self.hist_scale, 32, self.set_scale)
try:
fn = sys.argv[1]
except:
fn = 0
cam = video.create_capture(fn, fallback='synth:bg=baboon.jpg:class=chess:noise=0.05')
while True:
_flag, frame = cam.read()
cv.imshow('camera', frame)
small = cv.pyrDown(frame)
hsv = cv.cvtColor(small, cv.COLOR_BGR2HSV)
dark = hsv[...,2] < 32
hsv[dark] = 0
h = cv.calcHist([hsv], [0, 1], None, [180, 256], [0, 180, 0, 256])
h = np.clip(h*0.005*self.hist_scale, 0, 1)
vis = hsv_map*h[:,:,np.newaxis] / 255.0
cv.imshow('hist', vis)
ch = cv.waitKey(1)
if ch == 27:
break
print('Done')
if __name__ == '__main__':
print(__doc__)
App().run()
cv.destroyAllWindows()
| |
245340
|
import numpy as np
import cv2 as cv
import argparse
parser = argparse.ArgumentParser(description='This sample demonstrates the camshift algorithm. \
The example file can be downloaded from: \
https://www.bogotobogo.com/python/OpenCV_Python/images/mean_shift_tracking/slow_traffic_small.mp4')
parser.add_argument('image', type=str, help='path to image file')
args = parser.parse_args()
cap = cv.VideoCapture(args.image)
# take first frame of the video
ret,frame = cap.read()
# setup initial location of window
x, y, w, h = 300, 200, 100, 50 # simply hardcoded the values
track_window = (x, y, w, h)
# set up the ROI for tracking
roi = frame[y:y+h, x:x+w]
hsv_roi = cv.cvtColor(roi, cv.COLOR_BGR2HSV)
mask = cv.inRange(hsv_roi, np.array((0., 60.,32.)), np.array((180.,255.,255.)))
roi_hist = cv.calcHist([hsv_roi],[0],mask,[180],[0,180])
cv.normalize(roi_hist,roi_hist,0,255,cv.NORM_MINMAX)
# Setup the termination criteria, either 10 iteration or move by at least 1 pt
term_crit = ( cv.TERM_CRITERIA_EPS | cv.TERM_CRITERIA_COUNT, 10, 1 )
while(1):
ret, frame = cap.read()
if ret == True:
hsv = cv.cvtColor(frame, cv.COLOR_BGR2HSV)
dst = cv.calcBackProject([hsv],[0],roi_hist,[0,180],1)
# apply camshift to get the new location
ret, track_window = cv.CamShift(dst, track_window, term_crit)
# Draw it on image
pts = cv.boxPoints(ret)
pts = np.int0(pts)
img2 = cv.polylines(frame,[pts],True, 255,2)
cv.imshow('img2',img2)
k = cv.waitKey(30) & 0xff
if k == 27:
break
else:
break
| |
245341
|
import numpy as np
import cv2 as cv
import argparse
parser = argparse.ArgumentParser(description='This sample demonstrates the meanshift algorithm. \
The example file can be downloaded from: \
https://www.bogotobogo.com/python/OpenCV_Python/images/mean_shift_tracking/slow_traffic_small.mp4')
parser.add_argument('image', type=str, help='path to image file')
args = parser.parse_args()
cap = cv.VideoCapture(args.image)
# take first frame of the video
ret,frame = cap.read()
# setup initial location of window
x, y, w, h = 300, 200, 100, 50 # simply hardcoded the values
track_window = (x, y, w, h)
# set up the ROI for tracking
roi = frame[y:y+h, x:x+w]
hsv_roi = cv.cvtColor(roi, cv.COLOR_BGR2HSV)
mask = cv.inRange(hsv_roi, np.array((0., 60.,32.)), np.array((180.,255.,255.)))
roi_hist = cv.calcHist([hsv_roi],[0],mask,[180],[0,180])
cv.normalize(roi_hist,roi_hist,0,255,cv.NORM_MINMAX)
# Setup the termination criteria, either 10 iteration or move by at least 1 pt
term_crit = ( cv.TERM_CRITERIA_EPS | cv.TERM_CRITERIA_COUNT, 10, 1 )
while(1):
ret, frame = cap.read()
if ret == True:
hsv = cv.cvtColor(frame, cv.COLOR_BGR2HSV)
dst = cv.calcBackProject([hsv],[0],roi_hist,[0,180],1)
# apply meanshift to get the new location
ret, track_window = cv.meanShift(dst, track_window, term_crit)
# Draw it on image
x,y,w,h = track_window
img2 = cv.rectangle(frame, (x,y), (x+w,y+h), 255,2)
cv.imshow('img2',img2)
k = cv.waitKey(30) & 0xff
if k == 27:
break
else:
break
| |
245365
|
from __future__ import print_function
import cv2 as cv
import argparse
max_value = 255
max_value_H = 360//2
low_H = 0
low_S = 0
low_V = 0
high_H = max_value_H
high_S = max_value
high_V = max_value
window_capture_name = 'Video Capture'
window_detection_name = 'Object Detection'
low_H_name = 'Low H'
low_S_name = 'Low S'
low_V_name = 'Low V'
high_H_name = 'High H'
high_S_name = 'High S'
high_V_name = 'High V'
## [low]
def on_low_H_thresh_trackbar(val):
global low_H
global high_H
low_H = val
low_H = min(high_H-1, low_H)
cv.setTrackbarPos(low_H_name, window_detection_name, low_H)
## [low]
## [high]
def on_high_H_thresh_trackbar(val):
global low_H
global high_H
high_H = val
high_H = max(high_H, low_H+1)
cv.setTrackbarPos(high_H_name, window_detection_name, high_H)
## [high]
def on_low_S_thresh_trackbar(val):
global low_S
global high_S
low_S = val
low_S = min(high_S-1, low_S)
cv.setTrackbarPos(low_S_name, window_detection_name, low_S)
def on_high_S_thresh_trackbar(val):
global low_S
global high_S
high_S = val
high_S = max(high_S, low_S+1)
cv.setTrackbarPos(high_S_name, window_detection_name, high_S)
def on_low_V_thresh_trackbar(val):
global low_V
global high_V
low_V = val
low_V = min(high_V-1, low_V)
cv.setTrackbarPos(low_V_name, window_detection_name, low_V)
def on_high_V_thresh_trackbar(val):
global low_V
global high_V
high_V = val
high_V = max(high_V, low_V+1)
cv.setTrackbarPos(high_V_name, window_detection_name, high_V)
parser = argparse.ArgumentParser(description='Code for Thresholding Operations using inRange tutorial.')
parser.add_argument('--camera', help='Camera divide number.', default=0, type=int)
args = parser.parse_args()
## [cap]
cap = cv.VideoCapture(args.camera)
## [cap]
## [window]
cv.namedWindow(window_capture_name)
cv.namedWindow(window_detection_name)
## [window]
## [trackbar]
cv.createTrackbar(low_H_name, window_detection_name , low_H, max_value_H, on_low_H_thresh_trackbar)
cv.createTrackbar(high_H_name, window_detection_name , high_H, max_value_H, on_high_H_thresh_trackbar)
cv.createTrackbar(low_S_name, window_detection_name , low_S, max_value, on_low_S_thresh_trackbar)
cv.createTrackbar(high_S_name, window_detection_name , high_S, max_value, on_high_S_thresh_trackbar)
cv.createTrackbar(low_V_name, window_detection_name , low_V, max_value, on_low_V_thresh_trackbar)
cv.createTrackbar(high_V_name, window_detection_name , high_V, max_value, on_high_V_thresh_trackbar)
## [trackbar]
while True:
## [while]
ret, frame = cap.read()
if frame is None:
break
frame_HSV = cv.cvtColor(frame, cv.COLOR_BGR2HSV)
frame_threshold = cv.inRange(frame_HSV, (low_H, low_S, low_V), (high_H, high_S, high_V))
## [while]
## [show]
cv.imshow(window_capture_name, frame)
cv.imshow(window_detection_name, frame_threshold)
## [show]
key = cv.waitKey(30)
if key == ord('q') or key == 27:
break
| |
245376
|
from __future__ import print_function
import cv2 as cv
import argparse
def detectAndDisplay(frame):
frame_gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
frame_gray = cv.equalizeHist(frame_gray)
#-- Detect faces
faces = face_cascade.detectMultiScale(frame_gray)
for (x,y,w,h) in faces:
center = (x + w//2, y + h//2)
frame = cv.ellipse(frame, center, (w//2, h//2), 0, 0, 360, (255, 0, 255), 4)
faceROI = frame_gray[y:y+h,x:x+w]
#-- In each face, detect eyes
eyes = eyes_cascade.detectMultiScale(faceROI)
for (x2,y2,w2,h2) in eyes:
eye_center = (x + x2 + w2//2, y + y2 + h2//2)
radius = int(round((w2 + h2)*0.25))
frame = cv.circle(frame, eye_center, radius, (255, 0, 0 ), 4)
cv.imshow('Capture - Face detection', frame)
parser = argparse.ArgumentParser(description='Code for Cascade Classifier tutorial.')
parser.add_argument('--face_cascade', help='Path to face cascade.', default='data/haarcascades/haarcascade_frontalface_alt.xml')
parser.add_argument('--eyes_cascade', help='Path to eyes cascade.', default='data/haarcascades/haarcascade_eye_tree_eyeglasses.xml')
parser.add_argument('--camera', help='Camera divide number.', type=int, default=0)
args = parser.parse_args()
face_cascade_name = args.face_cascade
eyes_cascade_name = args.eyes_cascade
face_cascade = cv.CascadeClassifier()
eyes_cascade = cv.CascadeClassifier()
#-- 1. Load the cascades
if not face_cascade.load(cv.samples.findFile(face_cascade_name)):
print('--(!)Error loading face cascade')
exit(0)
if not eyes_cascade.load(cv.samples.findFile(eyes_cascade_name)):
print('--(!)Error loading eyes cascade')
exit(0)
camera_device = args.camera
#-- 2. Read the video stream
cap = cv.VideoCapture(camera_device)
if not cap.isOpened:
print('--(!)Error opening video capture')
exit(0)
while True:
ret, frame = cap.read()
if frame is None:
print('--(!) No captured frame -- Break!')
break
detectAndDisplay(frame)
if cv.waitKey(10) == 27:
break
| |
245392
|
from __future__ import print_function
import cv2 as cv
import numpy as np
import argparse
import random as rng
rng.seed(12345)
def thresh_callback(val):
threshold = val
## [Canny]
# Detect edges using Canny
canny_output = cv.Canny(src_gray, threshold, threshold * 2)
## [Canny]
## [findContours]
# Find contours
contours, _ = cv.findContours(canny_output, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)
## [findContours]
## [allthework]
# Approximate contours to polygons + get bounding rects and circles
contours_poly = [None]*len(contours)
boundRect = [None]*len(contours)
centers = [None]*len(contours)
radius = [None]*len(contours)
for i, c in enumerate(contours):
contours_poly[i] = cv.approxPolyDP(c, 3, True)
boundRect[i] = cv.boundingRect(contours_poly[i])
centers[i], radius[i] = cv.minEnclosingCircle(contours_poly[i])
## [allthework]
## [zeroMat]
drawing = np.zeros((canny_output.shape[0], canny_output.shape[1], 3), dtype=np.uint8)
## [zeroMat]
## [forContour]
# Draw polygonal contour + bonding rects + circles
for i in range(len(contours)):
color = (rng.randint(0,256), rng.randint(0,256), rng.randint(0,256))
cv.drawContours(drawing, contours_poly, i, color)
cv.rectangle(drawing, (int(boundRect[i][0]), int(boundRect[i][1])), \
(int(boundRect[i][0]+boundRect[i][2]), int(boundRect[i][1]+boundRect[i][3])), color, 2)
cv.circle(drawing, (int(centers[i][0]), int(centers[i][1])), int(radius[i]), color, 2)
## [forContour]
## [showDrawings]
# Show in a window
cv.imshow('Contours', drawing)
## [showDrawings]
## [setup]
# Load source image
parser = argparse.ArgumentParser(description='Code for Creating Bounding boxes and circles for contours tutorial.')
parser.add_argument('--input', help='Path to input image.', default='stuff.jpg')
args = parser.parse_args()
src = cv.imread(cv.samples.findFile(args.input))
if src is None:
print('Could not open or find the image:', args.input)
exit(0)
# Convert image to gray and blur it
src_gray = cv.cvtColor(src, cv.COLOR_BGR2GRAY)
src_gray = cv.blur(src_gray, (3,3))
## [setup]
## [createWindow]
# Create Window
source_window = 'Source'
cv.namedWindow(source_window)
cv.imshow(source_window, src)
## [createWindow]
## [trackbar]
max_thresh = 255
thresh = 100 # initial threshold
cv.createTrackbar('Canny thresh:', source_window, thresh, max_thresh, thresh_callback)
thresh_callback(thresh)
## [trackbar]
cv.waitKey()
| |
245826
|
package org.opencv.samples.opencv_mobilenet;
/*
// snippet was added for Android tutorial
//! [mobilenet_tutorial_package]
package com.example.myapplication;
//! [mobilenet_tutorial_package]
*/
//! [mobilenet_tutorial]
import android.content.Context;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import org.opencv.android.CameraActivity;
import org.opencv.android.CameraBridgeViewBase;
import org.opencv.android.CameraBridgeViewBase.CvCameraViewFrame;
import org.opencv.android.CameraBridgeViewBase.CvCameraViewListener2;
import org.opencv.android.OpenCVLoader;
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.MatOfByte;
import org.opencv.core.Point;
import org.opencv.core.Scalar;
import org.opencv.core.Size;
import org.opencv.dnn.Net;
import org.opencv.dnn.Dnn;
import org.opencv.imgproc.Imgproc;
import java.io.InputStream;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
public class MainActivity extends CameraActivity implements CvCameraViewListener2 {
@Override
public void onResume() {
super.onResume();
if (mOpenCvCameraView != null)
mOpenCvCameraView.enableView();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (OpenCVLoader.initLocal()) {
Log.i(TAG, "OpenCV loaded successfully");
} else {
Log.e(TAG, "OpenCV initialization failed!");
(Toast.makeText(this, "OpenCV initialization failed!", Toast.LENGTH_LONG)).show();
return;
}
//! [init_model_from_memory]
mModelBuffer = loadFileFromResource(R.raw.mobilenet_iter_73000);
mConfigBuffer = loadFileFromResource(R.raw.deploy);
if (mModelBuffer == null || mConfigBuffer == null) {
Log.e(TAG, "Failed to load model from resources");
} else
Log.i(TAG, "Model files loaded successfully");
net = Dnn.readNet("caffe", mModelBuffer, mConfigBuffer);
Log.i(TAG, "Network loaded successfully");
//! [init_model_from_memory]
setContentView(R.layout.activity_main);
// Set up camera listener.
mOpenCvCameraView = (CameraBridgeViewBase)findViewById(R.id.CameraView);
mOpenCvCameraView.setVisibility(CameraBridgeViewBase.VISIBLE);
mOpenCvCameraView.setCvCameraViewListener(this);
}
@Override
public void onPause()
{
super.onPause();
if (mOpenCvCameraView != null)
mOpenCvCameraView.disableView();
}
@Override
protected List<? extends CameraBridgeViewBase> getCameraViewList() {
return Collections.singletonList(mOpenCvCameraView);
}
public void onDestroy() {
super.onDestroy();
if (mOpenCvCameraView != null)
mOpenCvCameraView.disableView();
mModelBuffer.release();
mConfigBuffer.release();
}
// Load a network.
public void onCameraViewStarted(int width, int height) {
}
public Mat onCameraFrame(CvCameraViewFrame inputFrame) {
final int IN_WIDTH = 300;
final int IN_HEIGHT = 300;
final float WH_RATIO = (float)IN_WIDTH / IN_HEIGHT;
final double IN_SCALE_FACTOR = 0.007843;
final double MEAN_VAL = 127.5;
final double THRESHOLD = 0.2;
// Get a new frame
Log.d(TAG, "handle new frame!");
Mat frame = inputFrame.rgba();
Imgproc.cvtColor(frame, frame, Imgproc.COLOR_RGBA2RGB);
// Forward image through network.
//! [mobilenet_handle_frame]
Mat blob = Dnn.blobFromImage(frame, IN_SCALE_FACTOR,
new Size(IN_WIDTH, IN_HEIGHT),
new Scalar(MEAN_VAL, MEAN_VAL, MEAN_VAL), /*swapRB*/false, /*crop*/false);
net.setInput(blob);
Mat detections = net.forward();
int cols = frame.cols();
int rows = frame.rows();
detections = detections.reshape(1, (int)detections.total() / 7);
for (int i = 0; i < detections.rows(); ++i) {
double confidence = detections.get(i, 2)[0];
if (confidence > THRESHOLD) {
int classId = (int)detections.get(i, 1)[0];
int left = (int)(detections.get(i, 3)[0] * cols);
int top = (int)(detections.get(i, 4)[0] * rows);
int right = (int)(detections.get(i, 5)[0] * cols);
int bottom = (int)(detections.get(i, 6)[0] * rows);
// Draw rectangle around detected object.
Imgproc.rectangle(frame, new Point(left, top), new Point(right, bottom),
new Scalar(0, 255, 0));
String label = classNames[classId] + ": " + confidence;
int[] baseLine = new int[1];
Size labelSize = Imgproc.getTextSize(label, Imgproc.FONT_HERSHEY_SIMPLEX, 0.5, 1, baseLine);
// Draw background for label.
Imgproc.rectangle(frame, new Point(left, top - labelSize.height),
new Point(left + labelSize.width, top + baseLine[0]),
new Scalar(255, 255, 255), Imgproc.FILLED);
// Write class name and confidence.
Imgproc.putText(frame, label, new Point(left, top),
Imgproc.FONT_HERSHEY_SIMPLEX, 0.5, new Scalar(0, 0, 0));
}
}
//! [mobilenet_handle_frame]
return frame;
}
public void onCameraViewStopped() {}
//! [mobilenet_tutorial_resource]
private MatOfByte loadFileFromResource(int id) {
byte[] buffer;
try {
// load cascade file from application resources
InputStream is = getResources().openRawResource(id);
int size = is.available();
buffer = new byte[size];
int bytesRead = is.read(buffer);
is.close();
} catch (IOException e) {
e.printStackTrace();
Log.e(TAG, "Failed to ONNX model from resources! Exception thrown: " + e);
(Toast.makeText(this, "Failed to ONNX model from resources!", Toast.LENGTH_LONG)).show();
return null;
}
return new MatOfByte(buffer);
}
//! [mobilenet_tutorial_resource]
private static final String TAG = "OpenCV-MobileNet";
private static final String[] classNames = {"background",
"aeroplane", "bicycle", "bird", "boat",
"bottle", "bus", "car", "cat", "chair",
"cow", "diningtable", "dog", "horse",
"motorbike", "person", "pottedplant",
"sheep", "sofa", "train", "tvmonitor"};
private MatOfByte mConfigBuffer;
private MatOfByte mModelBuffer;
private Net net;
private CameraBridgeViewBase mOpenCvCameraView;
}
//! [mobilenet_tutorial]
| |
245846
|
import argparse
import cv2 as cv
import numpy as np
from common import *
def get_args_parser(func_args):
backends = (cv.dnn.DNN_BACKEND_DEFAULT, cv.dnn.DNN_BACKEND_HALIDE, cv.dnn.DNN_BACKEND_INFERENCE_ENGINE,
cv.dnn.DNN_BACKEND_OPENCV, cv.dnn.DNN_BACKEND_VKCOM, cv.dnn.DNN_BACKEND_CUDA)
targets = (cv.dnn.DNN_TARGET_CPU, cv.dnn.DNN_TARGET_OPENCL, cv.dnn.DNN_TARGET_OPENCL_FP16, cv.dnn.DNN_TARGET_MYRIAD,
cv.dnn.DNN_TARGET_HDDL, cv.dnn.DNN_TARGET_VULKAN, cv.dnn.DNN_TARGET_CUDA, cv.dnn.DNN_TARGET_CUDA_FP16)
parser = argparse.ArgumentParser(add_help=False)
parser.add_argument('--zoo', default=os.path.join(os.path.dirname(os.path.abspath(__file__)), 'models.yml'),
help='An optional path to file with preprocessing parameters.')
parser.add_argument('--input',
help='Path to input image or video file. Skip this argument to capture frames from a camera.')
parser.add_argument('--framework', choices=['caffe', 'tensorflow', 'torch', 'darknet'],
help='Optional name of an origin framework of the model. '
'Detect it automatically if it does not set.')
parser.add_argument('--std', nargs='*', type=float,
help='Preprocess input image by dividing on a standard deviation.')
parser.add_argument('--crop', type=bool, default=False,
help='Preprocess input image by dividing on a standard deviation.')
parser.add_argument('--initial_width', type=int,
help='Preprocess input image by initial resizing to a specific width.')
parser.add_argument('--initial_height', type=int,
help='Preprocess input image by initial resizing to a specific height.')
parser.add_argument('--backend', choices=backends, default=cv.dnn.DNN_BACKEND_DEFAULT, type=int,
help="Choose one of computation backends: "
"%d: automatically (by default), "
"%d: Halide language (http://halide-lang.org/), "
"%d: Intel's Deep Learning Inference Engine (https://software.intel.com/openvino-toolkit), "
"%d: OpenCV implementation, "
"%d: VKCOM, "
"%d: CUDA" % backends)
parser.add_argument('--target', choices=targets, default=cv.dnn.DNN_TARGET_CPU, type=int,
help='Choose one of target computation devices: '
'%d: CPU target (by default), '
'%d: OpenCL, '
'%d: OpenCL fp16 (half-float precision), '
'%d: NCS2 VPU, '
'%d: HDDL VPU, '
'%d: Vulkan, '
'%d: CUDA, '
'%d: CUDA fp16 (half-float preprocess)'% targets)
args, _ = parser.parse_known_args()
add_preproc_args(args.zoo, parser, 'classification')
parser = argparse.ArgumentParser(parents=[parser],
description='Use this script to run classification deep learning networks using OpenCV.',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
return parser.parse_args(func_args)
def main(func_args=None):
args = get_args_parser(func_args)
args.model = findFile(args.model)
args.config = findFile(args.config)
args.classes = findFile(args.classes)
# Load names of classes
classes = None
if args.classes:
with open(args.classes, 'rt') as f:
classes = f.read().rstrip('\n').split('\n')
# Load a network
net = cv.dnn.readNet(args.model, args.config, args.framework)
net.setPreferableBackend(args.backend)
net.setPreferableTarget(args.target)
winName = 'Deep learning image classification in OpenCV'
cv.namedWindow(winName, cv.WINDOW_NORMAL)
cap = cv.VideoCapture(args.input if args.input else 0)
while cv.waitKey(1) < 0:
hasFrame, frame = cap.read()
if not hasFrame:
cv.waitKey()
break
# Create a 4D blob from a frame.
inpWidth = args.width if args.width else frame.shape[1]
inpHeight = args.height if args.height else frame.shape[0]
if args.initial_width and args.initial_height:
frame = cv.resize(frame, (args.initial_width, args.initial_height))
blob = cv.dnn.blobFromImage(frame, args.scale, (inpWidth, inpHeight), args.mean, args.rgb, crop=args.crop)
if args.std:
blob[0] /= np.asarray(args.std, dtype=np.float32).reshape(3, 1, 1)
# Run a model
net.setInput(blob)
out = net.forward()
# Get a class with a highest score.
out = out.flatten()
classId = np.argmax(out)
confidence = out[classId]
# Put efficiency information.
t, _ = net.getPerfProfile()
label = 'Inference time: %.2f ms' % (t * 1000.0 / cv.getTickFrequency())
cv.putText(frame, label, (0, 15), cv.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0))
# Print predicted class.
label = '%s: %.4f' % (classes[classId] if classes else 'Class #%d' % classId, confidence)
cv.putText(frame, label, (0, 40), cv.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0))
cv.imshow(winName, frame)
if __name__ == "__main__":
main()
| |
245870
|
import cv2 as cv
import argparse
import numpy as np
parser = argparse.ArgumentParser(description=
'Use this script to run Mask-RCNN object detection and semantic '
'segmentation network from TensorFlow Object Detection API.')
parser.add_argument('--input', help='Path to input image or video file. Skip this argument to capture frames from a camera.')
parser.add_argument('--model', required=True, help='Path to a .pb file with weights.')
parser.add_argument('--config', required=True, help='Path to a .pxtxt file contains network configuration.')
parser.add_argument('--classes', help='Optional path to a text file with names of classes.')
parser.add_argument('--colors', help='Optional path to a text file with colors for an every class. '
'An every color is represented with three values from 0 to 255 in BGR channels order.')
parser.add_argument('--width', type=int, default=800,
help='Preprocess input image by resizing to a specific width.')
parser.add_argument('--height', type=int, default=800,
help='Preprocess input image by resizing to a specific height.')
parser.add_argument('--thr', type=float, default=0.5, help='Confidence threshold')
args = parser.parse_args()
np.random.seed(324)
# Load names of classes
classes = None
if args.classes:
with open(args.classes, 'rt') as f:
classes = f.read().rstrip('\n').split('\n')
# Load colors
colors = None
if args.colors:
with open(args.colors, 'rt') as f:
colors = [np.array(color.split(' '), np.uint8) for color in f.read().rstrip('\n').split('\n')]
legend = None
def showLegend(classes):
global legend
if not classes is None and legend is None:
blockHeight = 30
assert(len(classes) == len(colors))
legend = np.zeros((blockHeight * len(colors), 200, 3), np.uint8)
for i in range(len(classes)):
block = legend[i * blockHeight:(i + 1) * blockHeight]
block[:,:] = colors[i]
cv.putText(block, classes[i], (0, blockHeight//2), cv.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255))
cv.namedWindow('Legend', cv.WINDOW_NORMAL)
cv.imshow('Legend', legend)
classes = None
def drawBox(frame, classId, conf, left, top, right, bottom):
# Draw a bounding box.
cv.rectangle(frame, (left, top), (right, bottom), (0, 255, 0))
label = '%.2f' % conf
# Print a label of class.
if classes:
assert(classId < len(classes))
label = '%s: %s' % (classes[classId], label)
labelSize, baseLine = cv.getTextSize(label, cv.FONT_HERSHEY_SIMPLEX, 0.5, 1)
top = max(top, labelSize[1])
cv.rectangle(frame, (left, top - labelSize[1]), (left + labelSize[0], top + baseLine), (255, 255, 255), cv.FILLED)
cv.putText(frame, label, (left, top), cv.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0))
# Load a network
net = cv.dnn.readNet(cv.samples.findFile(args.model), cv.samples.findFile(args.config))
net.setPreferableBackend(cv.dnn.DNN_BACKEND_OPENCV)
winName = 'Mask-RCNN in OpenCV'
cv.namedWindow(winName, cv.WINDOW_NORMAL)
cap = cv.VideoCapture(cv.samples.findFileOrKeep(args.input) if args.input else 0)
legend = None
while cv.waitKey(1) < 0:
hasFrame, frame = cap.read()
if not hasFrame:
cv.waitKey()
break
frameH = frame.shape[0]
frameW = frame.shape[1]
# Create a 4D blob from a frame.
blob = cv.dnn.blobFromImage(frame, size=(args.width, args.height), swapRB=True, crop=False)
# Run a model
net.setInput(blob)
boxes, masks = net.forward(['detection_out_final', 'detection_masks'])
numClasses = masks.shape[1]
numDetections = boxes.shape[2]
# Draw segmentation
if not colors:
# Generate colors
colors = [np.array([0, 0, 0], np.uint8)]
for i in range(1, numClasses + 1):
colors.append((colors[i - 1] + np.random.randint(0, 256, [3], np.uint8)) / 2)
del colors[0]
boxesToDraw = []
for i in range(numDetections):
box = boxes[0, 0, i]
mask = masks[i]
score = box[2]
if score > args.thr:
classId = int(box[1])
left = int(frameW * box[3])
top = int(frameH * box[4])
right = int(frameW * box[5])
bottom = int(frameH * box[6])
left = max(0, min(left, frameW - 1))
top = max(0, min(top, frameH - 1))
right = max(0, min(right, frameW - 1))
bottom = max(0, min(bottom, frameH - 1))
boxesToDraw.append([frame, classId, score, left, top, right, bottom])
classMask = mask[classId]
classMask = cv.resize(classMask, (right - left + 1, bottom - top + 1))
mask = (classMask > 0.5)
roi = frame[top:bottom+1, left:right+1][mask]
frame[top:bottom+1, left:right+1][mask] = (0.7 * colors[classId] + 0.3 * roi).astype(np.uint8)
for box in boxesToDraw:
drawBox(*box)
# Put efficiency information.
t, _ = net.getPerfProfile()
label = 'Inference time: %.2f ms' % (t * 1000.0 / cv.getTickFrequency())
cv.putText(frame, label, (0, 15), cv.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0))
showLegend(classes)
cv.imshow(winName, frame)
| |
245876
|
%YAML 1.0
---
################################################################################
# Object detection models.
################################################################################
# OpenCV's face detection network
opencv_fd:
load_info:
url: "https://github.com/opencv/opencv_3rdparty/raw/dnn_samples_face_detector_20170830/res10_300x300_ssd_iter_140000.caffemodel"
sha1: "15aa726b4d46d9f023526d85537db81cbc8dd566"
model: "opencv_face_detector.caffemodel"
config: "opencv_face_detector.prototxt"
mean: [104, 177, 123]
scale: 1.0
width: 300
height: 300
rgb: false
sample: "object_detection"
# YOLOv8 object detection family from ultralytics (https://github.com/ultralytics/ultralytics)
# Might be used for all YOLOv8n YOLOv8s YOLOv8m YOLOv8l and YOLOv8x
yolov8x:
load_info:
url: "https://huggingface.co/cabelo/yolov8/resolve/main/yolov8x.onnx?download=true"
sha1: "462f15d668c046d38e27d3df01fe8142dd004cb4"
model: "yolov8x.onnx"
mean: 0.0
scale: 0.00392
width: 640
height: 640
rgb: true
classes: "object_detection_classes_yolo.txt"
background_label_id: 0
sample: "yolo_detector"
yolov8s:
load_info:
url: "https://github.com/CVHub520/X-AnyLabeling/releases/download/v0.1.0/yolov8s.onnx"
sha1: "82cd83984396fe929909ecb58212b0e86d0904b1"
model: "yolov8s.onnx"
mean: 0.0
scale: 0.00392
width: 640
height: 640
rgb: true
classes: "object_detection_classes_yolo.txt"
background_label_id: 0
sample: "yolo_detector"
yolov8n:
load_info:
url: "https://github.com/CVHub520/X-AnyLabeling/releases/download/v0.1.0/yolov8n.onnx"
sha1: "68f864475d06e2ec4037181052739f268eeac38d"
model: "yolov8n.onnx"
mean: 0.0
scale: 0.00392
width: 640
height: 640
rgb: true
classes: "object_detection_classes_yolo.txt"
background_label_id: 0
sample: "yolo_detector"
yolov8m:
load_info:
url: "https://github.com/CVHub520/X-AnyLabeling/releases/download/v0.1.0/yolov8m.onnx"
sha1: "656ffeb4f3b067bc30df956728b5f9c61a4cb090"
model: "yolov8m.onnx"
mean: 0.0
scale: 0.00392
width: 640
height: 640
rgb: true
classes: "object_detection_classes_yolo.txt"
background_label_id: 0
sample: "yolo_detector"
yolov8l:
load_info:
url: "https://github.com/CVHub520/X-AnyLabeling/releases/download/v0.1.0/yolov8l.onnx"
sha1: "462df53ca3a85d110bf6be7fc2e2bb1277124395"
model: "yolov8l.onnx"
mean: 0.0
scale: 0.00392
width: 640
height: 640
rgb: true
classes: "object_detection_classes_yolo.txt"
background_label_id: 0
sample: "yolo_detector"
# YOLOv5 object detection family from ultralytics (https://github.com/ultralytics/ultralytics)
# Might be used for all YOLOv5n YOLOv5s YOLOv5m YOLOv5l and YOLOv5x
yolov5l:
load_info:
url: "https://github.com/CVHub520/X-AnyLabeling/releases/download/v0.1.0/yolov5l.onnx"
sha1: "9de7e54c524b7fe7577bbd4cdbbdaed53375c8f1"
model: "yolov5l.onnx"
mean: 0.0
scale: 0.00392
width: 640
height: 640
rgb: true
classes: "object_detection_classes_yolo.txt"
background_label_id: 0
sample: "yolo_detector"
# YOLO4 object detection family from Darknet (https://github.com/AlexeyAB/darknet)
# YOLO object detection family from Darknet (https://pjreddie.com/darknet/yolo/)
# Might be used for all YOLOv2, TinyYolov2, YOLOv3, YOLOv4 and TinyYolov4
yolov4:
load_info:
url: "https://github.com/AlexeyAB/darknet/releases/download/darknet_yolo_v3_optimal/yolov4.weights"
sha1: "0143deb6c46fcc7f74dd35bf3c14edc3784e99ee"
model: "yolov4.weights"
config: "yolov4.cfg"
mean: [0, 0, 0]
scale: 0.00392
width: 416
height: 416
rgb: true
classes: "object_detection_classes_yolo.txt"
background_label_id: 0
sample: "object_detection"
yolov4-tiny:
load_info:
url: "https://github.com/AlexeyAB/darknet/releases/download/darknet_yolo_v4_pre/yolov4-tiny.weights"
sha1: "451caaab22fb9831aa1a5ee9b5ba74a35ffa5dcb"
model: "yolov4-tiny.weights"
config: "yolov4-tiny.cfg"
mean: [0, 0, 0]
scale: 0.00392
width: 416
height: 416
rgb: true
classes: "object_detection_classes_yolo.txt"
background_label_id: 0
sample: "object_detection"
yolov3:
load_info:
url: "https://pjreddie.com/media/files/yolov3.weights"
sha1: "520878f12e97cf820529daea502acca380f1cb8e"
model: "yolov3.weights"
config: "yolov3.cfg"
mean: [0, 0, 0]
scale: 0.00392
width: 416
height: 416
rgb: true
classes: "object_detection_classes_yolo.txt"
background_label_id: 0
sample: "object_detection"
tiny-yolo-voc:
load_info:
url: "https://pjreddie.com/media/files/yolov2-tiny-voc.weights"
sha1: "24b4bd049fc4fa5f5e95f684a8967e65c625dff9"
model: "tiny-yolo-voc.weights"
config: "tiny-yolo-voc.cfg"
mean: [0, 0, 0]
scale: 0.00392
width: 416
height: 416
rgb: true
classes: "object_detection_classes_pascal_voc.txt"
background_label_id: 0
sample: "object_detection"
| |
245880
|
import cv2 as cv
import argparse
import numpy as np
import sys
import copy
import time
from threading import Thread
if sys.version_info[0] == 2:
import Queue as queue
else:
import queue
from common import *
from tf_text_graph_common import readTextMessage
from tf_text_graph_ssd import createSSDGraph
from tf_text_graph_faster_rcnn import createFasterRCNNGraph
backends = (cv.dnn.DNN_BACKEND_DEFAULT, cv.dnn.DNN_BACKEND_HALIDE, cv.dnn.DNN_BACKEND_INFERENCE_ENGINE, cv.dnn.DNN_BACKEND_OPENCV,
cv.dnn.DNN_BACKEND_VKCOM, cv.dnn.DNN_BACKEND_CUDA)
targets = (cv.dnn.DNN_TARGET_CPU, cv.dnn.DNN_TARGET_OPENCL, cv.dnn.DNN_TARGET_OPENCL_FP16, cv.dnn.DNN_TARGET_MYRIAD, cv.dnn.DNN_TARGET_HDDL,
cv.dnn.DNN_TARGET_VULKAN, cv.dnn.DNN_TARGET_CUDA, cv.dnn.DNN_TARGET_CUDA_FP16)
parser = argparse.ArgumentParser(add_help=False)
parser.add_argument('--zoo', default=os.path.join(os.path.dirname(os.path.abspath(__file__)), 'models.yml'),
help='An optional path to file with preprocessing parameters.')
parser.add_argument('--input', help='Path to input image or video file. Skip this argument to capture frames from a camera.')
parser.add_argument('--out_tf_graph', default='graph.pbtxt',
help='For models from TensorFlow Object Detection API, you may '
'pass a .config file which was used for training through --config '
'argument. This way an additional .pbtxt file with TensorFlow graph will be created.')
parser.add_argument('--framework', choices=['caffe', 'tensorflow', 'torch', 'darknet', 'dldt', 'onnx'],
help='Optional name of an origin framework of the model. '
'Detect it automatically if it does not set.')
parser.add_argument('--thr', type=float, default=0.5, help='Confidence threshold')
parser.add_argument('--nms', type=float, default=0.4, help='Non-maximum suppression threshold')
parser.add_argument('--backend', choices=backends, default=cv.dnn.DNN_BACKEND_DEFAULT, type=int,
help="Choose one of computation backends: "
"%d: automatically (by default), "
"%d: Halide language (http://halide-lang.org/), "
"%d: Intel's Deep Learning Inference Engine (https://software.intel.com/openvino-toolkit), "
"%d: OpenCV implementation, "
"%d: VKCOM, "
"%d: CUDA" % backends)
parser.add_argument('--target', choices=targets, default=cv.dnn.DNN_TARGET_CPU, type=int,
help='Choose one of target computation devices: '
'%d: CPU target (by default), '
'%d: OpenCL, '
'%d: OpenCL fp16 (half-float precision), '
'%d: NCS2 VPU, '
'%d: HDDL VPU, '
'%d: Vulkan, '
'%d: CUDA, '
'%d: CUDA fp16 (half-float preprocess)' % targets)
parser.add_argument('--async', type=int, default=0,
dest='asyncN',
help='Number of asynchronous forwards at the same time. '
'Choose 0 for synchronous mode')
args, _ = parser.parse_known_args()
add_preproc_args(args.zoo, parser, 'object_detection')
parser = argparse.ArgumentParser(parents=[parser],
description='Use this script to run object detection deep learning networks using OpenCV.',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
args = parser.parse_args()
args.model = findFile(args.model)
args.config = findFile(args.config)
args.classes = findFile(args.classes)
# If config specified, try to load it as TensorFlow Object Detection API's pipeline.
config = readTextMessage(args.config)
if 'model' in config:
print('TensorFlow Object Detection API config detected')
if 'ssd' in config['model'][0]:
print('Preparing text graph representation for SSD model: ' + args.out_tf_graph)
createSSDGraph(args.model, args.config, args.out_tf_graph)
args.config = args.out_tf_graph
elif 'faster_rcnn' in config['model'][0]:
print('Preparing text graph representation for Faster-RCNN model: ' + args.out_tf_graph)
createFasterRCNNGraph(args.model, args.config, args.out_tf_graph)
args.config = args.out_tf_graph
# Load names of classes
classes = None
if args.classes:
with open(args.classes, 'rt') as f:
classes = f.read().rstrip('\n').split('\n')
# Load a network
net = cv.dnn.readNet(args.model, args.config, args.framework)
net.setPreferableBackend(args.backend)
net.setPreferableTarget(args.target)
outNames = net.getUnconnectedOutLayersNames()
confThreshold = args.thr
nmsThreshold = args.nms
| |
245881
|
def postprocess(frame, outs):
frameHeight = frame.shape[0]
frameWidth = frame.shape[1]
def drawPred(classId, conf, left, top, right, bottom):
# Draw a bounding box.
cv.rectangle(frame, (left, top), (right, bottom), (0, 255, 0))
label = '%.2f' % conf
# Print a label of class.
if classes:
assert(classId < len(classes))
label = '%s: %s' % (classes[classId], label)
labelSize, baseLine = cv.getTextSize(label, cv.FONT_HERSHEY_SIMPLEX, 0.5, 1)
top = max(top, labelSize[1])
cv.rectangle(frame, (left, top - labelSize[1]), (left + labelSize[0], top + baseLine), (255, 255, 255), cv.FILLED)
cv.putText(frame, label, (left, top), cv.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0))
layerNames = net.getLayerNames()
lastLayerId = net.getLayerId(layerNames[-1])
lastLayer = net.getLayer(lastLayerId)
classIds = []
confidences = []
boxes = []
if lastLayer.type == 'DetectionOutput':
# Network produces output blob with a shape 1x1xNx7 where N is a number of
# detections and an every detection is a vector of values
# [batchId, classId, confidence, left, top, right, bottom]
for out in outs:
for detection in out[0, 0]:
confidence = detection[2]
if confidence > confThreshold:
left = int(detection[3])
top = int(detection[4])
right = int(detection[5])
bottom = int(detection[6])
width = right - left + 1
height = bottom - top + 1
if width <= 2 or height <= 2:
left = int(detection[3] * frameWidth)
top = int(detection[4] * frameHeight)
right = int(detection[5] * frameWidth)
bottom = int(detection[6] * frameHeight)
width = right - left + 1
height = bottom - top + 1
classIds.append(int(detection[1]) - 1) # Skip background label
confidences.append(float(confidence))
boxes.append([left, top, width, height])
elif lastLayer.type == 'Region' or args.postprocessing == 'yolov8':
# Network produces output blob with a shape NxC where N is a number of
# detected objects and C is a number of classes + 4 where the first 4
# numbers are [center_x, center_y, width, height]
if args.postprocessing == 'yolov8':
box_scale_w = frameWidth / args.width
box_scale_h = frameHeight / args.height
else:
box_scale_w = frameWidth
box_scale_h = frameHeight
for out in outs:
if args.postprocessing == 'yolov8':
out = out[0].transpose(1, 0)
for detection in out:
scores = detection[4:]
if args.background_label_id >= 0:
scores = np.delete(scores, args.background_label_id)
classId = np.argmax(scores)
confidence = scores[classId]
if confidence > confThreshold:
center_x = int(detection[0] * box_scale_w)
center_y = int(detection[1] * box_scale_h)
width = int(detection[2] * box_scale_w)
height = int(detection[3] * box_scale_h)
left = int(center_x - width / 2)
top = int(center_y - height / 2)
classIds.append(classId)
confidences.append(float(confidence))
boxes.append([left, top, width, height])
else:
print('Unknown output layer type: ' + lastLayer.type)
exit()
# NMS is used inside Region layer only on DNN_BACKEND_OPENCV for another backends we need NMS in sample
# or NMS is required if number of outputs > 1
if len(outNames) > 1 or (lastLayer.type == 'Region' or args.postprocessing == 'yolov8') and args.backend != cv.dnn.DNN_BACKEND_OPENCV:
indices = []
classIds = np.array(classIds)
boxes = np.array(boxes)
confidences = np.array(confidences)
unique_classes = set(classIds)
for cl in unique_classes:
class_indices = np.where(classIds == cl)[0]
conf = confidences[class_indices]
box = boxes[class_indices].tolist()
nms_indices = cv.dnn.NMSBoxes(box, conf, confThreshold, nmsThreshold)
indices.extend(class_indices[nms_indices])
else:
indices = np.arange(0, len(classIds))
for i in indices:
box = boxes[i]
left = box[0]
top = box[1]
width = box[2]
height = box[3]
drawPred(classIds[i], confidences[i], left, top, left + width, top + height)
# Process inputs
winName = 'Deep learning object detection in OpenCV'
cv.namedWindow(winName, cv.WINDOW_NORMAL)
def callback(pos):
global confThreshold
confThreshold = pos / 100.0
cv.createTrackbar('Confidence threshold, %', winName, int(confThreshold * 100), 99, callback)
cap = cv.VideoCapture(cv.samples.findFileOrKeep(args.input) if args.input else 0)
class QueueFPS(queue.Queue):
def __init__(self):
queue.Queue.__init__(self)
self.startTime = 0
self.counter = 0
def put(self, v):
queue.Queue.put(self, v)
self.counter += 1
if self.counter == 1:
self.startTime = time.time()
def getFPS(self):
return self.counter / (time.time() - self.startTime)
process = True
#
# Frames capturing thread
#
framesQueue = QueueFPS()
def framesThreadBody():
global framesQueue, process
while process:
hasFrame, frame = cap.read()
if not hasFrame:
break
framesQueue.put(frame)
#
# Frames processing thread
#
processedFramesQueue = queue.Queue()
predictionsQueue = QueueFPS()
def processingThreadBody():
global processedFramesQueue, predictionsQueue, args, process
futureOutputs = []
while process:
# Get a next frame
frame = None
try:
frame = framesQueue.get_nowait()
if args.asyncN:
if len(futureOutputs) == args.asyncN:
frame = None # Skip the frame
else:
framesQueue.queue.clear() # Skip the rest of frames
except queue.Empty:
pass
if not frame is None:
frameHeight = frame.shape[0]
frameWidth = frame.shape[1]
# Create a 4D blob from a frame.
inpWidth = args.width if args.width else frameWidth
inpHeight = args.height if args.height else frameHeight
blob = cv.dnn.blobFromImage(frame, size=(inpWidth, inpHeight), swapRB=args.rgb, ddepth=cv.CV_8U)
processedFramesQueue.put(frame)
# Run a model
net.setInput(blob, scalefactor=args.scale, mean=args.mean)
if net.getLayer(0).outputNameToIndex('im_info') != -1: # Faster-RCNN or R-FCN
frame = cv.resize(frame, (inpWidth, inpHeight))
net.setInput(np.array([[inpHeight, inpWidth, 1.6]], dtype=np.float32), 'im_info')
if args.asyncN:
futureOutputs.append(net.forwardAsync())
else:
outs = net.forward(outNames)
predictionsQueue.put(copy.deepcopy(outs))
while futureOutputs and futureOutputs[0].wait_for(0):
out = futureOutputs[0].get()
predictionsQueue.put(copy.deepcopy([out]))
del futureOutputs[0]
framesThread = Thread(target=framesThreadBody)
framesThread.start()
processingThread = Thread(target=processingThreadBody)
processingThread.start()
#
# Postprocessing and rendering loop
#
| |
246100
|
<script id="codeSnippet5" type="text/code-snippet">
postProcess = function(result, labels, frame) {
let canvasOutput = document.getElementById('canvasOutput');
const outputWidth = canvasOutput.width;
const outputHeight = canvasOutput.height;
const resultData = result.data32F;
// Get the boxes(with class and confidence) from the output
let boxes = [];
switch(outType) {
case "YOLO": {
const vecNum = result.matSize[0];
const vecLength = result.matSize[1];
const classNum = vecLength - 5;
for (let i = 0; i < vecNum; ++i) {
let vector = resultData.slice(i*vecLength, (i+1)*vecLength);
let scores = vector.slice(5, vecLength);
let classId = scores.indexOf(Math.max(...scores));
let confidence = scores[classId];
if (confidence > confThreshold) {
let center_x = Math.round(vector[0] * outputWidth);
let center_y = Math.round(vector[1] * outputHeight);
let width = Math.round(vector[2] * outputWidth);
let height = Math.round(vector[3] * outputHeight);
let left = Math.round(center_x - width / 2);
let top = Math.round(center_y - height / 2);
let box = {
scores: scores,
classId: classId,
confidence: confidence,
bounding: [left, top, width, height],
toDraw: true
}
boxes.push(box);
}
}
// NMS(Non Maximum Suppression) algorithm
let boxNum = boxes.length;
let tmp_boxes = [];
let sorted_boxes = [];
for (let c = 0; c < classNum; ++c) {
for (let i = 0; i < boxes.length; ++i) {
tmp_boxes[i] = [boxes[i], i];
}
sorted_boxes = tmp_boxes.sort((a, b) => { return (b[0].scores[c] - a[0].scores[c]); });
for (let i = 0; i < boxNum; ++i) {
if (sorted_boxes[i][0].scores[c] === 0) continue;
else {
for (let j = i + 1; j < boxNum; ++j) {
if (IOU(sorted_boxes[i][0], sorted_boxes[j][0]) >= nmsThreshold) {
boxes[sorted_boxes[j][1]].toDraw = false;
}
}
}
}
}
} break;
case "SSD": {
const vecNum = result.matSize[2];
const vecLength = 7;
for (let i = 0; i < vecNum; ++i) {
let vector = resultData.slice(i*vecLength, (i+1)*vecLength);
let confidence = vector[2];
if (confidence > confThreshold) {
let left, top, right, bottom, width, height;
left = Math.round(vector[3]);
top = Math.round(vector[4]);
right = Math.round(vector[5]);
bottom = Math.round(vector[6]);
width = right - left + 1;
height = bottom - top + 1;
if (width <= 2 || height <= 2) {
left = Math.round(vector[3] * outputWidth);
top = Math.round(vector[4] * outputHeight);
right = Math.round(vector[5] * outputWidth);
bottom = Math.round(vector[6] * outputHeight);
width = right - left + 1;
height = bottom - top + 1;
}
let box = {
classId: vector[1] - 1,
confidence: confidence,
bounding: [left, top, width, height],
toDraw: true
}
boxes.push(box);
}
}
} break;
default:
console.error(`Unsupported output type ${outType}`)
}
// Draw the saved box into the image
let output = new cv.Mat(outputWidth, outputHeight, cv.CV_8UC3);
cv.cvtColor(frame, output, cv.COLOR_RGBA2RGB);
let boxNum = boxes.length;
for (let i = 0; i < boxNum; ++i) {
if (boxes[i].toDraw) {
drawBox(boxes[i]);
}
}
return output;
// Calculate the IOU(Intersection over Union) of two boxes
function IOU(box1, box2) {
let bounding1 = box1.bounding;
let bounding2 = box2.bounding;
let s1 = bounding1[2] * bounding1[3];
let s2 = bounding2[2] * bounding2[3];
let left1 = bounding1[0];
let right1 = left1 + bounding1[2];
let left2 = bounding2[0];
let right2 = left2 + bounding2[2];
let overlapW = calOverlap([left1, right1], [left2, right2]);
let top1 = bounding2[1];
let bottom1 = top1 + bounding1[3];
let top2 = bounding2[1];
let bottom2 = top2 + bounding2[3];
let overlapH = calOverlap([top1, bottom1], [top2, bottom2]);
let overlapS = overlapW * overlapH;
return overlapS / (s1 + s2 + overlapS);
}
// Calculate the overlap range of two vector
function calOverlap(range1, range2) {
let min1 = range1[0];
let max1 = range1[1];
let min2 = range2[0];
let max2 = range2[1];
if (min2 > min1 && min2 < max1) {
return max1 - min2;
} else if (max2 > min1 && max2 < max1) {
return max2 - min1;
} else {
return 0;
}
}
// Draw one predict box into the origin image
function drawBox(box) {
let bounding = box.bounding;
let left = bounding[0];
let top = bounding[1];
let width = bounding[2];
let height = bounding[3];
cv.rectangle(output, new cv.Point(left, top), new cv.Point(left + width, top + height),
new cv.Scalar(0, 255, 0));
cv.rectangle(output, new cv.Point(left, top), new cv.Point(left + width, top + 15),
new cv.Scalar(255, 255, 255), cv.FILLED);
let text = `${labels[box.classId]}: ${box.confidence.toFixed(4)}`;
cv.putText(output, text, new cv.Point(left, top + 10), cv.FONT_HERSHEY_SIMPLEX, 0.3,
new cv.Scalar(0, 0, 0));
}
}
</script>
| |
246116
|
<script id="codeSnippet5" type="text/code-snippet">
postProcess = function(result, labels) {
let canvasOutput = document.getElementById('canvasOutput');
const outputWidth = canvasOutput.width;
const outputHeight = canvasOutput.height;
const resultData = result.data32F;
// Get the boxes(with class and confidence) from the output
let boxes = [];
switch(outType) {
case "YOLO": {
const vecNum = result.matSize[0];
const vecLength = result.matSize[1];
const classNum = vecLength - 5;
for (let i = 0; i < vecNum; ++i) {
let vector = resultData.slice(i*vecLength, (i+1)*vecLength);
let scores = vector.slice(5, vecLength);
let classId = scores.indexOf(Math.max(...scores));
let confidence = scores[classId];
if (confidence > confThreshold) {
let center_x = Math.round(vector[0] * outputWidth);
let center_y = Math.round(vector[1] * outputHeight);
let width = Math.round(vector[2] * outputWidth);
let height = Math.round(vector[3] * outputHeight);
let left = Math.round(center_x - width / 2);
let top = Math.round(center_y - height / 2);
let box = {
scores: scores,
classId: classId,
confidence: confidence,
bounding: [left, top, width, height],
toDraw: true
}
boxes.push(box);
}
}
// NMS(Non Maximum Suppression) algorithm
let boxNum = boxes.length;
let tmp_boxes = [];
let sorted_boxes = [];
for (let c = 0; c < classNum; ++c) {
for (let i = 0; i < boxes.length; ++i) {
tmp_boxes[i] = [boxes[i], i];
}
sorted_boxes = tmp_boxes.sort((a, b) => { return (b[0].scores[c] - a[0].scores[c]); });
for (let i = 0; i < boxNum; ++i) {
if (sorted_boxes[i][0].scores[c] === 0) continue;
else {
for (let j = i + 1; j < boxNum; ++j) {
if (IOU(sorted_boxes[i][0], sorted_boxes[j][0]) >= nmsThreshold) {
boxes[sorted_boxes[j][1]].toDraw = false;
}
}
}
}
}
} break;
case "SSD": {
const vecNum = result.matSize[2];
const vecLength = 7;
for (let i = 0; i < vecNum; ++i) {
let vector = resultData.slice(i*vecLength, (i+1)*vecLength);
let confidence = vector[2];
if (confidence > confThreshold) {
let left, top, right, bottom, width, height;
left = Math.round(vector[3]);
top = Math.round(vector[4]);
right = Math.round(vector[5]);
bottom = Math.round(vector[6]);
width = right - left + 1;
height = bottom - top + 1;
if (width <= 2 || height <= 2) {
left = Math.round(vector[3] * outputWidth);
top = Math.round(vector[4] * outputHeight);
right = Math.round(vector[5] * outputWidth);
bottom = Math.round(vector[6] * outputHeight);
width = right - left + 1;
height = bottom - top + 1;
}
let box = {
classId: vector[1] - 1,
confidence: confidence,
bounding: [left, top, width, height],
toDraw: true
}
boxes.push(box);
}
}
} break;
default:
console.error(`Unsupported output type ${outType}`)
}
// Draw the saved box into the image
let image = cv.imread("canvasInput");
let output = new cv.Mat(outputWidth, outputHeight, cv.CV_8UC3);
cv.cvtColor(image, output, cv.COLOR_RGBA2RGB);
let boxNum = boxes.length;
for (let i = 0; i < boxNum; ++i) {
if (boxes[i].toDraw) {
drawBox(boxes[i]);
}
}
return output;
// Calculate the IOU(Intersection over Union) of two boxes
function IOU(box1, box2) {
let bounding1 = box1.bounding;
let bounding2 = box2.bounding;
let s1 = bounding1[2] * bounding1[3];
let s2 = bounding2[2] * bounding2[3];
let left1 = bounding1[0];
let right1 = left1 + bounding1[2];
let left2 = bounding2[0];
let right2 = left2 + bounding2[2];
let overlapW = calOverlap([left1, right1], [left2, right2]);
let top1 = bounding2[1];
let bottom1 = top1 + bounding1[3];
let top2 = bounding2[1];
let bottom2 = top2 + bounding2[3];
let overlapH = calOverlap([top1, bottom1], [top2, bottom2]);
let overlapS = overlapW * overlapH;
return overlapS / (s1 + s2 + overlapS);
}
// Calculate the overlap range of two vector
function calOverlap(range1, range2) {
let min1 = range1[0];
let max1 = range1[1];
let min2 = range2[0];
let max2 = range2[1];
if (min2 > min1 && min2 < max1) {
return max1 - min2;
} else if (max2 > min1 && max2 < max1) {
return max2 - min1;
} else {
return 0;
}
}
// Draw one predict box into the origin image
function drawBox(box) {
let bounding = box.bounding;
let left = bounding[0];
let top = bounding[1];
let width = bounding[2];
let height = bounding[3];
cv.rectangle(output, new cv.Point(left, top), new cv.Point(left + width, top + height),
new cv.Scalar(0, 255, 0));
cv.rectangle(output, new cv.Point(left, top), new cv.Point(left + width, top + 15),
new cv.Scalar(255, 255, 255), cv.FILLED);
let text = `${labels[box.classId]}: ${box.confidence.toFixed(4)}`;
cv.putText(output, text, new cv.Point(left, top + 10), cv.FONT_HERSHEY_SIMPLEX, 0.3,
new cv.Scalar(0, 0, 0));
}
}
</script>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.