Caching a model while loading - caching

I currently load a model in tfjs with the following code. I'm attempting to optimize the model by caching the files closer to where the model is called from using CloudFlare's Cache API. Is there a way for me to intercept the fetch call in the load operation to cache the model data and load data fetched from a cache into the model?
Current Code:
const model = await tf.loadLayersModel("model_url_from_gcp")
Trying to achieve:
// Will load data from cache if data is cached, else will fetch from URL and cache
const load_data = cache.get("model_url_from_gcp")
// Will load cached data into Model instead of using a URL
const model = await tf.loadLayersModel(load_data)
Is there also a way to achieve the same for GraphModels from TFHub?
const model = await tf.loadGraphModel("some_tfhub_url", { fromTFHub: true })

For using LocalStorage or IndexDB for TensorFlow.js please see this documentation:
IndexDB: https://www.tensorflow.org/js/guide/save_load#indexeddb_browser_only
LocalStorage: https://www.tensorflow.org/js/guide/save_load#local_storage_browser_only

Related

how update cached data when main data is change in laravel

i want to use a cache of laravel for ex: index method on a specific controllers!
i use Cache::rememberForever method of laravel cache.
i dont use Cache::remember with ttl time for caching data!
my question: i dont no when and how i update data in cache
imaging: i cached user profile with all relations! now user change avatar or personal data! now i should be renew (update) cache data in redis! (update cache data for get in next call) i want to know the best solution for updating cache data when update main data
To update a cache you can use such. event function in your User model:
protected static function boot()
{
parent::boot();
$removeCacheFunc = function ($model) {
$key = self::USER_CACHE_KEY . $model->id; //compile cache key in your way
\Cache::delete($key);
};
static::saved($removeCacheFunc);
static::deleting($removeCacheFunc);
}
Next time you call Cache::rememberForever() will not find this entity by key and will make it on the fly

Why is Laravel's database cache driver not remembering the items I tell it to?

I am implementing relatively simple caching (database driver) on Laravel 8 and have created the cache table in the database using the suggested migration :
$table->string('key')->unique();
$table->text('value');
$table->integer('expiration');
When I use a controller to store a simple entry in the cache it works as expected :
Cache::put('giles', "SOMETHING", 1000);
I can see the entry in the cache table.
But storing more complicated things isn't having the expected result. My original code is :
$statistics = Statistics::all();
$emails = OutgoingEmail::orderBy('created_at', 'DESC')->take(10)->get();
return view('admin.home')->with(compact('emails', 'statistics'));
Whether I try to use the remember method :
$expire = 1000;
// also tried $expire = Carbon::now()->addMinutes(10);
$statistics = Cache::remember('statistics', $expire, function() {
return Statistics::all();
});
or try a more inelegant method of seeing whether the caching is set first, retrieving it if so, or retrieving the collection then using Cache::set() (code not show)...it's not storing it in the cache table.

View Share doesn't return updated data, how then to share live data?

I currently have a model which access data like so:
$currentSessionID = session()->getId();
$displayCart = Cart::where('session_id', $currentSessionID)->get();
return view('layouts.cart')->with('cartDetails', $displayCart);
This model correctly retrieves the data in a current session.
To access this same data in a header file I'm using View::Share in the AppServiceProvider like so:
public funciton boot()
{
$currentSessionID = session()->getId();
$inCartDetails = Cart::where('session_id', $currentSessionID)->get();
View::share('inCartDetails', $inCartDetails);
}
In my blade the $inCartDetails returns empty. I get [].
My suspicion is that this function ONLY gets called at boot. Hence the name :) and that it's empty cause at the time of starting the session it's empty since user hasn't selected anything. If this is correct how would I then pass live data to multiple views?
The session is not available in the boot method of the service providers. You should create a middleware for this. Check out this answer here: How to retrieve session data in service providers in laravel?

Laravel5.5: save Provider data in session to avoid overload

I have made a ServiceProvider to load data on several views. Like this:
View::composer(['components.navigation.main.search','search.*','page-parts.cats','page-parts.categories_menu','page-parts.categories_more','page-parts.cats_top','components.modals.off-category'],function ($view) {
$view->with([
'toplevel_categories' => Category::topLevel()->orderBy('name')->get(),
]);
});
But on several html pages he needs to load multiple of these views and I don't want to load the topLevel categories each time to avoid overload and less runtime.
Can I store the loaded data (toplevel_categories) in a session or what is the most efficient way to handle this problem?
You could simply cache the variable and use it in the callback like:
$topLevelCategories = Category::topLevel()->orderBy('name')->get();
View::composer([], function($view) use ($topLevelCategories) {
$view->with([
'toplevel_categories' => $topLevelCategories
}
You could even use the cache mechanic from laravel itself to save an additional query, like caching it for 30 minutes (assuming the database hasnt changed in the meantime):
// Save the categories in the cache or retrieve them from it.
$topLevelCategories = Cache::remember('topLevelCategories', 30, function() {
return Category::topLevel()->orderBy('name')->get();
});
Note that for Laravel 5.8 the second parameter is in SECONDS, for 5.7 and below it is in MINUTES.
Since your service provider is only loaded once per request/lifecycle this should do the trick.

Ember JS: How to load a second model based on data from a first

I have an Ember app that, rather than using Ember Data, uses our own custom AJAX data layer to talk to an API.
We're able to load two models at once using RSVP - one is a Project object via our API wrapper, the second is an object representing the logged in user. Both are passed into the controller and templates and work just fine.
But I have a need to load a second model, based on a value in the returned Project object.
Once I've loaded a model in my route like this...
App.ProjectUpdateRoute = Ember.Route.extend({
setupController: function(controller, model) {
controller.set('model', model);
},
model: function(params) {
return Ember.RSVP.hash({
// Load Project from API - /myapi/v1/Project/:ProjectID
Project : App.Project.create().findById(params.ProjectID),
// Load current user from local object
User : App.AuthUser,
});
},
});
...I have a Project object (or rather model.Project) with various properties including the ID of the User that owns the project.
Now I'd like to make a second API call to /myapi/v1/User/:UserID to get the User's details.
Everything I've tried - including adding further App.User.create().findById(UserID) calls into the route's setupController function and the controller - results in the correct API call, but it's asyncronous, so Ember carries on rendering the page and I can't show the result of the API call on the page.
So - how, and where in the Ember structure, do I load a second model based on data from the first? How can I get ember to wait for the resolved promise of this second AJAX call?
UPDATE
I've also tried using afterModel:function() which is almost what I need - it makes the second API call in the right place in the app flow, but I still need to add the result into my existing model array:
afterModel: function(model, tranistion, params) {
// Returns the promise but doesn't update 'model'
return Ember.RSVP.hash({
ProjectOwner : App.User.create().findById(model.Project.UserID)
});
}
Chain the promise, and Ember will take the final resultant (from the model hook)
model: function(params) {
return Ember.RSVP.hash({
// Load Project from API - /myapi/v1/Project/:ProjectID
Project : App.Project.create().findById(params.ProjectID),
// Load current user from local object
User : App.AuthUser,
}).then(function(results){
return App.User.create().findById(results.Project.UserID).then(function(user){
results.projectUser = user;
return results;
});
});
},

Resources