


import argparse

import intel_extension_for_pytorch as ipex
import torch

from diffusers import DPMSolverMultistepScheduler, StableDiffusionPipeline


lowerCAmelCase__				    =       argparse.ArgumentParser('''Stable Diffusion script with intel optimization''', add_help=False)
parser.add_argument('''--dpm''', action='''store_true''', help='''Enable DPMSolver or not''')
parser.add_argument('''--steps''', default=None, type=int, help='''Num inference steps''')
lowerCAmelCase__				    =       parser.parse_args()


lowerCAmelCase__				    =       '''cpu'''
lowerCAmelCase__				    =       '''a lovely <dicoo> in red dress and hat, in the snowly and brightly night, with many brighly buildings'''

lowerCAmelCase__				    =       '''path-to-your-trained-model'''
lowerCAmelCase__				    =       StableDiffusionPipeline.from_pretrained(model_id)
if args.dpm:
     lowerCAmelCase__				    =       DPMSolverMultistepScheduler.from_config(pipe.scheduler.config)
lowerCAmelCase__				    =       pipe.to(device)

# to channels last
lowerCAmelCase__				    =       pipe.unet.to(memory_format=torch.channels_last)
lowerCAmelCase__				    =       pipe.vae.to(memory_format=torch.channels_last)
lowerCAmelCase__				    =       pipe.text_encoder.to(memory_format=torch.channels_last)
if pipe.requires_safety_checker:
     lowerCAmelCase__				    =       pipe.safety_checker.to(memory_format=torch.channels_last)

# optimize with ipex
lowerCAmelCase__				    =       torch.randn(2, 4, 64, 64)
lowerCAmelCase__				    =       torch.rand(1) * 999
lowerCAmelCase__				    =       torch.randn(2, 77, 768)
lowerCAmelCase__				    =       (sample, timestep, encoder_hidden_status)
try:
     lowerCAmelCase__				    =       ipex.optimize(pipe.unet.eval(), dtype=torch.bfloataa, inplace=True, sample_input=input_example)
except Exception:
     lowerCAmelCase__				    =       ipex.optimize(pipe.unet.eval(), dtype=torch.bfloataa, inplace=True)
lowerCAmelCase__				    =       ipex.optimize(pipe.vae.eval(), dtype=torch.bfloataa, inplace=True)
lowerCAmelCase__				    =       ipex.optimize(pipe.text_encoder.eval(), dtype=torch.bfloataa, inplace=True)
if pipe.requires_safety_checker:
     lowerCAmelCase__				    =       ipex.optimize(pipe.safety_checker.eval(), dtype=torch.bfloataa, inplace=True)

# compute
lowerCAmelCase__				    =       666
lowerCAmelCase__				    =       torch.Generator(device).manual_seed(seed)
lowerCAmelCase__				    =       {'''generator''': generator}
if args.steps is not None:
     lowerCAmelCase__				    =       args.steps

with torch.cpu.amp.autocast(enabled=True, dtype=torch.bfloataa):
     lowerCAmelCase__				    =       pipe(prompt, **generate_kwargs).images[0]

# save image
image.save('''generated.png''')









"""simple docstring"""







from typing import List

import jiwer
import jiwer.transforms as tr
from packaging import version

import datasets
from datasets.config import PY_VERSION


if PY_VERSION < version.parse('''3.8'''):
     import importlib_metadata
else:
     import importlib.metadata as importlib_metadata


lowerCAmelCase__				    =       ''''''


if version.parse(importlib_metadata.version('''jiwer''')) < version.parse('''2.3.0'''):


     class 				SCREAMING_SNAKE_CASE__    (		tr.AbstractTransform    ):
            """simple docstring"""


            def __init__(						self		,					snake_case__ = " "						):






              """simple docstring"""





              lowerCAmelCase					:					List[Any]								=							sentence_delimiter

            def 	lowercase__							(						self		,					snake_case__						):






              """simple docstring"""





              return list(snake_case__						)







            def 	lowercase__							(						self		,					snake_case__						):






              """simple docstring"""





              lowerCAmelCase					:					Any								=							[]
              for sent_idx, sentence in enumerate(snake_case__						):
                chars.extend(self.process_string(snake_case__						)						)
                if self.sentence_delimiter is not None and self.sentence_delimiter != "" and sent_idx < len(snake_case__						) - 1:
                  chars.append(self.sentence_delimiter						)
              return chars

     lowerCAmelCase__				    =       tr.Compose(
         [tr.RemoveMultipleSpaces(), tr.Strip(), SentencesToListOfCharacters(SENTENCE_DELIMITER)]
     )
