Spaces:
Runtime error
Runtime error
envs
Browse files304 unmodified lines305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406304 unmodified lines"""Caches all of the examples so that their predictions can be shown immediately."""if Context.root_block is None:raise ValueError("Cannot cache examples if not in a Blocks context")if Path(self.cached_file).exists():print(f"Using cache from '{utils.abspath(self.cached_folder)}' directory. If method or examples have changed since last caching, delete this folder to clear cache.\n")else:print(f"Caching examples at: '{utils.abspath(self.cached_folder)}'")cache_logger = CSVLogger()generated_values = []if inspect.isgeneratorfunction(self.fn):def get_final_item(*args): # type: ignorex = Nonegenerated_values.clear()for x in self.fn(*args): # noqa: B007 # type: ignoregenerated_values.append(x)return xfn = get_final_itemelif inspect.isasyncgenfunction(self.fn):async def get_final_item(*args):x = Nonegenerated_values.clear()async for x in self.fn(*args): # noqa: B007 # type: ignoregenerated_values.append(x)return xfn = get_final_itemelse:fn = self.fn# create a fake dependency to process the examples and get the predictionsfrom gradio.events import EventListenerMethoddependency, fn_index = Context.root_block.set_event_trigger([EventListenerMethod(Context.root_block, "load")],fn=fn,inputs=self.inputs_with_examples, # type: ignoreoutputs=self.outputs, # type: ignorepreprocess=self.preprocess and not self._api_mode,postprocess=self.postprocess and not self._api_mode,batch=self.batch,)assert self.outputs is not Nonecache_logger.setup(self.outputs, self.cached_folder)for example_id, _ in enumerate(self.examples):print(f"Caching example {example_id + 1}/{len(self.examples)}")processed_input = self.processed_examples[example_id]if self.batch:processed_input = [[value] for value in processed_input]with utils.MatplotlibBackendMananger():prediction = await Context.root_block.process_api(fn_index=fn_index,inputs=processed_input,request=None,)output = prediction["data"]if len(generated_values):output = merge_generated_values_into_output(self.outputs, generated_values, output)if self.batch:output = [value[0] for value in output]cache_logger.flag(output)# Remove the "fake_event" to prevent bugs in loading interfaces from spacesContext.root_block.dependencies.remove(dependency)Context.root_block.fns.pop(fn_index)# Remove the original load_input_event and replace it with one that# also populates the input. We do it this way to to allow the cache()# method to be called independently of the create() methodindex = Context.root_block.dependencies.index(self.load_input_event)Context.root_block.dependencies.pop(index)Context.root_block.fns.pop(index)def load_example(example_id):processed_example = self.non_none_processed_examples[example_id] + self.load_from_cache(example_id)return utils.resolve_singleton(processed_example)self.load_input_event = self.dataset.click(load_example,inputs=[self.dataset],outputs=self.inputs_with_examples + self.outputs, # type: ignoreshow_progress="hidden",postprocess=False,queue=False,api_name=self.api_name, # type: ignore)def load_from_cache(self, example_id: int) -> list[Any]:"""Loads a particular cached example for the interface.Parameters:304 unmodified lines305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407304 unmodified lines"""Caches all of the examples so that their predictions can be shown immediately."""# if Context.root_block is None:# raise ValueError("Cannot cache examples if not in a Blocks context")# if Path(self.cached_file).exists():# print(# f"Using cache from '{utils.abspath(self.cached_folder)}' directory. If method or examples have changed since last caching, delete this folder to clear cache.\n"# )# else:# print(f"Caching examples at: '{utils.abspath(self.cached_folder)}'")# cache_logger = CSVLogger()# generated_values = []# if inspect.isgeneratorfunction(self.fn):# def get_final_item(*args): # type: ignore# x = None# generated_values.clear()# for x in self.fn(*args): # noqa: B007 # type: ignore# generated_values.append(x)# return x# fn = get_final_item# elif inspect.isasyncgenfunction(self.fn):# async def get_final_item(*args):# x = None# generated_values.clear()# async for x in self.fn(*args): # noqa: B007 # type: ignore# generated_values.append(x)# return x# fn = get_final_item# else:# fn = self.fn# # create a fake dependency to process the examples and get the predictions# from gradio.events import EventListenerMethod# dependency, fn_index = Context.root_block.set_event_trigger(# [EventListenerMethod(Context.root_block, "load")],# fn=fn,# inputs=self.inputs_with_examples, # type: ignore# outputs=self.outputs, # type: ignore# preprocess=self.preprocess and not self._api_mode,# postprocess=self.postprocess and not self._api_mode,# batch=self.batch,# )# assert self.outputs is not None# cache_logger.setup(self.outputs, self.cached_folder)# for example_id, _ in enumerate(self.examples):# print(f"Caching example {example_id + 1}/{len(self.examples)}")# processed_input = self.processed_examples[example_id]# if self.batch:# processed_input = [[value] for value in processed_input]# with utils.MatplotlibBackendMananger():# prediction = await Context.root_block.process_api(# fn_index=fn_index,# inputs=processed_input,# request=None,# )# output = prediction["data"]# if len(generated_values):# output = merge_generated_values_into_output(# self.outputs, generated_values, output# )# if self.batch:# output = [value[0] for value in output]# cache_logger.flag(output)# # Remove the "fake_event" to prevent bugs in loading interfaces from spaces# Context.root_block.dependencies.remove(dependency)# Context.root_block.fns.pop(fn_index)# # Remove the original load_input_event and replace it with one that# # also populates the input. We do it this way to to allow the cache()# # method to be called independently of the create() method# index = Context.root_block.dependencies.index(self.load_input_event)# Context.root_block.dependencies.pop(index)# Context.root_block.fns.pop(index)# def load_example(example_id):# processed_example = self.non_none_processed_examples[# example_id# ] + self.load_from_cache(example_id)# return utils.resolve_singleton(processed_example)# self.load_input_event = self.dataset.click(# load_example,# inputs=[self.dataset],# outputs=self.inputs_with_examples + self.outputs, # type: ignore# show_progress="hidden",# postprocess=False,# queue=False,# api_name=self.api_name, # type: ignore# )passdef load_from_cache(self, example_id: int) -> list[Any]:"""Loads a particular cached example for the interface.Parameters:
helpers.py+96-95