else:
     lowerCAmelCase__				    =       tr.Compose(
         [
             tr.RemoveMultipleSpaces(),
             tr.Strip(),
             tr.ReduceToSingleSentence(SENTENCE_DELIMITER),
             tr.ReduceToListOfListOfChars(),
         ]
     )


lowerCAmelCase__				    =       '''\
@inproceedings{inproceedings,
    author = {Morris, Andrew and Maier, Viktoria and Green, Phil},
    year = {2004},
    month = {01},
    pages = {},
    title = {From WER and RIL to MER and WIL: improved evaluation measures for connected speech recognition.}
}
'''

lowerCAmelCase__				    =       '''\
Character error rate (CER) is a common metric of the performance of an automatic speech recognition system.

CER is similar to Word Error Rate (WER), but operates on character instead of word. Please refer to docs of WER for further information.

Character error rate can be computed as:

CER = (S + D + I) / N = (S + D + I) / (S + D + C)

where

S is the number of substitutions,
D is the number of deletions,
I is the number of insertions,
C is the number of correct characters,
N is the number of characters in the reference (N=S+D+C).

CER\'s output is not always a number between 0 and 1, in particular when there is a high number of insertions. This value is often associated to the percentage of characters that were incorrectly predicted. The lower the value, the better the
performance of the ASR system with a CER of 0 being a perfect score.
'''

lowerCAmelCase__				    =       '''
Computes CER score of transcribed segments against references.
Args:
    references: list of references for each speech input.
    predictions: list of transcribtions to score.
    concatenate_texts: Whether or not to concatenate sentences before evaluation, set to True for more accurate result.
Returns:
    (float): the character error rate

Examples:

    >>> predictions = ["this is the prediction", "there is an other sample"]
    >>> references = ["this is the reference", "there is another one"]
    >>> cer = datasets.load_metric("cer")
    >>> cer_score = cer.compute(predictions=predictions, references=references)
    >>> print(cer_score)
    0.34146341463414637
'''


@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION       ,   _KWARGS_DESCRIPTION    )
class 				SCREAMING_SNAKE_CASE__    (		datasets.Metric    ):
       """simple docstring"""


       def 	lowercase__							(						self						):






         """simple docstring"""





         return datasets.MetricInfo(
             description=_DESCRIPTION		,					citation=_CITATION		,					inputs_description=_KWARGS_DESCRIPTION		,					features=datasets.Features(
                 {
                     "predictions": datasets.Value("string"		,					id="sequence"						),
                     "references": datasets.Value("string"		,					id="sequence"						),
                 }						)		,					codebase_urls=["https://github.com/jitsi/jiwer/"]		,					reference_urls=[
                 "https://en.wikipedia.org/wiki/Word_error_rate",
                 "https://sites.google.com/site/textdigitisation/qualitymeasures/computingerrorrates",
             ]		,					)







       def 	lowercase__							(						self		,					snake_case__		,					snake_case__		,					snake_case__=False						):






         """simple docstring"""





         if concatenate_texts:
           return jiwer.compute_measures(
               snake_case__		,					snake_case__		,					truth_transform=snake_case__		,					hypothesis_transform=snake_case__		,					)["wer"]

         lowerCAmelCase					:					List[Any]								=							0
         lowerCAmelCase					:					Optional[Any]								=							0
         for prediction, reference in zip(snake_case__		,					snake_case__						):
           lowerCAmelCase					:					Optional[int]								=							jiwer.compute_measures(
               snake_case__		,					snake_case__		,					truth_transform=snake_case__		,					hypothesis_transform=snake_case__		,					)
           incorrect += measures["substitutions"] + measures["deletions"] + measures["insertions"]
           total += measures["substitutions"] + measures["deletions"] + measures["hits"]

         return incorrect / total





