diff --git a/spaces/101-5/gpt4free/g4f/.v1/gpt4free/hpgptai/__init__.py b/spaces/101-5/gpt4free/g4f/.v1/gpt4free/hpgptai/__init__.py deleted file mode 100644 index f5d1f0edc379b4a4bd0c18dc8665531c1e22fe91..0000000000000000000000000000000000000000 --- a/spaces/101-5/gpt4free/g4f/.v1/gpt4free/hpgptai/__init__.py +++ /dev/null @@ -1,103 +0,0 @@ -# -*- coding: utf-8 -*- -""" -@Time : 2023/5/22 14:04 -@Auth : Hp_mzx -@File :__init__.py.py -@IDE :PyCharm -""" -import re -import json -import base64 -import random -import string -import requests -from fake_useragent import UserAgent - - -class ChatCompletion: - @staticmethod - def create( - messages: list, - context: str = "Converse as if you were an AI assistant. Be friendly, creative.", - restNonce: str = None, - proxy: str = None - ): - url = "https://chatgptlogin.ac/wp-json/ai-chatbot/v1/chat" - if not restNonce: - restNonce = ChatCompletion.get_restNonce(proxy) - headers = { - "Content-Type": "application/json", - "X-Wp-Nonce": restNonce - } - proxies = {'http': 'http://' + proxy, 'https': 'http://' + proxy} if proxy else None - data = { - "env": "chatbot", - "session": "N/A", - "prompt": ChatCompletion.__build_prompt(context, messages), - "context": context, - "messages": messages, - "newMessage": messages[-1]["content"], - "userName": "
User:
", - "aiName": "
AI:
", - "model": "gpt-3.5-turbo", - "temperature": 0.8, - "maxTokens": 1024, - "maxResults": 1, - "apiKey": "", - "service": "openai", - "embeddingsIndex": "", - "stop": "", - "clientId": ChatCompletion.randomStr(), - } - res = requests.post(url=url, data=json.dumps(data), headers=headers, proxies=proxies) - if res.status_code == 200: - return res.json() - return res.text - - @staticmethod - def randomStr(): - return ''.join(random.choices(string.ascii_lowercase + string.digits, k=34))[:11] - - @classmethod - def __build_prompt(cls, context: str, message: list, isCasuallyFineTuned=False, last=15): - prompt = context + '\n\n' if context else '' - message = message[-last:] - if isCasuallyFineTuned: - lastLine = message[-1] - prompt = lastLine.content + "" - return prompt - conversation = [x["who"] + x["content"] for x in message] - prompt += '\n'.join(conversation) - prompt += '\n' + "AI: " - return prompt - - @classmethod - def get_restNonce(cls, proxy: str = None): - url = "https://chatgptlogin.ac/" - headers = { - "Referer": "https://chatgptlogin.ac/", - "User-Agent": UserAgent().random - } - proxies = {'http': 'http://' + proxy, 'https': 'http://' + proxy} if proxy else None - res = requests.get(url, headers=headers, proxies=proxies) - src = re.search( - 'class="mwai-chat mwai-chatgpt">.*Send - - - - - - - - - - - - - - - - - - - - - - - - - - + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/spaces/awacke1/VideoSummary2/summarize.py b/spaces/awacke1/VideoSummary2/summarize.py deleted file mode 100644 index 52e42585f66a92dc2e3a99822c4bb420ecf4bd52..0000000000000000000000000000000000000000 --- a/spaces/awacke1/VideoSummary2/summarize.py +++ /dev/null @@ -1,43 +0,0 @@ -import traceback -import sys - -from youtube_transcript_api import YouTubeTranscriptApi -from transformers import AutoTokenizer, AutoModelForSeq2SeqLM - -def Summarizer(link, model): - - video_id = link.split("=")[1] - - try: - transcript = YouTubeTranscriptApi.get_transcript(video_id) - FinalTranscript = ' '.join([i['text'] for i in transcript]) - - if model == "Pegasus": - checkpoint = "google/pegasus-large" - elif model == "mT5": - checkpoint = "csebuetnlp/mT5_multilingual_XLSum" - elif model == "BART": - checkpoint = "sshleifer/distilbart-cnn-12-6" - - tokenizer = AutoTokenizer.from_pretrained(checkpoint) - model = AutoModelForSeq2SeqLM.from_pretrained(checkpoint) - - - inputs = tokenizer(FinalTranscript, - max_length=1024, - truncation=True, - return_tensors="pt") - - summary_ids = model.generate(inputs["input_ids"]) - summary = tokenizer.batch_decode(summary_ids, - skip_special_tokens=True, - clean_up_tokenization_spaces=False) - - - return summary[0] - - - except Exception: - print(traceback.format_exc()) - # or - print(sys.exc_info()[2]) diff --git a/spaces/awacke1/VizLib-BeautifulSoup/app.py b/spaces/awacke1/VizLib-BeautifulSoup/app.py deleted file mode 100644 index 6f679181cb71638a208219a73882f844fcb49393..0000000000000000000000000000000000000000 --- a/spaces/awacke1/VizLib-BeautifulSoup/app.py +++ /dev/null @@ -1,114 +0,0 @@ -import requests -from bs4 import BeautifulSoup -import streamlit as st -import time -import plotly.express as px -import pandas as pd -from sklearn.feature_extraction.text import CountVectorizer - -urls = ['https://en.wikipedia.org/wiki/Health_care', - 'https://en.wikipedia.org/wiki/Health_information_on_the_Internet', - 'https://www.who.int/health-topics/coronavirus#tab=tab_1'] - -def scrape_wikipedia(url): - try: - start_time = time.time() - response = requests.get(url) - end_time = time.time() - return {'url': url, 'response_time': end_time - start_time, 'content': response.content} - except: - return {'url': url, 'response_time': None, 'content': ""} - -def plot_word_frequencies(content): - soup = BeautifulSoup(content, 'html.parser') - text = ' '.join([elem.text for elem in soup.find_all(['p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6'])]) - words = text.split() - word_freq = {} - for word in words: - word_freq[word] = word_freq.get(word, 0) + 1 - sorted_word_freq = sorted(word_freq.items(), key=lambda x: x[1], reverse=True) - df = pd.DataFrame({'word': [word for word, freq in sorted_word_freq], - 'freq': [freq for word, freq in sorted_word_freq], - 'len': [len(word) for word, freq in sorted_word_freq]}) - fig = px.treemap(df, path=['len', 'word'], values='freq', color='len') - fig.update_layout(margin=dict(l=0, r=0, t=0, b=0)) - st.plotly_chart(fig) - -def display_top_words(content): - soup = BeautifulSoup(content, 'html.parser') - text = ' '.join([elem.text for elem in soup.find_all(['p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6'])]) - vectorizer = CountVectorizer() - X = vectorizer.fit_transform([text]) - terms = vectorizer.get_feature_names() - word_freq = X.toarray()[0] - top_words = [terms[i] for i in word_freq.argsort()[-10:][::-1]] - st.write(f"Top words: {', '.join(top_words)}") - -def main(): - st.set_page_config(layout='wide') - st.title("List of Articles on Health Care") - - for url in urls: - st.write(f"Scraping {url}...") - scraped_data = scrape_wikipedia(url) - st.write(f"Response time: {scraped_data['response_time']}") - content = scraped_data['content'] - st.write(f"Content: ") - st.markdown(f"```{content.decode()}```") - - plot_word_frequencies(content) - display_top_words(content) - - st.markdown(""" - - # 📢 Press Release: Beautiful Soup - Your Ultimate Tool to Treat Internet as Your Dataset - -Mound, MN - In today's digital age, the internet has become the primary source of information, and analyzing online content has become a critical aspect of business, research, and academic activities. To make it possible, Beautiful Soup - a Python library - is becoming increasingly popular among data scientists, researchers, and business professionals. - -## 🤔 What is Beautiful Soup? - -Beautiful Soup is a Python library used for web scraping purposes to pull the data out of HTML and XML files. It creates a parse tree for parsed pages that can be used to extract data from HTML. The library provides methods that can be used to navigate, search, and modify the parse tree. - -## 🚀 Powerful Features of Beautiful Soup - -The Beautiful Soup library offers an array of features that make it the ultimate tool for web scraping and data extraction, including: - -- Ability to extract data from HTML/XML files -- Powerful search capabilities to navigate the parse tree and locate specific tags and elements -- Ability to handle badly formatted HTML/XML -- Ability to convert XML to a tree-based structure -- Wide range of output formats -- Supports common web parsing libraries like html5lib and lxml -- Free and open-source library - -## 💼 Applications of Beautiful Soup - -Beautiful Soup has a wide range of applications, including: - -- Data mining -- Web scraping -- Information extraction -- Research and analysis -- Content management -- Data journalism -- Competitive intelligence - -## 🤖 Program Demonstrating the Power of Beautiful Soup - -The recently developed Python program demonstrates how Beautiful Soup can be used to analyze content from Wikipedia pages and WHO's official website on Coronavirus. -The program uses various Beautiful Soup functions to scrape data from these websites and generate insights. - -## 🔥 Why Choose Beautiful Soup? - -Beautiful Soup is a user-friendly library that offers unmatched capabilities to treat the internet as a dataset. -Its powerful search capabilities, ability to handle badly formatted HTML/XML, and support for multiple output formats make it the go-to tool for web scraping and data extraction. - -## 🚀 About the Developers - -The program was developed by a team of data scientists and web developers who specialize in web scraping and data analysis and augmented using AI. -They are passionate about using technology to make data analysis more accessible and easy for everyone. - - """) - -if __name__ == '__main__': - main() diff --git a/spaces/awacke1/Voice-ChatGPT-Streamlit-12/README.md b/spaces/awacke1/Voice-ChatGPT-Streamlit-12/README.md deleted file mode 100644 index 9e0bbe09f0923aa2d12b6e974271aa5d3801c08b..0000000000000000000000000000000000000000 --- a/spaces/awacke1/Voice-ChatGPT-Streamlit-12/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: Voice ChatGPT Streamlit 12 -emoji: 🌍 -colorFrom: blue -colorTo: gray -sdk: streamlit -sdk_version: 1.21.0 -app_file: app.py -pinned: false -license: mit ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/badayvedat/LLaVA/llava/train/llama_flash_attn_monkey_patch.py b/spaces/badayvedat/LLaVA/llava/train/llama_flash_attn_monkey_patch.py deleted file mode 100644 index 31db2eff8d1c4b3ae645583dfc5e156e818b6f1c..0000000000000000000000000000000000000000 --- a/spaces/badayvedat/LLaVA/llava/train/llama_flash_attn_monkey_patch.py +++ /dev/null @@ -1,115 +0,0 @@ -from typing import Optional, Tuple -import warnings - -import torch - -import transformers -from transformers.models.llama.modeling_llama import apply_rotary_pos_emb, repeat_kv - -try: - from flash_attn.flash_attn_interface import flash_attn_unpadded_qkvpacked_func -except ImportError: - from flash_attn.flash_attn_interface import flash_attn_varlen_qkvpacked_func as flash_attn_unpadded_qkvpacked_func -from flash_attn.bert_padding import unpad_input, pad_input - - -def forward( - self, - hidden_states: torch.Tensor, - attention_mask: Optional[torch.Tensor] = None, - position_ids: Optional[torch.Tensor] = None, - past_key_value: Optional[Tuple[torch.Tensor]] = None, - output_attentions: bool = False, - use_cache: bool = False, -) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]: - if output_attentions: - warnings.warn( - "Output attentions is not supported for patched `LlamaAttention`, returning `None` instead." - ) - - bsz, q_len, _ = hidden_states.size() - - query_states = ( - self.q_proj(hidden_states) - .view(bsz, q_len, self.num_heads, self.head_dim) - .transpose(1, 2) - ) - key_states = ( - self.k_proj(hidden_states) - .view(bsz, q_len, self.num_key_value_heads, self.head_dim) - .transpose(1, 2) - ) - value_states = ( - self.v_proj(hidden_states) - .view(bsz, q_len, self.num_key_value_heads, self.head_dim) - .transpose(1, 2) - ) # shape: (b, num_heads, s, head_dim) - - kv_seq_len = key_states.shape[-2] - if past_key_value is not None: - kv_seq_len += past_key_value[0].shape[-2] - - cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len) - query_states, key_states = apply_rotary_pos_emb( - query_states, key_states, cos, sin, position_ids - ) - - if past_key_value is not None: - # reuse k, v - key_states = torch.cat([past_key_value[0], key_states], dim=2) - value_states = torch.cat([past_key_value[1], value_states], dim=2) - - past_key_value = (key_states, value_states) if use_cache else None - - # repeat k/v heads if n_kv_heads < n_heads - key_states = repeat_kv(key_states, self.num_key_value_groups) - value_states = repeat_kv(value_states, self.num_key_value_groups) - - # Transform the data into the format required by flash attention - qkv = torch.stack([query_states, key_states, value_states], dim=2) - qkv = qkv.transpose(1, 3) # shape: [b, s, 3, num_heads, head_dim] - key_padding_mask = attention_mask - - if key_padding_mask is None: - qkv = qkv.reshape(-1, 3, self.num_heads, self.head_dim) - cu_q_lens = torch.arange( - 0, (bsz + 1) * q_len, step=q_len, dtype=torch.int32, device=qkv.device - ) - max_s = q_len - output = flash_attn_unpadded_qkvpacked_func( - qkv, cu_q_lens, max_s, 0.0, softmax_scale=None, causal=True - ) - output = output.view(bsz, q_len, -1) - else: - qkv = qkv.reshape(bsz, q_len, -1) - qkv, indices, cu_q_lens, max_s = unpad_input(qkv, key_padding_mask) - qkv = qkv.view(-1, 3, self.num_heads, self.head_dim) - output_unpad = flash_attn_unpadded_qkvpacked_func( - qkv, cu_q_lens, max_s, 0.0, softmax_scale=None, causal=True - ) - output_unpad = output_unpad.reshape(-1, self.num_heads * self.head_dim) - output = pad_input(output_unpad, indices, bsz, q_len) - - return self.o_proj(output), None, past_key_value - - -# Disable the transformation of the attention mask in LlamaModel as the flash attention -# requires the attention mask to be the same as the key_padding_mask -def _prepare_decoder_attention_mask( - self, attention_mask, input_shape, inputs_embeds, past_key_values_length -): - # [bsz, seq_len] - return attention_mask - - -def replace_llama_attn_with_flash_attn(): - cuda_major, cuda_minor = torch.cuda.get_device_capability() - if cuda_major < 8: - warnings.warn( - "Flash attention is only supported on A100 or H100 GPU during training due to head dim > 64 backward." - "ref: https://github.com/HazyResearch/flash-attention/issues/190#issuecomment-1523359593" - ) - transformers.models.llama.modeling_llama.LlamaModel._prepare_decoder_attention_mask = ( - _prepare_decoder_attention_mask - ) - transformers.models.llama.modeling_llama.LlamaAttention.forward = forward diff --git a/spaces/banana-projects/web3d/node_modules/three/examples/js/ShaderSkin.js b/spaces/banana-projects/web3d/node_modules/three/examples/js/ShaderSkin.js deleted file mode 100644 index fb9e29a7f2634243361cc359bbf121ae6f7180d1..0000000000000000000000000000000000000000 --- a/spaces/banana-projects/web3d/node_modules/three/examples/js/ShaderSkin.js +++ /dev/null @@ -1,694 +0,0 @@ -/** - * @author alteredq / http://alteredqualia.com/ - * - */ - - -THREE.ShaderSkin = { - - /* ------------------------------------------------------------------------------------------ - // Simple skin shader - // - per-pixel Blinn-Phong diffuse term mixed with half-Lambert wrap-around term (per color component) - // - physically based specular term (Kelemen/Szirmay-Kalos specular reflectance) - // - // - diffuse map - // - bump map - // - specular map - // - point, directional and hemisphere lights (use with "lights: true" material option) - // - fog (use with "fog: true" material option) - // - // ------------------------------------------------------------------------------------------ */ - - 'skinSimple' : { - - uniforms: THREE.UniformsUtils.merge( [ - - THREE.UniformsLib[ "fog" ], - THREE.UniformsLib[ "lights" ], - - { - - "enableBump": { value: 0 }, - "enableSpecular": { value: 0 }, - - "tDiffuse": { value: null }, - "tBeckmann": { value: null }, - - "diffuse": { value: new THREE.Color( 0xeeeeee ) }, - "specular": { value: new THREE.Color( 0x111111 ) }, - "opacity": { value: 1 }, - - "uRoughness": { value: 0.15 }, - "uSpecularBrightness": { value: 0.75 }, - - "bumpMap": { value: null }, - "bumpScale": { value: 1 }, - - "specularMap": { value: null }, - - "offsetRepeat": { value: new THREE.Vector4( 0, 0, 1, 1 ) }, - - "uWrapRGB": { value: new THREE.Vector3( 0.75, 0.375, 0.1875 ) } - - } - - ] ), - - fragmentShader: [ - - "#define USE_BUMPMAP", - - "uniform bool enableBump;", - "uniform bool enableSpecular;", - - "uniform vec3 diffuse;", - "uniform vec3 specular;", - "uniform float opacity;", - - "uniform float uRoughness;", - "uniform float uSpecularBrightness;", - - "uniform vec3 uWrapRGB;", - - "uniform sampler2D tDiffuse;", - "uniform sampler2D tBeckmann;", - - "uniform sampler2D specularMap;", - - "varying vec3 vNormal;", - "varying vec2 vUv;", - - "varying vec3 vViewPosition;", - - THREE.ShaderChunk[ "common" ], - THREE.ShaderChunk[ "bsdfs" ], - THREE.ShaderChunk[ "packing" ], - THREE.ShaderChunk[ "lights_pars_begin" ], - THREE.ShaderChunk[ "fog_pars_fragment" ], - THREE.ShaderChunk[ "bumpmap_pars_fragment" ], - - // Fresnel term - - "float fresnelReflectance( vec3 H, vec3 V, float F0 ) {", - - "float base = 1.0 - dot( V, H );", - "float exponential = pow( base, 5.0 );", - - "return exponential + F0 * ( 1.0 - exponential );", - - "}", - - // Kelemen/Szirmay-Kalos specular BRDF - - "float KS_Skin_Specular( vec3 N,", // Bumped surface normal - "vec3 L,", // Points to light - "vec3 V,", // Points to eye - "float m,", // Roughness - "float rho_s", // Specular brightness - ") {", - - "float result = 0.0;", - "float ndotl = dot( N, L );", - - "if( ndotl > 0.0 ) {", - - "vec3 h = L + V;", // Unnormalized half-way vector - "vec3 H = normalize( h );", - - "float ndoth = dot( N, H );", - - "float PH = pow( 2.0 * texture2D( tBeckmann, vec2( ndoth, m ) ).x, 10.0 );", - - "float F = fresnelReflectance( H, V, 0.028 );", - "float frSpec = max( PH * F / dot( h, h ), 0.0 );", - - "result = ndotl * rho_s * frSpec;", // BRDF * dot(N,L) * rho_s - - "}", - - "return result;", - - "}", - - "void main() {", - - "vec3 outgoingLight = vec3( 0.0 );", // outgoing light does not have an alpha, the surface does - "vec4 diffuseColor = vec4( diffuse, opacity );", - - "vec4 colDiffuse = texture2D( tDiffuse, vUv );", - "colDiffuse.rgb *= colDiffuse.rgb;", - - "diffuseColor = diffuseColor * colDiffuse;", - - "vec3 normal = normalize( vNormal );", - "vec3 viewerDirection = normalize( vViewPosition );", - - "float specularStrength;", - - "if ( enableSpecular ) {", - - "vec4 texelSpecular = texture2D( specularMap, vUv );", - "specularStrength = texelSpecular.r;", - - "} else {", - - "specularStrength = 1.0;", - - "}", - - "#ifdef USE_BUMPMAP", - - "if ( enableBump ) normal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );", - - "#endif", - - // point lights - - "vec3 totalSpecularLight = vec3( 0.0 );", - "vec3 totalDiffuseLight = vec3( 0.0 );", - - "#if NUM_POINT_LIGHTS > 0", - - "for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {", - - "vec3 lVector = pointLights[ i ].position + vViewPosition.xyz;", - - "float attenuation = calcLightAttenuation( length( lVector ), pointLights[ i ].distance, pointLights[ i ].decay );", - - "lVector = normalize( lVector );", - - "float pointDiffuseWeightFull = max( dot( normal, lVector ), 0.0 );", - "float pointDiffuseWeightHalf = max( 0.5 * dot( normal, lVector ) + 0.5, 0.0 );", - "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), uWrapRGB );", - - "float pointSpecularWeight = KS_Skin_Specular( normal, lVector, viewerDirection, uRoughness, uSpecularBrightness );", - - "totalDiffuseLight += pointLight[ i ].color * ( pointDiffuseWeight * attenuation );", - "totalSpecularLight += pointLight[ i ].color * specular * ( pointSpecularWeight * specularStrength * attenuation );", - - "}", - - "#endif", - - // directional lights - - "#if NUM_DIR_LIGHTS > 0", - - "for( int i = 0; i < NUM_DIR_LIGHTS; i++ ) {", - - "vec3 dirVector = directionalLights[ i ].direction;", - - "float dirDiffuseWeightFull = max( dot( normal, dirVector ), 0.0 );", - "float dirDiffuseWeightHalf = max( 0.5 * dot( normal, dirVector ) + 0.5, 0.0 );", - "vec3 dirDiffuseWeight = mix( vec3 ( dirDiffuseWeightFull ), vec3( dirDiffuseWeightHalf ), uWrapRGB );", - - "float dirSpecularWeight = KS_Skin_Specular( normal, dirVector, viewerDirection, uRoughness, uSpecularBrightness );", - - "totalDiffuseLight += directionalLights[ i ].color * dirDiffuseWeight;", - "totalSpecularLight += directionalLights[ i ].color * ( dirSpecularWeight * specularStrength );", - - "}", - - "#endif", - - // hemisphere lights - - "#if NUM_HEMI_LIGHTS > 0", - - "for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {", - - "vec3 lVector = hemisphereLightDirection[ i ];", - - "float dotProduct = dot( normal, lVector );", - "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;", - - "totalDiffuseLight += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );", - - // specular (sky light) - - "float hemiSpecularWeight = 0.0;", - "hemiSpecularWeight += KS_Skin_Specular( normal, lVector, viewerDirection, uRoughness, uSpecularBrightness );", - - // specular (ground light) - - "vec3 lVectorGround = -lVector;", - "hemiSpecularWeight += KS_Skin_Specular( normal, lVectorGround, viewerDirection, uRoughness, uSpecularBrightness );", - - "vec3 hemiSpecularColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );", - - "totalSpecularLight += hemiSpecularColor * specular * ( hemiSpecularWeight * specularStrength );", - - "}", - - "#endif", - - "outgoingLight += diffuseColor.xyz * ( totalDiffuseLight + ambientLightColor * diffuse ) + totalSpecularLight;", - - "gl_FragColor = linearToOutputTexel( vec4( outgoingLight, diffuseColor.a ) );", // TODO, this should be pre-multiplied to allow for bright highlights on very transparent objects - - THREE.ShaderChunk[ "fog_fragment" ], - - "}" - - ].join( "\n" ), - - vertexShader: [ - - "uniform vec4 offsetRepeat;", - - "varying vec3 vNormal;", - "varying vec2 vUv;", - - "varying vec3 vViewPosition;", - - THREE.ShaderChunk[ "common" ], - THREE.ShaderChunk[ "lights_pars_begin" ], - THREE.ShaderChunk[ "fog_pars_vertex" ], - - "void main() {", - - "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );", - "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );", - - "vViewPosition = -mvPosition.xyz;", - - "vNormal = normalize( normalMatrix * normal );", - - "vUv = uv * offsetRepeat.zw + offsetRepeat.xy;", - - "gl_Position = projectionMatrix * mvPosition;", - - THREE.ShaderChunk[ "fog_vertex" ], - - "}" - - ].join( "\n" ) - - }, - - /* ------------------------------------------------------------------------------------------ - // Skin shader - // - Blinn-Phong diffuse term (using normal + diffuse maps) - // - subsurface scattering approximation by four blur layers - // - physically based specular term (Kelemen/Szirmay-Kalos specular reflectance) - // - // - point and directional lights (use with "lights: true" material option) - // - // - based on Nvidia Advanced Skin Rendering GDC 2007 presentation - // and GPU Gems 3 Chapter 14. Advanced Techniques for Realistic Real-Time Skin Rendering - // - // http://developer.download.nvidia.com/presentations/2007/gdc/Advanced_Skin.pdf - // http://http.developer.nvidia.com/GPUGems3/gpugems3_ch14.html - // ------------------------------------------------------------------------------------------ */ - - 'skin' : { - - uniforms: THREE.UniformsUtils.merge( [ - - THREE.UniformsLib[ "fog" ], - THREE.UniformsLib[ "lights" ], - - { - - "passID": { value: 0 }, - - "tDiffuse" : { value: null }, - "tNormal" : { value: null }, - - "tBlur1" : { value: null }, - "tBlur2" : { value: null }, - "tBlur3" : { value: null }, - "tBlur4" : { value: null }, - - "tBeckmann" : { value: null }, - - "uNormalScale": { value: 1.0 }, - - "diffuse": { value: new THREE.Color( 0xeeeeee ) }, - "specular": { value: new THREE.Color( 0x111111 ) }, - "opacity": { value: 1 }, - - "uRoughness": { value: 0.15 }, - "uSpecularBrightness": { value: 0.75 } - - } - - ] ), - - fragmentShader: [ - - "uniform vec3 diffuse;", - "uniform vec3 specular;", - "uniform float opacity;", - - "uniform float uRoughness;", - "uniform float uSpecularBrightness;", - - "uniform int passID;", - - "uniform sampler2D tDiffuse;", - "uniform sampler2D tNormal;", - - "uniform sampler2D tBlur1;", - "uniform sampler2D tBlur2;", - "uniform sampler2D tBlur3;", - "uniform sampler2D tBlur4;", - - "uniform sampler2D tBeckmann;", - - "uniform float uNormalScale;", - - "varying vec3 vNormal;", - "varying vec2 vUv;", - - "varying vec3 vViewPosition;", - - THREE.ShaderChunk[ "common" ], - THREE.ShaderChunk[ "lights_pars_begin" ], - THREE.ShaderChunk[ "fog_pars_fragment" ], - - "float fresnelReflectance( vec3 H, vec3 V, float F0 ) {", - - "float base = 1.0 - dot( V, H );", - "float exponential = pow( base, 5.0 );", - - "return exponential + F0 * ( 1.0 - exponential );", - - "}", - - // Kelemen/Szirmay-Kalos specular BRDF - - "float KS_Skin_Specular( vec3 N,", // Bumped surface normal - "vec3 L,", // Points to light - "vec3 V,", // Points to eye - "float m,", // Roughness - "float rho_s", // Specular brightness - ") {", - - "float result = 0.0;", - "float ndotl = dot( N, L );", - - "if( ndotl > 0.0 ) {", - - "vec3 h = L + V;", // Unnormalized half-way vector - "vec3 H = normalize( h );", - - "float ndoth = dot( N, H );", - - "float PH = pow( 2.0 * texture2D( tBeckmann, vec2( ndoth, m ) ).x, 10.0 );", - "float F = fresnelReflectance( H, V, 0.028 );", - "float frSpec = max( PH * F / dot( h, h ), 0.0 );", - - "result = ndotl * rho_s * frSpec;", // BRDF * dot(N,L) * rho_s - - "}", - - "return result;", - - "}", - - "void main() {", - - "vec3 outgoingLight = vec3( 0.0 );", // outgoing light does not have an alpha, the surface does - "vec4 diffuseColor = vec4( diffuse, opacity );", - - "vec4 mSpecular = vec4( specular, opacity );", - - "vec4 colDiffuse = texture2D( tDiffuse, vUv );", - "colDiffuse *= colDiffuse;", - - "diffuseColor *= colDiffuse;", - - // normal mapping - - "vec4 posAndU = vec4( -vViewPosition, vUv.x );", - "vec4 posAndU_dx = dFdx( posAndU ), posAndU_dy = dFdy( posAndU );", - "vec3 tangent = posAndU_dx.w * posAndU_dx.xyz + posAndU_dy.w * posAndU_dy.xyz;", - "vec3 normal = normalize( vNormal );", - "vec3 binormal = normalize( cross( tangent, normal ) );", - "tangent = cross( normal, binormal );", // no normalization required - "mat3 tsb = mat3( tangent, binormal, normal );", - - "vec3 normalTex = texture2D( tNormal, vUv ).xyz * 2.0 - 1.0;", - "normalTex.xy *= uNormalScale;", - "normalTex = normalize( normalTex );", - - "vec3 finalNormal = tsb * normalTex;", - "normal = normalize( finalNormal );", - - "vec3 viewerDirection = normalize( vViewPosition );", - - // point lights - - "vec3 totalDiffuseLight = vec3( 0.0 );", - "vec3 totalSpecularLight = vec3( 0.0 );", - - "#if NUM_POINT_LIGHTS > 0", - - "for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {", - - "vec3 pointVector = normalize( pointLights[ i ].direction );", - "float attenuation = calcLightAttenuation( length( lVector ), pointLights[ i ].distance, pointLights[ i ].decay );", - - "float pointDiffuseWeight = max( dot( normal, pointVector ), 0.0 );", - - "totalDiffuseLight += pointLightColor[ i ] * ( pointDiffuseWeight * attenuation );", - - "if ( passID == 1 ) {", - - "float pointSpecularWeight = KS_Skin_Specular( normal, pointVector, viewerDirection, uRoughness, uSpecularBrightness );", - - "totalSpecularLight += pointLightColor[ i ] * mSpecular.xyz * ( pointSpecularWeight * attenuation );", - - "}", - - "}", - - "#endif", - - // directional lights - - "#if NUM_DIR_LIGHTS > 0", - - "for( int i = 0; i < NUM_DIR_LIGHTS; i++ ) {", - - "vec3 dirVector = directionalLights[ i ].direction;", - - "float dirDiffuseWeight = max( dot( normal, dirVector ), 0.0 );", - - - "totalDiffuseLight += directionalLights[ i ].color * dirDiffuseWeight;", - - "if ( passID == 1 ) {", - - "float dirSpecularWeight = KS_Skin_Specular( normal, dirVector, viewerDirection, uRoughness, uSpecularBrightness );", - - "totalSpecularLight += directionalLights[ i ].color * mSpecular.xyz * dirSpecularWeight;", - - "}", - - "}", - - "#endif", - - - "outgoingLight += diffuseColor.rgb * ( totalDiffuseLight + totalSpecularLight );", - - "if ( passID == 0 ) {", - - "outgoingLight = sqrt( outgoingLight );", - - "} else if ( passID == 1 ) {", - - //"#define VERSION1", - - "#ifdef VERSION1", - - "vec3 nonblurColor = sqrt(outgoingLight );", - - "#else", - - "vec3 nonblurColor = outgoingLight;", - - "#endif", - - "vec3 blur1Color = texture2D( tBlur1, vUv ).xyz;", - "vec3 blur2Color = texture2D( tBlur2, vUv ).xyz;", - "vec3 blur3Color = texture2D( tBlur3, vUv ).xyz;", - "vec3 blur4Color = texture2D( tBlur4, vUv ).xyz;", - - - //"gl_FragColor = vec4( blur1Color, gl_FragColor.w );", - - //"gl_FragColor = vec4( vec3( 0.22, 0.5, 0.7 ) * nonblurColor + vec3( 0.2, 0.5, 0.3 ) * blur1Color + vec3( 0.58, 0.0, 0.0 ) * blur2Color, gl_FragColor.w );", - - //"gl_FragColor = vec4( vec3( 0.25, 0.6, 0.8 ) * nonblurColor + vec3( 0.15, 0.25, 0.2 ) * blur1Color + vec3( 0.15, 0.15, 0.0 ) * blur2Color + vec3( 0.45, 0.0, 0.0 ) * blur3Color, gl_FragColor.w );", - - - "outgoingLight = vec3( vec3( 0.22, 0.437, 0.635 ) * nonblurColor + ", - "vec3( 0.101, 0.355, 0.365 ) * blur1Color + ", - "vec3( 0.119, 0.208, 0.0 ) * blur2Color + ", - "vec3( 0.114, 0.0, 0.0 ) * blur3Color + ", - "vec3( 0.444, 0.0, 0.0 ) * blur4Color );", - - "outgoingLight *= sqrt( colDiffuse.xyz );", - - "outgoingLight += ambientLightColor * diffuse * colDiffuse.xyz + totalSpecularLight;", - - "#ifndef VERSION1", - - "outgoingLight = sqrt( outgoingLight );", - - "#endif", - - "}", - - "gl_FragColor = vec4( outgoingLight, diffuseColor.a );", // TODO, this should be pre-multiplied to allow for bright highlights on very transparent objects - - THREE.ShaderChunk[ "fog_fragment" ], - - "}" - - ].join( "\n" ), - - vertexShader: [ - - "#ifdef VERTEX_TEXTURES", - - "uniform sampler2D tDisplacement;", - "uniform float uDisplacementScale;", - "uniform float uDisplacementBias;", - - "#endif", - - "varying vec3 vNormal;", - "varying vec2 vUv;", - - "varying vec3 vViewPosition;", - - THREE.ShaderChunk[ "common" ], - THREE.ShaderChunk[ "fog_pars_vertex" ], - - "void main() {", - - "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );", - - "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );", - - "vViewPosition = -mvPosition.xyz;", - - "vNormal = normalize( normalMatrix * normal );", - - "vUv = uv;", - - // displacement mapping - - "#ifdef VERTEX_TEXTURES", - - "vec3 dv = texture2D( tDisplacement, uv ).xyz;", - "float df = uDisplacementScale * dv.x + uDisplacementBias;", - "vec4 displacedPosition = vec4( vNormal.xyz * df, 0.0 ) + mvPosition;", - "gl_Position = projectionMatrix * displacedPosition;", - - "#else", - - "gl_Position = projectionMatrix * mvPosition;", - - "#endif", - - THREE.ShaderChunk[ "fog_vertex" ], - - "}", - - - ].join( "\n" ), - - vertexShaderUV: [ - - "varying vec3 vNormal;", - "varying vec2 vUv;", - - "varying vec3 vViewPosition;", - - THREE.ShaderChunk[ "common" ], - - "void main() {", - - "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );", - - "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );", - - "vViewPosition = -mvPosition.xyz;", - - "vNormal = normalize( normalMatrix * normal );", - - "vUv = uv;", - - "gl_Position = vec4( uv.x * 2.0 - 1.0, uv.y * 2.0 - 1.0, 0.0, 1.0 );", - - "}" - - ].join( "\n" ) - - }, - - /* ------------------------------------------------------------------------------------------ - // Beckmann distribution function - // - to be used in specular term of skin shader - // - render a screen-aligned quad to precompute a 512 x 512 texture - // - // - from http://developer.nvidia.com/node/171 - ------------------------------------------------------------------------------------------ */ - - "beckmann" : { - - uniforms: {}, - - vertexShader: [ - - "varying vec2 vUv;", - - "void main() {", - - "vUv = uv;", - "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );", - - "}" - - ].join( "\n" ), - - fragmentShader: [ - - "varying vec2 vUv;", - - "float PHBeckmann( float ndoth, float m ) {", - - "float alpha = acos( ndoth );", - "float ta = tan( alpha );", - - "float val = 1.0 / ( m * m * pow( ndoth, 4.0 ) ) * exp( -( ta * ta ) / ( m * m ) );", - "return val;", - - "}", - - "float KSTextureCompute( vec2 tex ) {", - - // Scale the value to fit within [0,1] invert upon lookup. - - "return 0.5 * pow( PHBeckmann( tex.x, tex.y ), 0.1 );", - - "}", - - "void main() {", - - "float x = KSTextureCompute( vUv );", - - "gl_FragColor = vec4( x, x, x, 1.0 );", - - "}" - - ].join( "\n" ) - - } - -}; diff --git a/spaces/banana-projects/web3d/node_modules/three/examples/js/effects/StereoEffect.js b/spaces/banana-projects/web3d/node_modules/three/examples/js/effects/StereoEffect.js deleted file mode 100644 index 437fead806a7859ba914ed530eb4acae908132bf..0000000000000000000000000000000000000000 --- a/spaces/banana-projects/web3d/node_modules/three/examples/js/effects/StereoEffect.js +++ /dev/null @@ -1,51 +0,0 @@ -/** - * @author alteredq / http://alteredqualia.com/ - * @authod mrdoob / http://mrdoob.com/ - * @authod arodic / http://aleksandarrodic.com/ - * @authod fonserbc / http://fonserbc.github.io/ -*/ - -THREE.StereoEffect = function ( renderer ) { - - var _stereo = new THREE.StereoCamera(); - _stereo.aspect = 0.5; - var size = new THREE.Vector2(); - - this.setEyeSeparation = function ( eyeSep ) { - - _stereo.eyeSep = eyeSep; - - }; - - this.setSize = function ( width, height ) { - - renderer.setSize( width, height ); - - }; - - this.render = function ( scene, camera ) { - - scene.updateMatrixWorld(); - - if ( camera.parent === null ) camera.updateMatrixWorld(); - - _stereo.update( camera ); - - renderer.getSize( size ); - - if ( renderer.autoClear ) renderer.clear(); - renderer.setScissorTest( true ); - - renderer.setScissor( 0, 0, size.width / 2, size.height ); - renderer.setViewport( 0, 0, size.width / 2, size.height ); - renderer.render( scene, _stereo.cameraL ); - - renderer.setScissor( size.width / 2, 0, size.width / 2, size.height ); - renderer.setViewport( size.width / 2, 0, size.width / 2, size.height ); - renderer.render( scene, _stereo.cameraR ); - - renderer.setScissorTest( false ); - - }; - -}; diff --git a/spaces/billusanda007/DeepRank/app.py b/spaces/billusanda007/DeepRank/app.py deleted file mode 100644 index 2ea749ad689d11815b6aa01c15a8ab406751a6bc..0000000000000000000000000000000000000000 --- a/spaces/billusanda007/DeepRank/app.py +++ /dev/null @@ -1,117 +0,0 @@ -import streamlit as st -import pandas as pd -import numpy as np -import re -import pickle -import pdfminer -from pdfminer.high_level import extract_text -from tensorflow.keras.models import Sequential -from tensorflow.keras.layers import Embedding, Conv1D, MaxPooling1D, LSTM, Dense, GlobalMaxPooling1D -from tensorflow.keras.preprocessing.text import Tokenizer -from tensorflow.keras.preprocessing.sequence import pad_sequences -from tensorflow.keras.utils import to_categorical -from sklearn.preprocessing import LabelEncoder - - -def cleanResume(resumeText): - # Your existing cleanResume function remains unchanged - resumeText = re.sub('http\S+\s*', ' ', resumeText) - resumeText = re.sub('RT|cc', ' ', resumeText) - resumeText = re.sub('#\S+', '', resumeText) - resumeText = re.sub('@\S+', ' ', resumeText) - resumeText = re.sub('[%s]' % re.escape("""!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~"""), ' ', resumeText) - resumeText = re.sub(r'[^\x00-\x7f]',r' ', resumeText) - resumeText = re.sub('\s+', ' ', resumeText) - return resumeText - -def pdf_to_text(file): - # Use pdfminer.six to extract text from the PDF file - text = extract_text(file) - return text - -def predict_category(resumes_data, selected_category,max_sequence_length): - # Load the trained DeepRank model - model = load_deeprank_model(max_sequence_length) - - # Process the resumes data - resumes_df = pd.DataFrame(resumes_data) - resumes_text = resumes_df['ResumeText'].values - - # Tokenize the text and convert to sequences - tokenized_text = tokenizer.texts_to_sequences(resumes_text) - - # Pad sequences to have the same length - max_sequence_length = 500 # Assuming maximum sequence length of 500 words - padded_text = pad_sequences(tokenized_text, maxlen=max_sequence_length) - - # Make predictions - predicted_probs = model.predict(padded_text) - - # Assign probabilities to respective job categories - for i, category in enumerate(label.classes_): - resumes_df[category] = predicted_probs[:, i] - - resumes_df_sorted = resumes_df.sort_values(by=selected_category, ascending=False) - - # Get the ranks for the selected category - ranks = [] - for rank, (idx, row) in enumerate(resumes_df_sorted.iterrows()): - rank = rank + 1 - file_name = row['FileName'] - ranks.append({'Rank': rank, 'FileName': file_name}) - - return ranks - -def load_deeprank_model(max_sequence_length): - # Load the saved DeepRank model - model = Sequential() - # Add layers to the model (example architecture, adjust as needed) - model.add(Embedding(input_dim=vocab_size, output_dim=128, input_length=max_sequence_length)) - model.add(Conv1D(filters=128, kernel_size=5, activation='relu')) - model.add(MaxPooling1D(pool_size=2)) - model.add(LSTM(64)) - model.add(Dense(num_classes, activation='softmax')) - model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) - model.load_weights('deeprank_model_v2.h5') # Replace 'deeprank_model.h5' with your saved model file - return model - -def main(): - st.title("Resume Ranking App") - st.text("Upload resumes and select a category to rank them.") - - resumes_data = [] - selected_category = "" - - # Handle multiple file uploads - files = st.file_uploader("Upload resumes", type=["pdf"], accept_multiple_files=True) - if files: - for file in files: - text = cleanResume(pdf_to_text(file)) - resumes_data.append({'ResumeText': text, 'FileName': file.name}) - selected_category = st.selectbox("Select a category to rank by", label.classes_) - - if st.button("Rank Resumes"): - if not resumes_data or not selected_category: - st.warning("Please upload resumes and select a category to continue.") - else: - ranks = predict_category(resumes_data, selected_category,max_sequence_length) - st.write(pd.DataFrame(ranks)) - -if __name__ == '__main__': - # Load label encoder and tokenizer - df = pd.read_csv('UpdatedResumeDataSet.csv') - df['cleaned'] = df['Resume'].apply(lambda x: cleanResume(x)) - label = LabelEncoder() - df['Category'] = label.fit_transform(df['Category']) - - # Tokenize text and get vocabulary size and number of classes - text = df['cleaned'].values - #text=df['Resume'].values - tokenizer = Tokenizer() - tokenizer.fit_on_texts(text) - vocab_size = len(tokenizer.word_index) + 1 - num_classes = len(label.classes_) - - max_sequence_length = 500 - - main() diff --git a/spaces/bioriAsaeru/text-to-voice/Call Of Duty Black Ops English Language Pack.md b/spaces/bioriAsaeru/text-to-voice/Call Of Duty Black Ops English Language Pack.md deleted file mode 100644 index 6460592d8f99fc991c8fe4ef3d234b8f1d7b2cd1..0000000000000000000000000000000000000000 --- a/spaces/bioriAsaeru/text-to-voice/Call Of Duty Black Ops English Language Pack.md +++ /dev/null @@ -1,10 +0,0 @@ - -

zombies return
the fan favorite co-op mode made famous in call of duty: world at war is back as you and up to 3 friends use a multitude weapons to fend off endless waves of blood-thirsty zombies. fight to survive in one of the most thrilling and critically-acclaimed co-op experiences in gaming.

-

Call Of Duty Black Ops English Language Pack


Download File ····· https://urloso.com/2uyPML



-

the rambo call of duty: mobile bundle featuring john rambo will be available in the in-game store from may 20 to june 18, which will include the epic character, three epic blueprints one lmg, one assault rifle, and one knife an epic parachute, an avatar, a calling card, a grenade, a tank, and a frame for your profile.

-

current game version informational links featured threads weekly scheduledaily and weekly contractsparty-upfree talk and emblem sharing bonus pooltuesday:monthly: rules.all submissions should be relevant to black ops iii. keep posts sfw (safe for work). all submissions must be directly related to call of duty: black ops iii. if your submission wouldn't be related without the title, it will be removed. discussion relating to call of duty: black ops iiii should be posted on or.no derogatory language, harassment, bullying, witch hunting, etc.

-

the landmark is made from aluminum. the steel case is held in place by a mechanical fastener. the key has a "c" scrawled on the top. the "c" is made of metal and is embossed with the trademark of the call of duty series.

-

call of duty cold war is a call of duty game that is based on the cold war era. cold war offers a great and unique multiplayer experience. call of duty: black ops is a game that makes you feel like you are in the cold war.

-

899543212b
-
-
\ No newline at end of file diff --git a/spaces/bioriAsaeru/text-to-voice/Dacait 4 Full Movie In Hindi Free Download.md b/spaces/bioriAsaeru/text-to-voice/Dacait 4 Full Movie In Hindi Free Download.md deleted file mode 100644 index 226f368d86a003155dc57b07fe67b7882bbbaf0b..0000000000000000000000000000000000000000 --- a/spaces/bioriAsaeru/text-to-voice/Dacait 4 Full Movie In Hindi Free Download.md +++ /dev/null @@ -1,6 +0,0 @@ -

Dacait 4 Full Movie In Hindi Free Download


Download Filehttps://urloso.com/2uyQx3



-
- aaccfb2cb3
-
-
-

diff --git a/spaces/bioriAsaeru/text-to-voice/Download Automation Studio 5.6 Crack Free [UPD].md b/spaces/bioriAsaeru/text-to-voice/Download Automation Studio 5.6 Crack Free [UPD].md deleted file mode 100644 index 18b7c11ab5662fb6b85da244e70a5dca33797551..0000000000000000000000000000000000000000 --- a/spaces/bioriAsaeru/text-to-voice/Download Automation Studio 5.6 Crack Free [UPD].md +++ /dev/null @@ -1,6 +0,0 @@ -

download automation studio 5.6 crack free


DOWNLOAD ✓✓✓ https://urloso.com/2uyOrW



-
-Automation Studio 5.6 Full Crack Average ratng: 8,9/10 141 reviews ... Download Automation Recording studio 6 Expert Free Software Cracked ... 4d29de3e1b
-
-
-

diff --git a/spaces/biubiubiiu/EFDM/app.py b/spaces/biubiubiiu/EFDM/app.py deleted file mode 100644 index 105c9e41927a3296b99af5a4d69d935d04af99f9..0000000000000000000000000000000000000000 --- a/spaces/biubiubiiu/EFDM/app.py +++ /dev/null @@ -1,132 +0,0 @@ -import gradio as gr -import toml -import torch -from PIL import Image -from torch import nn -from torchvision import transforms - -import net -from function import * - -cfg = toml.load("config.toml") # static variables - -# Setup device -if torch.cuda.is_available() and cfg["use_cuda"]: - device = torch.device("cuda") -else: - device = torch.device("cpu") - -# Load pretrained models -decoder = net.decoder -vgg = net.vgg - -decoder.eval() -vgg.eval() - -decoder.load_state_dict(torch.load(cfg["decoder_weight"])) -vgg.load_state_dict(torch.load(cfg["vgg_weight"])) -vgg = nn.Sequential(*list(vgg.children())[:31]) - -vgg = vgg.to(device) -decoder = decoder.to(device) - - -def transform(img, size, crop): - transform_list = [] - if size > 0: - transform_list.append(transforms.Resize(size)) - if crop: - transform_list.append(transforms.CenterCrop(size)) - transform_list.append(transforms.ToTensor()) - transform = transforms.Compose(transform_list) - return transform(img) - - -@torch.inference_mode() -def style_transfer(content, style, style_type, alpha, keep_resolution): - """Stylize function""" - style_type = style_type.lower() - - # Step 1: convert image to PyTorch Tensor - if keep_resolution: - style = style.resize(content.size, Image.ANTIALIAS) - - if style_type == "efdm" and not keep_resolution: - content = transform(content, cfg["content_size"], cfg["crop"]) - style = transform(style, cfg["style_size"], cfg["crop"]) - else: - content = transform(content, -1, False) - style = transform(style, -1, False) - - content = content.to(device).unsqueeze(0) - style = style.to(device).unsqueeze(0) - - # Step 2: extract content feature and style feature - content_feat = vgg(content) - style_feat = vgg(style) - - # Step 3: perform style transfer - transfer = { - "adain": adaptive_instance_normalization, - "adamean": adaptive_mean_normalization, - "adastd": adaptive_std_normalization, - "efdm": exact_feature_distribution_matching, - "hm": histogram_matching, - }[style_type] - feat = transfer(content_feat, style_feat) - - # Step 4: content-style trade-off - feat = feat * alpha + content_feat * (1 - alpha) - - # Step 5: decode to image - output = decoder(feat).cpu().squeeze(0).clamp_(0, 1) - output = transforms.ToPILImage()(output) - - if torch.cuda.is_available(): - torch.cuda.ipc_collect() - torch.cuda.empty_cache() - - return output - - -# Add image examples -example_img_pairs = { - "examples/content/sailboat.jpg": "examples/style/sketch.png", - "examples/content/granatum.jpg": "examples/style/flowers_in_a_turquoise_vase.jpg", - "examples/content/einstein.jpeg": "examples/style/polasticot2.jpeg", - "examples/content/paris.jpeg": "examples/style/vangogh.jpeg", - "examples/content/cornell.jpg": "examples/style/asheville.jpg", -} - -# Customize interface -title = "Style Transfer with EFDM" -description = """ -Gradio demo for neural style transfer using exact feature distribution matching -""" -article = "

Exact Feature Distribution Matching for Arbitrary Style Transfer and Domain Generalization

" -content_input = gr.inputs.Image(label="Content Image", source="upload", type="pil") -style_input = gr.inputs.Image(label="Style Image", source="upload", type="pil") -style_type = gr.inputs.Radio( - ["EFDM", "AdaIN", "AdaMean", "AdaStd", "HM"], label="Method" -) -alpha_selector = gr.inputs.Slider( - minimum=0.0, maximum=1.0, step=0.01, default=1.0, label="Content-Style trade-off" -) -keep_resolution = gr.inputs.Checkbox( - default=True, label="Keep content image resolution" -) - -iface = gr.Interface( - fn=style_transfer, - inputs=[content_input, style_input, style_type, alpha_selector, keep_resolution], - outputs=["image"], - title=title, - description=description, - article=article, - theme="huggingface", - examples=[ - [content, style, "EFDM", 1.0, True] - for content, style in example_img_pairs.items() - ], -) -iface.launch(debug=False, enable_queue=True) diff --git a/spaces/bprzy/orchestration/main.css b/spaces/bprzy/orchestration/main.css deleted file mode 100644 index 3d31c5f97f914b49cf81098382d40bcfb5e43610..0000000000000000000000000000000000000000 --- a/spaces/bprzy/orchestration/main.css +++ /dev/null @@ -1,9 +0,0 @@ -footer { - visibility: hidden -} -#chatbot { - font-size: 1em; -} -#user_input { - font-size: 1em; -} \ No newline at end of file diff --git a/spaces/brjathu/HMR2.0/vendor/detectron2/detectron2/data/transforms/augmentation.py b/spaces/brjathu/HMR2.0/vendor/detectron2/detectron2/data/transforms/augmentation.py deleted file mode 100644 index 63dd41aef658c9b51c7246880399405a029c5580..0000000000000000000000000000000000000000 --- a/spaces/brjathu/HMR2.0/vendor/detectron2/detectron2/data/transforms/augmentation.py +++ /dev/null @@ -1,380 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright (c) Facebook, Inc. and its affiliates. - -import inspect -import numpy as np -import pprint -from typing import Any, List, Optional, Tuple, Union -from fvcore.transforms.transform import Transform, TransformList - -""" -See "Data Augmentation" tutorial for an overview of the system: -https://detectron2.readthedocs.io/tutorials/augmentation.html -""" - - -__all__ = [ - "Augmentation", - "AugmentationList", - "AugInput", - "TransformGen", - "apply_transform_gens", - "StandardAugInput", - "apply_augmentations", -] - - -def _check_img_dtype(img): - assert isinstance(img, np.ndarray), "[Augmentation] Needs an numpy array, but got a {}!".format( - type(img) - ) - assert not isinstance(img.dtype, np.integer) or ( - img.dtype == np.uint8 - ), "[Augmentation] Got image of type {}, use uint8 or floating points instead!".format( - img.dtype - ) - assert img.ndim in [2, 3], img.ndim - - -def _get_aug_input_args(aug, aug_input) -> List[Any]: - """ - Get the arguments to be passed to ``aug.get_transform`` from the input ``aug_input``. - """ - if aug.input_args is None: - # Decide what attributes are needed automatically - prms = list(inspect.signature(aug.get_transform).parameters.items()) - # The default behavior is: if there is one parameter, then its "image" - # (work automatically for majority of use cases, and also avoid BC breaking), - # Otherwise, use the argument names. - if len(prms) == 1: - names = ("image",) - else: - names = [] - for name, prm in prms: - if prm.kind in ( - inspect.Parameter.VAR_POSITIONAL, - inspect.Parameter.VAR_KEYWORD, - ): - raise TypeError( - f""" \ -The default implementation of `{type(aug)}.__call__` does not allow \ -`{type(aug)}.get_transform` to use variable-length arguments (*args, **kwargs)! \ -If arguments are unknown, reimplement `__call__` instead. \ -""" - ) - names.append(name) - aug.input_args = tuple(names) - - args = [] - for f in aug.input_args: - try: - args.append(getattr(aug_input, f)) - except AttributeError as e: - raise AttributeError( - f"{type(aug)}.get_transform needs input attribute '{f}', " - f"but it is not an attribute of {type(aug_input)}!" - ) from e - return args - - -class Augmentation: - """ - Augmentation defines (often random) policies/strategies to generate :class:`Transform` - from data. It is often used for pre-processing of input data. - - A "policy" that generates a :class:`Transform` may, in the most general case, - need arbitrary information from input data in order to determine what transforms - to apply. Therefore, each :class:`Augmentation` instance defines the arguments - needed by its :meth:`get_transform` method. When called with the positional arguments, - the :meth:`get_transform` method executes the policy. - - Note that :class:`Augmentation` defines the policies to create a :class:`Transform`, - but not how to execute the actual transform operations to those data. - Its :meth:`__call__` method will use :meth:`AugInput.transform` to execute the transform. - - The returned `Transform` object is meant to describe deterministic transformation, which means - it can be re-applied on associated data, e.g. the geometry of an image and its segmentation - masks need to be transformed together. - (If such re-application is not needed, then determinism is not a crucial requirement.) - """ - - input_args: Optional[Tuple[str]] = None - """ - Stores the attribute names needed by :meth:`get_transform`, e.g. ``("image", "sem_seg")``. - By default, it is just a tuple of argument names in :meth:`self.get_transform`, which often only - contain "image". As long as the argument name convention is followed, there is no need for - users to touch this attribute. - """ - - def _init(self, params=None): - if params: - for k, v in params.items(): - if k != "self" and not k.startswith("_"): - setattr(self, k, v) - - def get_transform(self, *args) -> Transform: - """ - Execute the policy based on input data, and decide what transform to apply to inputs. - - Args: - args: Any fixed-length positional arguments. By default, the name of the arguments - should exist in the :class:`AugInput` to be used. - - Returns: - Transform: Returns the deterministic transform to apply to the input. - - Examples: - :: - class MyAug: - # if a policy needs to know both image and semantic segmentation - def get_transform(image, sem_seg) -> T.Transform: - pass - tfm: Transform = MyAug().get_transform(image, sem_seg) - new_image = tfm.apply_image(image) - - Notes: - Users can freely use arbitrary new argument names in custom - :meth:`get_transform` method, as long as they are available in the - input data. In detectron2 we use the following convention: - - * image: (H,W) or (H,W,C) ndarray of type uint8 in range [0, 255], or - floating point in range [0, 1] or [0, 255]. - * boxes: (N,4) ndarray of float32. It represents the instance bounding boxes - of N instances. Each is in XYXY format in unit of absolute coordinates. - * sem_seg: (H,W) ndarray of type uint8. Each element is an integer label of pixel. - - We do not specify convention for other types and do not include builtin - :class:`Augmentation` that uses other types in detectron2. - """ - raise NotImplementedError - - def __call__(self, aug_input) -> Transform: - """ - Augment the given `aug_input` **in-place**, and return the transform that's used. - - This method will be called to apply the augmentation. In most augmentation, it - is enough to use the default implementation, which calls :meth:`get_transform` - using the inputs. But a subclass can overwrite it to have more complicated logic. - - Args: - aug_input (AugInput): an object that has attributes needed by this augmentation - (defined by ``self.get_transform``). Its ``transform`` method will be called - to in-place transform it. - - Returns: - Transform: the transform that is applied on the input. - """ - args = _get_aug_input_args(self, aug_input) - tfm = self.get_transform(*args) - assert isinstance(tfm, (Transform, TransformList)), ( - f"{type(self)}.get_transform must return an instance of Transform! " - f"Got {type(tfm)} instead." - ) - aug_input.transform(tfm) - return tfm - - def _rand_range(self, low=1.0, high=None, size=None): - """ - Uniform float random number between low and high. - """ - if high is None: - low, high = 0, low - if size is None: - size = [] - return np.random.uniform(low, high, size) - - def __repr__(self): - """ - Produce something like: - "MyAugmentation(field1={self.field1}, field2={self.field2})" - """ - try: - sig = inspect.signature(self.__init__) - classname = type(self).__name__ - argstr = [] - for name, param in sig.parameters.items(): - assert ( - param.kind != param.VAR_POSITIONAL and param.kind != param.VAR_KEYWORD - ), "The default __repr__ doesn't support *args or **kwargs" - assert hasattr(self, name), ( - "Attribute {} not found! " - "Default __repr__ only works if attributes match the constructor.".format(name) - ) - attr = getattr(self, name) - default = param.default - if default is attr: - continue - attr_str = pprint.pformat(attr) - if "\n" in attr_str: - # don't show it if pformat decides to use >1 lines - attr_str = "..." - argstr.append("{}={}".format(name, attr_str)) - return "{}({})".format(classname, ", ".join(argstr)) - except AssertionError: - return super().__repr__() - - __str__ = __repr__ - - -class _TransformToAug(Augmentation): - def __init__(self, tfm: Transform): - self.tfm = tfm - - def get_transform(self, *args): - return self.tfm - - def __repr__(self): - return repr(self.tfm) - - __str__ = __repr__ - - -def _transform_to_aug(tfm_or_aug): - """ - Wrap Transform into Augmentation. - Private, used internally to implement augmentations. - """ - assert isinstance(tfm_or_aug, (Transform, Augmentation)), tfm_or_aug - if isinstance(tfm_or_aug, Augmentation): - return tfm_or_aug - else: - return _TransformToAug(tfm_or_aug) - - -class AugmentationList(Augmentation): - """ - Apply a sequence of augmentations. - - It has ``__call__`` method to apply the augmentations. - - Note that :meth:`get_transform` method is impossible (will throw error if called) - for :class:`AugmentationList`, because in order to apply a sequence of augmentations, - the kth augmentation must be applied first, to provide inputs needed by the (k+1)th - augmentation. - """ - - def __init__(self, augs): - """ - Args: - augs (list[Augmentation or Transform]): - """ - super().__init__() - self.augs = [_transform_to_aug(x) for x in augs] - - def __call__(self, aug_input) -> TransformList: - tfms = [] - for x in self.augs: - tfm = x(aug_input) - tfms.append(tfm) - return TransformList(tfms) - - def __repr__(self): - msgs = [str(x) for x in self.augs] - return "AugmentationList[{}]".format(", ".join(msgs)) - - __str__ = __repr__ - - -class AugInput: - """ - Input that can be used with :meth:`Augmentation.__call__`. - This is a standard implementation for the majority of use cases. - This class provides the standard attributes **"image", "boxes", "sem_seg"** - defined in :meth:`__init__` and they may be needed by different augmentations. - Most augmentation policies do not need attributes beyond these three. - - After applying augmentations to these attributes (using :meth:`AugInput.transform`), - the returned transforms can then be used to transform other data structures that users have. - - Examples: - :: - input = AugInput(image, boxes=boxes) - tfms = augmentation(input) - transformed_image = input.image - transformed_boxes = input.boxes - transformed_other_data = tfms.apply_other(other_data) - - An extended project that works with new data types may implement augmentation policies - that need other inputs. An algorithm may need to transform inputs in a way different - from the standard approach defined in this class. In those rare situations, users can - implement a class similar to this class, that satify the following condition: - - * The input must provide access to these data in the form of attribute access - (``getattr``). For example, if an :class:`Augmentation` to be applied needs "image" - and "sem_seg" arguments, its input must have the attribute "image" and "sem_seg". - * The input must have a ``transform(tfm: Transform) -> None`` method which - in-place transforms all its attributes. - """ - - # TODO maybe should support more builtin data types here - def __init__( - self, - image: np.ndarray, - *, - boxes: Optional[np.ndarray] = None, - sem_seg: Optional[np.ndarray] = None, - ): - """ - Args: - image (ndarray): (H,W) or (H,W,C) ndarray of type uint8 in range [0, 255], or - floating point in range [0, 1] or [0, 255]. The meaning of C is up - to users. - boxes (ndarray or None): Nx4 float32 boxes in XYXY_ABS mode - sem_seg (ndarray or None): HxW uint8 semantic segmentation mask. Each element - is an integer label of pixel. - """ - _check_img_dtype(image) - self.image = image - self.boxes = boxes - self.sem_seg = sem_seg - - def transform(self, tfm: Transform) -> None: - """ - In-place transform all attributes of this class. - - By "in-place", it means after calling this method, accessing an attribute such - as ``self.image`` will return transformed data. - """ - self.image = tfm.apply_image(self.image) - if self.boxes is not None: - self.boxes = tfm.apply_box(self.boxes) - if self.sem_seg is not None: - self.sem_seg = tfm.apply_segmentation(self.sem_seg) - - def apply_augmentations( - self, augmentations: List[Union[Augmentation, Transform]] - ) -> TransformList: - """ - Equivalent of ``AugmentationList(augmentations)(self)`` - """ - return AugmentationList(augmentations)(self) - - -def apply_augmentations(augmentations: List[Union[Transform, Augmentation]], inputs): - """ - Use ``T.AugmentationList(augmentations)(inputs)`` instead. - """ - if isinstance(inputs, np.ndarray): - # handle the common case of image-only Augmentation, also for backward compatibility - image_only = True - inputs = AugInput(inputs) - else: - image_only = False - tfms = inputs.apply_augmentations(augmentations) - return inputs.image if image_only else inputs, tfms - - -apply_transform_gens = apply_augmentations -""" -Alias for backward-compatibility. -""" - -TransformGen = Augmentation -""" -Alias for Augmentation, since it is something that generates :class:`Transform`s -""" - -StandardAugInput = AugInput -""" -Alias for compatibility. It's not worth the complexity to have two classes. -""" diff --git a/spaces/brjathu/HMR2.0/vendor/detectron2/projects/DensePose/doc/BOOTSTRAPPING_PIPELINE.md b/spaces/brjathu/HMR2.0/vendor/detectron2/projects/DensePose/doc/BOOTSTRAPPING_PIPELINE.md deleted file mode 100644 index a1326862abe5479140269f5e6af50b68e7c2d0aa..0000000000000000000000000000000000000000 --- a/spaces/brjathu/HMR2.0/vendor/detectron2/projects/DensePose/doc/BOOTSTRAPPING_PIPELINE.md +++ /dev/null @@ -1,197 +0,0 @@ -# Bootstrapping Pipeline - -Bootstrapping pipeline for DensePose was proposed in -[Sanakoyeu et al., 2020](https://arxiv.org/pdf/2003.00080.pdf) -to extend DensePose from humans to proximal animal classes -(chimpanzees). Currently, the pipeline is only implemented for -[chart-based models](DENSEPOSE_IUV.md). -Bootstrapping proceeds in two steps. - -## Master Model Training - -Master model is trained on data from source domain (humans) -and supporting domain (animals). Instances from the source domain -contain full DensePose annotations (`S`, `I`, `U` and `V`) and -instances from the supporting domain have segmentation annotations only. -To ensure segmentation quality in the target domain, only a subset of -supporting domain classes is included into the training. This is achieved -through category filters, e.g. -(see [configs/evolution/Base-RCNN-FPN-Atop10P_CA.yaml](../configs/evolution/Base-RCNN-FPN-Atop10P_CA.yaml)): - -``` - WHITELISTED_CATEGORIES: - "base_coco_2017_train": - - 1 # person - - 16 # bird - - 17 # cat - - 18 # dog - - 19 # horse - - 20 # sheep - - 21 # cow - - 22 # elephant - - 23 # bear - - 24 # zebra - - 25 # girafe -``` -The acronym `Atop10P` in config file names indicates that categories are filtered to -only contain top 10 animals and person. - -The training is performed in a *class-agnostic* manner: all instances -are mapped into the same class (person), e.g. -(see [configs/evolution/Base-RCNN-FPN-Atop10P_CA.yaml](../configs/evolution/Base-RCNN-FPN-Atop10P_CA.yaml)): - -``` - CATEGORY_MAPS: - "base_coco_2017_train": - "16": 1 # bird -> person - "17": 1 # cat -> person - "18": 1 # dog -> person - "19": 1 # horse -> person - "20": 1 # sheep -> person - "21": 1 # cow -> person - "22": 1 # elephant -> person - "23": 1 # bear -> person - "24": 1 # zebra -> person - "25": 1 # girafe -> person -``` -The acronym `CA` in config file names indicates that the training is class-agnostic. - -## Student Model Training - -Student model is trained on data from source domain (humans), -supporting domain (animals) and target domain (chimpanzees). -Annotations in source and supporting domains are similar to the ones -used for the master model training. -Annotations in target domain are obtained by applying the master model -to images that contain instances from the target category and sampling -sparse annotations from dense results. This process is called *bootstrapping*. -Below we give details on how the bootstrapping pipeline is implemented. - -### Data Loaders - -The central components that enable bootstrapping are -[`InferenceBasedLoader`](../densepose/data/inference_based_loader.py) and -[`CombinedDataLoader`](../densepose/data/combined_loader.py). - -`InferenceBasedLoader` takes images from a data loader, applies a model -to the images, filters the model outputs based on the selected criteria and -samples the filtered outputs to produce annotations. - -`CombinedDataLoader` combines data obtained from the loaders based on specified -ratios. The standard data loader has the default ratio of 1.0, -ratios for bootstrap datasets are specified in the configuration file. -The higher the ratio the higher the probability to include samples from the -particular data loader into a batch. - -Here is an example of the bootstrapping configuration taken from -[`configs/evolution/densepose_R_50_FPN_DL_WC1M_3x_Atop10P_CA_B_uniform.yaml`](../configs/evolution/densepose_R_50_FPN_DL_WC1M_3x_Atop10P_CA_B_uniform.yaml): -``` -BOOTSTRAP_DATASETS: - - DATASET: "chimpnsee" - RATIO: 1.0 - IMAGE_LOADER: - TYPE: "video_keyframe" - SELECT: - STRATEGY: "random_k" - NUM_IMAGES: 4 - TRANSFORM: - TYPE: "resize" - MIN_SIZE: 800 - MAX_SIZE: 1333 - BATCH_SIZE: 8 - NUM_WORKERS: 1 - INFERENCE: - INPUT_BATCH_SIZE: 1 - OUTPUT_BATCH_SIZE: 1 - DATA_SAMPLER: - # supported types: - # densepose_uniform - # densepose_UV_confidence - # densepose_fine_segm_confidence - # densepose_coarse_segm_confidence - TYPE: "densepose_uniform" - COUNT_PER_CLASS: 8 - FILTER: - TYPE: "detection_score" - MIN_VALUE: 0.8 -BOOTSTRAP_MODEL: - WEIGHTS: https://dl.fbaipublicfiles.com/densepose/evolution/densepose_R_50_FPN_DL_WC1M_3x_Atop10P_CA/217578784/model_final_9fe1cc.pkl -``` - -The above example has one bootstrap dataset (`chimpnsee`). This dataset is registered as -a [VIDEO_LIST](../densepose/data/datasets/chimpnsee.py) dataset, which means that -it consists of a number of videos specified in a text file. For videos there can be -different strategies to sample individual images. Here we use `video_keyframe` strategy -which considers only keyframes; this ensures temporal offset between sampled images and -faster seek operations. We select at most 4 random keyframes in each video: - -``` -SELECT: - STRATEGY: "random_k" - NUM_IMAGES: 4 -``` - -The frames are then resized - -``` -TRANSFORM: - TYPE: "resize" - MIN_SIZE: 800 - MAX_SIZE: 1333 -``` - -and batched using the standard -[PyTorch DataLoader](https://pytorch.org/docs/stable/data.html#torch.utils.data.DataLoader): - -``` -BATCH_SIZE: 8 -NUM_WORKERS: 1 -``` - -`InferenceBasedLoader` decomposes those batches into batches of size `INPUT_BATCH_SIZE` -and applies the master model specified by `BOOTSTRAP_MODEL`. Models outputs are filtered -by detection score: - -``` -FILTER: - TYPE: "detection_score" - MIN_VALUE: 0.8 -``` - -and sampled using the specified sampling strategy: - -``` -DATA_SAMPLER: - # supported types: - # densepose_uniform - # densepose_UV_confidence - # densepose_fine_segm_confidence - # densepose_coarse_segm_confidence - TYPE: "densepose_uniform" - COUNT_PER_CLASS: 8 -``` - -The current implementation supports -[uniform sampling](../densepose/data/samplers/densepose_uniform.py) and -[confidence-based sampling](../densepose/data/samplers/densepose_confidence_based.py) -to obtain sparse annotations from dense results. For confidence-based -sampling one needs to use the master model which produces confidence estimates. -The `WC1M` master model used in the example above produces all three types of confidence -estimates. - -Finally, sampled data is grouped into batches of size `OUTPUT_BATCH_SIZE`: - -``` -INFERENCE: - INPUT_BATCH_SIZE: 1 - OUTPUT_BATCH_SIZE: 1 -``` - -The proportion of data from annotated datasets and bootstrapped dataset can be tracked -in the logs, e.g.: - -``` -[... densepose.engine.trainer]: batch/ 1.8, batch/base_coco_2017_train 6.4, batch/densepose_coco_2014_train 3.85 -``` - -which means that over the last 20 iterations, on average for 1.8 bootstrapped data samples there were 6.4 samples from `base_coco_2017_train` and 3.85 samples from `densepose_coco_2014_train`. diff --git a/spaces/camenduru-com/VITS-Umamusume-voice-synthesizer/Libtorch C++ Infer/VITS-LibTorch.cpp b/spaces/camenduru-com/VITS-Umamusume-voice-synthesizer/Libtorch C++ Infer/VITS-LibTorch.cpp deleted file mode 100644 index afdd98e45af2fbeb2ba63961f45167dd3ecd4685..0000000000000000000000000000000000000000 --- a/spaces/camenduru-com/VITS-Umamusume-voice-synthesizer/Libtorch C++ Infer/VITS-LibTorch.cpp +++ /dev/null @@ -1,121 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include -typedef int64_t int64; -namespace Shirakana { - - struct WavHead { - char RIFF[4]; - long int size0; - char WAVE[4]; - char FMT[4]; - long int size1; - short int fmttag; - short int channel; - long int samplespersec; - long int bytepersec; - short int blockalign; - short int bitpersamples; - char DATA[4]; - long int size2; - }; - - int conArr2Wav(int64 size, int16_t* input, const char* filename) { - WavHead head = { {'R','I','F','F'},0,{'W','A','V','E'},{'f','m','t',' '},16, - 1,1,22050,22050 * 2,2,16,{'d','a','t','a'}, - 0 }; - head.size0 = size * 2 + 36; - head.size2 = size * 2; - std::ofstream ocout; - char* outputData = (char*)input; - ocout.open(filename, std::ios::out | std::ios::binary); - ocout.write((char*)&head, 44); - ocout.write(outputData, (int32_t)(size * 2)); - ocout.close(); - return 0; - } - - inline std::wstring to_wide_string(const std::string& input) - { - std::wstring_convert> converter; - return converter.from_bytes(input); - } - - inline std::string to_byte_string(const std::wstring& input) - { - std::wstring_convert> converter; - return converter.to_bytes(input); - } -} - -#define val const auto -int main() -{ - torch::jit::Module Vits; - std::string buffer; - std::vector text; - std::vector data; - while(true) - { - while (true) - { - std::cin >> buffer; - if (buffer == "end") - return 0; - if(buffer == "model") - { - std::cin >> buffer; - Vits = torch::jit::load(buffer); - continue; - } - if (buffer == "endinfer") - { - Shirakana::conArr2Wav(data.size(), data.data(), "temp\\tmp.wav"); - data.clear(); - std::cout << "endofinfe"; - continue; - } - if (buffer == "line") - { - std::cin >> buffer; - while (buffer.find("endline")==std::string::npos) - { - text.push_back(std::atoi(buffer.c_str())); - std::cin >> buffer; - } - val InputTensor = torch::from_blob(text.data(), { 1,static_cast(text.size()) }, torch::kInt64); - std::array TextLength{ static_cast(text.size()) }; - val InputTensor_length = torch::from_blob(TextLength.data(), { 1 }, torch::kInt64); - std::vector inputs; - inputs.push_back(InputTensor); - inputs.push_back(InputTensor_length); - if (buffer.length() > 7) - { - std::array speakerIndex{ (int64)atoi(buffer.substr(7).c_str()) }; - inputs.push_back(torch::from_blob(speakerIndex.data(), { 1 }, torch::kLong)); - } - val output = Vits.forward(inputs).toTuple()->elements()[0].toTensor().multiply(32276.0F); - val outputSize = output.sizes().at(2); - val floatOutput = output.data_ptr(); - int16_t* outputTmp = (int16_t*)malloc(sizeof(float) * outputSize); - if (outputTmp == nullptr) { - throw std::exception("内存不足"); - } - for (int i = 0; i < outputSize; i++) { - *(outputTmp + i) = (int16_t) * (floatOutput + i); - } - data.insert(data.end(), outputTmp, outputTmp+outputSize); - free(outputTmp); - text.clear(); - std::cout << "endofline"; - } - } - } - //model S:\VSGIT\ShirakanaTTSUI\build\x64\Release\Mods\AtriVITS\AtriVITS_LJS.pt -} \ No newline at end of file diff --git a/spaces/caojiachen1/ChatGPT/predict.py b/spaces/caojiachen1/ChatGPT/predict.py deleted file mode 100644 index 844e623fec4833b5bb5400432e3bf453ffe36483..0000000000000000000000000000000000000000 --- a/spaces/caojiachen1/ChatGPT/predict.py +++ /dev/null @@ -1,185 +0,0 @@ -# 借鉴了 https://github.com/GaiZhenbiao/ChuanhuChatGPT 项目 - -import json -import gradio as gr -import logging -import traceback -import requests -import importlib - -# config_private.py放自己的秘密如API和代理网址 -# 读取时首先看是否存在私密的config_private配置文件(不受git管控),如果有,则覆盖原config文件 -try: from config_private import proxies, API_URL, API_KEY, TIMEOUT_SECONDS, MAX_RETRY, LLM_MODEL -except: from config import proxies, API_URL, API_KEY, TIMEOUT_SECONDS, MAX_RETRY, LLM_MODEL - -timeout_bot_msg = '[local] Request timeout, network error. please check proxy settings in config.py.' - -def get_full_error(chunk, stream_response): - """ - 获取完整的从Openai返回的报错 - """ - while True: - try: - chunk += next(stream_response) - except: - break - return chunk - -def predict_no_ui(inputs, top_p, temperature, history=[]): - """ - 发送至chatGPT,等待回复,一次性完成,不显示中间过程。 - predict函数的简化版。 - 用于payload比较大的情况,或者用于实现多线、带嵌套的复杂功能。 - - inputs 是本次问询的输入 - top_p, temperature是chatGPT的内部调优参数 - history 是之前的对话列表 - (注意无论是inputs还是history,内容太长了都会触发token数量溢出的错误,然后raise ConnectionAbortedError) - """ - headers, payload = generate_payload(inputs, top_p, temperature, history, system_prompt="", stream=False) - - retry = 0 - while True: - try: - # make a POST request to the API endpoint, stream=False - response = requests.post(API_URL, headers=headers, proxies=proxies, - json=payload, stream=False, timeout=TIMEOUT_SECONDS*2); break - except requests.exceptions.ReadTimeout as e: - retry += 1 - traceback.print_exc() - if MAX_RETRY!=0: print(f'请求超时,正在重试 ({retry}/{MAX_RETRY}) ……') - if retry > MAX_RETRY: raise TimeoutError - - try: - result = json.loads(response.text)["choices"][0]["message"]["content"] - return result - except Exception as e: - if "choices" not in response.text: print(response.text) - raise ConnectionAbortedError("Json解析不合常规,可能是文本过长" + response.text) - - -def predict(inputs, top_p, temperature, chatbot=[], history=[], system_prompt='', - stream = True, additional_fn=None): - """ - 发送至chatGPT,流式获取输出。 - 用于基础的对话功能。 - inputs 是本次问询的输入 - top_p, temperature是chatGPT的内部调优参数 - history 是之前的对话列表(注意无论是inputs还是history,内容太长了都会触发token数量溢出的错误) - chatbot 为WebUI中显示的对话列表,修改它,然后yeild出去,可以直接修改对话界面内容 - additional_fn代表点击的哪个按钮,按钮见functional.py - """ - if additional_fn is not None: - import functional - importlib.reload(functional) - functional = functional.get_functionals() - inputs = functional[additional_fn]["Prefix"] + inputs + functional[additional_fn]["Suffix"] - - if stream: - raw_input = inputs - logging.info(f'[raw_input] {raw_input}') - chatbot.append((inputs, "")) - yield chatbot, history, "等待响应" - - headers, payload = generate_payload(inputs, top_p, temperature, history, system_prompt, stream) - history.append(inputs); history.append(" ") - - retry = 0 - while True: - try: - # make a POST request to the API endpoint, stream=True - response = requests.post(API_URL, headers=headers, proxies=proxies, - json=payload, stream=True, timeout=TIMEOUT_SECONDS);break - except: - retry += 1 - chatbot[-1] = ((chatbot[-1][0], timeout_bot_msg)) - retry_msg = f",正在重试 ({retry}/{MAX_RETRY}) ……" if MAX_RETRY > 0 else "" - yield chatbot, history, "请求超时"+retry_msg - if retry > MAX_RETRY: raise TimeoutError - - gpt_replying_buffer = "" - - is_head_of_the_stream = True - if stream: - stream_response = response.iter_lines() - while True: - chunk = next(stream_response) - # print(chunk.decode()[6:]) - if is_head_of_the_stream: - # 数据流的第一帧不携带content - is_head_of_the_stream = False; continue - - if chunk: - try: - if len(json.loads(chunk.decode()[6:])['choices'][0]["delta"]) == 0: - # 判定为数据流的结束,gpt_replying_buffer也写完了 - logging.info(f'[response] {gpt_replying_buffer}') - break - # 处理数据流的主体 - chunkjson = json.loads(chunk.decode()[6:]) - status_text = f"finish_reason: {chunkjson['choices'][0]['finish_reason']}" - # 如果这里抛出异常,一般是文本过长,详情见get_full_error的输出 - gpt_replying_buffer = gpt_replying_buffer + json.loads(chunk.decode()[6:])['choices'][0]["delta"]["content"] - history[-1] = gpt_replying_buffer - chatbot[-1] = (history[-2], history[-1]) - yield chatbot, history, status_text - - except Exception as e: - traceback.print_exc() - yield chatbot, history, "Json解析不合常规,很可能是文本过长" - chunk = get_full_error(chunk, stream_response) - error_msg = chunk.decode() - if "reduce the length" in error_msg: - chatbot[-1] = (history[-1], "[Local Message] Input (or history) is too long, please reduce input or clear history by refleshing this page.") - history = [] - yield chatbot, history, "Json解析不合常规,很可能是文本过长" + error_msg - return - -def generate_payload(inputs, top_p, temperature, history, system_prompt, stream): - """ - 整合所有信息,选择LLM模型,生成http请求,为发送请求做准备 - """ - headers = { - "Content-Type": "application/json", - "Authorization": f"Bearer {API_KEY}" - } - - conversation_cnt = len(history) // 2 - - messages = [{"role": "system", "content": system_prompt}] - if conversation_cnt: - for index in range(0, 2*conversation_cnt, 2): - what_i_have_asked = {} - what_i_have_asked["role"] = "user" - what_i_have_asked["content"] = history[index] - what_gpt_answer = {} - what_gpt_answer["role"] = "assistant" - what_gpt_answer["content"] = history[index+1] - if what_i_have_asked["content"] != "": - if what_gpt_answer["content"] == "": continue - if what_gpt_answer["content"] == timeout_bot_msg: continue - messages.append(what_i_have_asked) - messages.append(what_gpt_answer) - else: - messages[-1]['content'] = what_gpt_answer['content'] - - what_i_ask_now = {} - what_i_ask_now["role"] = "user" - what_i_ask_now["content"] = inputs - messages.append(what_i_ask_now) - - payload = { - "model": LLM_MODEL, - "messages": messages, - "temperature": temperature, # 1.0, - "top_p": top_p, # 1.0, - "n": 1, - "stream": stream, - "presence_penalty": 0, - "frequency_penalty": 0, - } - - print(f" {LLM_MODEL} : {conversation_cnt} : {inputs}") - return headers,payload - - diff --git a/spaces/caoyiming/vits-uma-genshin-honkai/Docker/vits.sh b/spaces/caoyiming/vits-uma-genshin-honkai/Docker/vits.sh deleted file mode 100644 index 2b87f26eda96d3800b73b4a21b210c78888a2299..0000000000000000000000000000000000000000 --- a/spaces/caoyiming/vits-uma-genshin-honkai/Docker/vits.sh +++ /dev/null @@ -1,20 +0,0 @@ -#!/bin/bash -run() { - echo -e "\033[32m已完成初始化,启动服务...\033[0m" - python3 /app/vits-uma-genshin-honkai/app.py -} -install() { - echo -e "\033[33m正在初始化:安装依赖....\033[0m" - pip install -r /app/vits-uma-genshin-honkai/requirements.txt -i https://mirrors.ustc.edu.cn/pypi/web/simple - echo -e "\033[33m正在下载模型....\033[0m" - rm -f /app/vits-uma-genshin-honkai/model/G_953000.pth - wget -O /app/vits-uma-genshin-honkai/model/G_953000.pth https://huggingface.co/spaces/ikechan8370/vits-uma-genshin-honkai/resolve/main/model/G_953000.pth - echo -e "\033[32m初始化完成!\033[0m" - run -} - -if [ ! -f "/app/vits-uma-genshin-honkai/model/G_953000.pth" ] || [ "$(stat -c%s "/app/vits-uma-genshin-honkai/model/G_953000.pth")" -lt 10000 ]; then - install -else - run -fi diff --git a/spaces/carlosalonso/Detection-video/carpeta_deteccion/detectron2/data/datasets/lvis_v1_categories.py b/spaces/carlosalonso/Detection-video/carpeta_deteccion/detectron2/data/datasets/lvis_v1_categories.py deleted file mode 100644 index 7374e6968bb006f5d8c49e75d9d3b31ea3d77d05..0000000000000000000000000000000000000000 --- a/spaces/carlosalonso/Detection-video/carpeta_deteccion/detectron2/data/datasets/lvis_v1_categories.py +++ /dev/null @@ -1,16 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. -# Autogen with -# with open("lvis_v1_val.json", "r") as f: -# a = json.load(f) -# c = a["categories"] -# for x in c: -# del x["image_count"] -# del x["instance_count"] -# LVIS_CATEGORIES = repr(c) + " # noqa" -# with open("/tmp/lvis_categories.py", "wt") as f: -# f.write(f"LVIS_CATEGORIES = {LVIS_CATEGORIES}") -# Then paste the contents of that file below - -# fmt: off -LVIS_CATEGORIES = [{'frequency': 'c', 'synset': 'aerosol.n.02', 'synonyms': ['aerosol_can', 'spray_can'], 'id': 1, 'def': 'a dispenser that holds a substance under pressure', 'name': 'aerosol_can'}, {'frequency': 'f', 'synset': 'air_conditioner.n.01', 'synonyms': ['air_conditioner'], 'id': 2, 'def': 'a machine that keeps air cool and dry', 'name': 'air_conditioner'}, {'frequency': 'f', 'synset': 'airplane.n.01', 'synonyms': ['airplane', 'aeroplane'], 'id': 3, 'def': 'an aircraft that has a fixed wing and is powered by propellers or jets', 'name': 'airplane'}, {'frequency': 'f', 'synset': 'alarm_clock.n.01', 'synonyms': ['alarm_clock'], 'id': 4, 'def': 'a clock that wakes a sleeper at some preset time', 'name': 'alarm_clock'}, {'frequency': 'c', 'synset': 'alcohol.n.01', 'synonyms': ['alcohol', 'alcoholic_beverage'], 'id': 5, 'def': 'a liquor or brew containing alcohol as the active agent', 'name': 'alcohol'}, {'frequency': 'c', 'synset': 'alligator.n.02', 'synonyms': ['alligator', 'gator'], 'id': 6, 'def': 'amphibious reptiles related to crocodiles but with shorter broader snouts', 'name': 'alligator'}, {'frequency': 'c', 'synset': 'almond.n.02', 'synonyms': ['almond'], 'id': 7, 'def': 'oval-shaped edible seed of the almond tree', 'name': 'almond'}, {'frequency': 'c', 'synset': 'ambulance.n.01', 'synonyms': ['ambulance'], 'id': 8, 'def': 'a vehicle that takes people to and from hospitals', 'name': 'ambulance'}, {'frequency': 'c', 'synset': 'amplifier.n.01', 'synonyms': ['amplifier'], 'id': 9, 'def': 'electronic equipment that increases strength of signals', 'name': 'amplifier'}, {'frequency': 'c', 'synset': 'anklet.n.03', 'synonyms': ['anklet', 'ankle_bracelet'], 'id': 10, 'def': 'an ornament worn around the ankle', 'name': 'anklet'}, {'frequency': 'f', 'synset': 'antenna.n.01', 'synonyms': ['antenna', 'aerial', 'transmitting_aerial'], 'id': 11, 'def': 'an electrical device that sends or receives radio or television signals', 'name': 'antenna'}, {'frequency': 'f', 'synset': 'apple.n.01', 'synonyms': ['apple'], 'id': 12, 'def': 'fruit with red or yellow or green skin and sweet to tart crisp whitish flesh', 'name': 'apple'}, {'frequency': 'r', 'synset': 'applesauce.n.01', 'synonyms': ['applesauce'], 'id': 13, 'def': 'puree of stewed apples usually sweetened and spiced', 'name': 'applesauce'}, {'frequency': 'r', 'synset': 'apricot.n.02', 'synonyms': ['apricot'], 'id': 14, 'def': 'downy yellow to rosy-colored fruit resembling a small peach', 'name': 'apricot'}, {'frequency': 'f', 'synset': 'apron.n.01', 'synonyms': ['apron'], 'id': 15, 'def': 'a garment of cloth that is tied about the waist and worn to protect clothing', 'name': 'apron'}, {'frequency': 'c', 'synset': 'aquarium.n.01', 'synonyms': ['aquarium', 'fish_tank'], 'id': 16, 'def': 'a tank/pool/bowl filled with water for keeping live fish and underwater animals', 'name': 'aquarium'}, {'frequency': 'r', 'synset': 'arctic.n.02', 'synonyms': ['arctic_(type_of_shoe)', 'galosh', 'golosh', 'rubber_(type_of_shoe)', 'gumshoe'], 'id': 17, 'def': 'a waterproof overshoe that protects shoes from water or snow', 'name': 'arctic_(type_of_shoe)'}, {'frequency': 'c', 'synset': 'armband.n.02', 'synonyms': ['armband'], 'id': 18, 'def': 'a band worn around the upper arm', 'name': 'armband'}, {'frequency': 'f', 'synset': 'armchair.n.01', 'synonyms': ['armchair'], 'id': 19, 'def': 'chair with a support on each side for arms', 'name': 'armchair'}, {'frequency': 'r', 'synset': 'armoire.n.01', 'synonyms': ['armoire'], 'id': 20, 'def': 'a large wardrobe or cabinet', 'name': 'armoire'}, {'frequency': 'r', 'synset': 'armor.n.01', 'synonyms': ['armor', 'armour'], 'id': 21, 'def': 'protective covering made of metal and used in combat', 'name': 'armor'}, {'frequency': 'c', 'synset': 'artichoke.n.02', 'synonyms': ['artichoke'], 'id': 22, 'def': 'a thistlelike flower head with edible fleshy leaves and heart', 'name': 'artichoke'}, {'frequency': 'f', 'synset': 'ashcan.n.01', 'synonyms': ['trash_can', 'garbage_can', 'wastebin', 'dustbin', 'trash_barrel', 'trash_bin'], 'id': 23, 'def': 'a bin that holds rubbish until it is collected', 'name': 'trash_can'}, {'frequency': 'c', 'synset': 'ashtray.n.01', 'synonyms': ['ashtray'], 'id': 24, 'def': "a receptacle for the ash from smokers' cigars or cigarettes", 'name': 'ashtray'}, {'frequency': 'c', 'synset': 'asparagus.n.02', 'synonyms': ['asparagus'], 'id': 25, 'def': 'edible young shoots of the asparagus plant', 'name': 'asparagus'}, {'frequency': 'c', 'synset': 'atomizer.n.01', 'synonyms': ['atomizer', 'atomiser', 'spray', 'sprayer', 'nebulizer', 'nebuliser'], 'id': 26, 'def': 'a dispenser that turns a liquid (such as perfume) into a fine mist', 'name': 'atomizer'}, {'frequency': 'f', 'synset': 'avocado.n.01', 'synonyms': ['avocado'], 'id': 27, 'def': 'a pear-shaped fruit with green or blackish skin and rich yellowish pulp enclosing a single large seed', 'name': 'avocado'}, {'frequency': 'c', 'synset': 'award.n.02', 'synonyms': ['award', 'accolade'], 'id': 28, 'def': 'a tangible symbol signifying approval or distinction', 'name': 'award'}, {'frequency': 'f', 'synset': 'awning.n.01', 'synonyms': ['awning'], 'id': 29, 'def': 'a canopy made of canvas to shelter people or things from rain or sun', 'name': 'awning'}, {'frequency': 'r', 'synset': 'ax.n.01', 'synonyms': ['ax', 'axe'], 'id': 30, 'def': 'an edge tool with a heavy bladed head mounted across a handle', 'name': 'ax'}, {'frequency': 'r', 'synset': 'baboon.n.01', 'synonyms': ['baboon'], 'id': 31, 'def': 'large terrestrial monkeys having doglike muzzles', 'name': 'baboon'}, {'frequency': 'f', 'synset': 'baby_buggy.n.01', 'synonyms': ['baby_buggy', 'baby_carriage', 'perambulator', 'pram', 'stroller'], 'id': 32, 'def': 'a small vehicle with four wheels in which a baby or child is pushed around', 'name': 'baby_buggy'}, {'frequency': 'c', 'synset': 'backboard.n.01', 'synonyms': ['basketball_backboard'], 'id': 33, 'def': 'a raised vertical board with basket attached; used to play basketball', 'name': 'basketball_backboard'}, {'frequency': 'f', 'synset': 'backpack.n.01', 'synonyms': ['backpack', 'knapsack', 'packsack', 'rucksack', 'haversack'], 'id': 34, 'def': 'a bag carried by a strap on your back or shoulder', 'name': 'backpack'}, {'frequency': 'f', 'synset': 'bag.n.04', 'synonyms': ['handbag', 'purse', 'pocketbook'], 'id': 35, 'def': 'a container used for carrying money and small personal items or accessories', 'name': 'handbag'}, {'frequency': 'f', 'synset': 'bag.n.06', 'synonyms': ['suitcase', 'baggage', 'luggage'], 'id': 36, 'def': 'cases used to carry belongings when traveling', 'name': 'suitcase'}, {'frequency': 'c', 'synset': 'bagel.n.01', 'synonyms': ['bagel', 'beigel'], 'id': 37, 'def': 'glazed yeast-raised doughnut-shaped roll with hard crust', 'name': 'bagel'}, {'frequency': 'r', 'synset': 'bagpipe.n.01', 'synonyms': ['bagpipe'], 'id': 38, 'def': 'a tubular wind instrument; the player blows air into a bag and squeezes it out', 'name': 'bagpipe'}, {'frequency': 'r', 'synset': 'baguet.n.01', 'synonyms': ['baguet', 'baguette'], 'id': 39, 'def': 'narrow French stick loaf', 'name': 'baguet'}, {'frequency': 'r', 'synset': 'bait.n.02', 'synonyms': ['bait', 'lure'], 'id': 40, 'def': 'something used to lure fish or other animals into danger so they can be trapped or killed', 'name': 'bait'}, {'frequency': 'f', 'synset': 'ball.n.06', 'synonyms': ['ball'], 'id': 41, 'def': 'a spherical object used as a plaything', 'name': 'ball'}, {'frequency': 'r', 'synset': 'ballet_skirt.n.01', 'synonyms': ['ballet_skirt', 'tutu'], 'id': 42, 'def': 'very short skirt worn by ballerinas', 'name': 'ballet_skirt'}, {'frequency': 'f', 'synset': 'balloon.n.01', 'synonyms': ['balloon'], 'id': 43, 'def': 'large tough nonrigid bag filled with gas or heated air', 'name': 'balloon'}, {'frequency': 'c', 'synset': 'bamboo.n.02', 'synonyms': ['bamboo'], 'id': 44, 'def': 'woody tropical grass having hollow woody stems', 'name': 'bamboo'}, {'frequency': 'f', 'synset': 'banana.n.02', 'synonyms': ['banana'], 'id': 45, 'def': 'elongated crescent-shaped yellow fruit with soft sweet flesh', 'name': 'banana'}, {'frequency': 'c', 'synset': 'band_aid.n.01', 'synonyms': ['Band_Aid'], 'id': 46, 'def': 'trade name for an adhesive bandage to cover small cuts or blisters', 'name': 'Band_Aid'}, {'frequency': 'c', 'synset': 'bandage.n.01', 'synonyms': ['bandage'], 'id': 47, 'def': 'a piece of soft material that covers and protects an injured part of the body', 'name': 'bandage'}, {'frequency': 'f', 'synset': 'bandanna.n.01', 'synonyms': ['bandanna', 'bandana'], 'id': 48, 'def': 'large and brightly colored handkerchief; often used as a neckerchief', 'name': 'bandanna'}, {'frequency': 'r', 'synset': 'banjo.n.01', 'synonyms': ['banjo'], 'id': 49, 'def': 'a stringed instrument of the guitar family with a long neck and circular body', 'name': 'banjo'}, {'frequency': 'f', 'synset': 'banner.n.01', 'synonyms': ['banner', 'streamer'], 'id': 50, 'def': 'long strip of cloth or paper used for decoration or advertising', 'name': 'banner'}, {'frequency': 'r', 'synset': 'barbell.n.01', 'synonyms': ['barbell'], 'id': 51, 'def': 'a bar to which heavy discs are attached at each end; used in weightlifting', 'name': 'barbell'}, {'frequency': 'r', 'synset': 'barge.n.01', 'synonyms': ['barge'], 'id': 52, 'def': 'a flatbottom boat for carrying heavy loads (especially on canals)', 'name': 'barge'}, {'frequency': 'f', 'synset': 'barrel.n.02', 'synonyms': ['barrel', 'cask'], 'id': 53, 'def': 'a cylindrical container that holds liquids', 'name': 'barrel'}, {'frequency': 'c', 'synset': 'barrette.n.01', 'synonyms': ['barrette'], 'id': 54, 'def': "a pin for holding women's hair in place", 'name': 'barrette'}, {'frequency': 'c', 'synset': 'barrow.n.03', 'synonyms': ['barrow', 'garden_cart', 'lawn_cart', 'wheelbarrow'], 'id': 55, 'def': 'a cart for carrying small loads; has handles and one or more wheels', 'name': 'barrow'}, {'frequency': 'f', 'synset': 'base.n.03', 'synonyms': ['baseball_base'], 'id': 56, 'def': 'a place that the runner must touch before scoring', 'name': 'baseball_base'}, {'frequency': 'f', 'synset': 'baseball.n.02', 'synonyms': ['baseball'], 'id': 57, 'def': 'a ball used in playing baseball', 'name': 'baseball'}, {'frequency': 'f', 'synset': 'baseball_bat.n.01', 'synonyms': ['baseball_bat'], 'id': 58, 'def': 'an implement used in baseball by the batter', 'name': 'baseball_bat'}, {'frequency': 'f', 'synset': 'baseball_cap.n.01', 'synonyms': ['baseball_cap', 'jockey_cap', 'golf_cap'], 'id': 59, 'def': 'a cap with a bill', 'name': 'baseball_cap'}, {'frequency': 'f', 'synset': 'baseball_glove.n.01', 'synonyms': ['baseball_glove', 'baseball_mitt'], 'id': 60, 'def': 'the handwear used by fielders in playing baseball', 'name': 'baseball_glove'}, {'frequency': 'f', 'synset': 'basket.n.01', 'synonyms': ['basket', 'handbasket'], 'id': 61, 'def': 'a container that is usually woven and has handles', 'name': 'basket'}, {'frequency': 'c', 'synset': 'basketball.n.02', 'synonyms': ['basketball'], 'id': 62, 'def': 'an inflated ball used in playing basketball', 'name': 'basketball'}, {'frequency': 'r', 'synset': 'bass_horn.n.01', 'synonyms': ['bass_horn', 'sousaphone', 'tuba'], 'id': 63, 'def': 'the lowest brass wind instrument', 'name': 'bass_horn'}, {'frequency': 'c', 'synset': 'bat.n.01', 'synonyms': ['bat_(animal)'], 'id': 64, 'def': 'nocturnal mouselike mammal with forelimbs modified to form membranous wings', 'name': 'bat_(animal)'}, {'frequency': 'f', 'synset': 'bath_mat.n.01', 'synonyms': ['bath_mat'], 'id': 65, 'def': 'a heavy towel or mat to stand on while drying yourself after a bath', 'name': 'bath_mat'}, {'frequency': 'f', 'synset': 'bath_towel.n.01', 'synonyms': ['bath_towel'], 'id': 66, 'def': 'a large towel; to dry yourself after a bath', 'name': 'bath_towel'}, {'frequency': 'c', 'synset': 'bathrobe.n.01', 'synonyms': ['bathrobe'], 'id': 67, 'def': 'a loose-fitting robe of towelling; worn after a bath or swim', 'name': 'bathrobe'}, {'frequency': 'f', 'synset': 'bathtub.n.01', 'synonyms': ['bathtub', 'bathing_tub'], 'id': 68, 'def': 'a large open container that you fill with water and use to wash the body', 'name': 'bathtub'}, {'frequency': 'r', 'synset': 'batter.n.02', 'synonyms': ['batter_(food)'], 'id': 69, 'def': 'a liquid or semiliquid mixture, as of flour, eggs, and milk, used in cooking', 'name': 'batter_(food)'}, {'frequency': 'c', 'synset': 'battery.n.02', 'synonyms': ['battery'], 'id': 70, 'def': 'a portable device that produces electricity', 'name': 'battery'}, {'frequency': 'r', 'synset': 'beach_ball.n.01', 'synonyms': ['beachball'], 'id': 71, 'def': 'large and light ball; for play at the seaside', 'name': 'beachball'}, {'frequency': 'c', 'synset': 'bead.n.01', 'synonyms': ['bead'], 'id': 72, 'def': 'a small ball with a hole through the middle used for ornamentation, jewellery, etc.', 'name': 'bead'}, {'frequency': 'c', 'synset': 'bean_curd.n.01', 'synonyms': ['bean_curd', 'tofu'], 'id': 73, 'def': 'cheeselike food made of curdled soybean milk', 'name': 'bean_curd'}, {'frequency': 'c', 'synset': 'beanbag.n.01', 'synonyms': ['beanbag'], 'id': 74, 'def': 'a bag filled with dried beans or similar items; used in games or to sit on', 'name': 'beanbag'}, {'frequency': 'f', 'synset': 'beanie.n.01', 'synonyms': ['beanie', 'beany'], 'id': 75, 'def': 'a small skullcap; formerly worn by schoolboys and college freshmen', 'name': 'beanie'}, {'frequency': 'f', 'synset': 'bear.n.01', 'synonyms': ['bear'], 'id': 76, 'def': 'large carnivorous or omnivorous mammals with shaggy coats and claws', 'name': 'bear'}, {'frequency': 'f', 'synset': 'bed.n.01', 'synonyms': ['bed'], 'id': 77, 'def': 'a piece of furniture that provides a place to sleep', 'name': 'bed'}, {'frequency': 'r', 'synset': 'bedpan.n.01', 'synonyms': ['bedpan'], 'id': 78, 'def': 'a shallow vessel used by a bedridden patient for defecation and urination', 'name': 'bedpan'}, {'frequency': 'f', 'synset': 'bedspread.n.01', 'synonyms': ['bedspread', 'bedcover', 'bed_covering', 'counterpane', 'spread'], 'id': 79, 'def': 'decorative cover for a bed', 'name': 'bedspread'}, {'frequency': 'f', 'synset': 'beef.n.01', 'synonyms': ['cow'], 'id': 80, 'def': 'cattle/cow', 'name': 'cow'}, {'frequency': 'f', 'synset': 'beef.n.02', 'synonyms': ['beef_(food)', 'boeuf_(food)'], 'id': 81, 'def': 'meat from an adult domestic bovine', 'name': 'beef_(food)'}, {'frequency': 'r', 'synset': 'beeper.n.01', 'synonyms': ['beeper', 'pager'], 'id': 82, 'def': 'an device that beeps when the person carrying it is being paged', 'name': 'beeper'}, {'frequency': 'f', 'synset': 'beer_bottle.n.01', 'synonyms': ['beer_bottle'], 'id': 83, 'def': 'a bottle that holds beer', 'name': 'beer_bottle'}, {'frequency': 'c', 'synset': 'beer_can.n.01', 'synonyms': ['beer_can'], 'id': 84, 'def': 'a can that holds beer', 'name': 'beer_can'}, {'frequency': 'r', 'synset': 'beetle.n.01', 'synonyms': ['beetle'], 'id': 85, 'def': 'insect with hard wing covers', 'name': 'beetle'}, {'frequency': 'f', 'synset': 'bell.n.01', 'synonyms': ['bell'], 'id': 86, 'def': 'a hollow device made of metal that makes a ringing sound when struck', 'name': 'bell'}, {'frequency': 'f', 'synset': 'bell_pepper.n.02', 'synonyms': ['bell_pepper', 'capsicum'], 'id': 87, 'def': 'large bell-shaped sweet pepper in green or red or yellow or orange or black varieties', 'name': 'bell_pepper'}, {'frequency': 'f', 'synset': 'belt.n.02', 'synonyms': ['belt'], 'id': 88, 'def': 'a band to tie or buckle around the body (usually at the waist)', 'name': 'belt'}, {'frequency': 'f', 'synset': 'belt_buckle.n.01', 'synonyms': ['belt_buckle'], 'id': 89, 'def': 'the buckle used to fasten a belt', 'name': 'belt_buckle'}, {'frequency': 'f', 'synset': 'bench.n.01', 'synonyms': ['bench'], 'id': 90, 'def': 'a long seat for more than one person', 'name': 'bench'}, {'frequency': 'c', 'synset': 'beret.n.01', 'synonyms': ['beret'], 'id': 91, 'def': 'a cap with no brim or bill; made of soft cloth', 'name': 'beret'}, {'frequency': 'c', 'synset': 'bib.n.02', 'synonyms': ['bib'], 'id': 92, 'def': 'a napkin tied under the chin of a child while eating', 'name': 'bib'}, {'frequency': 'r', 'synset': 'bible.n.01', 'synonyms': ['Bible'], 'id': 93, 'def': 'the sacred writings of the Christian religions', 'name': 'Bible'}, {'frequency': 'f', 'synset': 'bicycle.n.01', 'synonyms': ['bicycle', 'bike_(bicycle)'], 'id': 94, 'def': 'a wheeled vehicle that has two wheels and is moved by foot pedals', 'name': 'bicycle'}, {'frequency': 'f', 'synset': 'bill.n.09', 'synonyms': ['visor', 'vizor'], 'id': 95, 'def': 'a brim that projects to the front to shade the eyes', 'name': 'visor'}, {'frequency': 'f', 'synset': 'billboard.n.01', 'synonyms': ['billboard'], 'id': 96, 'def': 'large outdoor signboard', 'name': 'billboard'}, {'frequency': 'c', 'synset': 'binder.n.03', 'synonyms': ['binder', 'ring-binder'], 'id': 97, 'def': 'holds loose papers or magazines', 'name': 'binder'}, {'frequency': 'c', 'synset': 'binoculars.n.01', 'synonyms': ['binoculars', 'field_glasses', 'opera_glasses'], 'id': 98, 'def': 'an optical instrument designed for simultaneous use by both eyes', 'name': 'binoculars'}, {'frequency': 'f', 'synset': 'bird.n.01', 'synonyms': ['bird'], 'id': 99, 'def': 'animal characterized by feathers and wings', 'name': 'bird'}, {'frequency': 'c', 'synset': 'bird_feeder.n.01', 'synonyms': ['birdfeeder'], 'id': 100, 'def': 'an outdoor device that supplies food for wild birds', 'name': 'birdfeeder'}, {'frequency': 'c', 'synset': 'birdbath.n.01', 'synonyms': ['birdbath'], 'id': 101, 'def': 'an ornamental basin (usually in a garden) for birds to bathe in', 'name': 'birdbath'}, {'frequency': 'c', 'synset': 'birdcage.n.01', 'synonyms': ['birdcage'], 'id': 102, 'def': 'a cage in which a bird can be kept', 'name': 'birdcage'}, {'frequency': 'c', 'synset': 'birdhouse.n.01', 'synonyms': ['birdhouse'], 'id': 103, 'def': 'a shelter for birds', 'name': 'birdhouse'}, {'frequency': 'f', 'synset': 'birthday_cake.n.01', 'synonyms': ['birthday_cake'], 'id': 104, 'def': 'decorated cake served at a birthday party', 'name': 'birthday_cake'}, {'frequency': 'r', 'synset': 'birthday_card.n.01', 'synonyms': ['birthday_card'], 'id': 105, 'def': 'a card expressing a birthday greeting', 'name': 'birthday_card'}, {'frequency': 'r', 'synset': 'black_flag.n.01', 'synonyms': ['pirate_flag'], 'id': 106, 'def': 'a flag usually bearing a white skull and crossbones on a black background', 'name': 'pirate_flag'}, {'frequency': 'c', 'synset': 'black_sheep.n.02', 'synonyms': ['black_sheep'], 'id': 107, 'def': 'sheep with a black coat', 'name': 'black_sheep'}, {'frequency': 'c', 'synset': 'blackberry.n.01', 'synonyms': ['blackberry'], 'id': 108, 'def': 'large sweet black or very dark purple edible aggregate fruit', 'name': 'blackberry'}, {'frequency': 'f', 'synset': 'blackboard.n.01', 'synonyms': ['blackboard', 'chalkboard'], 'id': 109, 'def': 'sheet of slate; for writing with chalk', 'name': 'blackboard'}, {'frequency': 'f', 'synset': 'blanket.n.01', 'synonyms': ['blanket'], 'id': 110, 'def': 'bedding that keeps a person warm in bed', 'name': 'blanket'}, {'frequency': 'c', 'synset': 'blazer.n.01', 'synonyms': ['blazer', 'sport_jacket', 'sport_coat', 'sports_jacket', 'sports_coat'], 'id': 111, 'def': 'lightweight jacket; often striped in the colors of a club or school', 'name': 'blazer'}, {'frequency': 'f', 'synset': 'blender.n.01', 'synonyms': ['blender', 'liquidizer', 'liquidiser'], 'id': 112, 'def': 'an electrically powered mixer that mix or chop or liquefy foods', 'name': 'blender'}, {'frequency': 'r', 'synset': 'blimp.n.02', 'synonyms': ['blimp'], 'id': 113, 'def': 'a small nonrigid airship used for observation or as a barrage balloon', 'name': 'blimp'}, {'frequency': 'f', 'synset': 'blinker.n.01', 'synonyms': ['blinker', 'flasher'], 'id': 114, 'def': 'a light that flashes on and off; used as a signal or to send messages', 'name': 'blinker'}, {'frequency': 'f', 'synset': 'blouse.n.01', 'synonyms': ['blouse'], 'id': 115, 'def': 'a top worn by women', 'name': 'blouse'}, {'frequency': 'f', 'synset': 'blueberry.n.02', 'synonyms': ['blueberry'], 'id': 116, 'def': 'sweet edible dark-blue berries of blueberry plants', 'name': 'blueberry'}, {'frequency': 'r', 'synset': 'board.n.09', 'synonyms': ['gameboard'], 'id': 117, 'def': 'a flat portable surface (usually rectangular) designed for board games', 'name': 'gameboard'}, {'frequency': 'f', 'synset': 'boat.n.01', 'synonyms': ['boat', 'ship_(boat)'], 'id': 118, 'def': 'a vessel for travel on water', 'name': 'boat'}, {'frequency': 'r', 'synset': 'bob.n.05', 'synonyms': ['bob', 'bobber', 'bobfloat'], 'id': 119, 'def': 'a small float usually made of cork; attached to a fishing line', 'name': 'bob'}, {'frequency': 'c', 'synset': 'bobbin.n.01', 'synonyms': ['bobbin', 'spool', 'reel'], 'id': 120, 'def': 'a thing around which thread/tape/film or other flexible materials can be wound', 'name': 'bobbin'}, {'frequency': 'c', 'synset': 'bobby_pin.n.01', 'synonyms': ['bobby_pin', 'hairgrip'], 'id': 121, 'def': 'a flat wire hairpin used to hold bobbed hair in place', 'name': 'bobby_pin'}, {'frequency': 'c', 'synset': 'boiled_egg.n.01', 'synonyms': ['boiled_egg', 'coddled_egg'], 'id': 122, 'def': 'egg cooked briefly in the shell in gently boiling water', 'name': 'boiled_egg'}, {'frequency': 'r', 'synset': 'bolo_tie.n.01', 'synonyms': ['bolo_tie', 'bolo', 'bola_tie', 'bola'], 'id': 123, 'def': 'a cord fastened around the neck with an ornamental clasp and worn as a necktie', 'name': 'bolo_tie'}, {'frequency': 'c', 'synset': 'bolt.n.03', 'synonyms': ['deadbolt'], 'id': 124, 'def': 'the part of a lock that is engaged or withdrawn with a key', 'name': 'deadbolt'}, {'frequency': 'f', 'synset': 'bolt.n.06', 'synonyms': ['bolt'], 'id': 125, 'def': 'a screw that screws into a nut to form a fastener', 'name': 'bolt'}, {'frequency': 'r', 'synset': 'bonnet.n.01', 'synonyms': ['bonnet'], 'id': 126, 'def': 'a hat tied under the chin', 'name': 'bonnet'}, {'frequency': 'f', 'synset': 'book.n.01', 'synonyms': ['book'], 'id': 127, 'def': 'a written work or composition that has been published', 'name': 'book'}, {'frequency': 'c', 'synset': 'bookcase.n.01', 'synonyms': ['bookcase'], 'id': 128, 'def': 'a piece of furniture with shelves for storing books', 'name': 'bookcase'}, {'frequency': 'c', 'synset': 'booklet.n.01', 'synonyms': ['booklet', 'brochure', 'leaflet', 'pamphlet'], 'id': 129, 'def': 'a small book usually having a paper cover', 'name': 'booklet'}, {'frequency': 'r', 'synset': 'bookmark.n.01', 'synonyms': ['bookmark', 'bookmarker'], 'id': 130, 'def': 'a marker (a piece of paper or ribbon) placed between the pages of a book', 'name': 'bookmark'}, {'frequency': 'r', 'synset': 'boom.n.04', 'synonyms': ['boom_microphone', 'microphone_boom'], 'id': 131, 'def': 'a pole carrying an overhead microphone projected over a film or tv set', 'name': 'boom_microphone'}, {'frequency': 'f', 'synset': 'boot.n.01', 'synonyms': ['boot'], 'id': 132, 'def': 'footwear that covers the whole foot and lower leg', 'name': 'boot'}, {'frequency': 'f', 'synset': 'bottle.n.01', 'synonyms': ['bottle'], 'id': 133, 'def': 'a glass or plastic vessel used for storing drinks or other liquids', 'name': 'bottle'}, {'frequency': 'c', 'synset': 'bottle_opener.n.01', 'synonyms': ['bottle_opener'], 'id': 134, 'def': 'an opener for removing caps or corks from bottles', 'name': 'bottle_opener'}, {'frequency': 'c', 'synset': 'bouquet.n.01', 'synonyms': ['bouquet'], 'id': 135, 'def': 'an arrangement of flowers that is usually given as a present', 'name': 'bouquet'}, {'frequency': 'r', 'synset': 'bow.n.04', 'synonyms': ['bow_(weapon)'], 'id': 136, 'def': 'a weapon for shooting arrows', 'name': 'bow_(weapon)'}, {'frequency': 'f', 'synset': 'bow.n.08', 'synonyms': ['bow_(decorative_ribbons)'], 'id': 137, 'def': 'a decorative interlacing of ribbons', 'name': 'bow_(decorative_ribbons)'}, {'frequency': 'f', 'synset': 'bow_tie.n.01', 'synonyms': ['bow-tie', 'bowtie'], 'id': 138, 'def': "a man's tie that ties in a bow", 'name': 'bow-tie'}, {'frequency': 'f', 'synset': 'bowl.n.03', 'synonyms': ['bowl'], 'id': 139, 'def': 'a dish that is round and open at the top for serving foods', 'name': 'bowl'}, {'frequency': 'r', 'synset': 'bowl.n.08', 'synonyms': ['pipe_bowl'], 'id': 140, 'def': 'a small round container that is open at the top for holding tobacco', 'name': 'pipe_bowl'}, {'frequency': 'c', 'synset': 'bowler_hat.n.01', 'synonyms': ['bowler_hat', 'bowler', 'derby_hat', 'derby', 'plug_hat'], 'id': 141, 'def': 'a felt hat that is round and hard with a narrow brim', 'name': 'bowler_hat'}, {'frequency': 'r', 'synset': 'bowling_ball.n.01', 'synonyms': ['bowling_ball'], 'id': 142, 'def': 'a large ball with finger holes used in the sport of bowling', 'name': 'bowling_ball'}, {'frequency': 'f', 'synset': 'box.n.01', 'synonyms': ['box'], 'id': 143, 'def': 'a (usually rectangular) container; may have a lid', 'name': 'box'}, {'frequency': 'r', 'synset': 'boxing_glove.n.01', 'synonyms': ['boxing_glove'], 'id': 144, 'def': 'large glove coverings the fists of a fighter worn for the sport of boxing', 'name': 'boxing_glove'}, {'frequency': 'c', 'synset': 'brace.n.06', 'synonyms': ['suspenders'], 'id': 145, 'def': 'elastic straps that hold trousers up (usually used in the plural)', 'name': 'suspenders'}, {'frequency': 'f', 'synset': 'bracelet.n.02', 'synonyms': ['bracelet', 'bangle'], 'id': 146, 'def': 'jewelry worn around the wrist for decoration', 'name': 'bracelet'}, {'frequency': 'r', 'synset': 'brass.n.07', 'synonyms': ['brass_plaque'], 'id': 147, 'def': 'a memorial made of brass', 'name': 'brass_plaque'}, {'frequency': 'c', 'synset': 'brassiere.n.01', 'synonyms': ['brassiere', 'bra', 'bandeau'], 'id': 148, 'def': 'an undergarment worn by women to support their breasts', 'name': 'brassiere'}, {'frequency': 'c', 'synset': 'bread-bin.n.01', 'synonyms': ['bread-bin', 'breadbox'], 'id': 149, 'def': 'a container used to keep bread or cake in', 'name': 'bread-bin'}, {'frequency': 'f', 'synset': 'bread.n.01', 'synonyms': ['bread'], 'id': 150, 'def': 'food made from dough of flour or meal and usually raised with yeast or baking powder and then baked', 'name': 'bread'}, {'frequency': 'r', 'synset': 'breechcloth.n.01', 'synonyms': ['breechcloth', 'breechclout', 'loincloth'], 'id': 151, 'def': 'a garment that provides covering for the loins', 'name': 'breechcloth'}, {'frequency': 'f', 'synset': 'bridal_gown.n.01', 'synonyms': ['bridal_gown', 'wedding_gown', 'wedding_dress'], 'id': 152, 'def': 'a gown worn by the bride at a wedding', 'name': 'bridal_gown'}, {'frequency': 'c', 'synset': 'briefcase.n.01', 'synonyms': ['briefcase'], 'id': 153, 'def': 'a case with a handle; for carrying papers or files or books', 'name': 'briefcase'}, {'frequency': 'f', 'synset': 'broccoli.n.01', 'synonyms': ['broccoli'], 'id': 154, 'def': 'plant with dense clusters of tight green flower buds', 'name': 'broccoli'}, {'frequency': 'r', 'synset': 'brooch.n.01', 'synonyms': ['broach'], 'id': 155, 'def': 'a decorative pin worn by women', 'name': 'broach'}, {'frequency': 'c', 'synset': 'broom.n.01', 'synonyms': ['broom'], 'id': 156, 'def': 'bundle of straws or twigs attached to a long handle; used for cleaning', 'name': 'broom'}, {'frequency': 'c', 'synset': 'brownie.n.03', 'synonyms': ['brownie'], 'id': 157, 'def': 'square or bar of very rich chocolate cake usually with nuts', 'name': 'brownie'}, {'frequency': 'c', 'synset': 'brussels_sprouts.n.01', 'synonyms': ['brussels_sprouts'], 'id': 158, 'def': 'the small edible cabbage-like buds growing along a stalk', 'name': 'brussels_sprouts'}, {'frequency': 'r', 'synset': 'bubble_gum.n.01', 'synonyms': ['bubble_gum'], 'id': 159, 'def': 'a kind of chewing gum that can be blown into bubbles', 'name': 'bubble_gum'}, {'frequency': 'f', 'synset': 'bucket.n.01', 'synonyms': ['bucket', 'pail'], 'id': 160, 'def': 'a roughly cylindrical vessel that is open at the top', 'name': 'bucket'}, {'frequency': 'r', 'synset': 'buggy.n.01', 'synonyms': ['horse_buggy'], 'id': 161, 'def': 'a small lightweight carriage; drawn by a single horse', 'name': 'horse_buggy'}, {'frequency': 'c', 'synset': 'bull.n.11', 'synonyms': ['horned_cow'], 'id': 162, 'def': 'a cow with horns', 'name': 'bull'}, {'frequency': 'c', 'synset': 'bulldog.n.01', 'synonyms': ['bulldog'], 'id': 163, 'def': 'a thickset short-haired dog with a large head and strong undershot lower jaw', 'name': 'bulldog'}, {'frequency': 'r', 'synset': 'bulldozer.n.01', 'synonyms': ['bulldozer', 'dozer'], 'id': 164, 'def': 'large powerful tractor; a large blade in front flattens areas of ground', 'name': 'bulldozer'}, {'frequency': 'c', 'synset': 'bullet_train.n.01', 'synonyms': ['bullet_train'], 'id': 165, 'def': 'a high-speed passenger train', 'name': 'bullet_train'}, {'frequency': 'c', 'synset': 'bulletin_board.n.02', 'synonyms': ['bulletin_board', 'notice_board'], 'id': 166, 'def': 'a board that hangs on a wall; displays announcements', 'name': 'bulletin_board'}, {'frequency': 'r', 'synset': 'bulletproof_vest.n.01', 'synonyms': ['bulletproof_vest'], 'id': 167, 'def': 'a vest capable of resisting the impact of a bullet', 'name': 'bulletproof_vest'}, {'frequency': 'c', 'synset': 'bullhorn.n.01', 'synonyms': ['bullhorn', 'megaphone'], 'id': 168, 'def': 'a portable loudspeaker with built-in microphone and amplifier', 'name': 'bullhorn'}, {'frequency': 'f', 'synset': 'bun.n.01', 'synonyms': ['bun', 'roll'], 'id': 169, 'def': 'small rounded bread either plain or sweet', 'name': 'bun'}, {'frequency': 'c', 'synset': 'bunk_bed.n.01', 'synonyms': ['bunk_bed'], 'id': 170, 'def': 'beds built one above the other', 'name': 'bunk_bed'}, {'frequency': 'f', 'synset': 'buoy.n.01', 'synonyms': ['buoy'], 'id': 171, 'def': 'a float attached by rope to the seabed to mark channels in a harbor or underwater hazards', 'name': 'buoy'}, {'frequency': 'r', 'synset': 'burrito.n.01', 'synonyms': ['burrito'], 'id': 172, 'def': 'a flour tortilla folded around a filling', 'name': 'burrito'}, {'frequency': 'f', 'synset': 'bus.n.01', 'synonyms': ['bus_(vehicle)', 'autobus', 'charabanc', 'double-decker', 'motorbus', 'motorcoach'], 'id': 173, 'def': 'a vehicle carrying many passengers; used for public transport', 'name': 'bus_(vehicle)'}, {'frequency': 'c', 'synset': 'business_card.n.01', 'synonyms': ['business_card'], 'id': 174, 'def': "a card on which are printed the person's name and business affiliation", 'name': 'business_card'}, {'frequency': 'f', 'synset': 'butter.n.01', 'synonyms': ['butter'], 'id': 175, 'def': 'an edible emulsion of fat globules made by churning milk or cream; for cooking and table use', 'name': 'butter'}, {'frequency': 'c', 'synset': 'butterfly.n.01', 'synonyms': ['butterfly'], 'id': 176, 'def': 'insect typically having a slender body with knobbed antennae and broad colorful wings', 'name': 'butterfly'}, {'frequency': 'f', 'synset': 'button.n.01', 'synonyms': ['button'], 'id': 177, 'def': 'a round fastener sewn to shirts and coats etc to fit through buttonholes', 'name': 'button'}, {'frequency': 'f', 'synset': 'cab.n.03', 'synonyms': ['cab_(taxi)', 'taxi', 'taxicab'], 'id': 178, 'def': 'a car that takes passengers where they want to go in exchange for money', 'name': 'cab_(taxi)'}, {'frequency': 'r', 'synset': 'cabana.n.01', 'synonyms': ['cabana'], 'id': 179, 'def': 'a small tent used as a dressing room beside the sea or a swimming pool', 'name': 'cabana'}, {'frequency': 'c', 'synset': 'cabin_car.n.01', 'synonyms': ['cabin_car', 'caboose'], 'id': 180, 'def': 'a car on a freight train for use of the train crew; usually the last car on the train', 'name': 'cabin_car'}, {'frequency': 'f', 'synset': 'cabinet.n.01', 'synonyms': ['cabinet'], 'id': 181, 'def': 'a piece of furniture resembling a cupboard with doors and shelves and drawers', 'name': 'cabinet'}, {'frequency': 'r', 'synset': 'cabinet.n.03', 'synonyms': ['locker', 'storage_locker'], 'id': 182, 'def': 'a storage compartment for clothes and valuables; usually it has a lock', 'name': 'locker'}, {'frequency': 'f', 'synset': 'cake.n.03', 'synonyms': ['cake'], 'id': 183, 'def': 'baked goods made from or based on a mixture of flour, sugar, eggs, and fat', 'name': 'cake'}, {'frequency': 'c', 'synset': 'calculator.n.02', 'synonyms': ['calculator'], 'id': 184, 'def': 'a small machine that is used for mathematical calculations', 'name': 'calculator'}, {'frequency': 'f', 'synset': 'calendar.n.02', 'synonyms': ['calendar'], 'id': 185, 'def': 'a list or register of events (appointments/social events/court cases, etc)', 'name': 'calendar'}, {'frequency': 'c', 'synset': 'calf.n.01', 'synonyms': ['calf'], 'id': 186, 'def': 'young of domestic cattle', 'name': 'calf'}, {'frequency': 'c', 'synset': 'camcorder.n.01', 'synonyms': ['camcorder'], 'id': 187, 'def': 'a portable television camera and videocassette recorder', 'name': 'camcorder'}, {'frequency': 'c', 'synset': 'camel.n.01', 'synonyms': ['camel'], 'id': 188, 'def': 'cud-chewing mammal used as a draft or saddle animal in desert regions', 'name': 'camel'}, {'frequency': 'f', 'synset': 'camera.n.01', 'synonyms': ['camera'], 'id': 189, 'def': 'equipment for taking photographs', 'name': 'camera'}, {'frequency': 'c', 'synset': 'camera_lens.n.01', 'synonyms': ['camera_lens'], 'id': 190, 'def': 'a lens that focuses the image in a camera', 'name': 'camera_lens'}, {'frequency': 'c', 'synset': 'camper.n.02', 'synonyms': ['camper_(vehicle)', 'camping_bus', 'motor_home'], 'id': 191, 'def': 'a recreational vehicle equipped for camping out while traveling', 'name': 'camper_(vehicle)'}, {'frequency': 'f', 'synset': 'can.n.01', 'synonyms': ['can', 'tin_can'], 'id': 192, 'def': 'airtight sealed metal container for food or drink or paint etc.', 'name': 'can'}, {'frequency': 'c', 'synset': 'can_opener.n.01', 'synonyms': ['can_opener', 'tin_opener'], 'id': 193, 'def': 'a device for cutting cans open', 'name': 'can_opener'}, {'frequency': 'f', 'synset': 'candle.n.01', 'synonyms': ['candle', 'candlestick'], 'id': 194, 'def': 'stick of wax with a wick in the middle', 'name': 'candle'}, {'frequency': 'f', 'synset': 'candlestick.n.01', 'synonyms': ['candle_holder'], 'id': 195, 'def': 'a holder with sockets for candles', 'name': 'candle_holder'}, {'frequency': 'r', 'synset': 'candy_bar.n.01', 'synonyms': ['candy_bar'], 'id': 196, 'def': 'a candy shaped as a bar', 'name': 'candy_bar'}, {'frequency': 'c', 'synset': 'candy_cane.n.01', 'synonyms': ['candy_cane'], 'id': 197, 'def': 'a hard candy in the shape of a rod (usually with stripes)', 'name': 'candy_cane'}, {'frequency': 'c', 'synset': 'cane.n.01', 'synonyms': ['walking_cane'], 'id': 198, 'def': 'a stick that people can lean on to help them walk', 'name': 'walking_cane'}, {'frequency': 'c', 'synset': 'canister.n.02', 'synonyms': ['canister', 'cannister'], 'id': 199, 'def': 'metal container for storing dry foods such as tea or flour', 'name': 'canister'}, {'frequency': 'c', 'synset': 'canoe.n.01', 'synonyms': ['canoe'], 'id': 200, 'def': 'small and light boat; pointed at both ends; propelled with a paddle', 'name': 'canoe'}, {'frequency': 'c', 'synset': 'cantaloup.n.02', 'synonyms': ['cantaloup', 'cantaloupe'], 'id': 201, 'def': 'the fruit of a cantaloup vine; small to medium-sized melon with yellowish flesh', 'name': 'cantaloup'}, {'frequency': 'r', 'synset': 'canteen.n.01', 'synonyms': ['canteen'], 'id': 202, 'def': 'a flask for carrying water; used by soldiers or travelers', 'name': 'canteen'}, {'frequency': 'f', 'synset': 'cap.n.01', 'synonyms': ['cap_(headwear)'], 'id': 203, 'def': 'a tight-fitting headwear', 'name': 'cap_(headwear)'}, {'frequency': 'f', 'synset': 'cap.n.02', 'synonyms': ['bottle_cap', 'cap_(container_lid)'], 'id': 204, 'def': 'a top (as for a bottle)', 'name': 'bottle_cap'}, {'frequency': 'c', 'synset': 'cape.n.02', 'synonyms': ['cape'], 'id': 205, 'def': 'a sleeveless garment like a cloak but shorter', 'name': 'cape'}, {'frequency': 'c', 'synset': 'cappuccino.n.01', 'synonyms': ['cappuccino', 'coffee_cappuccino'], 'id': 206, 'def': 'equal parts of espresso and steamed milk', 'name': 'cappuccino'}, {'frequency': 'f', 'synset': 'car.n.01', 'synonyms': ['car_(automobile)', 'auto_(automobile)', 'automobile'], 'id': 207, 'def': 'a motor vehicle with four wheels', 'name': 'car_(automobile)'}, {'frequency': 'f', 'synset': 'car.n.02', 'synonyms': ['railcar_(part_of_a_train)', 'railway_car_(part_of_a_train)', 'railroad_car_(part_of_a_train)'], 'id': 208, 'def': 'a wheeled vehicle adapted to the rails of railroad (mark each individual railcar separately)', 'name': 'railcar_(part_of_a_train)'}, {'frequency': 'r', 'synset': 'car.n.04', 'synonyms': ['elevator_car'], 'id': 209, 'def': 'where passengers ride up and down', 'name': 'elevator_car'}, {'frequency': 'r', 'synset': 'car_battery.n.01', 'synonyms': ['car_battery', 'automobile_battery'], 'id': 210, 'def': 'a battery in a motor vehicle', 'name': 'car_battery'}, {'frequency': 'c', 'synset': 'card.n.02', 'synonyms': ['identity_card'], 'id': 211, 'def': 'a card certifying the identity of the bearer', 'name': 'identity_card'}, {'frequency': 'c', 'synset': 'card.n.03', 'synonyms': ['card'], 'id': 212, 'def': 'a rectangular piece of paper used to send messages (e.g. greetings or pictures)', 'name': 'card'}, {'frequency': 'c', 'synset': 'cardigan.n.01', 'synonyms': ['cardigan'], 'id': 213, 'def': 'knitted jacket that is fastened up the front with buttons or a zipper', 'name': 'cardigan'}, {'frequency': 'r', 'synset': 'cargo_ship.n.01', 'synonyms': ['cargo_ship', 'cargo_vessel'], 'id': 214, 'def': 'a ship designed to carry cargo', 'name': 'cargo_ship'}, {'frequency': 'r', 'synset': 'carnation.n.01', 'synonyms': ['carnation'], 'id': 215, 'def': 'plant with pink to purple-red spice-scented usually double flowers', 'name': 'carnation'}, {'frequency': 'c', 'synset': 'carriage.n.02', 'synonyms': ['horse_carriage'], 'id': 216, 'def': 'a vehicle with wheels drawn by one or more horses', 'name': 'horse_carriage'}, {'frequency': 'f', 'synset': 'carrot.n.01', 'synonyms': ['carrot'], 'id': 217, 'def': 'deep orange edible root of the cultivated carrot plant', 'name': 'carrot'}, {'frequency': 'f', 'synset': 'carryall.n.01', 'synonyms': ['tote_bag'], 'id': 218, 'def': 'a capacious bag or basket', 'name': 'tote_bag'}, {'frequency': 'c', 'synset': 'cart.n.01', 'synonyms': ['cart'], 'id': 219, 'def': 'a heavy open wagon usually having two wheels and drawn by an animal', 'name': 'cart'}, {'frequency': 'c', 'synset': 'carton.n.02', 'synonyms': ['carton'], 'id': 220, 'def': 'a container made of cardboard for holding food or drink', 'name': 'carton'}, {'frequency': 'c', 'synset': 'cash_register.n.01', 'synonyms': ['cash_register', 'register_(for_cash_transactions)'], 'id': 221, 'def': 'a cashbox with an adding machine to register transactions', 'name': 'cash_register'}, {'frequency': 'r', 'synset': 'casserole.n.01', 'synonyms': ['casserole'], 'id': 222, 'def': 'food cooked and served in a casserole', 'name': 'casserole'}, {'frequency': 'r', 'synset': 'cassette.n.01', 'synonyms': ['cassette'], 'id': 223, 'def': 'a container that holds a magnetic tape used for recording or playing sound or video', 'name': 'cassette'}, {'frequency': 'c', 'synset': 'cast.n.05', 'synonyms': ['cast', 'plaster_cast', 'plaster_bandage'], 'id': 224, 'def': 'bandage consisting of a firm covering that immobilizes broken bones while they heal', 'name': 'cast'}, {'frequency': 'f', 'synset': 'cat.n.01', 'synonyms': ['cat'], 'id': 225, 'def': 'a domestic house cat', 'name': 'cat'}, {'frequency': 'f', 'synset': 'cauliflower.n.02', 'synonyms': ['cauliflower'], 'id': 226, 'def': 'edible compact head of white undeveloped flowers', 'name': 'cauliflower'}, {'frequency': 'c', 'synset': 'cayenne.n.02', 'synonyms': ['cayenne_(spice)', 'cayenne_pepper_(spice)', 'red_pepper_(spice)'], 'id': 227, 'def': 'ground pods and seeds of pungent red peppers of the genus Capsicum', 'name': 'cayenne_(spice)'}, {'frequency': 'c', 'synset': 'cd_player.n.01', 'synonyms': ['CD_player'], 'id': 228, 'def': 'electronic equipment for playing compact discs (CDs)', 'name': 'CD_player'}, {'frequency': 'f', 'synset': 'celery.n.01', 'synonyms': ['celery'], 'id': 229, 'def': 'widely cultivated herb with aromatic leaf stalks that are eaten raw or cooked', 'name': 'celery'}, {'frequency': 'f', 'synset': 'cellular_telephone.n.01', 'synonyms': ['cellular_telephone', 'cellular_phone', 'cellphone', 'mobile_phone', 'smart_phone'], 'id': 230, 'def': 'a hand-held mobile telephone', 'name': 'cellular_telephone'}, {'frequency': 'r', 'synset': 'chain_mail.n.01', 'synonyms': ['chain_mail', 'ring_mail', 'chain_armor', 'chain_armour', 'ring_armor', 'ring_armour'], 'id': 231, 'def': '(Middle Ages) flexible armor made of interlinked metal rings', 'name': 'chain_mail'}, {'frequency': 'f', 'synset': 'chair.n.01', 'synonyms': ['chair'], 'id': 232, 'def': 'a seat for one person, with a support for the back', 'name': 'chair'}, {'frequency': 'r', 'synset': 'chaise_longue.n.01', 'synonyms': ['chaise_longue', 'chaise', 'daybed'], 'id': 233, 'def': 'a long chair; for reclining', 'name': 'chaise_longue'}, {'frequency': 'r', 'synset': 'chalice.n.01', 'synonyms': ['chalice'], 'id': 234, 'def': 'a bowl-shaped drinking vessel; especially the Eucharistic cup', 'name': 'chalice'}, {'frequency': 'f', 'synset': 'chandelier.n.01', 'synonyms': ['chandelier'], 'id': 235, 'def': 'branched lighting fixture; often ornate; hangs from the ceiling', 'name': 'chandelier'}, {'frequency': 'r', 'synset': 'chap.n.04', 'synonyms': ['chap'], 'id': 236, 'def': 'leather leggings without a seat; worn over trousers by cowboys to protect their legs', 'name': 'chap'}, {'frequency': 'r', 'synset': 'checkbook.n.01', 'synonyms': ['checkbook', 'chequebook'], 'id': 237, 'def': 'a book issued to holders of checking accounts', 'name': 'checkbook'}, {'frequency': 'r', 'synset': 'checkerboard.n.01', 'synonyms': ['checkerboard'], 'id': 238, 'def': 'a board having 64 squares of two alternating colors', 'name': 'checkerboard'}, {'frequency': 'c', 'synset': 'cherry.n.03', 'synonyms': ['cherry'], 'id': 239, 'def': 'a red fruit with a single hard stone', 'name': 'cherry'}, {'frequency': 'r', 'synset': 'chessboard.n.01', 'synonyms': ['chessboard'], 'id': 240, 'def': 'a checkerboard used to play chess', 'name': 'chessboard'}, {'frequency': 'c', 'synset': 'chicken.n.02', 'synonyms': ['chicken_(animal)'], 'id': 241, 'def': 'a domestic fowl bred for flesh or eggs', 'name': 'chicken_(animal)'}, {'frequency': 'c', 'synset': 'chickpea.n.01', 'synonyms': ['chickpea', 'garbanzo'], 'id': 242, 'def': 'the seed of the chickpea plant; usually dried', 'name': 'chickpea'}, {'frequency': 'c', 'synset': 'chili.n.02', 'synonyms': ['chili_(vegetable)', 'chili_pepper_(vegetable)', 'chilli_(vegetable)', 'chilly_(vegetable)', 'chile_(vegetable)'], 'id': 243, 'def': 'very hot and finely tapering pepper of special pungency', 'name': 'chili_(vegetable)'}, {'frequency': 'r', 'synset': 'chime.n.01', 'synonyms': ['chime', 'gong'], 'id': 244, 'def': 'an instrument consisting of a set of bells that are struck with a hammer', 'name': 'chime'}, {'frequency': 'r', 'synset': 'chinaware.n.01', 'synonyms': ['chinaware'], 'id': 245, 'def': 'dishware made of high quality porcelain', 'name': 'chinaware'}, {'frequency': 'c', 'synset': 'chip.n.04', 'synonyms': ['crisp_(potato_chip)', 'potato_chip'], 'id': 246, 'def': 'a thin crisp slice of potato fried in deep fat', 'name': 'crisp_(potato_chip)'}, {'frequency': 'r', 'synset': 'chip.n.06', 'synonyms': ['poker_chip'], 'id': 247, 'def': 'a small disk-shaped counter used to represent money when gambling', 'name': 'poker_chip'}, {'frequency': 'c', 'synset': 'chocolate_bar.n.01', 'synonyms': ['chocolate_bar'], 'id': 248, 'def': 'a bar of chocolate candy', 'name': 'chocolate_bar'}, {'frequency': 'c', 'synset': 'chocolate_cake.n.01', 'synonyms': ['chocolate_cake'], 'id': 249, 'def': 'cake containing chocolate', 'name': 'chocolate_cake'}, {'frequency': 'r', 'synset': 'chocolate_milk.n.01', 'synonyms': ['chocolate_milk'], 'id': 250, 'def': 'milk flavored with chocolate syrup', 'name': 'chocolate_milk'}, {'frequency': 'r', 'synset': 'chocolate_mousse.n.01', 'synonyms': ['chocolate_mousse'], 'id': 251, 'def': 'dessert mousse made with chocolate', 'name': 'chocolate_mousse'}, {'frequency': 'f', 'synset': 'choker.n.03', 'synonyms': ['choker', 'collar', 'neckband'], 'id': 252, 'def': 'shirt collar, animal collar, or tight-fitting necklace', 'name': 'choker'}, {'frequency': 'f', 'synset': 'chopping_board.n.01', 'synonyms': ['chopping_board', 'cutting_board', 'chopping_block'], 'id': 253, 'def': 'a wooden board where meats or vegetables can be cut', 'name': 'chopping_board'}, {'frequency': 'f', 'synset': 'chopstick.n.01', 'synonyms': ['chopstick'], 'id': 254, 'def': 'one of a pair of slender sticks used as oriental tableware to eat food with', 'name': 'chopstick'}, {'frequency': 'f', 'synset': 'christmas_tree.n.05', 'synonyms': ['Christmas_tree'], 'id': 255, 'def': 'an ornamented evergreen used as a Christmas decoration', 'name': 'Christmas_tree'}, {'frequency': 'c', 'synset': 'chute.n.02', 'synonyms': ['slide'], 'id': 256, 'def': 'sloping channel through which things can descend', 'name': 'slide'}, {'frequency': 'r', 'synset': 'cider.n.01', 'synonyms': ['cider', 'cyder'], 'id': 257, 'def': 'a beverage made from juice pressed from apples', 'name': 'cider'}, {'frequency': 'r', 'synset': 'cigar_box.n.01', 'synonyms': ['cigar_box'], 'id': 258, 'def': 'a box for holding cigars', 'name': 'cigar_box'}, {'frequency': 'f', 'synset': 'cigarette.n.01', 'synonyms': ['cigarette'], 'id': 259, 'def': 'finely ground tobacco wrapped in paper; for smoking', 'name': 'cigarette'}, {'frequency': 'c', 'synset': 'cigarette_case.n.01', 'synonyms': ['cigarette_case', 'cigarette_pack'], 'id': 260, 'def': 'a small flat case for holding cigarettes', 'name': 'cigarette_case'}, {'frequency': 'f', 'synset': 'cistern.n.02', 'synonyms': ['cistern', 'water_tank'], 'id': 261, 'def': 'a tank that holds the water used to flush a toilet', 'name': 'cistern'}, {'frequency': 'r', 'synset': 'clarinet.n.01', 'synonyms': ['clarinet'], 'id': 262, 'def': 'a single-reed instrument with a straight tube', 'name': 'clarinet'}, {'frequency': 'c', 'synset': 'clasp.n.01', 'synonyms': ['clasp'], 'id': 263, 'def': 'a fastener (as a buckle or hook) that is used to hold two things together', 'name': 'clasp'}, {'frequency': 'c', 'synset': 'cleansing_agent.n.01', 'synonyms': ['cleansing_agent', 'cleanser', 'cleaner'], 'id': 264, 'def': 'a preparation used in cleaning something', 'name': 'cleansing_agent'}, {'frequency': 'r', 'synset': 'cleat.n.02', 'synonyms': ['cleat_(for_securing_rope)'], 'id': 265, 'def': 'a fastener (usually with two projecting horns) around which a rope can be secured', 'name': 'cleat_(for_securing_rope)'}, {'frequency': 'r', 'synset': 'clementine.n.01', 'synonyms': ['clementine'], 'id': 266, 'def': 'a variety of mandarin orange', 'name': 'clementine'}, {'frequency': 'c', 'synset': 'clip.n.03', 'synonyms': ['clip'], 'id': 267, 'def': 'any of various small fasteners used to hold loose articles together', 'name': 'clip'}, {'frequency': 'c', 'synset': 'clipboard.n.01', 'synonyms': ['clipboard'], 'id': 268, 'def': 'a small writing board with a clip at the top for holding papers', 'name': 'clipboard'}, {'frequency': 'r', 'synset': 'clipper.n.03', 'synonyms': ['clippers_(for_plants)'], 'id': 269, 'def': 'shears for cutting grass or shrubbery (often used in the plural)', 'name': 'clippers_(for_plants)'}, {'frequency': 'r', 'synset': 'cloak.n.02', 'synonyms': ['cloak'], 'id': 270, 'def': 'a loose outer garment', 'name': 'cloak'}, {'frequency': 'f', 'synset': 'clock.n.01', 'synonyms': ['clock', 'timepiece', 'timekeeper'], 'id': 271, 'def': 'a timepiece that shows the time of day', 'name': 'clock'}, {'frequency': 'f', 'synset': 'clock_tower.n.01', 'synonyms': ['clock_tower'], 'id': 272, 'def': 'a tower with a large clock visible high up on an outside face', 'name': 'clock_tower'}, {'frequency': 'c', 'synset': 'clothes_hamper.n.01', 'synonyms': ['clothes_hamper', 'laundry_basket', 'clothes_basket'], 'id': 273, 'def': 'a hamper that holds dirty clothes to be washed or wet clothes to be dried', 'name': 'clothes_hamper'}, {'frequency': 'c', 'synset': 'clothespin.n.01', 'synonyms': ['clothespin', 'clothes_peg'], 'id': 274, 'def': 'wood or plastic fastener; for holding clothes on a clothesline', 'name': 'clothespin'}, {'frequency': 'r', 'synset': 'clutch_bag.n.01', 'synonyms': ['clutch_bag'], 'id': 275, 'def': "a woman's strapless purse that is carried in the hand", 'name': 'clutch_bag'}, {'frequency': 'f', 'synset': 'coaster.n.03', 'synonyms': ['coaster'], 'id': 276, 'def': 'a covering (plate or mat) that protects the surface of a table', 'name': 'coaster'}, {'frequency': 'f', 'synset': 'coat.n.01', 'synonyms': ['coat'], 'id': 277, 'def': 'an outer garment that has sleeves and covers the body from shoulder down', 'name': 'coat'}, {'frequency': 'c', 'synset': 'coat_hanger.n.01', 'synonyms': ['coat_hanger', 'clothes_hanger', 'dress_hanger'], 'id': 278, 'def': "a hanger that is shaped like a person's shoulders", 'name': 'coat_hanger'}, {'frequency': 'c', 'synset': 'coatrack.n.01', 'synonyms': ['coatrack', 'hatrack'], 'id': 279, 'def': 'a rack with hooks for temporarily holding coats and hats', 'name': 'coatrack'}, {'frequency': 'c', 'synset': 'cock.n.04', 'synonyms': ['cock', 'rooster'], 'id': 280, 'def': 'adult male chicken', 'name': 'cock'}, {'frequency': 'r', 'synset': 'cockroach.n.01', 'synonyms': ['cockroach'], 'id': 281, 'def': 'any of numerous chiefly nocturnal insects; some are domestic pests', 'name': 'cockroach'}, {'frequency': 'r', 'synset': 'cocoa.n.01', 'synonyms': ['cocoa_(beverage)', 'hot_chocolate_(beverage)', 'drinking_chocolate'], 'id': 282, 'def': 'a beverage made from cocoa powder and milk and sugar; usually drunk hot', 'name': 'cocoa_(beverage)'}, {'frequency': 'c', 'synset': 'coconut.n.02', 'synonyms': ['coconut', 'cocoanut'], 'id': 283, 'def': 'large hard-shelled brown oval nut with a fibrous husk', 'name': 'coconut'}, {'frequency': 'f', 'synset': 'coffee_maker.n.01', 'synonyms': ['coffee_maker', 'coffee_machine'], 'id': 284, 'def': 'a kitchen appliance for brewing coffee automatically', 'name': 'coffee_maker'}, {'frequency': 'f', 'synset': 'coffee_table.n.01', 'synonyms': ['coffee_table', 'cocktail_table'], 'id': 285, 'def': 'low table where magazines can be placed and coffee or cocktails are served', 'name': 'coffee_table'}, {'frequency': 'c', 'synset': 'coffeepot.n.01', 'synonyms': ['coffeepot'], 'id': 286, 'def': 'tall pot in which coffee is brewed', 'name': 'coffeepot'}, {'frequency': 'r', 'synset': 'coil.n.05', 'synonyms': ['coil'], 'id': 287, 'def': 'tubing that is wound in a spiral', 'name': 'coil'}, {'frequency': 'c', 'synset': 'coin.n.01', 'synonyms': ['coin'], 'id': 288, 'def': 'a flat metal piece (usually a disc) used as money', 'name': 'coin'}, {'frequency': 'c', 'synset': 'colander.n.01', 'synonyms': ['colander', 'cullender'], 'id': 289, 'def': 'bowl-shaped strainer; used to wash or drain foods', 'name': 'colander'}, {'frequency': 'c', 'synset': 'coleslaw.n.01', 'synonyms': ['coleslaw', 'slaw'], 'id': 290, 'def': 'basically shredded cabbage', 'name': 'coleslaw'}, {'frequency': 'r', 'synset': 'coloring_material.n.01', 'synonyms': ['coloring_material', 'colouring_material'], 'id': 291, 'def': 'any material used for its color', 'name': 'coloring_material'}, {'frequency': 'r', 'synset': 'combination_lock.n.01', 'synonyms': ['combination_lock'], 'id': 292, 'def': 'lock that can be opened only by turning dials in a special sequence', 'name': 'combination_lock'}, {'frequency': 'c', 'synset': 'comforter.n.04', 'synonyms': ['pacifier', 'teething_ring'], 'id': 293, 'def': 'device used for an infant to suck or bite on', 'name': 'pacifier'}, {'frequency': 'r', 'synset': 'comic_book.n.01', 'synonyms': ['comic_book'], 'id': 294, 'def': 'a magazine devoted to comic strips', 'name': 'comic_book'}, {'frequency': 'r', 'synset': 'compass.n.01', 'synonyms': ['compass'], 'id': 295, 'def': 'navigational instrument for finding directions', 'name': 'compass'}, {'frequency': 'f', 'synset': 'computer_keyboard.n.01', 'synonyms': ['computer_keyboard', 'keyboard_(computer)'], 'id': 296, 'def': 'a keyboard that is a data input device for computers', 'name': 'computer_keyboard'}, {'frequency': 'f', 'synset': 'condiment.n.01', 'synonyms': ['condiment'], 'id': 297, 'def': 'a preparation (a sauce or relish or spice) to enhance flavor or enjoyment', 'name': 'condiment'}, {'frequency': 'f', 'synset': 'cone.n.01', 'synonyms': ['cone', 'traffic_cone'], 'id': 298, 'def': 'a cone-shaped object used to direct traffic', 'name': 'cone'}, {'frequency': 'f', 'synset': 'control.n.09', 'synonyms': ['control', 'controller'], 'id': 299, 'def': 'a mechanism that controls the operation of a machine', 'name': 'control'}, {'frequency': 'r', 'synset': 'convertible.n.01', 'synonyms': ['convertible_(automobile)'], 'id': 300, 'def': 'a car that has top that can be folded or removed', 'name': 'convertible_(automobile)'}, {'frequency': 'r', 'synset': 'convertible.n.03', 'synonyms': ['sofa_bed'], 'id': 301, 'def': 'a sofa that can be converted into a bed', 'name': 'sofa_bed'}, {'frequency': 'r', 'synset': 'cooker.n.01', 'synonyms': ['cooker'], 'id': 302, 'def': 'a utensil for cooking', 'name': 'cooker'}, {'frequency': 'f', 'synset': 'cookie.n.01', 'synonyms': ['cookie', 'cooky', 'biscuit_(cookie)'], 'id': 303, 'def': "any of various small flat sweet cakes (`biscuit' is the British term)", 'name': 'cookie'}, {'frequency': 'r', 'synset': 'cooking_utensil.n.01', 'synonyms': ['cooking_utensil'], 'id': 304, 'def': 'a kitchen utensil made of material that does not melt easily; used for cooking', 'name': 'cooking_utensil'}, {'frequency': 'f', 'synset': 'cooler.n.01', 'synonyms': ['cooler_(for_food)', 'ice_chest'], 'id': 305, 'def': 'an insulated box for storing food often with ice', 'name': 'cooler_(for_food)'}, {'frequency': 'f', 'synset': 'cork.n.04', 'synonyms': ['cork_(bottle_plug)', 'bottle_cork'], 'id': 306, 'def': 'the plug in the mouth of a bottle (especially a wine bottle)', 'name': 'cork_(bottle_plug)'}, {'frequency': 'r', 'synset': 'corkboard.n.01', 'synonyms': ['corkboard'], 'id': 307, 'def': 'a sheet consisting of cork granules', 'name': 'corkboard'}, {'frequency': 'c', 'synset': 'corkscrew.n.01', 'synonyms': ['corkscrew', 'bottle_screw'], 'id': 308, 'def': 'a bottle opener that pulls corks', 'name': 'corkscrew'}, {'frequency': 'f', 'synset': 'corn.n.03', 'synonyms': ['edible_corn', 'corn', 'maize'], 'id': 309, 'def': 'ears or kernels of corn that can be prepared and served for human food (only mark individual ears or kernels)', 'name': 'edible_corn'}, {'frequency': 'r', 'synset': 'cornbread.n.01', 'synonyms': ['cornbread'], 'id': 310, 'def': 'bread made primarily of cornmeal', 'name': 'cornbread'}, {'frequency': 'c', 'synset': 'cornet.n.01', 'synonyms': ['cornet', 'horn', 'trumpet'], 'id': 311, 'def': 'a brass musical instrument with a narrow tube and a flared bell and many valves', 'name': 'cornet'}, {'frequency': 'c', 'synset': 'cornice.n.01', 'synonyms': ['cornice', 'valance', 'valance_board', 'pelmet'], 'id': 312, 'def': 'a decorative framework to conceal curtain fixtures at the top of a window casing', 'name': 'cornice'}, {'frequency': 'r', 'synset': 'cornmeal.n.01', 'synonyms': ['cornmeal'], 'id': 313, 'def': 'coarsely ground corn', 'name': 'cornmeal'}, {'frequency': 'c', 'synset': 'corset.n.01', 'synonyms': ['corset', 'girdle'], 'id': 314, 'def': "a woman's close-fitting foundation garment", 'name': 'corset'}, {'frequency': 'c', 'synset': 'costume.n.04', 'synonyms': ['costume'], 'id': 315, 'def': 'the attire characteristic of a country or a time or a social class', 'name': 'costume'}, {'frequency': 'r', 'synset': 'cougar.n.01', 'synonyms': ['cougar', 'puma', 'catamount', 'mountain_lion', 'panther'], 'id': 316, 'def': 'large American feline resembling a lion', 'name': 'cougar'}, {'frequency': 'r', 'synset': 'coverall.n.01', 'synonyms': ['coverall'], 'id': 317, 'def': 'a loose-fitting protective garment that is worn over other clothing', 'name': 'coverall'}, {'frequency': 'c', 'synset': 'cowbell.n.01', 'synonyms': ['cowbell'], 'id': 318, 'def': 'a bell hung around the neck of cow so that the cow can be easily located', 'name': 'cowbell'}, {'frequency': 'f', 'synset': 'cowboy_hat.n.01', 'synonyms': ['cowboy_hat', 'ten-gallon_hat'], 'id': 319, 'def': 'a hat with a wide brim and a soft crown; worn by American ranch hands', 'name': 'cowboy_hat'}, {'frequency': 'c', 'synset': 'crab.n.01', 'synonyms': ['crab_(animal)'], 'id': 320, 'def': 'decapod having eyes on short stalks and a broad flattened shell and pincers', 'name': 'crab_(animal)'}, {'frequency': 'r', 'synset': 'crab.n.05', 'synonyms': ['crabmeat'], 'id': 321, 'def': 'the edible flesh of any of various crabs', 'name': 'crabmeat'}, {'frequency': 'c', 'synset': 'cracker.n.01', 'synonyms': ['cracker'], 'id': 322, 'def': 'a thin crisp wafer', 'name': 'cracker'}, {'frequency': 'r', 'synset': 'crape.n.01', 'synonyms': ['crape', 'crepe', 'French_pancake'], 'id': 323, 'def': 'small very thin pancake', 'name': 'crape'}, {'frequency': 'f', 'synset': 'crate.n.01', 'synonyms': ['crate'], 'id': 324, 'def': 'a rugged box (usually made of wood); used for shipping', 'name': 'crate'}, {'frequency': 'c', 'synset': 'crayon.n.01', 'synonyms': ['crayon', 'wax_crayon'], 'id': 325, 'def': 'writing or drawing implement made of a colored stick of composition wax', 'name': 'crayon'}, {'frequency': 'r', 'synset': 'cream_pitcher.n.01', 'synonyms': ['cream_pitcher'], 'id': 326, 'def': 'a small pitcher for serving cream', 'name': 'cream_pitcher'}, {'frequency': 'c', 'synset': 'crescent_roll.n.01', 'synonyms': ['crescent_roll', 'croissant'], 'id': 327, 'def': 'very rich flaky crescent-shaped roll', 'name': 'crescent_roll'}, {'frequency': 'c', 'synset': 'crib.n.01', 'synonyms': ['crib', 'cot'], 'id': 328, 'def': 'baby bed with high sides made of slats', 'name': 'crib'}, {'frequency': 'c', 'synset': 'crock.n.03', 'synonyms': ['crock_pot', 'earthenware_jar'], 'id': 329, 'def': 'an earthen jar (made of baked clay) or a modern electric crockpot', 'name': 'crock_pot'}, {'frequency': 'f', 'synset': 'crossbar.n.01', 'synonyms': ['crossbar'], 'id': 330, 'def': 'a horizontal bar that goes across something', 'name': 'crossbar'}, {'frequency': 'r', 'synset': 'crouton.n.01', 'synonyms': ['crouton'], 'id': 331, 'def': 'a small piece of toasted or fried bread; served in soup or salads', 'name': 'crouton'}, {'frequency': 'c', 'synset': 'crow.n.01', 'synonyms': ['crow'], 'id': 332, 'def': 'black birds having a raucous call', 'name': 'crow'}, {'frequency': 'r', 'synset': 'crowbar.n.01', 'synonyms': ['crowbar', 'wrecking_bar', 'pry_bar'], 'id': 333, 'def': 'a heavy iron lever with one end forged into a wedge', 'name': 'crowbar'}, {'frequency': 'c', 'synset': 'crown.n.04', 'synonyms': ['crown'], 'id': 334, 'def': 'an ornamental jeweled headdress signifying sovereignty', 'name': 'crown'}, {'frequency': 'c', 'synset': 'crucifix.n.01', 'synonyms': ['crucifix'], 'id': 335, 'def': 'representation of the cross on which Jesus died', 'name': 'crucifix'}, {'frequency': 'c', 'synset': 'cruise_ship.n.01', 'synonyms': ['cruise_ship', 'cruise_liner'], 'id': 336, 'def': 'a passenger ship used commercially for pleasure cruises', 'name': 'cruise_ship'}, {'frequency': 'c', 'synset': 'cruiser.n.01', 'synonyms': ['police_cruiser', 'patrol_car', 'police_car', 'squad_car'], 'id': 337, 'def': 'a car in which policemen cruise the streets', 'name': 'police_cruiser'}, {'frequency': 'f', 'synset': 'crumb.n.03', 'synonyms': ['crumb'], 'id': 338, 'def': 'small piece of e.g. bread or cake', 'name': 'crumb'}, {'frequency': 'c', 'synset': 'crutch.n.01', 'synonyms': ['crutch'], 'id': 339, 'def': 'a wooden or metal staff that fits under the armpit and reaches to the ground', 'name': 'crutch'}, {'frequency': 'c', 'synset': 'cub.n.03', 'synonyms': ['cub_(animal)'], 'id': 340, 'def': 'the young of certain carnivorous mammals such as the bear or wolf or lion', 'name': 'cub_(animal)'}, {'frequency': 'c', 'synset': 'cube.n.05', 'synonyms': ['cube', 'square_block'], 'id': 341, 'def': 'a block in the (approximate) shape of a cube', 'name': 'cube'}, {'frequency': 'f', 'synset': 'cucumber.n.02', 'synonyms': ['cucumber', 'cuke'], 'id': 342, 'def': 'cylindrical green fruit with thin green rind and white flesh eaten as a vegetable', 'name': 'cucumber'}, {'frequency': 'c', 'synset': 'cufflink.n.01', 'synonyms': ['cufflink'], 'id': 343, 'def': 'jewelry consisting of linked buttons used to fasten the cuffs of a shirt', 'name': 'cufflink'}, {'frequency': 'f', 'synset': 'cup.n.01', 'synonyms': ['cup'], 'id': 344, 'def': 'a small open container usually used for drinking; usually has a handle', 'name': 'cup'}, {'frequency': 'c', 'synset': 'cup.n.08', 'synonyms': ['trophy_cup'], 'id': 345, 'def': 'a metal award or cup-shaped vessel with handles that is awarded as a trophy to a competition winner', 'name': 'trophy_cup'}, {'frequency': 'f', 'synset': 'cupboard.n.01', 'synonyms': ['cupboard', 'closet'], 'id': 346, 'def': 'a small room (or recess) or cabinet used for storage space', 'name': 'cupboard'}, {'frequency': 'f', 'synset': 'cupcake.n.01', 'synonyms': ['cupcake'], 'id': 347, 'def': 'small cake baked in a muffin tin', 'name': 'cupcake'}, {'frequency': 'r', 'synset': 'curler.n.01', 'synonyms': ['hair_curler', 'hair_roller', 'hair_crimper'], 'id': 348, 'def': 'a cylindrical tube around which the hair is wound to curl it', 'name': 'hair_curler'}, {'frequency': 'r', 'synset': 'curling_iron.n.01', 'synonyms': ['curling_iron'], 'id': 349, 'def': 'a cylindrical home appliance that heats hair that has been curled around it', 'name': 'curling_iron'}, {'frequency': 'f', 'synset': 'curtain.n.01', 'synonyms': ['curtain', 'drapery'], 'id': 350, 'def': 'hanging cloth used as a blind (especially for a window)', 'name': 'curtain'}, {'frequency': 'f', 'synset': 'cushion.n.03', 'synonyms': ['cushion'], 'id': 351, 'def': 'a soft bag filled with air or padding such as feathers or foam rubber', 'name': 'cushion'}, {'frequency': 'r', 'synset': 'cylinder.n.04', 'synonyms': ['cylinder'], 'id': 352, 'def': 'a cylindrical container', 'name': 'cylinder'}, {'frequency': 'r', 'synset': 'cymbal.n.01', 'synonyms': ['cymbal'], 'id': 353, 'def': 'a percussion instrument consisting of a concave brass disk', 'name': 'cymbal'}, {'frequency': 'r', 'synset': 'dagger.n.01', 'synonyms': ['dagger'], 'id': 354, 'def': 'a short knife with a pointed blade used for piercing or stabbing', 'name': 'dagger'}, {'frequency': 'r', 'synset': 'dalmatian.n.02', 'synonyms': ['dalmatian'], 'id': 355, 'def': 'a large breed having a smooth white coat with black or brown spots', 'name': 'dalmatian'}, {'frequency': 'c', 'synset': 'dartboard.n.01', 'synonyms': ['dartboard'], 'id': 356, 'def': 'a circular board of wood or cork used as the target in the game of darts', 'name': 'dartboard'}, {'frequency': 'r', 'synset': 'date.n.08', 'synonyms': ['date_(fruit)'], 'id': 357, 'def': 'sweet edible fruit of the date palm with a single long woody seed', 'name': 'date_(fruit)'}, {'frequency': 'f', 'synset': 'deck_chair.n.01', 'synonyms': ['deck_chair', 'beach_chair'], 'id': 358, 'def': 'a folding chair for use outdoors; a wooden frame supports a length of canvas', 'name': 'deck_chair'}, {'frequency': 'c', 'synset': 'deer.n.01', 'synonyms': ['deer', 'cervid'], 'id': 359, 'def': "distinguished from Bovidae by the male's having solid deciduous antlers", 'name': 'deer'}, {'frequency': 'c', 'synset': 'dental_floss.n.01', 'synonyms': ['dental_floss', 'floss'], 'id': 360, 'def': 'a soft thread for cleaning the spaces between the teeth', 'name': 'dental_floss'}, {'frequency': 'f', 'synset': 'desk.n.01', 'synonyms': ['desk'], 'id': 361, 'def': 'a piece of furniture with a writing surface and usually drawers or other compartments', 'name': 'desk'}, {'frequency': 'r', 'synset': 'detergent.n.01', 'synonyms': ['detergent'], 'id': 362, 'def': 'a surface-active chemical widely used in industry and laundering', 'name': 'detergent'}, {'frequency': 'c', 'synset': 'diaper.n.01', 'synonyms': ['diaper'], 'id': 363, 'def': 'garment consisting of a folded cloth drawn up between the legs and fastened at the waist', 'name': 'diaper'}, {'frequency': 'r', 'synset': 'diary.n.01', 'synonyms': ['diary', 'journal'], 'id': 364, 'def': 'yearly planner book', 'name': 'diary'}, {'frequency': 'r', 'synset': 'die.n.01', 'synonyms': ['die', 'dice'], 'id': 365, 'def': 'a small cube with 1 to 6 spots on the six faces; used in gambling', 'name': 'die'}, {'frequency': 'r', 'synset': 'dinghy.n.01', 'synonyms': ['dinghy', 'dory', 'rowboat'], 'id': 366, 'def': 'a small boat of shallow draft with seats and oars with which it is propelled', 'name': 'dinghy'}, {'frequency': 'f', 'synset': 'dining_table.n.01', 'synonyms': ['dining_table'], 'id': 367, 'def': 'a table at which meals are served', 'name': 'dining_table'}, {'frequency': 'r', 'synset': 'dinner_jacket.n.01', 'synonyms': ['tux', 'tuxedo'], 'id': 368, 'def': 'semiformal evening dress for men', 'name': 'tux'}, {'frequency': 'f', 'synset': 'dish.n.01', 'synonyms': ['dish'], 'id': 369, 'def': 'a piece of dishware normally used as a container for holding or serving food', 'name': 'dish'}, {'frequency': 'c', 'synset': 'dish.n.05', 'synonyms': ['dish_antenna'], 'id': 370, 'def': 'directional antenna consisting of a parabolic reflector', 'name': 'dish_antenna'}, {'frequency': 'c', 'synset': 'dishrag.n.01', 'synonyms': ['dishrag', 'dishcloth'], 'id': 371, 'def': 'a cloth for washing dishes or cleaning in general', 'name': 'dishrag'}, {'frequency': 'f', 'synset': 'dishtowel.n.01', 'synonyms': ['dishtowel', 'tea_towel'], 'id': 372, 'def': 'a towel for drying dishes', 'name': 'dishtowel'}, {'frequency': 'f', 'synset': 'dishwasher.n.01', 'synonyms': ['dishwasher', 'dishwashing_machine'], 'id': 373, 'def': 'a machine for washing dishes', 'name': 'dishwasher'}, {'frequency': 'r', 'synset': 'dishwasher_detergent.n.01', 'synonyms': ['dishwasher_detergent', 'dishwashing_detergent', 'dishwashing_liquid', 'dishsoap'], 'id': 374, 'def': 'dishsoap or dish detergent designed for use in dishwashers', 'name': 'dishwasher_detergent'}, {'frequency': 'f', 'synset': 'dispenser.n.01', 'synonyms': ['dispenser'], 'id': 375, 'def': 'a container so designed that the contents can be used in prescribed amounts', 'name': 'dispenser'}, {'frequency': 'r', 'synset': 'diving_board.n.01', 'synonyms': ['diving_board'], 'id': 376, 'def': 'a springboard from which swimmers can dive', 'name': 'diving_board'}, {'frequency': 'f', 'synset': 'dixie_cup.n.01', 'synonyms': ['Dixie_cup', 'paper_cup'], 'id': 377, 'def': 'a disposable cup made of paper; for holding drinks', 'name': 'Dixie_cup'}, {'frequency': 'f', 'synset': 'dog.n.01', 'synonyms': ['dog'], 'id': 378, 'def': 'a common domesticated dog', 'name': 'dog'}, {'frequency': 'f', 'synset': 'dog_collar.n.01', 'synonyms': ['dog_collar'], 'id': 379, 'def': 'a collar for a dog', 'name': 'dog_collar'}, {'frequency': 'f', 'synset': 'doll.n.01', 'synonyms': ['doll'], 'id': 380, 'def': 'a toy replica of a HUMAN (NOT AN ANIMAL)', 'name': 'doll'}, {'frequency': 'r', 'synset': 'dollar.n.02', 'synonyms': ['dollar', 'dollar_bill', 'one_dollar_bill'], 'id': 381, 'def': 'a piece of paper money worth one dollar', 'name': 'dollar'}, {'frequency': 'r', 'synset': 'dollhouse.n.01', 'synonyms': ['dollhouse', "doll's_house"], 'id': 382, 'def': "a house so small that it is likened to a child's plaything", 'name': 'dollhouse'}, {'frequency': 'c', 'synset': 'dolphin.n.02', 'synonyms': ['dolphin'], 'id': 383, 'def': 'any of various small toothed whales with a beaklike snout; larger than porpoises', 'name': 'dolphin'}, {'frequency': 'c', 'synset': 'domestic_ass.n.01', 'synonyms': ['domestic_ass', 'donkey'], 'id': 384, 'def': 'domestic beast of burden descended from the African wild ass; patient but stubborn', 'name': 'domestic_ass'}, {'frequency': 'f', 'synset': 'doorknob.n.01', 'synonyms': ['doorknob', 'doorhandle'], 'id': 385, 'def': "a knob used to open a door (often called `doorhandle' in Great Britain)", 'name': 'doorknob'}, {'frequency': 'c', 'synset': 'doormat.n.02', 'synonyms': ['doormat', 'welcome_mat'], 'id': 386, 'def': 'a mat placed outside an exterior door for wiping the shoes before entering', 'name': 'doormat'}, {'frequency': 'f', 'synset': 'doughnut.n.02', 'synonyms': ['doughnut', 'donut'], 'id': 387, 'def': 'a small ring-shaped friedcake', 'name': 'doughnut'}, {'frequency': 'r', 'synset': 'dove.n.01', 'synonyms': ['dove'], 'id': 388, 'def': 'any of numerous small pigeons', 'name': 'dove'}, {'frequency': 'r', 'synset': 'dragonfly.n.01', 'synonyms': ['dragonfly'], 'id': 389, 'def': 'slender-bodied non-stinging insect having iridescent wings that are outspread at rest', 'name': 'dragonfly'}, {'frequency': 'f', 'synset': 'drawer.n.01', 'synonyms': ['drawer'], 'id': 390, 'def': 'a boxlike container in a piece of furniture; made so as to slide in and out', 'name': 'drawer'}, {'frequency': 'c', 'synset': 'drawers.n.01', 'synonyms': ['underdrawers', 'boxers', 'boxershorts'], 'id': 391, 'def': 'underpants worn by men', 'name': 'underdrawers'}, {'frequency': 'f', 'synset': 'dress.n.01', 'synonyms': ['dress', 'frock'], 'id': 392, 'def': 'a one-piece garment for a woman; has skirt and bodice', 'name': 'dress'}, {'frequency': 'c', 'synset': 'dress_hat.n.01', 'synonyms': ['dress_hat', 'high_hat', 'opera_hat', 'silk_hat', 'top_hat'], 'id': 393, 'def': "a man's hat with a tall crown; usually covered with silk or with beaver fur", 'name': 'dress_hat'}, {'frequency': 'f', 'synset': 'dress_suit.n.01', 'synonyms': ['dress_suit'], 'id': 394, 'def': 'formalwear consisting of full evening dress for men', 'name': 'dress_suit'}, {'frequency': 'f', 'synset': 'dresser.n.05', 'synonyms': ['dresser'], 'id': 395, 'def': 'a cabinet with shelves', 'name': 'dresser'}, {'frequency': 'c', 'synset': 'drill.n.01', 'synonyms': ['drill'], 'id': 396, 'def': 'a tool with a sharp rotating point for making holes in hard materials', 'name': 'drill'}, {'frequency': 'r', 'synset': 'drone.n.04', 'synonyms': ['drone'], 'id': 397, 'def': 'an aircraft without a pilot that is operated by remote control', 'name': 'drone'}, {'frequency': 'r', 'synset': 'dropper.n.01', 'synonyms': ['dropper', 'eye_dropper'], 'id': 398, 'def': 'pipet consisting of a small tube with a vacuum bulb at one end for drawing liquid in and releasing it a drop at a time', 'name': 'dropper'}, {'frequency': 'c', 'synset': 'drum.n.01', 'synonyms': ['drum_(musical_instrument)'], 'id': 399, 'def': 'a musical percussion instrument; usually consists of a hollow cylinder with a membrane stretched across each end', 'name': 'drum_(musical_instrument)'}, {'frequency': 'r', 'synset': 'drumstick.n.02', 'synonyms': ['drumstick'], 'id': 400, 'def': 'a stick used for playing a drum', 'name': 'drumstick'}, {'frequency': 'f', 'synset': 'duck.n.01', 'synonyms': ['duck'], 'id': 401, 'def': 'small web-footed broad-billed swimming bird', 'name': 'duck'}, {'frequency': 'c', 'synset': 'duckling.n.02', 'synonyms': ['duckling'], 'id': 402, 'def': 'young duck', 'name': 'duckling'}, {'frequency': 'c', 'synset': 'duct_tape.n.01', 'synonyms': ['duct_tape'], 'id': 403, 'def': 'a wide silvery adhesive tape', 'name': 'duct_tape'}, {'frequency': 'f', 'synset': 'duffel_bag.n.01', 'synonyms': ['duffel_bag', 'duffle_bag', 'duffel', 'duffle'], 'id': 404, 'def': 'a large cylindrical bag of heavy cloth (does not include suitcases)', 'name': 'duffel_bag'}, {'frequency': 'r', 'synset': 'dumbbell.n.01', 'synonyms': ['dumbbell'], 'id': 405, 'def': 'an exercising weight with two ball-like ends connected by a short handle', 'name': 'dumbbell'}, {'frequency': 'c', 'synset': 'dumpster.n.01', 'synonyms': ['dumpster'], 'id': 406, 'def': 'a container designed to receive and transport and dump waste', 'name': 'dumpster'}, {'frequency': 'r', 'synset': 'dustpan.n.02', 'synonyms': ['dustpan'], 'id': 407, 'def': 'a short-handled receptacle into which dust can be swept', 'name': 'dustpan'}, {'frequency': 'c', 'synset': 'eagle.n.01', 'synonyms': ['eagle'], 'id': 408, 'def': 'large birds of prey noted for their broad wings and strong soaring flight', 'name': 'eagle'}, {'frequency': 'f', 'synset': 'earphone.n.01', 'synonyms': ['earphone', 'earpiece', 'headphone'], 'id': 409, 'def': 'device for listening to audio that is held over or inserted into the ear', 'name': 'earphone'}, {'frequency': 'r', 'synset': 'earplug.n.01', 'synonyms': ['earplug'], 'id': 410, 'def': 'a soft plug that is inserted into the ear canal to block sound', 'name': 'earplug'}, {'frequency': 'f', 'synset': 'earring.n.01', 'synonyms': ['earring'], 'id': 411, 'def': 'jewelry to ornament the ear', 'name': 'earring'}, {'frequency': 'c', 'synset': 'easel.n.01', 'synonyms': ['easel'], 'id': 412, 'def': "an upright tripod for displaying something (usually an artist's canvas)", 'name': 'easel'}, {'frequency': 'r', 'synset': 'eclair.n.01', 'synonyms': ['eclair'], 'id': 413, 'def': 'oblong cream puff', 'name': 'eclair'}, {'frequency': 'r', 'synset': 'eel.n.01', 'synonyms': ['eel'], 'id': 414, 'def': 'an elongate fish with fatty flesh', 'name': 'eel'}, {'frequency': 'f', 'synset': 'egg.n.02', 'synonyms': ['egg', 'eggs'], 'id': 415, 'def': 'oval reproductive body of a fowl (especially a hen) used as food', 'name': 'egg'}, {'frequency': 'r', 'synset': 'egg_roll.n.01', 'synonyms': ['egg_roll', 'spring_roll'], 'id': 416, 'def': 'minced vegetables and meat wrapped in a pancake and fried', 'name': 'egg_roll'}, {'frequency': 'c', 'synset': 'egg_yolk.n.01', 'synonyms': ['egg_yolk', 'yolk_(egg)'], 'id': 417, 'def': 'the yellow spherical part of an egg', 'name': 'egg_yolk'}, {'frequency': 'c', 'synset': 'eggbeater.n.02', 'synonyms': ['eggbeater', 'eggwhisk'], 'id': 418, 'def': 'a mixer for beating eggs or whipping cream', 'name': 'eggbeater'}, {'frequency': 'c', 'synset': 'eggplant.n.01', 'synonyms': ['eggplant', 'aubergine'], 'id': 419, 'def': 'egg-shaped vegetable having a shiny skin typically dark purple', 'name': 'eggplant'}, {'frequency': 'r', 'synset': 'electric_chair.n.01', 'synonyms': ['electric_chair'], 'id': 420, 'def': 'a chair-shaped instrument of execution by electrocution', 'name': 'electric_chair'}, {'frequency': 'f', 'synset': 'electric_refrigerator.n.01', 'synonyms': ['refrigerator'], 'id': 421, 'def': 'a refrigerator in which the coolant is pumped around by an electric motor', 'name': 'refrigerator'}, {'frequency': 'f', 'synset': 'elephant.n.01', 'synonyms': ['elephant'], 'id': 422, 'def': 'a common elephant', 'name': 'elephant'}, {'frequency': 'c', 'synset': 'elk.n.01', 'synonyms': ['elk', 'moose'], 'id': 423, 'def': 'large northern deer with enormous flattened antlers in the male', 'name': 'elk'}, {'frequency': 'c', 'synset': 'envelope.n.01', 'synonyms': ['envelope'], 'id': 424, 'def': 'a flat (usually rectangular) container for a letter, thin package, etc.', 'name': 'envelope'}, {'frequency': 'c', 'synset': 'eraser.n.01', 'synonyms': ['eraser'], 'id': 425, 'def': 'an implement used to erase something', 'name': 'eraser'}, {'frequency': 'r', 'synset': 'escargot.n.01', 'synonyms': ['escargot'], 'id': 426, 'def': 'edible snail usually served in the shell with a sauce of melted butter and garlic', 'name': 'escargot'}, {'frequency': 'r', 'synset': 'eyepatch.n.01', 'synonyms': ['eyepatch'], 'id': 427, 'def': 'a protective cloth covering for an injured eye', 'name': 'eyepatch'}, {'frequency': 'r', 'synset': 'falcon.n.01', 'synonyms': ['falcon'], 'id': 428, 'def': 'birds of prey having long pointed powerful wings adapted for swift flight', 'name': 'falcon'}, {'frequency': 'f', 'synset': 'fan.n.01', 'synonyms': ['fan'], 'id': 429, 'def': 'a device for creating a current of air by movement of a surface or surfaces', 'name': 'fan'}, {'frequency': 'f', 'synset': 'faucet.n.01', 'synonyms': ['faucet', 'spigot', 'tap'], 'id': 430, 'def': 'a regulator for controlling the flow of a liquid from a reservoir', 'name': 'faucet'}, {'frequency': 'r', 'synset': 'fedora.n.01', 'synonyms': ['fedora'], 'id': 431, 'def': 'a hat made of felt with a creased crown', 'name': 'fedora'}, {'frequency': 'r', 'synset': 'ferret.n.02', 'synonyms': ['ferret'], 'id': 432, 'def': 'domesticated albino variety of the European polecat bred for hunting rats and rabbits', 'name': 'ferret'}, {'frequency': 'c', 'synset': 'ferris_wheel.n.01', 'synonyms': ['Ferris_wheel'], 'id': 433, 'def': 'a large wheel with suspended seats that remain upright as the wheel rotates', 'name': 'Ferris_wheel'}, {'frequency': 'c', 'synset': 'ferry.n.01', 'synonyms': ['ferry', 'ferryboat'], 'id': 434, 'def': 'a boat that transports people or vehicles across a body of water and operates on a regular schedule', 'name': 'ferry'}, {'frequency': 'r', 'synset': 'fig.n.04', 'synonyms': ['fig_(fruit)'], 'id': 435, 'def': 'fleshy sweet pear-shaped yellowish or purple fruit eaten fresh or preserved or dried', 'name': 'fig_(fruit)'}, {'frequency': 'c', 'synset': 'fighter.n.02', 'synonyms': ['fighter_jet', 'fighter_aircraft', 'attack_aircraft'], 'id': 436, 'def': 'a high-speed military or naval airplane designed to destroy enemy targets', 'name': 'fighter_jet'}, {'frequency': 'f', 'synset': 'figurine.n.01', 'synonyms': ['figurine'], 'id': 437, 'def': 'a small carved or molded figure', 'name': 'figurine'}, {'frequency': 'c', 'synset': 'file.n.03', 'synonyms': ['file_cabinet', 'filing_cabinet'], 'id': 438, 'def': 'office furniture consisting of a container for keeping papers in order', 'name': 'file_cabinet'}, {'frequency': 'r', 'synset': 'file.n.04', 'synonyms': ['file_(tool)'], 'id': 439, 'def': 'a steel hand tool with small sharp teeth on some or all of its surfaces; used for smoothing wood or metal', 'name': 'file_(tool)'}, {'frequency': 'f', 'synset': 'fire_alarm.n.02', 'synonyms': ['fire_alarm', 'smoke_alarm'], 'id': 440, 'def': 'an alarm that is tripped off by fire or smoke', 'name': 'fire_alarm'}, {'frequency': 'f', 'synset': 'fire_engine.n.01', 'synonyms': ['fire_engine', 'fire_truck'], 'id': 441, 'def': 'large trucks that carry firefighters and equipment to the site of a fire', 'name': 'fire_engine'}, {'frequency': 'f', 'synset': 'fire_extinguisher.n.01', 'synonyms': ['fire_extinguisher', 'extinguisher'], 'id': 442, 'def': 'a manually operated device for extinguishing small fires', 'name': 'fire_extinguisher'}, {'frequency': 'c', 'synset': 'fire_hose.n.01', 'synonyms': ['fire_hose'], 'id': 443, 'def': 'a large hose that carries water from a fire hydrant to the site of the fire', 'name': 'fire_hose'}, {'frequency': 'f', 'synset': 'fireplace.n.01', 'synonyms': ['fireplace'], 'id': 444, 'def': 'an open recess in a wall at the base of a chimney where a fire can be built', 'name': 'fireplace'}, {'frequency': 'f', 'synset': 'fireplug.n.01', 'synonyms': ['fireplug', 'fire_hydrant', 'hydrant'], 'id': 445, 'def': 'an upright hydrant for drawing water to use in fighting a fire', 'name': 'fireplug'}, {'frequency': 'r', 'synset': 'first-aid_kit.n.01', 'synonyms': ['first-aid_kit'], 'id': 446, 'def': 'kit consisting of a set of bandages and medicines for giving first aid', 'name': 'first-aid_kit'}, {'frequency': 'f', 'synset': 'fish.n.01', 'synonyms': ['fish'], 'id': 447, 'def': 'any of various mostly cold-blooded aquatic vertebrates usually having scales and breathing through gills', 'name': 'fish'}, {'frequency': 'c', 'synset': 'fish.n.02', 'synonyms': ['fish_(food)'], 'id': 448, 'def': 'the flesh of fish used as food', 'name': 'fish_(food)'}, {'frequency': 'r', 'synset': 'fishbowl.n.02', 'synonyms': ['fishbowl', 'goldfish_bowl'], 'id': 449, 'def': 'a transparent bowl in which small fish are kept', 'name': 'fishbowl'}, {'frequency': 'c', 'synset': 'fishing_rod.n.01', 'synonyms': ['fishing_rod', 'fishing_pole'], 'id': 450, 'def': 'a rod that is used in fishing to extend the fishing line', 'name': 'fishing_rod'}, {'frequency': 'f', 'synset': 'flag.n.01', 'synonyms': ['flag'], 'id': 451, 'def': 'emblem usually consisting of a rectangular piece of cloth of distinctive design (do not include pole)', 'name': 'flag'}, {'frequency': 'f', 'synset': 'flagpole.n.02', 'synonyms': ['flagpole', 'flagstaff'], 'id': 452, 'def': 'a tall staff or pole on which a flag is raised', 'name': 'flagpole'}, {'frequency': 'c', 'synset': 'flamingo.n.01', 'synonyms': ['flamingo'], 'id': 453, 'def': 'large pink web-footed bird with down-bent bill', 'name': 'flamingo'}, {'frequency': 'c', 'synset': 'flannel.n.01', 'synonyms': ['flannel'], 'id': 454, 'def': 'a soft light woolen fabric; used for clothing', 'name': 'flannel'}, {'frequency': 'c', 'synset': 'flap.n.01', 'synonyms': ['flap'], 'id': 455, 'def': 'any broad thin covering attached at one edge, such as a mud flap next to a wheel or a flap on an airplane wing', 'name': 'flap'}, {'frequency': 'r', 'synset': 'flash.n.10', 'synonyms': ['flash', 'flashbulb'], 'id': 456, 'def': 'a lamp for providing momentary light to take a photograph', 'name': 'flash'}, {'frequency': 'c', 'synset': 'flashlight.n.01', 'synonyms': ['flashlight', 'torch'], 'id': 457, 'def': 'a small portable battery-powered electric lamp', 'name': 'flashlight'}, {'frequency': 'r', 'synset': 'fleece.n.03', 'synonyms': ['fleece'], 'id': 458, 'def': 'a soft bulky fabric with deep pile; used chiefly for clothing', 'name': 'fleece'}, {'frequency': 'f', 'synset': 'flip-flop.n.02', 'synonyms': ['flip-flop_(sandal)'], 'id': 459, 'def': 'a backless sandal held to the foot by a thong between two toes', 'name': 'flip-flop_(sandal)'}, {'frequency': 'c', 'synset': 'flipper.n.01', 'synonyms': ['flipper_(footwear)', 'fin_(footwear)'], 'id': 460, 'def': 'a shoe to aid a person in swimming', 'name': 'flipper_(footwear)'}, {'frequency': 'f', 'synset': 'flower_arrangement.n.01', 'synonyms': ['flower_arrangement', 'floral_arrangement'], 'id': 461, 'def': 'a decorative arrangement of flowers', 'name': 'flower_arrangement'}, {'frequency': 'c', 'synset': 'flute.n.02', 'synonyms': ['flute_glass', 'champagne_flute'], 'id': 462, 'def': 'a tall narrow wineglass', 'name': 'flute_glass'}, {'frequency': 'c', 'synset': 'foal.n.01', 'synonyms': ['foal'], 'id': 463, 'def': 'a young horse', 'name': 'foal'}, {'frequency': 'c', 'synset': 'folding_chair.n.01', 'synonyms': ['folding_chair'], 'id': 464, 'def': 'a chair that can be folded flat for storage', 'name': 'folding_chair'}, {'frequency': 'c', 'synset': 'food_processor.n.01', 'synonyms': ['food_processor'], 'id': 465, 'def': 'a kitchen appliance for shredding, blending, chopping, or slicing food', 'name': 'food_processor'}, {'frequency': 'c', 'synset': 'football.n.02', 'synonyms': ['football_(American)'], 'id': 466, 'def': 'the inflated oblong ball used in playing American football', 'name': 'football_(American)'}, {'frequency': 'r', 'synset': 'football_helmet.n.01', 'synonyms': ['football_helmet'], 'id': 467, 'def': 'a padded helmet with a face mask to protect the head of football players', 'name': 'football_helmet'}, {'frequency': 'c', 'synset': 'footstool.n.01', 'synonyms': ['footstool', 'footrest'], 'id': 468, 'def': 'a low seat or a stool to rest the feet of a seated person', 'name': 'footstool'}, {'frequency': 'f', 'synset': 'fork.n.01', 'synonyms': ['fork'], 'id': 469, 'def': 'cutlery used for serving and eating food', 'name': 'fork'}, {'frequency': 'c', 'synset': 'forklift.n.01', 'synonyms': ['forklift'], 'id': 470, 'def': 'an industrial vehicle with a power operated fork in front that can be inserted under loads to lift and move them', 'name': 'forklift'}, {'frequency': 'c', 'synset': 'freight_car.n.01', 'synonyms': ['freight_car'], 'id': 471, 'def': 'a railway car that carries freight', 'name': 'freight_car'}, {'frequency': 'c', 'synset': 'french_toast.n.01', 'synonyms': ['French_toast'], 'id': 472, 'def': 'bread slice dipped in egg and milk and fried', 'name': 'French_toast'}, {'frequency': 'c', 'synset': 'freshener.n.01', 'synonyms': ['freshener', 'air_freshener'], 'id': 473, 'def': 'anything that freshens air by removing or covering odor', 'name': 'freshener'}, {'frequency': 'f', 'synset': 'frisbee.n.01', 'synonyms': ['frisbee'], 'id': 474, 'def': 'a light, plastic disk propelled with a flip of the wrist for recreation or competition', 'name': 'frisbee'}, {'frequency': 'c', 'synset': 'frog.n.01', 'synonyms': ['frog', 'toad', 'toad_frog'], 'id': 475, 'def': 'a tailless stout-bodied amphibians with long hind limbs for leaping', 'name': 'frog'}, {'frequency': 'c', 'synset': 'fruit_juice.n.01', 'synonyms': ['fruit_juice'], 'id': 476, 'def': 'drink produced by squeezing or crushing fruit', 'name': 'fruit_juice'}, {'frequency': 'f', 'synset': 'frying_pan.n.01', 'synonyms': ['frying_pan', 'frypan', 'skillet'], 'id': 477, 'def': 'a pan used for frying foods', 'name': 'frying_pan'}, {'frequency': 'r', 'synset': 'fudge.n.01', 'synonyms': ['fudge'], 'id': 478, 'def': 'soft creamy candy', 'name': 'fudge'}, {'frequency': 'r', 'synset': 'funnel.n.02', 'synonyms': ['funnel'], 'id': 479, 'def': 'a cone-shaped utensil used to channel a substance into a container with a small mouth', 'name': 'funnel'}, {'frequency': 'r', 'synset': 'futon.n.01', 'synonyms': ['futon'], 'id': 480, 'def': 'a pad that is used for sleeping on the floor or on a raised frame', 'name': 'futon'}, {'frequency': 'r', 'synset': 'gag.n.02', 'synonyms': ['gag', 'muzzle'], 'id': 481, 'def': "restraint put into a person's mouth to prevent speaking or shouting", 'name': 'gag'}, {'frequency': 'r', 'synset': 'garbage.n.03', 'synonyms': ['garbage'], 'id': 482, 'def': 'a receptacle where waste can be discarded', 'name': 'garbage'}, {'frequency': 'c', 'synset': 'garbage_truck.n.01', 'synonyms': ['garbage_truck'], 'id': 483, 'def': 'a truck for collecting domestic refuse', 'name': 'garbage_truck'}, {'frequency': 'c', 'synset': 'garden_hose.n.01', 'synonyms': ['garden_hose'], 'id': 484, 'def': 'a hose used for watering a lawn or garden', 'name': 'garden_hose'}, {'frequency': 'c', 'synset': 'gargle.n.01', 'synonyms': ['gargle', 'mouthwash'], 'id': 485, 'def': 'a medicated solution used for gargling and rinsing the mouth', 'name': 'gargle'}, {'frequency': 'r', 'synset': 'gargoyle.n.02', 'synonyms': ['gargoyle'], 'id': 486, 'def': 'an ornament consisting of a grotesquely carved figure of a person or animal', 'name': 'gargoyle'}, {'frequency': 'c', 'synset': 'garlic.n.02', 'synonyms': ['garlic', 'ail'], 'id': 487, 'def': 'aromatic bulb used as seasoning', 'name': 'garlic'}, {'frequency': 'r', 'synset': 'gasmask.n.01', 'synonyms': ['gasmask', 'respirator', 'gas_helmet'], 'id': 488, 'def': 'a protective face mask with a filter', 'name': 'gasmask'}, {'frequency': 'c', 'synset': 'gazelle.n.01', 'synonyms': ['gazelle'], 'id': 489, 'def': 'small swift graceful antelope of Africa and Asia having lustrous eyes', 'name': 'gazelle'}, {'frequency': 'c', 'synset': 'gelatin.n.02', 'synonyms': ['gelatin', 'jelly'], 'id': 490, 'def': 'an edible jelly made with gelatin and used as a dessert or salad base or a coating for foods', 'name': 'gelatin'}, {'frequency': 'r', 'synset': 'gem.n.02', 'synonyms': ['gemstone'], 'id': 491, 'def': 'a crystalline rock that can be cut and polished for jewelry', 'name': 'gemstone'}, {'frequency': 'r', 'synset': 'generator.n.02', 'synonyms': ['generator'], 'id': 492, 'def': 'engine that converts mechanical energy into electrical energy by electromagnetic induction', 'name': 'generator'}, {'frequency': 'c', 'synset': 'giant_panda.n.01', 'synonyms': ['giant_panda', 'panda', 'panda_bear'], 'id': 493, 'def': 'large black-and-white herbivorous mammal of bamboo forests of China and Tibet', 'name': 'giant_panda'}, {'frequency': 'c', 'synset': 'gift_wrap.n.01', 'synonyms': ['gift_wrap'], 'id': 494, 'def': 'attractive wrapping paper suitable for wrapping gifts', 'name': 'gift_wrap'}, {'frequency': 'c', 'synset': 'ginger.n.03', 'synonyms': ['ginger', 'gingerroot'], 'id': 495, 'def': 'the root of the common ginger plant; used fresh as a seasoning', 'name': 'ginger'}, {'frequency': 'f', 'synset': 'giraffe.n.01', 'synonyms': ['giraffe'], 'id': 496, 'def': 'tall animal having a spotted coat and small horns and very long neck and legs', 'name': 'giraffe'}, {'frequency': 'c', 'synset': 'girdle.n.02', 'synonyms': ['cincture', 'sash', 'waistband', 'waistcloth'], 'id': 497, 'def': 'a band of material around the waist that strengthens a skirt or trousers', 'name': 'cincture'}, {'frequency': 'f', 'synset': 'glass.n.02', 'synonyms': ['glass_(drink_container)', 'drinking_glass'], 'id': 498, 'def': 'a container for holding liquids while drinking', 'name': 'glass_(drink_container)'}, {'frequency': 'c', 'synset': 'globe.n.03', 'synonyms': ['globe'], 'id': 499, 'def': 'a sphere on which a map (especially of the earth) is represented', 'name': 'globe'}, {'frequency': 'f', 'synset': 'glove.n.02', 'synonyms': ['glove'], 'id': 500, 'def': 'handwear covering the hand', 'name': 'glove'}, {'frequency': 'c', 'synset': 'goat.n.01', 'synonyms': ['goat'], 'id': 501, 'def': 'a common goat', 'name': 'goat'}, {'frequency': 'f', 'synset': 'goggles.n.01', 'synonyms': ['goggles'], 'id': 502, 'def': 'tight-fitting spectacles worn to protect the eyes', 'name': 'goggles'}, {'frequency': 'r', 'synset': 'goldfish.n.01', 'synonyms': ['goldfish'], 'id': 503, 'def': 'small golden or orange-red freshwater fishes used as pond or aquarium pets', 'name': 'goldfish'}, {'frequency': 'c', 'synset': 'golf_club.n.02', 'synonyms': ['golf_club', 'golf-club'], 'id': 504, 'def': 'golf equipment used by a golfer to hit a golf ball', 'name': 'golf_club'}, {'frequency': 'c', 'synset': 'golfcart.n.01', 'synonyms': ['golfcart'], 'id': 505, 'def': 'a small motor vehicle in which golfers can ride between shots', 'name': 'golfcart'}, {'frequency': 'r', 'synset': 'gondola.n.02', 'synonyms': ['gondola_(boat)'], 'id': 506, 'def': 'long narrow flat-bottomed boat propelled by sculling; traditionally used on canals of Venice', 'name': 'gondola_(boat)'}, {'frequency': 'c', 'synset': 'goose.n.01', 'synonyms': ['goose'], 'id': 507, 'def': 'loud, web-footed long-necked aquatic birds usually larger than ducks', 'name': 'goose'}, {'frequency': 'r', 'synset': 'gorilla.n.01', 'synonyms': ['gorilla'], 'id': 508, 'def': 'largest ape', 'name': 'gorilla'}, {'frequency': 'r', 'synset': 'gourd.n.02', 'synonyms': ['gourd'], 'id': 509, 'def': 'any of numerous inedible fruits with hard rinds', 'name': 'gourd'}, {'frequency': 'f', 'synset': 'grape.n.01', 'synonyms': ['grape'], 'id': 510, 'def': 'any of various juicy fruit with green or purple skins; grow in clusters', 'name': 'grape'}, {'frequency': 'c', 'synset': 'grater.n.01', 'synonyms': ['grater'], 'id': 511, 'def': 'utensil with sharp perforations for shredding foods (as vegetables or cheese)', 'name': 'grater'}, {'frequency': 'c', 'synset': 'gravestone.n.01', 'synonyms': ['gravestone', 'headstone', 'tombstone'], 'id': 512, 'def': 'a stone that is used to mark a grave', 'name': 'gravestone'}, {'frequency': 'r', 'synset': 'gravy_boat.n.01', 'synonyms': ['gravy_boat', 'gravy_holder'], 'id': 513, 'def': 'a dish (often boat-shaped) for serving gravy or sauce', 'name': 'gravy_boat'}, {'frequency': 'f', 'synset': 'green_bean.n.02', 'synonyms': ['green_bean'], 'id': 514, 'def': 'a common bean plant cultivated for its slender green edible pods', 'name': 'green_bean'}, {'frequency': 'f', 'synset': 'green_onion.n.01', 'synonyms': ['green_onion', 'spring_onion', 'scallion'], 'id': 515, 'def': 'a young onion before the bulb has enlarged', 'name': 'green_onion'}, {'frequency': 'r', 'synset': 'griddle.n.01', 'synonyms': ['griddle'], 'id': 516, 'def': 'cooking utensil consisting of a flat heated surface on which food is cooked', 'name': 'griddle'}, {'frequency': 'f', 'synset': 'grill.n.02', 'synonyms': ['grill', 'grille', 'grillwork', 'radiator_grille'], 'id': 517, 'def': 'a framework of metal bars used as a partition or a grate', 'name': 'grill'}, {'frequency': 'r', 'synset': 'grits.n.01', 'synonyms': ['grits', 'hominy_grits'], 'id': 518, 'def': 'coarsely ground corn boiled as a breakfast dish', 'name': 'grits'}, {'frequency': 'c', 'synset': 'grizzly.n.01', 'synonyms': ['grizzly', 'grizzly_bear'], 'id': 519, 'def': 'powerful brownish-yellow bear of the uplands of western North America', 'name': 'grizzly'}, {'frequency': 'c', 'synset': 'grocery_bag.n.01', 'synonyms': ['grocery_bag'], 'id': 520, 'def': "a sack for holding customer's groceries", 'name': 'grocery_bag'}, {'frequency': 'f', 'synset': 'guitar.n.01', 'synonyms': ['guitar'], 'id': 521, 'def': 'a stringed instrument usually having six strings; played by strumming or plucking', 'name': 'guitar'}, {'frequency': 'c', 'synset': 'gull.n.02', 'synonyms': ['gull', 'seagull'], 'id': 522, 'def': 'mostly white aquatic bird having long pointed wings and short legs', 'name': 'gull'}, {'frequency': 'c', 'synset': 'gun.n.01', 'synonyms': ['gun'], 'id': 523, 'def': 'a weapon that discharges a bullet at high velocity from a metal tube', 'name': 'gun'}, {'frequency': 'f', 'synset': 'hairbrush.n.01', 'synonyms': ['hairbrush'], 'id': 524, 'def': "a brush used to groom a person's hair", 'name': 'hairbrush'}, {'frequency': 'c', 'synset': 'hairnet.n.01', 'synonyms': ['hairnet'], 'id': 525, 'def': 'a small net that someone wears over their hair to keep it in place', 'name': 'hairnet'}, {'frequency': 'c', 'synset': 'hairpin.n.01', 'synonyms': ['hairpin'], 'id': 526, 'def': "a double pronged pin used to hold women's hair in place", 'name': 'hairpin'}, {'frequency': 'r', 'synset': 'halter.n.03', 'synonyms': ['halter_top'], 'id': 527, 'def': "a woman's top that fastens behind the back and neck leaving the back and arms uncovered", 'name': 'halter_top'}, {'frequency': 'f', 'synset': 'ham.n.01', 'synonyms': ['ham', 'jambon', 'gammon'], 'id': 528, 'def': 'meat cut from the thigh of a hog (usually smoked)', 'name': 'ham'}, {'frequency': 'c', 'synset': 'hamburger.n.01', 'synonyms': ['hamburger', 'beefburger', 'burger'], 'id': 529, 'def': 'a sandwich consisting of a patty of minced beef served on a bun', 'name': 'hamburger'}, {'frequency': 'c', 'synset': 'hammer.n.02', 'synonyms': ['hammer'], 'id': 530, 'def': 'a hand tool with a heavy head and a handle; used to deliver an impulsive force by striking', 'name': 'hammer'}, {'frequency': 'c', 'synset': 'hammock.n.02', 'synonyms': ['hammock'], 'id': 531, 'def': 'a hanging bed of canvas or rope netting (usually suspended between two trees)', 'name': 'hammock'}, {'frequency': 'r', 'synset': 'hamper.n.02', 'synonyms': ['hamper'], 'id': 532, 'def': 'a basket usually with a cover', 'name': 'hamper'}, {'frequency': 'c', 'synset': 'hamster.n.01', 'synonyms': ['hamster'], 'id': 533, 'def': 'short-tailed burrowing rodent with large cheek pouches', 'name': 'hamster'}, {'frequency': 'f', 'synset': 'hand_blower.n.01', 'synonyms': ['hair_dryer'], 'id': 534, 'def': 'a hand-held electric blower that can blow warm air onto the hair', 'name': 'hair_dryer'}, {'frequency': 'r', 'synset': 'hand_glass.n.01', 'synonyms': ['hand_glass', 'hand_mirror'], 'id': 535, 'def': 'a mirror intended to be held in the hand', 'name': 'hand_glass'}, {'frequency': 'f', 'synset': 'hand_towel.n.01', 'synonyms': ['hand_towel', 'face_towel'], 'id': 536, 'def': 'a small towel used to dry the hands or face', 'name': 'hand_towel'}, {'frequency': 'c', 'synset': 'handcart.n.01', 'synonyms': ['handcart', 'pushcart', 'hand_truck'], 'id': 537, 'def': 'wheeled vehicle that can be pushed by a person', 'name': 'handcart'}, {'frequency': 'r', 'synset': 'handcuff.n.01', 'synonyms': ['handcuff'], 'id': 538, 'def': 'shackle that consists of a metal loop that can be locked around the wrist', 'name': 'handcuff'}, {'frequency': 'c', 'synset': 'handkerchief.n.01', 'synonyms': ['handkerchief'], 'id': 539, 'def': 'a square piece of cloth used for wiping the eyes or nose or as a costume accessory', 'name': 'handkerchief'}, {'frequency': 'f', 'synset': 'handle.n.01', 'synonyms': ['handle', 'grip', 'handgrip'], 'id': 540, 'def': 'the appendage to an object that is designed to be held in order to use or move it', 'name': 'handle'}, {'frequency': 'r', 'synset': 'handsaw.n.01', 'synonyms': ['handsaw', "carpenter's_saw"], 'id': 541, 'def': 'a saw used with one hand for cutting wood', 'name': 'handsaw'}, {'frequency': 'r', 'synset': 'hardback.n.01', 'synonyms': ['hardback_book', 'hardcover_book'], 'id': 542, 'def': 'a book with cardboard or cloth or leather covers', 'name': 'hardback_book'}, {'frequency': 'r', 'synset': 'harmonium.n.01', 'synonyms': ['harmonium', 'organ_(musical_instrument)', 'reed_organ_(musical_instrument)'], 'id': 543, 'def': 'a free-reed instrument in which air is forced through the reeds by bellows', 'name': 'harmonium'}, {'frequency': 'f', 'synset': 'hat.n.01', 'synonyms': ['hat'], 'id': 544, 'def': 'headwear that protects the head from bad weather, sun, or worn for fashion', 'name': 'hat'}, {'frequency': 'r', 'synset': 'hatbox.n.01', 'synonyms': ['hatbox'], 'id': 545, 'def': 'a round piece of luggage for carrying hats', 'name': 'hatbox'}, {'frequency': 'c', 'synset': 'head_covering.n.01', 'synonyms': ['veil'], 'id': 546, 'def': 'a garment that covers the head OR face', 'name': 'veil'}, {'frequency': 'f', 'synset': 'headband.n.01', 'synonyms': ['headband'], 'id': 547, 'def': 'a band worn around or over the head', 'name': 'headband'}, {'frequency': 'f', 'synset': 'headboard.n.01', 'synonyms': ['headboard'], 'id': 548, 'def': 'a vertical board or panel forming the head of a bedstead', 'name': 'headboard'}, {'frequency': 'f', 'synset': 'headlight.n.01', 'synonyms': ['headlight', 'headlamp'], 'id': 549, 'def': 'a powerful light with reflector; attached to the front of an automobile or locomotive', 'name': 'headlight'}, {'frequency': 'c', 'synset': 'headscarf.n.01', 'synonyms': ['headscarf'], 'id': 550, 'def': 'a kerchief worn over the head and tied under the chin', 'name': 'headscarf'}, {'frequency': 'r', 'synset': 'headset.n.01', 'synonyms': ['headset'], 'id': 551, 'def': 'receiver consisting of a pair of headphones', 'name': 'headset'}, {'frequency': 'c', 'synset': 'headstall.n.01', 'synonyms': ['headstall_(for_horses)', 'headpiece_(for_horses)'], 'id': 552, 'def': "the band that is the part of a bridle that fits around a horse's head", 'name': 'headstall_(for_horses)'}, {'frequency': 'c', 'synset': 'heart.n.02', 'synonyms': ['heart'], 'id': 553, 'def': 'a muscular organ; its contractions move the blood through the body', 'name': 'heart'}, {'frequency': 'c', 'synset': 'heater.n.01', 'synonyms': ['heater', 'warmer'], 'id': 554, 'def': 'device that heats water or supplies warmth to a room', 'name': 'heater'}, {'frequency': 'c', 'synset': 'helicopter.n.01', 'synonyms': ['helicopter'], 'id': 555, 'def': 'an aircraft without wings that obtains its lift from the rotation of overhead blades', 'name': 'helicopter'}, {'frequency': 'f', 'synset': 'helmet.n.02', 'synonyms': ['helmet'], 'id': 556, 'def': 'a protective headgear made of hard material to resist blows', 'name': 'helmet'}, {'frequency': 'r', 'synset': 'heron.n.02', 'synonyms': ['heron'], 'id': 557, 'def': 'grey or white wading bird with long neck and long legs and (usually) long bill', 'name': 'heron'}, {'frequency': 'c', 'synset': 'highchair.n.01', 'synonyms': ['highchair', 'feeding_chair'], 'id': 558, 'def': 'a chair for feeding a very young child', 'name': 'highchair'}, {'frequency': 'f', 'synset': 'hinge.n.01', 'synonyms': ['hinge'], 'id': 559, 'def': 'a joint that holds two parts together so that one can swing relative to the other', 'name': 'hinge'}, {'frequency': 'r', 'synset': 'hippopotamus.n.01', 'synonyms': ['hippopotamus'], 'id': 560, 'def': 'massive thick-skinned animal living in or around rivers of tropical Africa', 'name': 'hippopotamus'}, {'frequency': 'r', 'synset': 'hockey_stick.n.01', 'synonyms': ['hockey_stick'], 'id': 561, 'def': 'sports implement consisting of a stick used by hockey players to move the puck', 'name': 'hockey_stick'}, {'frequency': 'c', 'synset': 'hog.n.03', 'synonyms': ['hog', 'pig'], 'id': 562, 'def': 'domestic swine', 'name': 'hog'}, {'frequency': 'f', 'synset': 'home_plate.n.01', 'synonyms': ['home_plate_(baseball)', 'home_base_(baseball)'], 'id': 563, 'def': '(baseball) a rubber slab where the batter stands; it must be touched by a base runner in order to score', 'name': 'home_plate_(baseball)'}, {'frequency': 'c', 'synset': 'honey.n.01', 'synonyms': ['honey'], 'id': 564, 'def': 'a sweet yellow liquid produced by bees', 'name': 'honey'}, {'frequency': 'f', 'synset': 'hood.n.06', 'synonyms': ['fume_hood', 'exhaust_hood'], 'id': 565, 'def': 'metal covering leading to a vent that exhausts smoke or fumes', 'name': 'fume_hood'}, {'frequency': 'f', 'synset': 'hook.n.05', 'synonyms': ['hook'], 'id': 566, 'def': 'a curved or bent implement for suspending or pulling something', 'name': 'hook'}, {'frequency': 'r', 'synset': 'hookah.n.01', 'synonyms': ['hookah', 'narghile', 'nargileh', 'sheesha', 'shisha', 'water_pipe'], 'id': 567, 'def': 'a tobacco pipe with a long flexible tube connected to a container where the smoke is cooled by passing through water', 'name': 'hookah'}, {'frequency': 'r', 'synset': 'hornet.n.01', 'synonyms': ['hornet'], 'id': 568, 'def': 'large stinging wasp', 'name': 'hornet'}, {'frequency': 'f', 'synset': 'horse.n.01', 'synonyms': ['horse'], 'id': 569, 'def': 'a common horse', 'name': 'horse'}, {'frequency': 'f', 'synset': 'hose.n.03', 'synonyms': ['hose', 'hosepipe'], 'id': 570, 'def': 'a flexible pipe for conveying a liquid or gas', 'name': 'hose'}, {'frequency': 'r', 'synset': 'hot-air_balloon.n.01', 'synonyms': ['hot-air_balloon'], 'id': 571, 'def': 'balloon for travel through the air in a basket suspended below a large bag of heated air', 'name': 'hot-air_balloon'}, {'frequency': 'r', 'synset': 'hot_plate.n.01', 'synonyms': ['hotplate'], 'id': 572, 'def': 'a portable electric appliance for heating or cooking or keeping food warm', 'name': 'hotplate'}, {'frequency': 'c', 'synset': 'hot_sauce.n.01', 'synonyms': ['hot_sauce'], 'id': 573, 'def': 'a pungent peppery sauce', 'name': 'hot_sauce'}, {'frequency': 'r', 'synset': 'hourglass.n.01', 'synonyms': ['hourglass'], 'id': 574, 'def': 'a sandglass timer that runs for sixty minutes', 'name': 'hourglass'}, {'frequency': 'r', 'synset': 'houseboat.n.01', 'synonyms': ['houseboat'], 'id': 575, 'def': 'a barge that is designed and equipped for use as a dwelling', 'name': 'houseboat'}, {'frequency': 'c', 'synset': 'hummingbird.n.01', 'synonyms': ['hummingbird'], 'id': 576, 'def': 'tiny American bird having brilliant iridescent plumage and long slender bills', 'name': 'hummingbird'}, {'frequency': 'r', 'synset': 'hummus.n.01', 'synonyms': ['hummus', 'humus', 'hommos', 'hoummos', 'humous'], 'id': 577, 'def': 'a thick spread made from mashed chickpeas', 'name': 'hummus'}, {'frequency': 'f', 'synset': 'ice_bear.n.01', 'synonyms': ['polar_bear'], 'id': 578, 'def': 'white bear of Arctic regions', 'name': 'polar_bear'}, {'frequency': 'c', 'synset': 'ice_cream.n.01', 'synonyms': ['icecream'], 'id': 579, 'def': 'frozen dessert containing cream and sugar and flavoring', 'name': 'icecream'}, {'frequency': 'r', 'synset': 'ice_lolly.n.01', 'synonyms': ['popsicle'], 'id': 580, 'def': 'ice cream or water ice on a small wooden stick', 'name': 'popsicle'}, {'frequency': 'c', 'synset': 'ice_maker.n.01', 'synonyms': ['ice_maker'], 'id': 581, 'def': 'an appliance included in some electric refrigerators for making ice cubes', 'name': 'ice_maker'}, {'frequency': 'r', 'synset': 'ice_pack.n.01', 'synonyms': ['ice_pack', 'ice_bag'], 'id': 582, 'def': 'a waterproof bag filled with ice: applied to the body (especially the head) to cool or reduce swelling', 'name': 'ice_pack'}, {'frequency': 'r', 'synset': 'ice_skate.n.01', 'synonyms': ['ice_skate'], 'id': 583, 'def': 'skate consisting of a boot with a steel blade fitted to the sole', 'name': 'ice_skate'}, {'frequency': 'c', 'synset': 'igniter.n.01', 'synonyms': ['igniter', 'ignitor', 'lighter'], 'id': 584, 'def': 'a substance or device used to start a fire', 'name': 'igniter'}, {'frequency': 'r', 'synset': 'inhaler.n.01', 'synonyms': ['inhaler', 'inhalator'], 'id': 585, 'def': 'a dispenser that produces a chemical vapor to be inhaled through mouth or nose', 'name': 'inhaler'}, {'frequency': 'f', 'synset': 'ipod.n.01', 'synonyms': ['iPod'], 'id': 586, 'def': 'a pocket-sized device used to play music files', 'name': 'iPod'}, {'frequency': 'c', 'synset': 'iron.n.04', 'synonyms': ['iron_(for_clothing)', 'smoothing_iron_(for_clothing)'], 'id': 587, 'def': 'home appliance consisting of a flat metal base that is heated and used to smooth cloth', 'name': 'iron_(for_clothing)'}, {'frequency': 'c', 'synset': 'ironing_board.n.01', 'synonyms': ['ironing_board'], 'id': 588, 'def': 'narrow padded board on collapsible supports; used for ironing clothes', 'name': 'ironing_board'}, {'frequency': 'f', 'synset': 'jacket.n.01', 'synonyms': ['jacket'], 'id': 589, 'def': 'a waist-length coat', 'name': 'jacket'}, {'frequency': 'c', 'synset': 'jam.n.01', 'synonyms': ['jam'], 'id': 590, 'def': 'preserve of crushed fruit', 'name': 'jam'}, {'frequency': 'f', 'synset': 'jar.n.01', 'synonyms': ['jar'], 'id': 591, 'def': 'a vessel (usually cylindrical) with a wide mouth and without handles', 'name': 'jar'}, {'frequency': 'f', 'synset': 'jean.n.01', 'synonyms': ['jean', 'blue_jean', 'denim'], 'id': 592, 'def': '(usually plural) close-fitting trousers of heavy denim for manual work or casual wear', 'name': 'jean'}, {'frequency': 'c', 'synset': 'jeep.n.01', 'synonyms': ['jeep', 'landrover'], 'id': 593, 'def': 'a car suitable for traveling over rough terrain', 'name': 'jeep'}, {'frequency': 'r', 'synset': 'jelly_bean.n.01', 'synonyms': ['jelly_bean', 'jelly_egg'], 'id': 594, 'def': 'sugar-glazed jellied candy', 'name': 'jelly_bean'}, {'frequency': 'f', 'synset': 'jersey.n.03', 'synonyms': ['jersey', 'T-shirt', 'tee_shirt'], 'id': 595, 'def': 'a close-fitting pullover shirt', 'name': 'jersey'}, {'frequency': 'c', 'synset': 'jet.n.01', 'synonyms': ['jet_plane', 'jet-propelled_plane'], 'id': 596, 'def': 'an airplane powered by one or more jet engines', 'name': 'jet_plane'}, {'frequency': 'r', 'synset': 'jewel.n.01', 'synonyms': ['jewel', 'gem', 'precious_stone'], 'id': 597, 'def': 'a precious or semiprecious stone incorporated into a piece of jewelry', 'name': 'jewel'}, {'frequency': 'c', 'synset': 'jewelry.n.01', 'synonyms': ['jewelry', 'jewellery'], 'id': 598, 'def': 'an adornment (as a bracelet or ring or necklace) made of precious metals and set with gems (or imitation gems)', 'name': 'jewelry'}, {'frequency': 'r', 'synset': 'joystick.n.02', 'synonyms': ['joystick'], 'id': 599, 'def': 'a control device for computers consisting of a vertical handle that can move freely in two directions', 'name': 'joystick'}, {'frequency': 'c', 'synset': 'jump_suit.n.01', 'synonyms': ['jumpsuit'], 'id': 600, 'def': "one-piece garment fashioned after a parachutist's uniform", 'name': 'jumpsuit'}, {'frequency': 'c', 'synset': 'kayak.n.01', 'synonyms': ['kayak'], 'id': 601, 'def': 'a small canoe consisting of a light frame made watertight with animal skins', 'name': 'kayak'}, {'frequency': 'r', 'synset': 'keg.n.02', 'synonyms': ['keg'], 'id': 602, 'def': 'small cask or barrel', 'name': 'keg'}, {'frequency': 'r', 'synset': 'kennel.n.01', 'synonyms': ['kennel', 'doghouse'], 'id': 603, 'def': 'outbuilding that serves as a shelter for a dog', 'name': 'kennel'}, {'frequency': 'c', 'synset': 'kettle.n.01', 'synonyms': ['kettle', 'boiler'], 'id': 604, 'def': 'a metal pot for stewing or boiling; usually has a lid', 'name': 'kettle'}, {'frequency': 'f', 'synset': 'key.n.01', 'synonyms': ['key'], 'id': 605, 'def': 'metal instrument used to unlock a lock', 'name': 'key'}, {'frequency': 'r', 'synset': 'keycard.n.01', 'synonyms': ['keycard'], 'id': 606, 'def': 'a plastic card used to gain access typically to a door', 'name': 'keycard'}, {'frequency': 'c', 'synset': 'kilt.n.01', 'synonyms': ['kilt'], 'id': 607, 'def': 'a knee-length pleated tartan skirt worn by men as part of the traditional dress in the Highlands of northern Scotland', 'name': 'kilt'}, {'frequency': 'c', 'synset': 'kimono.n.01', 'synonyms': ['kimono'], 'id': 608, 'def': 'a loose robe; imitated from robes originally worn by Japanese', 'name': 'kimono'}, {'frequency': 'f', 'synset': 'kitchen_sink.n.01', 'synonyms': ['kitchen_sink'], 'id': 609, 'def': 'a sink in a kitchen', 'name': 'kitchen_sink'}, {'frequency': 'r', 'synset': 'kitchen_table.n.01', 'synonyms': ['kitchen_table'], 'id': 610, 'def': 'a table in the kitchen', 'name': 'kitchen_table'}, {'frequency': 'f', 'synset': 'kite.n.03', 'synonyms': ['kite'], 'id': 611, 'def': 'plaything consisting of a light frame covered with tissue paper; flown in wind at end of a string', 'name': 'kite'}, {'frequency': 'c', 'synset': 'kitten.n.01', 'synonyms': ['kitten', 'kitty'], 'id': 612, 'def': 'young domestic cat', 'name': 'kitten'}, {'frequency': 'c', 'synset': 'kiwi.n.03', 'synonyms': ['kiwi_fruit'], 'id': 613, 'def': 'fuzzy brown egg-shaped fruit with slightly tart green flesh', 'name': 'kiwi_fruit'}, {'frequency': 'f', 'synset': 'knee_pad.n.01', 'synonyms': ['knee_pad'], 'id': 614, 'def': 'protective garment consisting of a pad worn by football or baseball or hockey players', 'name': 'knee_pad'}, {'frequency': 'f', 'synset': 'knife.n.01', 'synonyms': ['knife'], 'id': 615, 'def': 'tool with a blade and point used as a cutting instrument', 'name': 'knife'}, {'frequency': 'r', 'synset': 'knitting_needle.n.01', 'synonyms': ['knitting_needle'], 'id': 616, 'def': 'needle consisting of a slender rod with pointed ends; usually used in pairs', 'name': 'knitting_needle'}, {'frequency': 'f', 'synset': 'knob.n.02', 'synonyms': ['knob'], 'id': 617, 'def': 'a round handle often found on a door', 'name': 'knob'}, {'frequency': 'r', 'synset': 'knocker.n.05', 'synonyms': ['knocker_(on_a_door)', 'doorknocker'], 'id': 618, 'def': 'a device (usually metal and ornamental) attached by a hinge to a door', 'name': 'knocker_(on_a_door)'}, {'frequency': 'r', 'synset': 'koala.n.01', 'synonyms': ['koala', 'koala_bear'], 'id': 619, 'def': 'sluggish tailless Australian marsupial with grey furry ears and coat', 'name': 'koala'}, {'frequency': 'r', 'synset': 'lab_coat.n.01', 'synonyms': ['lab_coat', 'laboratory_coat'], 'id': 620, 'def': 'a light coat worn to protect clothing from substances used while working in a laboratory', 'name': 'lab_coat'}, {'frequency': 'f', 'synset': 'ladder.n.01', 'synonyms': ['ladder'], 'id': 621, 'def': 'steps consisting of two parallel members connected by rungs', 'name': 'ladder'}, {'frequency': 'c', 'synset': 'ladle.n.01', 'synonyms': ['ladle'], 'id': 622, 'def': 'a spoon-shaped vessel with a long handle frequently used to transfer liquids', 'name': 'ladle'}, {'frequency': 'c', 'synset': 'ladybug.n.01', 'synonyms': ['ladybug', 'ladybeetle', 'ladybird_beetle'], 'id': 623, 'def': 'small round bright-colored and spotted beetle, typically red and black', 'name': 'ladybug'}, {'frequency': 'f', 'synset': 'lamb.n.01', 'synonyms': ['lamb_(animal)'], 'id': 624, 'def': 'young sheep', 'name': 'lamb_(animal)'}, {'frequency': 'r', 'synset': 'lamb_chop.n.01', 'synonyms': ['lamb-chop', 'lambchop'], 'id': 625, 'def': 'chop cut from a lamb', 'name': 'lamb-chop'}, {'frequency': 'f', 'synset': 'lamp.n.02', 'synonyms': ['lamp'], 'id': 626, 'def': 'a piece of furniture holding one or more electric light bulbs', 'name': 'lamp'}, {'frequency': 'f', 'synset': 'lamppost.n.01', 'synonyms': ['lamppost'], 'id': 627, 'def': 'a metal post supporting an outdoor lamp (such as a streetlight)', 'name': 'lamppost'}, {'frequency': 'f', 'synset': 'lampshade.n.01', 'synonyms': ['lampshade'], 'id': 628, 'def': 'a protective ornamental shade used to screen a light bulb from direct view', 'name': 'lampshade'}, {'frequency': 'c', 'synset': 'lantern.n.01', 'synonyms': ['lantern'], 'id': 629, 'def': 'light in a transparent protective case', 'name': 'lantern'}, {'frequency': 'f', 'synset': 'lanyard.n.02', 'synonyms': ['lanyard', 'laniard'], 'id': 630, 'def': 'a cord worn around the neck to hold a knife or whistle, etc.', 'name': 'lanyard'}, {'frequency': 'f', 'synset': 'laptop.n.01', 'synonyms': ['laptop_computer', 'notebook_computer'], 'id': 631, 'def': 'a portable computer small enough to use in your lap', 'name': 'laptop_computer'}, {'frequency': 'r', 'synset': 'lasagna.n.01', 'synonyms': ['lasagna', 'lasagne'], 'id': 632, 'def': 'baked dish of layers of lasagna pasta with sauce and cheese and meat or vegetables', 'name': 'lasagna'}, {'frequency': 'f', 'synset': 'latch.n.02', 'synonyms': ['latch'], 'id': 633, 'def': 'a bar that can be lowered or slid into a groove to fasten a door or gate', 'name': 'latch'}, {'frequency': 'r', 'synset': 'lawn_mower.n.01', 'synonyms': ['lawn_mower'], 'id': 634, 'def': 'garden tool for mowing grass on lawns', 'name': 'lawn_mower'}, {'frequency': 'r', 'synset': 'leather.n.01', 'synonyms': ['leather'], 'id': 635, 'def': 'an animal skin made smooth and flexible by removing the hair and then tanning', 'name': 'leather'}, {'frequency': 'c', 'synset': 'legging.n.01', 'synonyms': ['legging_(clothing)', 'leging_(clothing)', 'leg_covering'], 'id': 636, 'def': 'a garment covering the leg (usually extending from the knee to the ankle)', 'name': 'legging_(clothing)'}, {'frequency': 'c', 'synset': 'lego.n.01', 'synonyms': ['Lego', 'Lego_set'], 'id': 637, 'def': "a child's plastic construction set for making models from blocks", 'name': 'Lego'}, {'frequency': 'r', 'synset': 'legume.n.02', 'synonyms': ['legume'], 'id': 638, 'def': 'the fruit or seed of bean or pea plants', 'name': 'legume'}, {'frequency': 'f', 'synset': 'lemon.n.01', 'synonyms': ['lemon'], 'id': 639, 'def': 'yellow oval fruit with juicy acidic flesh', 'name': 'lemon'}, {'frequency': 'r', 'synset': 'lemonade.n.01', 'synonyms': ['lemonade'], 'id': 640, 'def': 'sweetened beverage of diluted lemon juice', 'name': 'lemonade'}, {'frequency': 'f', 'synset': 'lettuce.n.02', 'synonyms': ['lettuce'], 'id': 641, 'def': 'leafy plant commonly eaten in salad or on sandwiches', 'name': 'lettuce'}, {'frequency': 'f', 'synset': 'license_plate.n.01', 'synonyms': ['license_plate', 'numberplate'], 'id': 642, 'def': "a plate mounted on the front and back of car and bearing the car's registration number", 'name': 'license_plate'}, {'frequency': 'f', 'synset': 'life_buoy.n.01', 'synonyms': ['life_buoy', 'lifesaver', 'life_belt', 'life_ring'], 'id': 643, 'def': 'a ring-shaped life preserver used to prevent drowning (NOT a life-jacket or vest)', 'name': 'life_buoy'}, {'frequency': 'f', 'synset': 'life_jacket.n.01', 'synonyms': ['life_jacket', 'life_vest'], 'id': 644, 'def': 'life preserver consisting of a sleeveless jacket of buoyant or inflatable design', 'name': 'life_jacket'}, {'frequency': 'f', 'synset': 'light_bulb.n.01', 'synonyms': ['lightbulb'], 'id': 645, 'def': 'lightblub/source of light', 'name': 'lightbulb'}, {'frequency': 'r', 'synset': 'lightning_rod.n.02', 'synonyms': ['lightning_rod', 'lightning_conductor'], 'id': 646, 'def': 'a metallic conductor that is attached to a high point and leads to the ground', 'name': 'lightning_rod'}, {'frequency': 'f', 'synset': 'lime.n.06', 'synonyms': ['lime'], 'id': 647, 'def': 'the green acidic fruit of any of various lime trees', 'name': 'lime'}, {'frequency': 'r', 'synset': 'limousine.n.01', 'synonyms': ['limousine'], 'id': 648, 'def': 'long luxurious car; usually driven by a chauffeur', 'name': 'limousine'}, {'frequency': 'c', 'synset': 'lion.n.01', 'synonyms': ['lion'], 'id': 649, 'def': 'large gregarious predatory cat of Africa and India', 'name': 'lion'}, {'frequency': 'c', 'synset': 'lip_balm.n.01', 'synonyms': ['lip_balm'], 'id': 650, 'def': 'a balm applied to the lips', 'name': 'lip_balm'}, {'frequency': 'r', 'synset': 'liquor.n.01', 'synonyms': ['liquor', 'spirits', 'hard_liquor', 'liqueur', 'cordial'], 'id': 651, 'def': 'liquor or beer', 'name': 'liquor'}, {'frequency': 'c', 'synset': 'lizard.n.01', 'synonyms': ['lizard'], 'id': 652, 'def': 'a reptile with usually two pairs of legs and a tapering tail', 'name': 'lizard'}, {'frequency': 'f', 'synset': 'log.n.01', 'synonyms': ['log'], 'id': 653, 'def': 'a segment of the trunk of a tree when stripped of branches', 'name': 'log'}, {'frequency': 'c', 'synset': 'lollipop.n.02', 'synonyms': ['lollipop'], 'id': 654, 'def': 'hard candy on a stick', 'name': 'lollipop'}, {'frequency': 'f', 'synset': 'loudspeaker.n.01', 'synonyms': ['speaker_(stero_equipment)'], 'id': 655, 'def': 'electronic device that produces sound often as part of a stereo system', 'name': 'speaker_(stero_equipment)'}, {'frequency': 'c', 'synset': 'love_seat.n.01', 'synonyms': ['loveseat'], 'id': 656, 'def': 'small sofa that seats two people', 'name': 'loveseat'}, {'frequency': 'r', 'synset': 'machine_gun.n.01', 'synonyms': ['machine_gun'], 'id': 657, 'def': 'a rapidly firing automatic gun', 'name': 'machine_gun'}, {'frequency': 'f', 'synset': 'magazine.n.02', 'synonyms': ['magazine'], 'id': 658, 'def': 'a paperback periodic publication', 'name': 'magazine'}, {'frequency': 'f', 'synset': 'magnet.n.01', 'synonyms': ['magnet'], 'id': 659, 'def': 'a device that attracts iron and produces a magnetic field', 'name': 'magnet'}, {'frequency': 'c', 'synset': 'mail_slot.n.01', 'synonyms': ['mail_slot'], 'id': 660, 'def': 'a slot (usually in a door) through which mail can be delivered', 'name': 'mail_slot'}, {'frequency': 'f', 'synset': 'mailbox.n.01', 'synonyms': ['mailbox_(at_home)', 'letter_box_(at_home)'], 'id': 661, 'def': 'a private box for delivery of mail', 'name': 'mailbox_(at_home)'}, {'frequency': 'r', 'synset': 'mallard.n.01', 'synonyms': ['mallard'], 'id': 662, 'def': 'wild dabbling duck from which domestic ducks are descended', 'name': 'mallard'}, {'frequency': 'r', 'synset': 'mallet.n.01', 'synonyms': ['mallet'], 'id': 663, 'def': 'a sports implement with a long handle and a hammer-like head used to hit a ball', 'name': 'mallet'}, {'frequency': 'r', 'synset': 'mammoth.n.01', 'synonyms': ['mammoth'], 'id': 664, 'def': 'any of numerous extinct elephants widely distributed in the Pleistocene', 'name': 'mammoth'}, {'frequency': 'r', 'synset': 'manatee.n.01', 'synonyms': ['manatee'], 'id': 665, 'def': 'sirenian mammal of tropical coastal waters of America', 'name': 'manatee'}, {'frequency': 'c', 'synset': 'mandarin.n.05', 'synonyms': ['mandarin_orange'], 'id': 666, 'def': 'a somewhat flat reddish-orange loose skinned citrus of China', 'name': 'mandarin_orange'}, {'frequency': 'c', 'synset': 'manger.n.01', 'synonyms': ['manger', 'trough'], 'id': 667, 'def': 'a container (usually in a barn or stable) from which cattle or horses feed', 'name': 'manger'}, {'frequency': 'f', 'synset': 'manhole.n.01', 'synonyms': ['manhole'], 'id': 668, 'def': 'a hole (usually with a flush cover) through which a person can gain access to an underground structure', 'name': 'manhole'}, {'frequency': 'f', 'synset': 'map.n.01', 'synonyms': ['map'], 'id': 669, 'def': "a diagrammatic representation of the earth's surface (or part of it)", 'name': 'map'}, {'frequency': 'f', 'synset': 'marker.n.03', 'synonyms': ['marker'], 'id': 670, 'def': 'a writing implement for making a mark', 'name': 'marker'}, {'frequency': 'r', 'synset': 'martini.n.01', 'synonyms': ['martini'], 'id': 671, 'def': 'a cocktail made of gin (or vodka) with dry vermouth', 'name': 'martini'}, {'frequency': 'r', 'synset': 'mascot.n.01', 'synonyms': ['mascot'], 'id': 672, 'def': 'a person or animal that is adopted by a team or other group as a symbolic figure', 'name': 'mascot'}, {'frequency': 'c', 'synset': 'mashed_potato.n.01', 'synonyms': ['mashed_potato'], 'id': 673, 'def': 'potato that has been peeled and boiled and then mashed', 'name': 'mashed_potato'}, {'frequency': 'r', 'synset': 'masher.n.02', 'synonyms': ['masher'], 'id': 674, 'def': 'a kitchen utensil used for mashing (e.g. potatoes)', 'name': 'masher'}, {'frequency': 'f', 'synset': 'mask.n.04', 'synonyms': ['mask', 'facemask'], 'id': 675, 'def': 'a protective covering worn over the face', 'name': 'mask'}, {'frequency': 'f', 'synset': 'mast.n.01', 'synonyms': ['mast'], 'id': 676, 'def': 'a vertical spar for supporting sails', 'name': 'mast'}, {'frequency': 'c', 'synset': 'mat.n.03', 'synonyms': ['mat_(gym_equipment)', 'gym_mat'], 'id': 677, 'def': 'sports equipment consisting of a piece of thick padding on the floor for gymnastics', 'name': 'mat_(gym_equipment)'}, {'frequency': 'r', 'synset': 'matchbox.n.01', 'synonyms': ['matchbox'], 'id': 678, 'def': 'a box for holding matches', 'name': 'matchbox'}, {'frequency': 'f', 'synset': 'mattress.n.01', 'synonyms': ['mattress'], 'id': 679, 'def': 'a thick pad filled with resilient material used as a bed or part of a bed', 'name': 'mattress'}, {'frequency': 'c', 'synset': 'measuring_cup.n.01', 'synonyms': ['measuring_cup'], 'id': 680, 'def': 'graduated cup used to measure liquid or granular ingredients', 'name': 'measuring_cup'}, {'frequency': 'c', 'synset': 'measuring_stick.n.01', 'synonyms': ['measuring_stick', 'ruler_(measuring_stick)', 'measuring_rod'], 'id': 681, 'def': 'measuring instrument having a sequence of marks at regular intervals', 'name': 'measuring_stick'}, {'frequency': 'c', 'synset': 'meatball.n.01', 'synonyms': ['meatball'], 'id': 682, 'def': 'ground meat formed into a ball and fried or simmered in broth', 'name': 'meatball'}, {'frequency': 'c', 'synset': 'medicine.n.02', 'synonyms': ['medicine'], 'id': 683, 'def': 'something that treats or prevents or alleviates the symptoms of disease', 'name': 'medicine'}, {'frequency': 'c', 'synset': 'melon.n.01', 'synonyms': ['melon'], 'id': 684, 'def': 'fruit of the gourd family having a hard rind and sweet juicy flesh', 'name': 'melon'}, {'frequency': 'f', 'synset': 'microphone.n.01', 'synonyms': ['microphone'], 'id': 685, 'def': 'device for converting sound waves into electrical energy', 'name': 'microphone'}, {'frequency': 'r', 'synset': 'microscope.n.01', 'synonyms': ['microscope'], 'id': 686, 'def': 'magnifier of the image of small objects', 'name': 'microscope'}, {'frequency': 'f', 'synset': 'microwave.n.02', 'synonyms': ['microwave_oven'], 'id': 687, 'def': 'kitchen appliance that cooks food by passing an electromagnetic wave through it', 'name': 'microwave_oven'}, {'frequency': 'r', 'synset': 'milestone.n.01', 'synonyms': ['milestone', 'milepost'], 'id': 688, 'def': 'stone post at side of a road to show distances', 'name': 'milestone'}, {'frequency': 'f', 'synset': 'milk.n.01', 'synonyms': ['milk'], 'id': 689, 'def': 'a white nutritious liquid secreted by mammals and used as food by human beings', 'name': 'milk'}, {'frequency': 'r', 'synset': 'milk_can.n.01', 'synonyms': ['milk_can'], 'id': 690, 'def': 'can for transporting milk', 'name': 'milk_can'}, {'frequency': 'r', 'synset': 'milkshake.n.01', 'synonyms': ['milkshake'], 'id': 691, 'def': 'frothy drink of milk and flavoring and sometimes fruit or ice cream', 'name': 'milkshake'}, {'frequency': 'f', 'synset': 'minivan.n.01', 'synonyms': ['minivan'], 'id': 692, 'def': 'a small box-shaped passenger van', 'name': 'minivan'}, {'frequency': 'r', 'synset': 'mint.n.05', 'synonyms': ['mint_candy'], 'id': 693, 'def': 'a candy that is flavored with a mint oil', 'name': 'mint_candy'}, {'frequency': 'f', 'synset': 'mirror.n.01', 'synonyms': ['mirror'], 'id': 694, 'def': 'polished surface that forms images by reflecting light', 'name': 'mirror'}, {'frequency': 'c', 'synset': 'mitten.n.01', 'synonyms': ['mitten'], 'id': 695, 'def': 'glove that encases the thumb separately and the other four fingers together', 'name': 'mitten'}, {'frequency': 'c', 'synset': 'mixer.n.04', 'synonyms': ['mixer_(kitchen_tool)', 'stand_mixer'], 'id': 696, 'def': 'a kitchen utensil that is used for mixing foods', 'name': 'mixer_(kitchen_tool)'}, {'frequency': 'c', 'synset': 'money.n.03', 'synonyms': ['money'], 'id': 697, 'def': 'the official currency issued by a government or national bank', 'name': 'money'}, {'frequency': 'f', 'synset': 'monitor.n.04', 'synonyms': ['monitor_(computer_equipment) computer_monitor'], 'id': 698, 'def': 'a computer monitor', 'name': 'monitor_(computer_equipment) computer_monitor'}, {'frequency': 'c', 'synset': 'monkey.n.01', 'synonyms': ['monkey'], 'id': 699, 'def': 'any of various long-tailed primates', 'name': 'monkey'}, {'frequency': 'f', 'synset': 'motor.n.01', 'synonyms': ['motor'], 'id': 700, 'def': 'machine that converts other forms of energy into mechanical energy and so imparts motion', 'name': 'motor'}, {'frequency': 'f', 'synset': 'motor_scooter.n.01', 'synonyms': ['motor_scooter', 'scooter'], 'id': 701, 'def': 'a wheeled vehicle with small wheels and a low-powered engine', 'name': 'motor_scooter'}, {'frequency': 'r', 'synset': 'motor_vehicle.n.01', 'synonyms': ['motor_vehicle', 'automotive_vehicle'], 'id': 702, 'def': 'a self-propelled wheeled vehicle that does not run on rails', 'name': 'motor_vehicle'}, {'frequency': 'f', 'synset': 'motorcycle.n.01', 'synonyms': ['motorcycle'], 'id': 703, 'def': 'a motor vehicle with two wheels and a strong frame', 'name': 'motorcycle'}, {'frequency': 'f', 'synset': 'mound.n.01', 'synonyms': ['mound_(baseball)', "pitcher's_mound"], 'id': 704, 'def': '(baseball) the slight elevation on which the pitcher stands', 'name': 'mound_(baseball)'}, {'frequency': 'f', 'synset': 'mouse.n.04', 'synonyms': ['mouse_(computer_equipment)', 'computer_mouse'], 'id': 705, 'def': 'a computer input device that controls an on-screen pointer (does not include trackpads / touchpads)', 'name': 'mouse_(computer_equipment)'}, {'frequency': 'f', 'synset': 'mousepad.n.01', 'synonyms': ['mousepad'], 'id': 706, 'def': 'a small portable pad that provides an operating surface for a computer mouse', 'name': 'mousepad'}, {'frequency': 'c', 'synset': 'muffin.n.01', 'synonyms': ['muffin'], 'id': 707, 'def': 'a sweet quick bread baked in a cup-shaped pan', 'name': 'muffin'}, {'frequency': 'f', 'synset': 'mug.n.04', 'synonyms': ['mug'], 'id': 708, 'def': 'with handle and usually cylindrical', 'name': 'mug'}, {'frequency': 'f', 'synset': 'mushroom.n.02', 'synonyms': ['mushroom'], 'id': 709, 'def': 'a common mushroom', 'name': 'mushroom'}, {'frequency': 'r', 'synset': 'music_stool.n.01', 'synonyms': ['music_stool', 'piano_stool'], 'id': 710, 'def': 'a stool for piano players; usually adjustable in height', 'name': 'music_stool'}, {'frequency': 'c', 'synset': 'musical_instrument.n.01', 'synonyms': ['musical_instrument', 'instrument_(musical)'], 'id': 711, 'def': 'any of various devices or contrivances that can be used to produce musical tones or sounds', 'name': 'musical_instrument'}, {'frequency': 'r', 'synset': 'nailfile.n.01', 'synonyms': ['nailfile'], 'id': 712, 'def': 'a small flat file for shaping the nails', 'name': 'nailfile'}, {'frequency': 'f', 'synset': 'napkin.n.01', 'synonyms': ['napkin', 'table_napkin', 'serviette'], 'id': 713, 'def': 'a small piece of table linen or paper that is used to wipe the mouth and to cover the lap in order to protect clothing', 'name': 'napkin'}, {'frequency': 'r', 'synset': 'neckerchief.n.01', 'synonyms': ['neckerchief'], 'id': 714, 'def': 'a kerchief worn around the neck', 'name': 'neckerchief'}, {'frequency': 'f', 'synset': 'necklace.n.01', 'synonyms': ['necklace'], 'id': 715, 'def': 'jewelry consisting of a cord or chain (often bearing gems) worn about the neck as an ornament', 'name': 'necklace'}, {'frequency': 'f', 'synset': 'necktie.n.01', 'synonyms': ['necktie', 'tie_(necktie)'], 'id': 716, 'def': 'neckwear consisting of a long narrow piece of material worn under a collar and tied in knot at the front', 'name': 'necktie'}, {'frequency': 'c', 'synset': 'needle.n.03', 'synonyms': ['needle'], 'id': 717, 'def': 'a sharp pointed implement (usually metal)', 'name': 'needle'}, {'frequency': 'c', 'synset': 'nest.n.01', 'synonyms': ['nest'], 'id': 718, 'def': 'a structure in which animals lay eggs or give birth to their young', 'name': 'nest'}, {'frequency': 'f', 'synset': 'newspaper.n.01', 'synonyms': ['newspaper', 'paper_(newspaper)'], 'id': 719, 'def': 'a daily or weekly publication on folded sheets containing news, articles, and advertisements', 'name': 'newspaper'}, {'frequency': 'c', 'synset': 'newsstand.n.01', 'synonyms': ['newsstand'], 'id': 720, 'def': 'a stall where newspapers and other periodicals are sold', 'name': 'newsstand'}, {'frequency': 'c', 'synset': 'nightwear.n.01', 'synonyms': ['nightshirt', 'nightwear', 'sleepwear', 'nightclothes'], 'id': 721, 'def': 'garments designed to be worn in bed', 'name': 'nightshirt'}, {'frequency': 'r', 'synset': 'nosebag.n.01', 'synonyms': ['nosebag_(for_animals)', 'feedbag'], 'id': 722, 'def': 'a canvas bag that is used to feed an animal (such as a horse); covers the muzzle and fastens at the top of the head', 'name': 'nosebag_(for_animals)'}, {'frequency': 'c', 'synset': 'noseband.n.01', 'synonyms': ['noseband_(for_animals)', 'nosepiece_(for_animals)'], 'id': 723, 'def': "a strap that is the part of a bridle that goes over the animal's nose", 'name': 'noseband_(for_animals)'}, {'frequency': 'f', 'synset': 'notebook.n.01', 'synonyms': ['notebook'], 'id': 724, 'def': 'a book with blank pages for recording notes or memoranda', 'name': 'notebook'}, {'frequency': 'c', 'synset': 'notepad.n.01', 'synonyms': ['notepad'], 'id': 725, 'def': 'a pad of paper for keeping notes', 'name': 'notepad'}, {'frequency': 'f', 'synset': 'nut.n.03', 'synonyms': ['nut'], 'id': 726, 'def': 'a small metal block (usually square or hexagonal) with internal screw thread to be fitted onto a bolt', 'name': 'nut'}, {'frequency': 'r', 'synset': 'nutcracker.n.01', 'synonyms': ['nutcracker'], 'id': 727, 'def': 'a hand tool used to crack nuts open', 'name': 'nutcracker'}, {'frequency': 'f', 'synset': 'oar.n.01', 'synonyms': ['oar'], 'id': 728, 'def': 'an implement used to propel or steer a boat', 'name': 'oar'}, {'frequency': 'r', 'synset': 'octopus.n.01', 'synonyms': ['octopus_(food)'], 'id': 729, 'def': 'tentacles of octopus prepared as food', 'name': 'octopus_(food)'}, {'frequency': 'r', 'synset': 'octopus.n.02', 'synonyms': ['octopus_(animal)'], 'id': 730, 'def': 'bottom-living cephalopod having a soft oval body with eight long tentacles', 'name': 'octopus_(animal)'}, {'frequency': 'c', 'synset': 'oil_lamp.n.01', 'synonyms': ['oil_lamp', 'kerosene_lamp', 'kerosine_lamp'], 'id': 731, 'def': 'a lamp that burns oil (as kerosine) for light', 'name': 'oil_lamp'}, {'frequency': 'c', 'synset': 'olive_oil.n.01', 'synonyms': ['olive_oil'], 'id': 732, 'def': 'oil from olives', 'name': 'olive_oil'}, {'frequency': 'r', 'synset': 'omelet.n.01', 'synonyms': ['omelet', 'omelette'], 'id': 733, 'def': 'beaten eggs cooked until just set; may be folded around e.g. ham or cheese or jelly', 'name': 'omelet'}, {'frequency': 'f', 'synset': 'onion.n.01', 'synonyms': ['onion'], 'id': 734, 'def': 'the bulb of an onion plant', 'name': 'onion'}, {'frequency': 'f', 'synset': 'orange.n.01', 'synonyms': ['orange_(fruit)'], 'id': 735, 'def': 'orange (FRUIT of an orange tree)', 'name': 'orange_(fruit)'}, {'frequency': 'c', 'synset': 'orange_juice.n.01', 'synonyms': ['orange_juice'], 'id': 736, 'def': 'bottled or freshly squeezed juice of oranges', 'name': 'orange_juice'}, {'frequency': 'c', 'synset': 'ostrich.n.02', 'synonyms': ['ostrich'], 'id': 737, 'def': 'fast-running African flightless bird with two-toed feet; largest living bird', 'name': 'ostrich'}, {'frequency': 'f', 'synset': 'ottoman.n.03', 'synonyms': ['ottoman', 'pouf', 'pouffe', 'hassock'], 'id': 738, 'def': 'a thick standalone cushion used as a seat or footrest, often next to a chair', 'name': 'ottoman'}, {'frequency': 'f', 'synset': 'oven.n.01', 'synonyms': ['oven'], 'id': 739, 'def': 'kitchen appliance used for baking or roasting', 'name': 'oven'}, {'frequency': 'c', 'synset': 'overall.n.01', 'synonyms': ['overalls_(clothing)'], 'id': 740, 'def': 'work clothing consisting of denim trousers usually with a bib and shoulder straps', 'name': 'overalls_(clothing)'}, {'frequency': 'c', 'synset': 'owl.n.01', 'synonyms': ['owl'], 'id': 741, 'def': 'nocturnal bird of prey with hawk-like beak and claws and large head with front-facing eyes', 'name': 'owl'}, {'frequency': 'c', 'synset': 'packet.n.03', 'synonyms': ['packet'], 'id': 742, 'def': 'a small package or bundle', 'name': 'packet'}, {'frequency': 'r', 'synset': 'pad.n.03', 'synonyms': ['inkpad', 'inking_pad', 'stamp_pad'], 'id': 743, 'def': 'absorbent material saturated with ink used to transfer ink evenly to a rubber stamp', 'name': 'inkpad'}, {'frequency': 'c', 'synset': 'pad.n.04', 'synonyms': ['pad'], 'id': 744, 'def': 'mostly arm/knee pads labeled', 'name': 'pad'}, {'frequency': 'f', 'synset': 'paddle.n.04', 'synonyms': ['paddle', 'boat_paddle'], 'id': 745, 'def': 'a short light oar used without an oarlock to propel a canoe or small boat', 'name': 'paddle'}, {'frequency': 'c', 'synset': 'padlock.n.01', 'synonyms': ['padlock'], 'id': 746, 'def': 'a detachable, portable lock', 'name': 'padlock'}, {'frequency': 'c', 'synset': 'paintbrush.n.01', 'synonyms': ['paintbrush'], 'id': 747, 'def': 'a brush used as an applicator to apply paint', 'name': 'paintbrush'}, {'frequency': 'f', 'synset': 'painting.n.01', 'synonyms': ['painting'], 'id': 748, 'def': 'graphic art consisting of an artistic composition made by applying paints to a surface', 'name': 'painting'}, {'frequency': 'f', 'synset': 'pajama.n.02', 'synonyms': ['pajamas', 'pyjamas'], 'id': 749, 'def': 'loose-fitting nightclothes worn for sleeping or lounging', 'name': 'pajamas'}, {'frequency': 'c', 'synset': 'palette.n.02', 'synonyms': ['palette', 'pallet'], 'id': 750, 'def': 'board that provides a flat surface on which artists mix paints and the range of colors used', 'name': 'palette'}, {'frequency': 'f', 'synset': 'pan.n.01', 'synonyms': ['pan_(for_cooking)', 'cooking_pan'], 'id': 751, 'def': 'cooking utensil consisting of a wide metal vessel', 'name': 'pan_(for_cooking)'}, {'frequency': 'r', 'synset': 'pan.n.03', 'synonyms': ['pan_(metal_container)'], 'id': 752, 'def': 'shallow container made of metal', 'name': 'pan_(metal_container)'}, {'frequency': 'c', 'synset': 'pancake.n.01', 'synonyms': ['pancake'], 'id': 753, 'def': 'a flat cake of thin batter fried on both sides on a griddle', 'name': 'pancake'}, {'frequency': 'r', 'synset': 'pantyhose.n.01', 'synonyms': ['pantyhose'], 'id': 754, 'def': "a woman's tights consisting of underpants and stockings", 'name': 'pantyhose'}, {'frequency': 'r', 'synset': 'papaya.n.02', 'synonyms': ['papaya'], 'id': 755, 'def': 'large oval melon-like tropical fruit with yellowish flesh', 'name': 'papaya'}, {'frequency': 'f', 'synset': 'paper_plate.n.01', 'synonyms': ['paper_plate'], 'id': 756, 'def': 'a disposable plate made of cardboard', 'name': 'paper_plate'}, {'frequency': 'f', 'synset': 'paper_towel.n.01', 'synonyms': ['paper_towel'], 'id': 757, 'def': 'a disposable towel made of absorbent paper', 'name': 'paper_towel'}, {'frequency': 'r', 'synset': 'paperback_book.n.01', 'synonyms': ['paperback_book', 'paper-back_book', 'softback_book', 'soft-cover_book'], 'id': 758, 'def': 'a book with paper covers', 'name': 'paperback_book'}, {'frequency': 'r', 'synset': 'paperweight.n.01', 'synonyms': ['paperweight'], 'id': 759, 'def': 'a weight used to hold down a stack of papers', 'name': 'paperweight'}, {'frequency': 'c', 'synset': 'parachute.n.01', 'synonyms': ['parachute'], 'id': 760, 'def': 'rescue equipment consisting of a device that fills with air and retards your fall', 'name': 'parachute'}, {'frequency': 'c', 'synset': 'parakeet.n.01', 'synonyms': ['parakeet', 'parrakeet', 'parroket', 'paraquet', 'paroquet', 'parroquet'], 'id': 761, 'def': 'any of numerous small slender long-tailed parrots', 'name': 'parakeet'}, {'frequency': 'c', 'synset': 'parasail.n.01', 'synonyms': ['parasail_(sports)'], 'id': 762, 'def': 'parachute that will lift a person up into the air when it is towed by a motorboat or a car', 'name': 'parasail_(sports)'}, {'frequency': 'c', 'synset': 'parasol.n.01', 'synonyms': ['parasol', 'sunshade'], 'id': 763, 'def': 'a handheld collapsible source of shade', 'name': 'parasol'}, {'frequency': 'r', 'synset': 'parchment.n.01', 'synonyms': ['parchment'], 'id': 764, 'def': 'a superior paper resembling sheepskin', 'name': 'parchment'}, {'frequency': 'c', 'synset': 'parka.n.01', 'synonyms': ['parka', 'anorak'], 'id': 765, 'def': "a kind of heavy jacket (`windcheater' is a British term)", 'name': 'parka'}, {'frequency': 'f', 'synset': 'parking_meter.n.01', 'synonyms': ['parking_meter'], 'id': 766, 'def': 'a coin-operated timer located next to a parking space', 'name': 'parking_meter'}, {'frequency': 'c', 'synset': 'parrot.n.01', 'synonyms': ['parrot'], 'id': 767, 'def': 'usually brightly colored tropical birds with short hooked beaks and the ability to mimic sounds', 'name': 'parrot'}, {'frequency': 'c', 'synset': 'passenger_car.n.01', 'synonyms': ['passenger_car_(part_of_a_train)', 'coach_(part_of_a_train)'], 'id': 768, 'def': 'a railcar where passengers ride', 'name': 'passenger_car_(part_of_a_train)'}, {'frequency': 'r', 'synset': 'passenger_ship.n.01', 'synonyms': ['passenger_ship'], 'id': 769, 'def': 'a ship built to carry passengers', 'name': 'passenger_ship'}, {'frequency': 'c', 'synset': 'passport.n.02', 'synonyms': ['passport'], 'id': 770, 'def': 'a document issued by a country to a citizen allowing that person to travel abroad and re-enter the home country', 'name': 'passport'}, {'frequency': 'f', 'synset': 'pastry.n.02', 'synonyms': ['pastry'], 'id': 771, 'def': 'any of various baked foods made of dough or batter', 'name': 'pastry'}, {'frequency': 'r', 'synset': 'patty.n.01', 'synonyms': ['patty_(food)'], 'id': 772, 'def': 'small flat mass of chopped food', 'name': 'patty_(food)'}, {'frequency': 'c', 'synset': 'pea.n.01', 'synonyms': ['pea_(food)'], 'id': 773, 'def': 'seed of a pea plant used for food', 'name': 'pea_(food)'}, {'frequency': 'c', 'synset': 'peach.n.03', 'synonyms': ['peach'], 'id': 774, 'def': 'downy juicy fruit with sweet yellowish or whitish flesh', 'name': 'peach'}, {'frequency': 'c', 'synset': 'peanut_butter.n.01', 'synonyms': ['peanut_butter'], 'id': 775, 'def': 'a spread made from ground peanuts', 'name': 'peanut_butter'}, {'frequency': 'f', 'synset': 'pear.n.01', 'synonyms': ['pear'], 'id': 776, 'def': 'sweet juicy gritty-textured fruit available in many varieties', 'name': 'pear'}, {'frequency': 'c', 'synset': 'peeler.n.03', 'synonyms': ['peeler_(tool_for_fruit_and_vegetables)'], 'id': 777, 'def': 'a device for peeling vegetables or fruits', 'name': 'peeler_(tool_for_fruit_and_vegetables)'}, {'frequency': 'r', 'synset': 'peg.n.04', 'synonyms': ['wooden_leg', 'pegleg'], 'id': 778, 'def': 'a prosthesis that replaces a missing leg', 'name': 'wooden_leg'}, {'frequency': 'r', 'synset': 'pegboard.n.01', 'synonyms': ['pegboard'], 'id': 779, 'def': 'a board perforated with regularly spaced holes into which pegs can be fitted', 'name': 'pegboard'}, {'frequency': 'c', 'synset': 'pelican.n.01', 'synonyms': ['pelican'], 'id': 780, 'def': 'large long-winged warm-water seabird having a large bill with a distensible pouch for fish', 'name': 'pelican'}, {'frequency': 'f', 'synset': 'pen.n.01', 'synonyms': ['pen'], 'id': 781, 'def': 'a writing implement with a point from which ink flows', 'name': 'pen'}, {'frequency': 'f', 'synset': 'pencil.n.01', 'synonyms': ['pencil'], 'id': 782, 'def': 'a thin cylindrical pointed writing implement made of wood and graphite', 'name': 'pencil'}, {'frequency': 'r', 'synset': 'pencil_box.n.01', 'synonyms': ['pencil_box', 'pencil_case'], 'id': 783, 'def': 'a box for holding pencils', 'name': 'pencil_box'}, {'frequency': 'r', 'synset': 'pencil_sharpener.n.01', 'synonyms': ['pencil_sharpener'], 'id': 784, 'def': 'a rotary implement for sharpening the point on pencils', 'name': 'pencil_sharpener'}, {'frequency': 'r', 'synset': 'pendulum.n.01', 'synonyms': ['pendulum'], 'id': 785, 'def': 'an apparatus consisting of an object mounted so that it swings freely under the influence of gravity', 'name': 'pendulum'}, {'frequency': 'c', 'synset': 'penguin.n.01', 'synonyms': ['penguin'], 'id': 786, 'def': 'short-legged flightless birds of cold southern regions having webbed feet and wings modified as flippers', 'name': 'penguin'}, {'frequency': 'r', 'synset': 'pennant.n.02', 'synonyms': ['pennant'], 'id': 787, 'def': 'a flag longer than it is wide (and often tapering)', 'name': 'pennant'}, {'frequency': 'r', 'synset': 'penny.n.02', 'synonyms': ['penny_(coin)'], 'id': 788, 'def': 'a coin worth one-hundredth of the value of the basic unit', 'name': 'penny_(coin)'}, {'frequency': 'f', 'synset': 'pepper.n.03', 'synonyms': ['pepper', 'peppercorn'], 'id': 789, 'def': 'pungent seasoning from the berry of the common pepper plant; whole or ground', 'name': 'pepper'}, {'frequency': 'c', 'synset': 'pepper_mill.n.01', 'synonyms': ['pepper_mill', 'pepper_grinder'], 'id': 790, 'def': 'a mill for grinding pepper', 'name': 'pepper_mill'}, {'frequency': 'c', 'synset': 'perfume.n.02', 'synonyms': ['perfume'], 'id': 791, 'def': 'a toiletry that emits and diffuses a fragrant odor', 'name': 'perfume'}, {'frequency': 'r', 'synset': 'persimmon.n.02', 'synonyms': ['persimmon'], 'id': 792, 'def': 'orange fruit resembling a plum; edible when fully ripe', 'name': 'persimmon'}, {'frequency': 'f', 'synset': 'person.n.01', 'synonyms': ['person', 'baby', 'child', 'boy', 'girl', 'man', 'woman', 'human'], 'id': 793, 'def': 'a human being', 'name': 'person'}, {'frequency': 'c', 'synset': 'pet.n.01', 'synonyms': ['pet'], 'id': 794, 'def': 'a domesticated animal kept for companionship or amusement', 'name': 'pet'}, {'frequency': 'c', 'synset': 'pew.n.01', 'synonyms': ['pew_(church_bench)', 'church_bench'], 'id': 795, 'def': 'long bench with backs; used in church by the congregation', 'name': 'pew_(church_bench)'}, {'frequency': 'r', 'synset': 'phonebook.n.01', 'synonyms': ['phonebook', 'telephone_book', 'telephone_directory'], 'id': 796, 'def': 'a directory containing an alphabetical list of telephone subscribers and their telephone numbers', 'name': 'phonebook'}, {'frequency': 'c', 'synset': 'phonograph_record.n.01', 'synonyms': ['phonograph_record', 'phonograph_recording', 'record_(phonograph_recording)'], 'id': 797, 'def': 'sound recording consisting of a typically black disk with a continuous groove', 'name': 'phonograph_record'}, {'frequency': 'f', 'synset': 'piano.n.01', 'synonyms': ['piano'], 'id': 798, 'def': 'a keyboard instrument that is played by depressing keys that cause hammers to strike tuned strings and produce sounds', 'name': 'piano'}, {'frequency': 'f', 'synset': 'pickle.n.01', 'synonyms': ['pickle'], 'id': 799, 'def': 'vegetables (especially cucumbers) preserved in brine or vinegar', 'name': 'pickle'}, {'frequency': 'f', 'synset': 'pickup.n.01', 'synonyms': ['pickup_truck'], 'id': 800, 'def': 'a light truck with an open body and low sides and a tailboard', 'name': 'pickup_truck'}, {'frequency': 'c', 'synset': 'pie.n.01', 'synonyms': ['pie'], 'id': 801, 'def': 'dish baked in pastry-lined pan often with a pastry top', 'name': 'pie'}, {'frequency': 'c', 'synset': 'pigeon.n.01', 'synonyms': ['pigeon'], 'id': 802, 'def': 'wild and domesticated birds having a heavy body and short legs', 'name': 'pigeon'}, {'frequency': 'r', 'synset': 'piggy_bank.n.01', 'synonyms': ['piggy_bank', 'penny_bank'], 'id': 803, 'def': "a child's coin bank (often shaped like a pig)", 'name': 'piggy_bank'}, {'frequency': 'f', 'synset': 'pillow.n.01', 'synonyms': ['pillow'], 'id': 804, 'def': 'a cushion to support the head of a sleeping person', 'name': 'pillow'}, {'frequency': 'r', 'synset': 'pin.n.09', 'synonyms': ['pin_(non_jewelry)'], 'id': 805, 'def': 'a small slender (often pointed) piece of wood or metal used to support or fasten or attach things', 'name': 'pin_(non_jewelry)'}, {'frequency': 'f', 'synset': 'pineapple.n.02', 'synonyms': ['pineapple'], 'id': 806, 'def': 'large sweet fleshy tropical fruit with a tuft of stiff leaves', 'name': 'pineapple'}, {'frequency': 'c', 'synset': 'pinecone.n.01', 'synonyms': ['pinecone'], 'id': 807, 'def': 'the seed-producing cone of a pine tree', 'name': 'pinecone'}, {'frequency': 'r', 'synset': 'ping-pong_ball.n.01', 'synonyms': ['ping-pong_ball'], 'id': 808, 'def': 'light hollow ball used in playing table tennis', 'name': 'ping-pong_ball'}, {'frequency': 'r', 'synset': 'pinwheel.n.03', 'synonyms': ['pinwheel'], 'id': 809, 'def': 'a toy consisting of vanes of colored paper or plastic that is pinned to a stick and spins when it is pointed into the wind', 'name': 'pinwheel'}, {'frequency': 'r', 'synset': 'pipe.n.01', 'synonyms': ['tobacco_pipe'], 'id': 810, 'def': 'a tube with a small bowl at one end; used for smoking tobacco', 'name': 'tobacco_pipe'}, {'frequency': 'f', 'synset': 'pipe.n.02', 'synonyms': ['pipe', 'piping'], 'id': 811, 'def': 'a long tube made of metal or plastic that is used to carry water or oil or gas etc.', 'name': 'pipe'}, {'frequency': 'r', 'synset': 'pistol.n.01', 'synonyms': ['pistol', 'handgun'], 'id': 812, 'def': 'a firearm that is held and fired with one hand', 'name': 'pistol'}, {'frequency': 'c', 'synset': 'pita.n.01', 'synonyms': ['pita_(bread)', 'pocket_bread'], 'id': 813, 'def': 'usually small round bread that can open into a pocket for filling', 'name': 'pita_(bread)'}, {'frequency': 'f', 'synset': 'pitcher.n.02', 'synonyms': ['pitcher_(vessel_for_liquid)', 'ewer'], 'id': 814, 'def': 'an open vessel with a handle and a spout for pouring', 'name': 'pitcher_(vessel_for_liquid)'}, {'frequency': 'r', 'synset': 'pitchfork.n.01', 'synonyms': ['pitchfork'], 'id': 815, 'def': 'a long-handled hand tool with sharp widely spaced prongs for lifting and pitching hay', 'name': 'pitchfork'}, {'frequency': 'f', 'synset': 'pizza.n.01', 'synonyms': ['pizza'], 'id': 816, 'def': 'Italian open pie made of thin bread dough spread with a spiced mixture of e.g. tomato sauce and cheese', 'name': 'pizza'}, {'frequency': 'f', 'synset': 'place_mat.n.01', 'synonyms': ['place_mat'], 'id': 817, 'def': 'a mat placed on a table for an individual place setting', 'name': 'place_mat'}, {'frequency': 'f', 'synset': 'plate.n.04', 'synonyms': ['plate'], 'id': 818, 'def': 'dish on which food is served or from which food is eaten', 'name': 'plate'}, {'frequency': 'c', 'synset': 'platter.n.01', 'synonyms': ['platter'], 'id': 819, 'def': 'a large shallow dish used for serving food', 'name': 'platter'}, {'frequency': 'r', 'synset': 'playpen.n.01', 'synonyms': ['playpen'], 'id': 820, 'def': 'a portable enclosure in which babies may be left to play', 'name': 'playpen'}, {'frequency': 'c', 'synset': 'pliers.n.01', 'synonyms': ['pliers', 'plyers'], 'id': 821, 'def': 'a gripping hand tool with two hinged arms and (usually) serrated jaws', 'name': 'pliers'}, {'frequency': 'r', 'synset': 'plow.n.01', 'synonyms': ['plow_(farm_equipment)', 'plough_(farm_equipment)'], 'id': 822, 'def': 'a farm tool having one or more heavy blades to break the soil and cut a furrow prior to sowing', 'name': 'plow_(farm_equipment)'}, {'frequency': 'r', 'synset': 'plume.n.02', 'synonyms': ['plume'], 'id': 823, 'def': 'a feather or cluster of feathers worn as an ornament', 'name': 'plume'}, {'frequency': 'r', 'synset': 'pocket_watch.n.01', 'synonyms': ['pocket_watch'], 'id': 824, 'def': 'a watch that is carried in a small watch pocket', 'name': 'pocket_watch'}, {'frequency': 'c', 'synset': 'pocketknife.n.01', 'synonyms': ['pocketknife'], 'id': 825, 'def': 'a knife with a blade that folds into the handle; suitable for carrying in the pocket', 'name': 'pocketknife'}, {'frequency': 'c', 'synset': 'poker.n.01', 'synonyms': ['poker_(fire_stirring_tool)', 'stove_poker', 'fire_hook'], 'id': 826, 'def': 'fire iron consisting of a metal rod with a handle; used to stir a fire', 'name': 'poker_(fire_stirring_tool)'}, {'frequency': 'f', 'synset': 'pole.n.01', 'synonyms': ['pole', 'post'], 'id': 827, 'def': 'a long (usually round) rod of wood or metal or plastic', 'name': 'pole'}, {'frequency': 'f', 'synset': 'polo_shirt.n.01', 'synonyms': ['polo_shirt', 'sport_shirt'], 'id': 828, 'def': 'a shirt with short sleeves designed for comfort and casual wear', 'name': 'polo_shirt'}, {'frequency': 'r', 'synset': 'poncho.n.01', 'synonyms': ['poncho'], 'id': 829, 'def': 'a blanket-like cloak with a hole in the center for the head', 'name': 'poncho'}, {'frequency': 'c', 'synset': 'pony.n.05', 'synonyms': ['pony'], 'id': 830, 'def': 'any of various breeds of small gentle horses usually less than five feet high at the shoulder', 'name': 'pony'}, {'frequency': 'r', 'synset': 'pool_table.n.01', 'synonyms': ['pool_table', 'billiard_table', 'snooker_table'], 'id': 831, 'def': 'game equipment consisting of a heavy table on which pool is played', 'name': 'pool_table'}, {'frequency': 'f', 'synset': 'pop.n.02', 'synonyms': ['pop_(soda)', 'soda_(pop)', 'tonic', 'soft_drink'], 'id': 832, 'def': 'a sweet drink containing carbonated water and flavoring', 'name': 'pop_(soda)'}, {'frequency': 'c', 'synset': 'postbox.n.01', 'synonyms': ['postbox_(public)', 'mailbox_(public)'], 'id': 833, 'def': 'public box for deposit of mail', 'name': 'postbox_(public)'}, {'frequency': 'c', 'synset': 'postcard.n.01', 'synonyms': ['postcard', 'postal_card', 'mailing-card'], 'id': 834, 'def': 'a card for sending messages by post without an envelope', 'name': 'postcard'}, {'frequency': 'f', 'synset': 'poster.n.01', 'synonyms': ['poster', 'placard'], 'id': 835, 'def': 'a sign posted in a public place as an advertisement', 'name': 'poster'}, {'frequency': 'f', 'synset': 'pot.n.01', 'synonyms': ['pot'], 'id': 836, 'def': 'metal or earthenware cooking vessel that is usually round and deep; often has a handle and lid', 'name': 'pot'}, {'frequency': 'f', 'synset': 'pot.n.04', 'synonyms': ['flowerpot'], 'id': 837, 'def': 'a container in which plants are cultivated', 'name': 'flowerpot'}, {'frequency': 'f', 'synset': 'potato.n.01', 'synonyms': ['potato'], 'id': 838, 'def': 'an edible tuber native to South America', 'name': 'potato'}, {'frequency': 'c', 'synset': 'potholder.n.01', 'synonyms': ['potholder'], 'id': 839, 'def': 'an insulated pad for holding hot pots', 'name': 'potholder'}, {'frequency': 'c', 'synset': 'pottery.n.01', 'synonyms': ['pottery', 'clayware'], 'id': 840, 'def': 'ceramic ware made from clay and baked in a kiln', 'name': 'pottery'}, {'frequency': 'c', 'synset': 'pouch.n.01', 'synonyms': ['pouch'], 'id': 841, 'def': 'a small or medium size container for holding or carrying things', 'name': 'pouch'}, {'frequency': 'c', 'synset': 'power_shovel.n.01', 'synonyms': ['power_shovel', 'excavator', 'digger'], 'id': 842, 'def': 'a machine for excavating', 'name': 'power_shovel'}, {'frequency': 'c', 'synset': 'prawn.n.01', 'synonyms': ['prawn', 'shrimp'], 'id': 843, 'def': 'any of various edible decapod crustaceans', 'name': 'prawn'}, {'frequency': 'c', 'synset': 'pretzel.n.01', 'synonyms': ['pretzel'], 'id': 844, 'def': 'glazed and salted cracker typically in the shape of a loose knot', 'name': 'pretzel'}, {'frequency': 'f', 'synset': 'printer.n.03', 'synonyms': ['printer', 'printing_machine'], 'id': 845, 'def': 'a machine that prints', 'name': 'printer'}, {'frequency': 'c', 'synset': 'projectile.n.01', 'synonyms': ['projectile_(weapon)', 'missile'], 'id': 846, 'def': 'a weapon that is forcibly thrown or projected at a targets', 'name': 'projectile_(weapon)'}, {'frequency': 'c', 'synset': 'projector.n.02', 'synonyms': ['projector'], 'id': 847, 'def': 'an optical instrument that projects an enlarged image onto a screen', 'name': 'projector'}, {'frequency': 'f', 'synset': 'propeller.n.01', 'synonyms': ['propeller', 'propellor'], 'id': 848, 'def': 'a mechanical device that rotates to push against air or water', 'name': 'propeller'}, {'frequency': 'r', 'synset': 'prune.n.01', 'synonyms': ['prune'], 'id': 849, 'def': 'dried plum', 'name': 'prune'}, {'frequency': 'r', 'synset': 'pudding.n.01', 'synonyms': ['pudding'], 'id': 850, 'def': 'any of various soft thick unsweetened baked dishes', 'name': 'pudding'}, {'frequency': 'r', 'synset': 'puffer.n.02', 'synonyms': ['puffer_(fish)', 'pufferfish', 'blowfish', 'globefish'], 'id': 851, 'def': 'fishes whose elongated spiny body can inflate itself with water or air to form a globe', 'name': 'puffer_(fish)'}, {'frequency': 'r', 'synset': 'puffin.n.01', 'synonyms': ['puffin'], 'id': 852, 'def': 'seabirds having short necks and brightly colored compressed bills', 'name': 'puffin'}, {'frequency': 'r', 'synset': 'pug.n.01', 'synonyms': ['pug-dog'], 'id': 853, 'def': 'small compact smooth-coated breed of Asiatic origin having a tightly curled tail and broad flat wrinkled muzzle', 'name': 'pug-dog'}, {'frequency': 'c', 'synset': 'pumpkin.n.02', 'synonyms': ['pumpkin'], 'id': 854, 'def': 'usually large pulpy deep-yellow round fruit of the squash family maturing in late summer or early autumn', 'name': 'pumpkin'}, {'frequency': 'r', 'synset': 'punch.n.03', 'synonyms': ['puncher'], 'id': 855, 'def': 'a tool for making holes or indentations', 'name': 'puncher'}, {'frequency': 'r', 'synset': 'puppet.n.01', 'synonyms': ['puppet', 'marionette'], 'id': 856, 'def': 'a small figure of a person operated from above with strings by a puppeteer', 'name': 'puppet'}, {'frequency': 'c', 'synset': 'puppy.n.01', 'synonyms': ['puppy'], 'id': 857, 'def': 'a young dog', 'name': 'puppy'}, {'frequency': 'r', 'synset': 'quesadilla.n.01', 'synonyms': ['quesadilla'], 'id': 858, 'def': 'a tortilla that is filled with cheese and heated', 'name': 'quesadilla'}, {'frequency': 'r', 'synset': 'quiche.n.02', 'synonyms': ['quiche'], 'id': 859, 'def': 'a tart filled with rich unsweetened custard; often contains other ingredients (as cheese or ham or seafood or vegetables)', 'name': 'quiche'}, {'frequency': 'f', 'synset': 'quilt.n.01', 'synonyms': ['quilt', 'comforter'], 'id': 860, 'def': 'bedding made of two layers of cloth filled with stuffing and stitched together', 'name': 'quilt'}, {'frequency': 'c', 'synset': 'rabbit.n.01', 'synonyms': ['rabbit'], 'id': 861, 'def': 'any of various burrowing animals of the family Leporidae having long ears and short tails', 'name': 'rabbit'}, {'frequency': 'r', 'synset': 'racer.n.02', 'synonyms': ['race_car', 'racing_car'], 'id': 862, 'def': 'a fast car that competes in races', 'name': 'race_car'}, {'frequency': 'c', 'synset': 'racket.n.04', 'synonyms': ['racket', 'racquet'], 'id': 863, 'def': 'a sports implement used to strike a ball in various games', 'name': 'racket'}, {'frequency': 'r', 'synset': 'radar.n.01', 'synonyms': ['radar'], 'id': 864, 'def': 'measuring instrument in which the echo of a pulse of microwave radiation is used to detect and locate distant objects', 'name': 'radar'}, {'frequency': 'f', 'synset': 'radiator.n.03', 'synonyms': ['radiator'], 'id': 865, 'def': 'a mechanism consisting of a metal honeycomb through which hot fluids circulate', 'name': 'radiator'}, {'frequency': 'c', 'synset': 'radio_receiver.n.01', 'synonyms': ['radio_receiver', 'radio_set', 'radio', 'tuner_(radio)'], 'id': 866, 'def': 'an electronic receiver that detects and demodulates and amplifies transmitted radio signals', 'name': 'radio_receiver'}, {'frequency': 'c', 'synset': 'radish.n.03', 'synonyms': ['radish', 'daikon'], 'id': 867, 'def': 'pungent edible root of any of various cultivated radish plants', 'name': 'radish'}, {'frequency': 'c', 'synset': 'raft.n.01', 'synonyms': ['raft'], 'id': 868, 'def': 'a flat float (usually made of logs or planks) that can be used for transport or as a platform for swimmers', 'name': 'raft'}, {'frequency': 'r', 'synset': 'rag_doll.n.01', 'synonyms': ['rag_doll'], 'id': 869, 'def': 'a cloth doll that is stuffed and (usually) painted', 'name': 'rag_doll'}, {'frequency': 'c', 'synset': 'raincoat.n.01', 'synonyms': ['raincoat', 'waterproof_jacket'], 'id': 870, 'def': 'a water-resistant coat', 'name': 'raincoat'}, {'frequency': 'c', 'synset': 'ram.n.05', 'synonyms': ['ram_(animal)'], 'id': 871, 'def': 'uncastrated adult male sheep', 'name': 'ram_(animal)'}, {'frequency': 'c', 'synset': 'raspberry.n.02', 'synonyms': ['raspberry'], 'id': 872, 'def': 'red or black edible aggregate berries usually smaller than the related blackberries', 'name': 'raspberry'}, {'frequency': 'r', 'synset': 'rat.n.01', 'synonyms': ['rat'], 'id': 873, 'def': 'any of various long-tailed rodents similar to but larger than a mouse', 'name': 'rat'}, {'frequency': 'c', 'synset': 'razorblade.n.01', 'synonyms': ['razorblade'], 'id': 874, 'def': 'a blade that has very sharp edge', 'name': 'razorblade'}, {'frequency': 'c', 'synset': 'reamer.n.01', 'synonyms': ['reamer_(juicer)', 'juicer', 'juice_reamer'], 'id': 875, 'def': 'a squeezer with a conical ridged center that is used for squeezing juice from citrus fruit', 'name': 'reamer_(juicer)'}, {'frequency': 'f', 'synset': 'rearview_mirror.n.01', 'synonyms': ['rearview_mirror'], 'id': 876, 'def': 'vehicle mirror (side or rearview)', 'name': 'rearview_mirror'}, {'frequency': 'c', 'synset': 'receipt.n.02', 'synonyms': ['receipt'], 'id': 877, 'def': 'an acknowledgment (usually tangible) that payment has been made', 'name': 'receipt'}, {'frequency': 'c', 'synset': 'recliner.n.01', 'synonyms': ['recliner', 'reclining_chair', 'lounger_(chair)'], 'id': 878, 'def': 'an armchair whose back can be lowered and foot can be raised to allow the sitter to recline in it', 'name': 'recliner'}, {'frequency': 'c', 'synset': 'record_player.n.01', 'synonyms': ['record_player', 'phonograph_(record_player)', 'turntable'], 'id': 879, 'def': 'machine in which rotating records cause a stylus to vibrate and the vibrations are amplified acoustically or electronically', 'name': 'record_player'}, {'frequency': 'f', 'synset': 'reflector.n.01', 'synonyms': ['reflector'], 'id': 880, 'def': 'device that reflects light, radiation, etc.', 'name': 'reflector'}, {'frequency': 'f', 'synset': 'remote_control.n.01', 'synonyms': ['remote_control'], 'id': 881, 'def': 'a device that can be used to control a machine or apparatus from a distance', 'name': 'remote_control'}, {'frequency': 'c', 'synset': 'rhinoceros.n.01', 'synonyms': ['rhinoceros'], 'id': 882, 'def': 'massive powerful herbivorous odd-toed ungulate of southeast Asia and Africa having very thick skin and one or two horns on the snout', 'name': 'rhinoceros'}, {'frequency': 'r', 'synset': 'rib.n.03', 'synonyms': ['rib_(food)'], 'id': 883, 'def': 'cut of meat including one or more ribs', 'name': 'rib_(food)'}, {'frequency': 'c', 'synset': 'rifle.n.01', 'synonyms': ['rifle'], 'id': 884, 'def': 'a shoulder firearm with a long barrel', 'name': 'rifle'}, {'frequency': 'f', 'synset': 'ring.n.08', 'synonyms': ['ring'], 'id': 885, 'def': 'jewelry consisting of a circlet of precious metal (often set with jewels) worn on the finger', 'name': 'ring'}, {'frequency': 'r', 'synset': 'river_boat.n.01', 'synonyms': ['river_boat'], 'id': 886, 'def': 'a boat used on rivers or to ply a river', 'name': 'river_boat'}, {'frequency': 'r', 'synset': 'road_map.n.02', 'synonyms': ['road_map'], 'id': 887, 'def': '(NOT A ROAD) a MAP showing roads (for automobile travel)', 'name': 'road_map'}, {'frequency': 'c', 'synset': 'robe.n.01', 'synonyms': ['robe'], 'id': 888, 'def': 'any loose flowing garment', 'name': 'robe'}, {'frequency': 'c', 'synset': 'rocking_chair.n.01', 'synonyms': ['rocking_chair'], 'id': 889, 'def': 'a chair mounted on rockers', 'name': 'rocking_chair'}, {'frequency': 'r', 'synset': 'rodent.n.01', 'synonyms': ['rodent'], 'id': 890, 'def': 'relatively small placental mammals having a single pair of constantly growing incisor teeth specialized for gnawing', 'name': 'rodent'}, {'frequency': 'r', 'synset': 'roller_skate.n.01', 'synonyms': ['roller_skate'], 'id': 891, 'def': 'a shoe with pairs of rollers (small hard wheels) fixed to the sole', 'name': 'roller_skate'}, {'frequency': 'r', 'synset': 'rollerblade.n.01', 'synonyms': ['Rollerblade'], 'id': 892, 'def': 'an in-line variant of a roller skate', 'name': 'Rollerblade'}, {'frequency': 'c', 'synset': 'rolling_pin.n.01', 'synonyms': ['rolling_pin'], 'id': 893, 'def': 'utensil consisting of a cylinder (usually of wood) with a handle at each end; used to roll out dough', 'name': 'rolling_pin'}, {'frequency': 'r', 'synset': 'root_beer.n.01', 'synonyms': ['root_beer'], 'id': 894, 'def': 'carbonated drink containing extracts of roots and herbs', 'name': 'root_beer'}, {'frequency': 'c', 'synset': 'router.n.02', 'synonyms': ['router_(computer_equipment)'], 'id': 895, 'def': 'a device that forwards data packets between computer networks', 'name': 'router_(computer_equipment)'}, {'frequency': 'f', 'synset': 'rubber_band.n.01', 'synonyms': ['rubber_band', 'elastic_band'], 'id': 896, 'def': 'a narrow band of elastic rubber used to hold things (such as papers) together', 'name': 'rubber_band'}, {'frequency': 'c', 'synset': 'runner.n.08', 'synonyms': ['runner_(carpet)'], 'id': 897, 'def': 'a long narrow carpet', 'name': 'runner_(carpet)'}, {'frequency': 'f', 'synset': 'sack.n.01', 'synonyms': ['plastic_bag', 'paper_bag'], 'id': 898, 'def': "a bag made of paper or plastic for holding customer's purchases", 'name': 'plastic_bag'}, {'frequency': 'f', 'synset': 'saddle.n.01', 'synonyms': ['saddle_(on_an_animal)'], 'id': 899, 'def': 'a seat for the rider of a horse or camel', 'name': 'saddle_(on_an_animal)'}, {'frequency': 'f', 'synset': 'saddle_blanket.n.01', 'synonyms': ['saddle_blanket', 'saddlecloth', 'horse_blanket'], 'id': 900, 'def': 'stable gear consisting of a blanket placed under the saddle', 'name': 'saddle_blanket'}, {'frequency': 'c', 'synset': 'saddlebag.n.01', 'synonyms': ['saddlebag'], 'id': 901, 'def': 'a large bag (or pair of bags) hung over a saddle', 'name': 'saddlebag'}, {'frequency': 'r', 'synset': 'safety_pin.n.01', 'synonyms': ['safety_pin'], 'id': 902, 'def': 'a pin in the form of a clasp; has a guard so the point of the pin will not stick the user', 'name': 'safety_pin'}, {'frequency': 'f', 'synset': 'sail.n.01', 'synonyms': ['sail'], 'id': 903, 'def': 'a large piece of fabric by means of which wind is used to propel a sailing vessel', 'name': 'sail'}, {'frequency': 'f', 'synset': 'salad.n.01', 'synonyms': ['salad'], 'id': 904, 'def': 'food mixtures either arranged on a plate or tossed and served with a moist dressing; usually consisting of or including greens', 'name': 'salad'}, {'frequency': 'r', 'synset': 'salad_plate.n.01', 'synonyms': ['salad_plate', 'salad_bowl'], 'id': 905, 'def': 'a plate or bowl for individual servings of salad', 'name': 'salad_plate'}, {'frequency': 'c', 'synset': 'salami.n.01', 'synonyms': ['salami'], 'id': 906, 'def': 'highly seasoned fatty sausage of pork and beef usually dried', 'name': 'salami'}, {'frequency': 'c', 'synset': 'salmon.n.01', 'synonyms': ['salmon_(fish)'], 'id': 907, 'def': 'any of various large food and game fishes of northern waters', 'name': 'salmon_(fish)'}, {'frequency': 'r', 'synset': 'salmon.n.03', 'synonyms': ['salmon_(food)'], 'id': 908, 'def': 'flesh of any of various marine or freshwater fish of the family Salmonidae', 'name': 'salmon_(food)'}, {'frequency': 'c', 'synset': 'salsa.n.01', 'synonyms': ['salsa'], 'id': 909, 'def': 'spicy sauce of tomatoes and onions and chili peppers to accompany Mexican foods', 'name': 'salsa'}, {'frequency': 'f', 'synset': 'saltshaker.n.01', 'synonyms': ['saltshaker'], 'id': 910, 'def': 'a shaker with a perforated top for sprinkling salt', 'name': 'saltshaker'}, {'frequency': 'f', 'synset': 'sandal.n.01', 'synonyms': ['sandal_(type_of_shoe)'], 'id': 911, 'def': 'a shoe consisting of a sole fastened by straps to the foot', 'name': 'sandal_(type_of_shoe)'}, {'frequency': 'f', 'synset': 'sandwich.n.01', 'synonyms': ['sandwich'], 'id': 912, 'def': 'two (or more) slices of bread with a filling between them', 'name': 'sandwich'}, {'frequency': 'r', 'synset': 'satchel.n.01', 'synonyms': ['satchel'], 'id': 913, 'def': 'luggage consisting of a small case with a flat bottom and (usually) a shoulder strap', 'name': 'satchel'}, {'frequency': 'r', 'synset': 'saucepan.n.01', 'synonyms': ['saucepan'], 'id': 914, 'def': 'a deep pan with a handle; used for stewing or boiling', 'name': 'saucepan'}, {'frequency': 'f', 'synset': 'saucer.n.02', 'synonyms': ['saucer'], 'id': 915, 'def': 'a small shallow dish for holding a cup at the table', 'name': 'saucer'}, {'frequency': 'f', 'synset': 'sausage.n.01', 'synonyms': ['sausage'], 'id': 916, 'def': 'highly seasoned minced meat stuffed in casings', 'name': 'sausage'}, {'frequency': 'r', 'synset': 'sawhorse.n.01', 'synonyms': ['sawhorse', 'sawbuck'], 'id': 917, 'def': 'a framework for holding wood that is being sawed', 'name': 'sawhorse'}, {'frequency': 'r', 'synset': 'sax.n.02', 'synonyms': ['saxophone'], 'id': 918, 'def': "a wind instrument with a `J'-shaped form typically made of brass", 'name': 'saxophone'}, {'frequency': 'f', 'synset': 'scale.n.07', 'synonyms': ['scale_(measuring_instrument)'], 'id': 919, 'def': 'a measuring instrument for weighing; shows amount of mass', 'name': 'scale_(measuring_instrument)'}, {'frequency': 'r', 'synset': 'scarecrow.n.01', 'synonyms': ['scarecrow', 'strawman'], 'id': 920, 'def': 'an effigy in the shape of a man to frighten birds away from seeds', 'name': 'scarecrow'}, {'frequency': 'f', 'synset': 'scarf.n.01', 'synonyms': ['scarf'], 'id': 921, 'def': 'a garment worn around the head or neck or shoulders for warmth or decoration', 'name': 'scarf'}, {'frequency': 'c', 'synset': 'school_bus.n.01', 'synonyms': ['school_bus'], 'id': 922, 'def': 'a bus used to transport children to or from school', 'name': 'school_bus'}, {'frequency': 'f', 'synset': 'scissors.n.01', 'synonyms': ['scissors'], 'id': 923, 'def': 'a tool having two crossed pivoting blades with looped handles', 'name': 'scissors'}, {'frequency': 'f', 'synset': 'scoreboard.n.01', 'synonyms': ['scoreboard'], 'id': 924, 'def': 'a large board for displaying the score of a contest (and some other information)', 'name': 'scoreboard'}, {'frequency': 'r', 'synset': 'scraper.n.01', 'synonyms': ['scraper'], 'id': 925, 'def': 'any of various hand tools for scraping', 'name': 'scraper'}, {'frequency': 'c', 'synset': 'screwdriver.n.01', 'synonyms': ['screwdriver'], 'id': 926, 'def': 'a hand tool for driving screws; has a tip that fits into the head of a screw', 'name': 'screwdriver'}, {'frequency': 'f', 'synset': 'scrub_brush.n.01', 'synonyms': ['scrubbing_brush'], 'id': 927, 'def': 'a brush with short stiff bristles for heavy cleaning', 'name': 'scrubbing_brush'}, {'frequency': 'c', 'synset': 'sculpture.n.01', 'synonyms': ['sculpture'], 'id': 928, 'def': 'a three-dimensional work of art', 'name': 'sculpture'}, {'frequency': 'c', 'synset': 'seabird.n.01', 'synonyms': ['seabird', 'seafowl'], 'id': 929, 'def': 'a bird that frequents coastal waters and the open ocean: gulls; pelicans; gannets; cormorants; albatrosses; petrels; etc.', 'name': 'seabird'}, {'frequency': 'c', 'synset': 'seahorse.n.02', 'synonyms': ['seahorse'], 'id': 930, 'def': 'small fish with horse-like heads bent sharply downward and curled tails', 'name': 'seahorse'}, {'frequency': 'r', 'synset': 'seaplane.n.01', 'synonyms': ['seaplane', 'hydroplane'], 'id': 931, 'def': 'an airplane that can land on or take off from water', 'name': 'seaplane'}, {'frequency': 'c', 'synset': 'seashell.n.01', 'synonyms': ['seashell'], 'id': 932, 'def': 'the shell of a marine organism', 'name': 'seashell'}, {'frequency': 'c', 'synset': 'sewing_machine.n.01', 'synonyms': ['sewing_machine'], 'id': 933, 'def': 'a textile machine used as a home appliance for sewing', 'name': 'sewing_machine'}, {'frequency': 'c', 'synset': 'shaker.n.03', 'synonyms': ['shaker'], 'id': 934, 'def': 'a container in which something can be shaken', 'name': 'shaker'}, {'frequency': 'c', 'synset': 'shampoo.n.01', 'synonyms': ['shampoo'], 'id': 935, 'def': 'cleansing agent consisting of soaps or detergents used for washing the hair', 'name': 'shampoo'}, {'frequency': 'c', 'synset': 'shark.n.01', 'synonyms': ['shark'], 'id': 936, 'def': 'typically large carnivorous fishes with sharpe teeth', 'name': 'shark'}, {'frequency': 'r', 'synset': 'sharpener.n.01', 'synonyms': ['sharpener'], 'id': 937, 'def': 'any implement that is used to make something (an edge or a point) sharper', 'name': 'sharpener'}, {'frequency': 'r', 'synset': 'sharpie.n.03', 'synonyms': ['Sharpie'], 'id': 938, 'def': 'a pen with indelible ink that will write on any surface', 'name': 'Sharpie'}, {'frequency': 'r', 'synset': 'shaver.n.03', 'synonyms': ['shaver_(electric)', 'electric_shaver', 'electric_razor'], 'id': 939, 'def': 'a razor powered by an electric motor', 'name': 'shaver_(electric)'}, {'frequency': 'c', 'synset': 'shaving_cream.n.01', 'synonyms': ['shaving_cream', 'shaving_soap'], 'id': 940, 'def': 'toiletry consisting that forms a rich lather for softening the beard before shaving', 'name': 'shaving_cream'}, {'frequency': 'r', 'synset': 'shawl.n.01', 'synonyms': ['shawl'], 'id': 941, 'def': 'cloak consisting of an oblong piece of cloth used to cover the head and shoulders', 'name': 'shawl'}, {'frequency': 'r', 'synset': 'shears.n.01', 'synonyms': ['shears'], 'id': 942, 'def': 'large scissors with strong blades', 'name': 'shears'}, {'frequency': 'f', 'synset': 'sheep.n.01', 'synonyms': ['sheep'], 'id': 943, 'def': 'woolly usually horned ruminant mammal related to the goat', 'name': 'sheep'}, {'frequency': 'r', 'synset': 'shepherd_dog.n.01', 'synonyms': ['shepherd_dog', 'sheepdog'], 'id': 944, 'def': 'any of various usually long-haired breeds of dog reared to herd and guard sheep', 'name': 'shepherd_dog'}, {'frequency': 'r', 'synset': 'sherbert.n.01', 'synonyms': ['sherbert', 'sherbet'], 'id': 945, 'def': 'a frozen dessert made primarily of fruit juice and sugar', 'name': 'sherbert'}, {'frequency': 'c', 'synset': 'shield.n.02', 'synonyms': ['shield'], 'id': 946, 'def': 'armor carried on the arm to intercept blows', 'name': 'shield'}, {'frequency': 'f', 'synset': 'shirt.n.01', 'synonyms': ['shirt'], 'id': 947, 'def': 'a garment worn on the upper half of the body', 'name': 'shirt'}, {'frequency': 'f', 'synset': 'shoe.n.01', 'synonyms': ['shoe', 'sneaker_(type_of_shoe)', 'tennis_shoe'], 'id': 948, 'def': 'common footwear covering the foot', 'name': 'shoe'}, {'frequency': 'f', 'synset': 'shopping_bag.n.01', 'synonyms': ['shopping_bag'], 'id': 949, 'def': 'a bag made of plastic or strong paper (often with handles); used to transport goods after shopping', 'name': 'shopping_bag'}, {'frequency': 'c', 'synset': 'shopping_cart.n.01', 'synonyms': ['shopping_cart'], 'id': 950, 'def': 'a handcart that holds groceries or other goods while shopping', 'name': 'shopping_cart'}, {'frequency': 'f', 'synset': 'short_pants.n.01', 'synonyms': ['short_pants', 'shorts_(clothing)', 'trunks_(clothing)'], 'id': 951, 'def': 'trousers that end at or above the knee', 'name': 'short_pants'}, {'frequency': 'r', 'synset': 'shot_glass.n.01', 'synonyms': ['shot_glass'], 'id': 952, 'def': 'a small glass adequate to hold a single swallow of whiskey', 'name': 'shot_glass'}, {'frequency': 'f', 'synset': 'shoulder_bag.n.01', 'synonyms': ['shoulder_bag'], 'id': 953, 'def': 'a large handbag that can be carried by a strap looped over the shoulder', 'name': 'shoulder_bag'}, {'frequency': 'c', 'synset': 'shovel.n.01', 'synonyms': ['shovel'], 'id': 954, 'def': 'a hand tool for lifting loose material such as snow, dirt, etc.', 'name': 'shovel'}, {'frequency': 'f', 'synset': 'shower.n.01', 'synonyms': ['shower_head'], 'id': 955, 'def': 'a plumbing fixture that sprays water over you', 'name': 'shower_head'}, {'frequency': 'r', 'synset': 'shower_cap.n.01', 'synonyms': ['shower_cap'], 'id': 956, 'def': 'a tight cap worn to keep hair dry while showering', 'name': 'shower_cap'}, {'frequency': 'f', 'synset': 'shower_curtain.n.01', 'synonyms': ['shower_curtain'], 'id': 957, 'def': 'a curtain that keeps water from splashing out of the shower area', 'name': 'shower_curtain'}, {'frequency': 'r', 'synset': 'shredder.n.01', 'synonyms': ['shredder_(for_paper)'], 'id': 958, 'def': 'a device that shreds documents', 'name': 'shredder_(for_paper)'}, {'frequency': 'f', 'synset': 'signboard.n.01', 'synonyms': ['signboard'], 'id': 959, 'def': 'structure displaying a board on which advertisements can be posted', 'name': 'signboard'}, {'frequency': 'c', 'synset': 'silo.n.01', 'synonyms': ['silo'], 'id': 960, 'def': 'a cylindrical tower used for storing goods', 'name': 'silo'}, {'frequency': 'f', 'synset': 'sink.n.01', 'synonyms': ['sink'], 'id': 961, 'def': 'plumbing fixture consisting of a water basin fixed to a wall or floor and having a drainpipe', 'name': 'sink'}, {'frequency': 'f', 'synset': 'skateboard.n.01', 'synonyms': ['skateboard'], 'id': 962, 'def': 'a board with wheels that is ridden in a standing or crouching position and propelled by foot', 'name': 'skateboard'}, {'frequency': 'c', 'synset': 'skewer.n.01', 'synonyms': ['skewer'], 'id': 963, 'def': 'a long pin for holding meat in position while it is being roasted', 'name': 'skewer'}, {'frequency': 'f', 'synset': 'ski.n.01', 'synonyms': ['ski'], 'id': 964, 'def': 'sports equipment for skiing on snow', 'name': 'ski'}, {'frequency': 'f', 'synset': 'ski_boot.n.01', 'synonyms': ['ski_boot'], 'id': 965, 'def': 'a stiff boot that is fastened to a ski with a ski binding', 'name': 'ski_boot'}, {'frequency': 'f', 'synset': 'ski_parka.n.01', 'synonyms': ['ski_parka', 'ski_jacket'], 'id': 966, 'def': 'a parka to be worn while skiing', 'name': 'ski_parka'}, {'frequency': 'f', 'synset': 'ski_pole.n.01', 'synonyms': ['ski_pole'], 'id': 967, 'def': 'a pole with metal points used as an aid in skiing', 'name': 'ski_pole'}, {'frequency': 'f', 'synset': 'skirt.n.02', 'synonyms': ['skirt'], 'id': 968, 'def': 'a garment hanging from the waist; worn mainly by girls and women', 'name': 'skirt'}, {'frequency': 'r', 'synset': 'skullcap.n.01', 'synonyms': ['skullcap'], 'id': 969, 'def': 'rounded brimless cap fitting the crown of the head', 'name': 'skullcap'}, {'frequency': 'c', 'synset': 'sled.n.01', 'synonyms': ['sled', 'sledge', 'sleigh'], 'id': 970, 'def': 'a vehicle or flat object for transportation over snow by sliding or pulled by dogs, etc.', 'name': 'sled'}, {'frequency': 'c', 'synset': 'sleeping_bag.n.01', 'synonyms': ['sleeping_bag'], 'id': 971, 'def': 'large padded bag designed to be slept in outdoors', 'name': 'sleeping_bag'}, {'frequency': 'r', 'synset': 'sling.n.05', 'synonyms': ['sling_(bandage)', 'triangular_bandage'], 'id': 972, 'def': 'bandage to support an injured forearm; slung over the shoulder or neck', 'name': 'sling_(bandage)'}, {'frequency': 'c', 'synset': 'slipper.n.01', 'synonyms': ['slipper_(footwear)', 'carpet_slipper_(footwear)'], 'id': 973, 'def': 'low footwear that can be slipped on and off easily; usually worn indoors', 'name': 'slipper_(footwear)'}, {'frequency': 'r', 'synset': 'smoothie.n.02', 'synonyms': ['smoothie'], 'id': 974, 'def': 'a thick smooth drink consisting of fresh fruit pureed with ice cream or yoghurt or milk', 'name': 'smoothie'}, {'frequency': 'r', 'synset': 'snake.n.01', 'synonyms': ['snake', 'serpent'], 'id': 975, 'def': 'limbless scaly elongate reptile; some are venomous', 'name': 'snake'}, {'frequency': 'f', 'synset': 'snowboard.n.01', 'synonyms': ['snowboard'], 'id': 976, 'def': 'a board that resembles a broad ski or a small surfboard; used in a standing position to slide down snow-covered slopes', 'name': 'snowboard'}, {'frequency': 'c', 'synset': 'snowman.n.01', 'synonyms': ['snowman'], 'id': 977, 'def': 'a figure of a person made of packed snow', 'name': 'snowman'}, {'frequency': 'c', 'synset': 'snowmobile.n.01', 'synonyms': ['snowmobile'], 'id': 978, 'def': 'tracked vehicle for travel on snow having skis in front', 'name': 'snowmobile'}, {'frequency': 'f', 'synset': 'soap.n.01', 'synonyms': ['soap'], 'id': 979, 'def': 'a cleansing agent made from the salts of vegetable or animal fats', 'name': 'soap'}, {'frequency': 'f', 'synset': 'soccer_ball.n.01', 'synonyms': ['soccer_ball'], 'id': 980, 'def': "an inflated ball used in playing soccer (called `football' outside of the United States)", 'name': 'soccer_ball'}, {'frequency': 'f', 'synset': 'sock.n.01', 'synonyms': ['sock'], 'id': 981, 'def': 'cloth covering for the foot; worn inside the shoe; reaches to between the ankle and the knee', 'name': 'sock'}, {'frequency': 'f', 'synset': 'sofa.n.01', 'synonyms': ['sofa', 'couch', 'lounge'], 'id': 982, 'def': 'an upholstered seat for more than one person', 'name': 'sofa'}, {'frequency': 'r', 'synset': 'softball.n.01', 'synonyms': ['softball'], 'id': 983, 'def': 'ball used in playing softball', 'name': 'softball'}, {'frequency': 'c', 'synset': 'solar_array.n.01', 'synonyms': ['solar_array', 'solar_battery', 'solar_panel'], 'id': 984, 'def': 'electrical device consisting of a large array of connected solar cells', 'name': 'solar_array'}, {'frequency': 'r', 'synset': 'sombrero.n.02', 'synonyms': ['sombrero'], 'id': 985, 'def': 'a straw hat with a tall crown and broad brim; worn in American southwest and in Mexico', 'name': 'sombrero'}, {'frequency': 'f', 'synset': 'soup.n.01', 'synonyms': ['soup'], 'id': 986, 'def': 'liquid food especially of meat or fish or vegetable stock often containing pieces of solid food', 'name': 'soup'}, {'frequency': 'r', 'synset': 'soup_bowl.n.01', 'synonyms': ['soup_bowl'], 'id': 987, 'def': 'a bowl for serving soup', 'name': 'soup_bowl'}, {'frequency': 'c', 'synset': 'soupspoon.n.01', 'synonyms': ['soupspoon'], 'id': 988, 'def': 'a spoon with a rounded bowl for eating soup', 'name': 'soupspoon'}, {'frequency': 'c', 'synset': 'sour_cream.n.01', 'synonyms': ['sour_cream', 'soured_cream'], 'id': 989, 'def': 'soured light cream', 'name': 'sour_cream'}, {'frequency': 'r', 'synset': 'soya_milk.n.01', 'synonyms': ['soya_milk', 'soybean_milk', 'soymilk'], 'id': 990, 'def': 'a milk substitute containing soybean flour and water; used in some infant formulas and in making tofu', 'name': 'soya_milk'}, {'frequency': 'r', 'synset': 'space_shuttle.n.01', 'synonyms': ['space_shuttle'], 'id': 991, 'def': "a reusable spacecraft with wings for a controlled descent through the Earth's atmosphere", 'name': 'space_shuttle'}, {'frequency': 'r', 'synset': 'sparkler.n.02', 'synonyms': ['sparkler_(fireworks)'], 'id': 992, 'def': 'a firework that burns slowly and throws out a shower of sparks', 'name': 'sparkler_(fireworks)'}, {'frequency': 'f', 'synset': 'spatula.n.02', 'synonyms': ['spatula'], 'id': 993, 'def': 'a hand tool with a thin flexible blade used to mix or spread soft substances', 'name': 'spatula'}, {'frequency': 'r', 'synset': 'spear.n.01', 'synonyms': ['spear', 'lance'], 'id': 994, 'def': 'a long pointed rod used as a tool or weapon', 'name': 'spear'}, {'frequency': 'f', 'synset': 'spectacles.n.01', 'synonyms': ['spectacles', 'specs', 'eyeglasses', 'glasses'], 'id': 995, 'def': 'optical instrument consisting of a frame that holds a pair of lenses for correcting defective vision', 'name': 'spectacles'}, {'frequency': 'c', 'synset': 'spice_rack.n.01', 'synonyms': ['spice_rack'], 'id': 996, 'def': 'a rack for displaying containers filled with spices', 'name': 'spice_rack'}, {'frequency': 'c', 'synset': 'spider.n.01', 'synonyms': ['spider'], 'id': 997, 'def': 'predatory arachnid with eight legs, two poison fangs, two feelers, and usually two silk-spinning organs at the back end of the body', 'name': 'spider'}, {'frequency': 'r', 'synset': 'spiny_lobster.n.02', 'synonyms': ['crawfish', 'crayfish'], 'id': 998, 'def': 'large edible marine crustacean having a spiny carapace but lacking the large pincers of true lobsters', 'name': 'crawfish'}, {'frequency': 'c', 'synset': 'sponge.n.01', 'synonyms': ['sponge'], 'id': 999, 'def': 'a porous mass usable to absorb water typically used for cleaning', 'name': 'sponge'}, {'frequency': 'f', 'synset': 'spoon.n.01', 'synonyms': ['spoon'], 'id': 1000, 'def': 'a piece of cutlery with a shallow bowl-shaped container and a handle', 'name': 'spoon'}, {'frequency': 'c', 'synset': 'sportswear.n.01', 'synonyms': ['sportswear', 'athletic_wear', 'activewear'], 'id': 1001, 'def': 'attire worn for sport or for casual wear', 'name': 'sportswear'}, {'frequency': 'c', 'synset': 'spotlight.n.02', 'synonyms': ['spotlight'], 'id': 1002, 'def': 'a lamp that produces a strong beam of light to illuminate a restricted area; used to focus attention of a stage performer', 'name': 'spotlight'}, {'frequency': 'r', 'synset': 'squid.n.01', 'synonyms': ['squid_(food)', 'calamari', 'calamary'], 'id': 1003, 'def': '(Italian cuisine) squid prepared as food', 'name': 'squid_(food)'}, {'frequency': 'c', 'synset': 'squirrel.n.01', 'synonyms': ['squirrel'], 'id': 1004, 'def': 'a kind of arboreal rodent having a long bushy tail', 'name': 'squirrel'}, {'frequency': 'r', 'synset': 'stagecoach.n.01', 'synonyms': ['stagecoach'], 'id': 1005, 'def': 'a large coach-and-four formerly used to carry passengers and mail on regular routes between towns', 'name': 'stagecoach'}, {'frequency': 'c', 'synset': 'stapler.n.01', 'synonyms': ['stapler_(stapling_machine)'], 'id': 1006, 'def': 'a machine that inserts staples into sheets of paper in order to fasten them together', 'name': 'stapler_(stapling_machine)'}, {'frequency': 'c', 'synset': 'starfish.n.01', 'synonyms': ['starfish', 'sea_star'], 'id': 1007, 'def': 'echinoderms characterized by five arms extending from a central disk', 'name': 'starfish'}, {'frequency': 'f', 'synset': 'statue.n.01', 'synonyms': ['statue_(sculpture)'], 'id': 1008, 'def': 'a sculpture representing a human or animal', 'name': 'statue_(sculpture)'}, {'frequency': 'c', 'synset': 'steak.n.01', 'synonyms': ['steak_(food)'], 'id': 1009, 'def': 'a slice of meat cut from the fleshy part of an animal or large fish', 'name': 'steak_(food)'}, {'frequency': 'r', 'synset': 'steak_knife.n.01', 'synonyms': ['steak_knife'], 'id': 1010, 'def': 'a sharp table knife used in eating steak', 'name': 'steak_knife'}, {'frequency': 'f', 'synset': 'steering_wheel.n.01', 'synonyms': ['steering_wheel'], 'id': 1011, 'def': 'a handwheel that is used for steering', 'name': 'steering_wheel'}, {'frequency': 'r', 'synset': 'step_ladder.n.01', 'synonyms': ['stepladder'], 'id': 1012, 'def': 'a folding portable ladder hinged at the top', 'name': 'stepladder'}, {'frequency': 'c', 'synset': 'step_stool.n.01', 'synonyms': ['step_stool'], 'id': 1013, 'def': 'a stool that has one or two steps that fold under the seat', 'name': 'step_stool'}, {'frequency': 'c', 'synset': 'stereo.n.01', 'synonyms': ['stereo_(sound_system)'], 'id': 1014, 'def': 'electronic device for playing audio', 'name': 'stereo_(sound_system)'}, {'frequency': 'r', 'synset': 'stew.n.02', 'synonyms': ['stew'], 'id': 1015, 'def': 'food prepared by stewing especially meat or fish with vegetables', 'name': 'stew'}, {'frequency': 'r', 'synset': 'stirrer.n.02', 'synonyms': ['stirrer'], 'id': 1016, 'def': 'an implement used for stirring', 'name': 'stirrer'}, {'frequency': 'f', 'synset': 'stirrup.n.01', 'synonyms': ['stirrup'], 'id': 1017, 'def': "support consisting of metal loops into which rider's feet go", 'name': 'stirrup'}, {'frequency': 'f', 'synset': 'stool.n.01', 'synonyms': ['stool'], 'id': 1018, 'def': 'a simple seat without a back or arms', 'name': 'stool'}, {'frequency': 'f', 'synset': 'stop_sign.n.01', 'synonyms': ['stop_sign'], 'id': 1019, 'def': 'a traffic sign to notify drivers that they must come to a complete stop', 'name': 'stop_sign'}, {'frequency': 'f', 'synset': 'stoplight.n.01', 'synonyms': ['brake_light'], 'id': 1020, 'def': 'a red light on the rear of a motor vehicle that signals when the brakes are applied', 'name': 'brake_light'}, {'frequency': 'f', 'synset': 'stove.n.01', 'synonyms': ['stove', 'kitchen_stove', 'range_(kitchen_appliance)', 'kitchen_range', 'cooking_stove'], 'id': 1021, 'def': 'a kitchen appliance used for cooking food', 'name': 'stove'}, {'frequency': 'c', 'synset': 'strainer.n.01', 'synonyms': ['strainer'], 'id': 1022, 'def': 'a filter to retain larger pieces while smaller pieces and liquids pass through', 'name': 'strainer'}, {'frequency': 'f', 'synset': 'strap.n.01', 'synonyms': ['strap'], 'id': 1023, 'def': 'an elongated strip of material for binding things together or holding', 'name': 'strap'}, {'frequency': 'f', 'synset': 'straw.n.04', 'synonyms': ['straw_(for_drinking)', 'drinking_straw'], 'id': 1024, 'def': 'a thin paper or plastic tube used to suck liquids into the mouth', 'name': 'straw_(for_drinking)'}, {'frequency': 'f', 'synset': 'strawberry.n.01', 'synonyms': ['strawberry'], 'id': 1025, 'def': 'sweet fleshy red fruit', 'name': 'strawberry'}, {'frequency': 'f', 'synset': 'street_sign.n.01', 'synonyms': ['street_sign'], 'id': 1026, 'def': 'a sign visible from the street', 'name': 'street_sign'}, {'frequency': 'f', 'synset': 'streetlight.n.01', 'synonyms': ['streetlight', 'street_lamp'], 'id': 1027, 'def': 'a lamp supported on a lamppost; for illuminating a street', 'name': 'streetlight'}, {'frequency': 'r', 'synset': 'string_cheese.n.01', 'synonyms': ['string_cheese'], 'id': 1028, 'def': 'cheese formed in long strings twisted together', 'name': 'string_cheese'}, {'frequency': 'r', 'synset': 'stylus.n.02', 'synonyms': ['stylus'], 'id': 1029, 'def': 'a pointed tool for writing or drawing or engraving, including pens', 'name': 'stylus'}, {'frequency': 'r', 'synset': 'subwoofer.n.01', 'synonyms': ['subwoofer'], 'id': 1030, 'def': 'a loudspeaker that is designed to reproduce very low bass frequencies', 'name': 'subwoofer'}, {'frequency': 'r', 'synset': 'sugar_bowl.n.01', 'synonyms': ['sugar_bowl'], 'id': 1031, 'def': 'a dish in which sugar is served', 'name': 'sugar_bowl'}, {'frequency': 'r', 'synset': 'sugarcane.n.01', 'synonyms': ['sugarcane_(plant)'], 'id': 1032, 'def': 'juicy canes whose sap is a source of molasses and commercial sugar; fresh canes are sometimes chewed for the juice', 'name': 'sugarcane_(plant)'}, {'frequency': 'f', 'synset': 'suit.n.01', 'synonyms': ['suit_(clothing)'], 'id': 1033, 'def': 'a set of garments (usually including a jacket and trousers or skirt) for outerwear all of the same fabric and color', 'name': 'suit_(clothing)'}, {'frequency': 'c', 'synset': 'sunflower.n.01', 'synonyms': ['sunflower'], 'id': 1034, 'def': 'any plant of the genus Helianthus having large flower heads with dark disk florets and showy yellow rays', 'name': 'sunflower'}, {'frequency': 'f', 'synset': 'sunglasses.n.01', 'synonyms': ['sunglasses'], 'id': 1035, 'def': 'spectacles that are darkened or polarized to protect the eyes from the glare of the sun', 'name': 'sunglasses'}, {'frequency': 'c', 'synset': 'sunhat.n.01', 'synonyms': ['sunhat'], 'id': 1036, 'def': 'a hat with a broad brim that protects the face from direct exposure to the sun', 'name': 'sunhat'}, {'frequency': 'f', 'synset': 'surfboard.n.01', 'synonyms': ['surfboard'], 'id': 1037, 'def': 'a narrow buoyant board for riding surf', 'name': 'surfboard'}, {'frequency': 'c', 'synset': 'sushi.n.01', 'synonyms': ['sushi'], 'id': 1038, 'def': 'rice (with raw fish) wrapped in seaweed', 'name': 'sushi'}, {'frequency': 'c', 'synset': 'swab.n.02', 'synonyms': ['mop'], 'id': 1039, 'def': 'cleaning implement consisting of absorbent material fastened to a handle; for cleaning floors', 'name': 'mop'}, {'frequency': 'c', 'synset': 'sweat_pants.n.01', 'synonyms': ['sweat_pants'], 'id': 1040, 'def': 'loose-fitting trousers with elastic cuffs; worn by athletes', 'name': 'sweat_pants'}, {'frequency': 'c', 'synset': 'sweatband.n.02', 'synonyms': ['sweatband'], 'id': 1041, 'def': 'a band of material tied around the forehead or wrist to absorb sweat', 'name': 'sweatband'}, {'frequency': 'f', 'synset': 'sweater.n.01', 'synonyms': ['sweater'], 'id': 1042, 'def': 'a crocheted or knitted garment covering the upper part of the body', 'name': 'sweater'}, {'frequency': 'f', 'synset': 'sweatshirt.n.01', 'synonyms': ['sweatshirt'], 'id': 1043, 'def': 'cotton knit pullover with long sleeves worn during athletic activity', 'name': 'sweatshirt'}, {'frequency': 'c', 'synset': 'sweet_potato.n.02', 'synonyms': ['sweet_potato'], 'id': 1044, 'def': 'the edible tuberous root of the sweet potato vine', 'name': 'sweet_potato'}, {'frequency': 'f', 'synset': 'swimsuit.n.01', 'synonyms': ['swimsuit', 'swimwear', 'bathing_suit', 'swimming_costume', 'bathing_costume', 'swimming_trunks', 'bathing_trunks'], 'id': 1045, 'def': 'garment worn for swimming', 'name': 'swimsuit'}, {'frequency': 'c', 'synset': 'sword.n.01', 'synonyms': ['sword'], 'id': 1046, 'def': 'a cutting or thrusting weapon that has a long metal blade', 'name': 'sword'}, {'frequency': 'r', 'synset': 'syringe.n.01', 'synonyms': ['syringe'], 'id': 1047, 'def': 'a medical instrument used to inject or withdraw fluids', 'name': 'syringe'}, {'frequency': 'r', 'synset': 'tabasco.n.02', 'synonyms': ['Tabasco_sauce'], 'id': 1048, 'def': 'very spicy sauce (trade name Tabasco) made from fully-aged red peppers', 'name': 'Tabasco_sauce'}, {'frequency': 'r', 'synset': 'table-tennis_table.n.01', 'synonyms': ['table-tennis_table', 'ping-pong_table'], 'id': 1049, 'def': 'a table used for playing table tennis', 'name': 'table-tennis_table'}, {'frequency': 'f', 'synset': 'table.n.02', 'synonyms': ['table'], 'id': 1050, 'def': 'a piece of furniture having a smooth flat top that is usually supported by one or more vertical legs', 'name': 'table'}, {'frequency': 'c', 'synset': 'table_lamp.n.01', 'synonyms': ['table_lamp'], 'id': 1051, 'def': 'a lamp that sits on a table', 'name': 'table_lamp'}, {'frequency': 'f', 'synset': 'tablecloth.n.01', 'synonyms': ['tablecloth'], 'id': 1052, 'def': 'a covering spread over a dining table', 'name': 'tablecloth'}, {'frequency': 'r', 'synset': 'tachometer.n.01', 'synonyms': ['tachometer'], 'id': 1053, 'def': 'measuring instrument for indicating speed of rotation', 'name': 'tachometer'}, {'frequency': 'r', 'synset': 'taco.n.02', 'synonyms': ['taco'], 'id': 1054, 'def': 'a small tortilla cupped around a filling', 'name': 'taco'}, {'frequency': 'f', 'synset': 'tag.n.02', 'synonyms': ['tag'], 'id': 1055, 'def': 'a label associated with something for the purpose of identification or information', 'name': 'tag'}, {'frequency': 'f', 'synset': 'taillight.n.01', 'synonyms': ['taillight', 'rear_light'], 'id': 1056, 'def': 'lamp (usually red) mounted at the rear of a motor vehicle', 'name': 'taillight'}, {'frequency': 'r', 'synset': 'tambourine.n.01', 'synonyms': ['tambourine'], 'id': 1057, 'def': 'a shallow drum with a single drumhead and with metallic disks in the sides', 'name': 'tambourine'}, {'frequency': 'r', 'synset': 'tank.n.01', 'synonyms': ['army_tank', 'armored_combat_vehicle', 'armoured_combat_vehicle'], 'id': 1058, 'def': 'an enclosed armored military vehicle; has a cannon and moves on caterpillar treads', 'name': 'army_tank'}, {'frequency': 'f', 'synset': 'tank.n.02', 'synonyms': ['tank_(storage_vessel)', 'storage_tank'], 'id': 1059, 'def': 'a large (usually metallic) vessel for holding gases or liquids', 'name': 'tank_(storage_vessel)'}, {'frequency': 'f', 'synset': 'tank_top.n.01', 'synonyms': ['tank_top_(clothing)'], 'id': 1060, 'def': 'a tight-fitting sleeveless shirt with wide shoulder straps and low neck and no front opening', 'name': 'tank_top_(clothing)'}, {'frequency': 'f', 'synset': 'tape.n.01', 'synonyms': ['tape_(sticky_cloth_or_paper)'], 'id': 1061, 'def': 'a long thin piece of cloth or paper as used for binding or fastening', 'name': 'tape_(sticky_cloth_or_paper)'}, {'frequency': 'c', 'synset': 'tape.n.04', 'synonyms': ['tape_measure', 'measuring_tape'], 'id': 1062, 'def': 'measuring instrument consisting of a narrow strip (cloth or metal) marked in inches or centimeters and used for measuring lengths', 'name': 'tape_measure'}, {'frequency': 'c', 'synset': 'tapestry.n.02', 'synonyms': ['tapestry'], 'id': 1063, 'def': 'a heavy textile with a woven design; used for curtains and upholstery', 'name': 'tapestry'}, {'frequency': 'f', 'synset': 'tarpaulin.n.01', 'synonyms': ['tarp'], 'id': 1064, 'def': 'waterproofed canvas', 'name': 'tarp'}, {'frequency': 'c', 'synset': 'tartan.n.01', 'synonyms': ['tartan', 'plaid'], 'id': 1065, 'def': 'a cloth having a crisscross design', 'name': 'tartan'}, {'frequency': 'c', 'synset': 'tassel.n.01', 'synonyms': ['tassel'], 'id': 1066, 'def': 'adornment consisting of a bunch of cords fastened at one end', 'name': 'tassel'}, {'frequency': 'c', 'synset': 'tea_bag.n.01', 'synonyms': ['tea_bag'], 'id': 1067, 'def': 'a measured amount of tea in a bag for an individual serving of tea', 'name': 'tea_bag'}, {'frequency': 'c', 'synset': 'teacup.n.02', 'synonyms': ['teacup'], 'id': 1068, 'def': 'a cup from which tea is drunk', 'name': 'teacup'}, {'frequency': 'c', 'synset': 'teakettle.n.01', 'synonyms': ['teakettle'], 'id': 1069, 'def': 'kettle for boiling water to make tea', 'name': 'teakettle'}, {'frequency': 'f', 'synset': 'teapot.n.01', 'synonyms': ['teapot'], 'id': 1070, 'def': 'pot for brewing tea; usually has a spout and handle', 'name': 'teapot'}, {'frequency': 'f', 'synset': 'teddy.n.01', 'synonyms': ['teddy_bear'], 'id': 1071, 'def': "plaything consisting of a child's toy bear (usually plush and stuffed with soft materials)", 'name': 'teddy_bear'}, {'frequency': 'f', 'synset': 'telephone.n.01', 'synonyms': ['telephone', 'phone', 'telephone_set'], 'id': 1072, 'def': 'electronic device for communicating by voice over long distances (includes wired and wireless/cell phones)', 'name': 'telephone'}, {'frequency': 'c', 'synset': 'telephone_booth.n.01', 'synonyms': ['telephone_booth', 'phone_booth', 'call_box', 'telephone_box', 'telephone_kiosk'], 'id': 1073, 'def': 'booth for using a telephone', 'name': 'telephone_booth'}, {'frequency': 'f', 'synset': 'telephone_pole.n.01', 'synonyms': ['telephone_pole', 'telegraph_pole', 'telegraph_post'], 'id': 1074, 'def': 'tall pole supporting telephone wires', 'name': 'telephone_pole'}, {'frequency': 'r', 'synset': 'telephoto_lens.n.01', 'synonyms': ['telephoto_lens', 'zoom_lens'], 'id': 1075, 'def': 'a camera lens that magnifies the image', 'name': 'telephoto_lens'}, {'frequency': 'c', 'synset': 'television_camera.n.01', 'synonyms': ['television_camera', 'tv_camera'], 'id': 1076, 'def': 'television equipment for capturing and recording video', 'name': 'television_camera'}, {'frequency': 'f', 'synset': 'television_receiver.n.01', 'synonyms': ['television_set', 'tv', 'tv_set'], 'id': 1077, 'def': 'an electronic device that receives television signals and displays them on a screen', 'name': 'television_set'}, {'frequency': 'f', 'synset': 'tennis_ball.n.01', 'synonyms': ['tennis_ball'], 'id': 1078, 'def': 'ball about the size of a fist used in playing tennis', 'name': 'tennis_ball'}, {'frequency': 'f', 'synset': 'tennis_racket.n.01', 'synonyms': ['tennis_racket'], 'id': 1079, 'def': 'a racket used to play tennis', 'name': 'tennis_racket'}, {'frequency': 'r', 'synset': 'tequila.n.01', 'synonyms': ['tequila'], 'id': 1080, 'def': 'Mexican liquor made from fermented juices of an agave plant', 'name': 'tequila'}, {'frequency': 'c', 'synset': 'thermometer.n.01', 'synonyms': ['thermometer'], 'id': 1081, 'def': 'measuring instrument for measuring temperature', 'name': 'thermometer'}, {'frequency': 'c', 'synset': 'thermos.n.01', 'synonyms': ['thermos_bottle'], 'id': 1082, 'def': 'vacuum flask that preserves temperature of hot or cold drinks', 'name': 'thermos_bottle'}, {'frequency': 'f', 'synset': 'thermostat.n.01', 'synonyms': ['thermostat'], 'id': 1083, 'def': 'a regulator for automatically regulating temperature by starting or stopping the supply of heat', 'name': 'thermostat'}, {'frequency': 'r', 'synset': 'thimble.n.02', 'synonyms': ['thimble'], 'id': 1084, 'def': 'a small metal cap to protect the finger while sewing; can be used as a small container', 'name': 'thimble'}, {'frequency': 'c', 'synset': 'thread.n.01', 'synonyms': ['thread', 'yarn'], 'id': 1085, 'def': 'a fine cord of twisted fibers (of cotton or silk or wool or nylon etc.) used in sewing and weaving', 'name': 'thread'}, {'frequency': 'c', 'synset': 'thumbtack.n.01', 'synonyms': ['thumbtack', 'drawing_pin', 'pushpin'], 'id': 1086, 'def': 'a tack for attaching papers to a bulletin board or drawing board', 'name': 'thumbtack'}, {'frequency': 'c', 'synset': 'tiara.n.01', 'synonyms': ['tiara'], 'id': 1087, 'def': 'a jeweled headdress worn by women on formal occasions', 'name': 'tiara'}, {'frequency': 'c', 'synset': 'tiger.n.02', 'synonyms': ['tiger'], 'id': 1088, 'def': 'large feline of forests in most of Asia having a tawny coat with black stripes', 'name': 'tiger'}, {'frequency': 'c', 'synset': 'tights.n.01', 'synonyms': ['tights_(clothing)', 'leotards'], 'id': 1089, 'def': 'skintight knit hose covering the body from the waist to the feet worn by acrobats and dancers and as stockings by women and girls', 'name': 'tights_(clothing)'}, {'frequency': 'c', 'synset': 'timer.n.01', 'synonyms': ['timer', 'stopwatch'], 'id': 1090, 'def': 'a timepiece that measures a time interval and signals its end', 'name': 'timer'}, {'frequency': 'f', 'synset': 'tinfoil.n.01', 'synonyms': ['tinfoil'], 'id': 1091, 'def': 'foil made of tin or an alloy of tin and lead', 'name': 'tinfoil'}, {'frequency': 'c', 'synset': 'tinsel.n.01', 'synonyms': ['tinsel'], 'id': 1092, 'def': 'a showy decoration that is basically valueless', 'name': 'tinsel'}, {'frequency': 'f', 'synset': 'tissue.n.02', 'synonyms': ['tissue_paper'], 'id': 1093, 'def': 'a soft thin (usually translucent) paper', 'name': 'tissue_paper'}, {'frequency': 'c', 'synset': 'toast.n.01', 'synonyms': ['toast_(food)'], 'id': 1094, 'def': 'slice of bread that has been toasted', 'name': 'toast_(food)'}, {'frequency': 'f', 'synset': 'toaster.n.02', 'synonyms': ['toaster'], 'id': 1095, 'def': 'a kitchen appliance (usually electric) for toasting bread', 'name': 'toaster'}, {'frequency': 'f', 'synset': 'toaster_oven.n.01', 'synonyms': ['toaster_oven'], 'id': 1096, 'def': 'kitchen appliance consisting of a small electric oven for toasting or warming food', 'name': 'toaster_oven'}, {'frequency': 'f', 'synset': 'toilet.n.02', 'synonyms': ['toilet'], 'id': 1097, 'def': 'a plumbing fixture for defecation and urination', 'name': 'toilet'}, {'frequency': 'f', 'synset': 'toilet_tissue.n.01', 'synonyms': ['toilet_tissue', 'toilet_paper', 'bathroom_tissue'], 'id': 1098, 'def': 'a soft thin absorbent paper for use in toilets', 'name': 'toilet_tissue'}, {'frequency': 'f', 'synset': 'tomato.n.01', 'synonyms': ['tomato'], 'id': 1099, 'def': 'mildly acid red or yellow pulpy fruit eaten as a vegetable', 'name': 'tomato'}, {'frequency': 'f', 'synset': 'tongs.n.01', 'synonyms': ['tongs'], 'id': 1100, 'def': 'any of various devices for taking hold of objects; usually have two hinged legs with handles above and pointed hooks below', 'name': 'tongs'}, {'frequency': 'c', 'synset': 'toolbox.n.01', 'synonyms': ['toolbox'], 'id': 1101, 'def': 'a box or chest or cabinet for holding hand tools', 'name': 'toolbox'}, {'frequency': 'f', 'synset': 'toothbrush.n.01', 'synonyms': ['toothbrush'], 'id': 1102, 'def': 'small brush; has long handle; used to clean teeth', 'name': 'toothbrush'}, {'frequency': 'f', 'synset': 'toothpaste.n.01', 'synonyms': ['toothpaste'], 'id': 1103, 'def': 'a dentifrice in the form of a paste', 'name': 'toothpaste'}, {'frequency': 'f', 'synset': 'toothpick.n.01', 'synonyms': ['toothpick'], 'id': 1104, 'def': 'pick consisting of a small strip of wood or plastic; used to pick food from between the teeth', 'name': 'toothpick'}, {'frequency': 'f', 'synset': 'top.n.09', 'synonyms': ['cover'], 'id': 1105, 'def': 'covering for a hole (especially a hole in the top of a container)', 'name': 'cover'}, {'frequency': 'c', 'synset': 'tortilla.n.01', 'synonyms': ['tortilla'], 'id': 1106, 'def': 'thin unleavened pancake made from cornmeal or wheat flour', 'name': 'tortilla'}, {'frequency': 'c', 'synset': 'tow_truck.n.01', 'synonyms': ['tow_truck'], 'id': 1107, 'def': 'a truck equipped to hoist and pull wrecked cars (or to remove cars from no-parking zones)', 'name': 'tow_truck'}, {'frequency': 'f', 'synset': 'towel.n.01', 'synonyms': ['towel'], 'id': 1108, 'def': 'a rectangular piece of absorbent cloth (or paper) for drying or wiping', 'name': 'towel'}, {'frequency': 'f', 'synset': 'towel_rack.n.01', 'synonyms': ['towel_rack', 'towel_rail', 'towel_bar'], 'id': 1109, 'def': 'a rack consisting of one or more bars on which towels can be hung', 'name': 'towel_rack'}, {'frequency': 'f', 'synset': 'toy.n.03', 'synonyms': ['toy'], 'id': 1110, 'def': 'a device regarded as providing amusement', 'name': 'toy'}, {'frequency': 'c', 'synset': 'tractor.n.01', 'synonyms': ['tractor_(farm_equipment)'], 'id': 1111, 'def': 'a wheeled vehicle with large wheels; used in farming and other applications', 'name': 'tractor_(farm_equipment)'}, {'frequency': 'f', 'synset': 'traffic_light.n.01', 'synonyms': ['traffic_light'], 'id': 1112, 'def': 'a device to control vehicle traffic often consisting of three or more lights', 'name': 'traffic_light'}, {'frequency': 'c', 'synset': 'trail_bike.n.01', 'synonyms': ['dirt_bike'], 'id': 1113, 'def': 'a lightweight motorcycle equipped with rugged tires and suspension for off-road use', 'name': 'dirt_bike'}, {'frequency': 'f', 'synset': 'trailer_truck.n.01', 'synonyms': ['trailer_truck', 'tractor_trailer', 'trucking_rig', 'articulated_lorry', 'semi_truck'], 'id': 1114, 'def': 'a truck consisting of a tractor and trailer together', 'name': 'trailer_truck'}, {'frequency': 'f', 'synset': 'train.n.01', 'synonyms': ['train_(railroad_vehicle)', 'railroad_train'], 'id': 1115, 'def': 'public or private transport provided by a line of railway cars coupled together and drawn by a locomotive', 'name': 'train_(railroad_vehicle)'}, {'frequency': 'r', 'synset': 'trampoline.n.01', 'synonyms': ['trampoline'], 'id': 1116, 'def': 'gymnastic apparatus consisting of a strong canvas sheet attached with springs to a metal frame', 'name': 'trampoline'}, {'frequency': 'f', 'synset': 'tray.n.01', 'synonyms': ['tray'], 'id': 1117, 'def': 'an open receptacle for holding or displaying or serving articles or food', 'name': 'tray'}, {'frequency': 'r', 'synset': 'trench_coat.n.01', 'synonyms': ['trench_coat'], 'id': 1118, 'def': 'a military style raincoat; belted with deep pockets', 'name': 'trench_coat'}, {'frequency': 'r', 'synset': 'triangle.n.05', 'synonyms': ['triangle_(musical_instrument)'], 'id': 1119, 'def': 'a percussion instrument consisting of a metal bar bent in the shape of an open triangle', 'name': 'triangle_(musical_instrument)'}, {'frequency': 'c', 'synset': 'tricycle.n.01', 'synonyms': ['tricycle'], 'id': 1120, 'def': 'a vehicle with three wheels that is moved by foot pedals', 'name': 'tricycle'}, {'frequency': 'f', 'synset': 'tripod.n.01', 'synonyms': ['tripod'], 'id': 1121, 'def': 'a three-legged rack used for support', 'name': 'tripod'}, {'frequency': 'f', 'synset': 'trouser.n.01', 'synonyms': ['trousers', 'pants_(clothing)'], 'id': 1122, 'def': 'a garment extending from the waist to the knee or ankle, covering each leg separately', 'name': 'trousers'}, {'frequency': 'f', 'synset': 'truck.n.01', 'synonyms': ['truck'], 'id': 1123, 'def': 'an automotive vehicle suitable for hauling', 'name': 'truck'}, {'frequency': 'r', 'synset': 'truffle.n.03', 'synonyms': ['truffle_(chocolate)', 'chocolate_truffle'], 'id': 1124, 'def': 'creamy chocolate candy', 'name': 'truffle_(chocolate)'}, {'frequency': 'c', 'synset': 'trunk.n.02', 'synonyms': ['trunk'], 'id': 1125, 'def': 'luggage consisting of a large strong case used when traveling or for storage', 'name': 'trunk'}, {'frequency': 'r', 'synset': 'tub.n.02', 'synonyms': ['vat'], 'id': 1126, 'def': 'a large vessel for holding or storing liquids', 'name': 'vat'}, {'frequency': 'c', 'synset': 'turban.n.01', 'synonyms': ['turban'], 'id': 1127, 'def': 'a traditional headdress consisting of a long scarf wrapped around the head', 'name': 'turban'}, {'frequency': 'c', 'synset': 'turkey.n.04', 'synonyms': ['turkey_(food)'], 'id': 1128, 'def': 'flesh of large domesticated fowl usually roasted', 'name': 'turkey_(food)'}, {'frequency': 'r', 'synset': 'turnip.n.01', 'synonyms': ['turnip'], 'id': 1129, 'def': 'widely cultivated plant having a large fleshy edible white or yellow root', 'name': 'turnip'}, {'frequency': 'c', 'synset': 'turtle.n.02', 'synonyms': ['turtle'], 'id': 1130, 'def': 'any of various aquatic and land reptiles having a bony shell and flipper-like limbs for swimming', 'name': 'turtle'}, {'frequency': 'c', 'synset': 'turtleneck.n.01', 'synonyms': ['turtleneck_(clothing)', 'polo-neck'], 'id': 1131, 'def': 'a sweater or jersey with a high close-fitting collar', 'name': 'turtleneck_(clothing)'}, {'frequency': 'c', 'synset': 'typewriter.n.01', 'synonyms': ['typewriter'], 'id': 1132, 'def': 'hand-operated character printer for printing written messages one character at a time', 'name': 'typewriter'}, {'frequency': 'f', 'synset': 'umbrella.n.01', 'synonyms': ['umbrella'], 'id': 1133, 'def': 'a lightweight handheld collapsible canopy', 'name': 'umbrella'}, {'frequency': 'f', 'synset': 'underwear.n.01', 'synonyms': ['underwear', 'underclothes', 'underclothing', 'underpants'], 'id': 1134, 'def': 'undergarment worn next to the skin and under the outer garments', 'name': 'underwear'}, {'frequency': 'r', 'synset': 'unicycle.n.01', 'synonyms': ['unicycle'], 'id': 1135, 'def': 'a vehicle with a single wheel that is driven by pedals', 'name': 'unicycle'}, {'frequency': 'f', 'synset': 'urinal.n.01', 'synonyms': ['urinal'], 'id': 1136, 'def': 'a plumbing fixture (usually attached to the wall) used by men to urinate', 'name': 'urinal'}, {'frequency': 'c', 'synset': 'urn.n.01', 'synonyms': ['urn'], 'id': 1137, 'def': 'a large vase that usually has a pedestal or feet', 'name': 'urn'}, {'frequency': 'c', 'synset': 'vacuum.n.04', 'synonyms': ['vacuum_cleaner'], 'id': 1138, 'def': 'an electrical home appliance that cleans by suction', 'name': 'vacuum_cleaner'}, {'frequency': 'f', 'synset': 'vase.n.01', 'synonyms': ['vase'], 'id': 1139, 'def': 'an open jar of glass or porcelain used as an ornament or to hold flowers', 'name': 'vase'}, {'frequency': 'c', 'synset': 'vending_machine.n.01', 'synonyms': ['vending_machine'], 'id': 1140, 'def': 'a slot machine for selling goods', 'name': 'vending_machine'}, {'frequency': 'f', 'synset': 'vent.n.01', 'synonyms': ['vent', 'blowhole', 'air_vent'], 'id': 1141, 'def': 'a hole for the escape of gas or air', 'name': 'vent'}, {'frequency': 'f', 'synset': 'vest.n.01', 'synonyms': ['vest', 'waistcoat'], 'id': 1142, 'def': "a man's sleeveless garment worn underneath a coat", 'name': 'vest'}, {'frequency': 'c', 'synset': 'videotape.n.01', 'synonyms': ['videotape'], 'id': 1143, 'def': 'a video recording made on magnetic tape', 'name': 'videotape'}, {'frequency': 'r', 'synset': 'vinegar.n.01', 'synonyms': ['vinegar'], 'id': 1144, 'def': 'sour-tasting liquid produced usually by oxidation of the alcohol in wine or cider and used as a condiment or food preservative', 'name': 'vinegar'}, {'frequency': 'r', 'synset': 'violin.n.01', 'synonyms': ['violin', 'fiddle'], 'id': 1145, 'def': 'bowed stringed instrument that is the highest member of the violin family', 'name': 'violin'}, {'frequency': 'r', 'synset': 'vodka.n.01', 'synonyms': ['vodka'], 'id': 1146, 'def': 'unaged colorless liquor originating in Russia', 'name': 'vodka'}, {'frequency': 'c', 'synset': 'volleyball.n.02', 'synonyms': ['volleyball'], 'id': 1147, 'def': 'an inflated ball used in playing volleyball', 'name': 'volleyball'}, {'frequency': 'r', 'synset': 'vulture.n.01', 'synonyms': ['vulture'], 'id': 1148, 'def': 'any of various large birds of prey having naked heads and weak claws and feeding chiefly on carrion', 'name': 'vulture'}, {'frequency': 'c', 'synset': 'waffle.n.01', 'synonyms': ['waffle'], 'id': 1149, 'def': 'pancake batter baked in a waffle iron', 'name': 'waffle'}, {'frequency': 'r', 'synset': 'waffle_iron.n.01', 'synonyms': ['waffle_iron'], 'id': 1150, 'def': 'a kitchen appliance for baking waffles', 'name': 'waffle_iron'}, {'frequency': 'c', 'synset': 'wagon.n.01', 'synonyms': ['wagon'], 'id': 1151, 'def': 'any of various kinds of wheeled vehicles drawn by an animal or a tractor', 'name': 'wagon'}, {'frequency': 'c', 'synset': 'wagon_wheel.n.01', 'synonyms': ['wagon_wheel'], 'id': 1152, 'def': 'a wheel of a wagon', 'name': 'wagon_wheel'}, {'frequency': 'c', 'synset': 'walking_stick.n.01', 'synonyms': ['walking_stick'], 'id': 1153, 'def': 'a stick carried in the hand for support in walking', 'name': 'walking_stick'}, {'frequency': 'c', 'synset': 'wall_clock.n.01', 'synonyms': ['wall_clock'], 'id': 1154, 'def': 'a clock mounted on a wall', 'name': 'wall_clock'}, {'frequency': 'f', 'synset': 'wall_socket.n.01', 'synonyms': ['wall_socket', 'wall_plug', 'electric_outlet', 'electrical_outlet', 'outlet', 'electric_receptacle'], 'id': 1155, 'def': 'receptacle providing a place in a wiring system where current can be taken to run electrical devices', 'name': 'wall_socket'}, {'frequency': 'f', 'synset': 'wallet.n.01', 'synonyms': ['wallet', 'billfold'], 'id': 1156, 'def': 'a pocket-size case for holding papers and paper money', 'name': 'wallet'}, {'frequency': 'r', 'synset': 'walrus.n.01', 'synonyms': ['walrus'], 'id': 1157, 'def': 'either of two large northern marine mammals having ivory tusks and tough hide over thick blubber', 'name': 'walrus'}, {'frequency': 'r', 'synset': 'wardrobe.n.01', 'synonyms': ['wardrobe'], 'id': 1158, 'def': 'a tall piece of furniture that provides storage space for clothes; has a door and rails or hooks for hanging clothes', 'name': 'wardrobe'}, {'frequency': 'r', 'synset': 'washbasin.n.01', 'synonyms': ['washbasin', 'basin_(for_washing)', 'washbowl', 'washstand', 'handbasin'], 'id': 1159, 'def': 'a bathroom sink that is permanently installed and connected to a water supply and drainpipe; where you can wash your hands and face', 'name': 'washbasin'}, {'frequency': 'c', 'synset': 'washer.n.03', 'synonyms': ['automatic_washer', 'washing_machine'], 'id': 1160, 'def': 'a home appliance for washing clothes and linens automatically', 'name': 'automatic_washer'}, {'frequency': 'f', 'synset': 'watch.n.01', 'synonyms': ['watch', 'wristwatch'], 'id': 1161, 'def': 'a small, portable timepiece', 'name': 'watch'}, {'frequency': 'f', 'synset': 'water_bottle.n.01', 'synonyms': ['water_bottle'], 'id': 1162, 'def': 'a bottle for holding water', 'name': 'water_bottle'}, {'frequency': 'c', 'synset': 'water_cooler.n.01', 'synonyms': ['water_cooler'], 'id': 1163, 'def': 'a device for cooling and dispensing drinking water', 'name': 'water_cooler'}, {'frequency': 'c', 'synset': 'water_faucet.n.01', 'synonyms': ['water_faucet', 'water_tap', 'tap_(water_faucet)'], 'id': 1164, 'def': 'a faucet for drawing water from a pipe or cask', 'name': 'water_faucet'}, {'frequency': 'r', 'synset': 'water_heater.n.01', 'synonyms': ['water_heater', 'hot-water_heater'], 'id': 1165, 'def': 'a heater and storage tank to supply heated water', 'name': 'water_heater'}, {'frequency': 'c', 'synset': 'water_jug.n.01', 'synonyms': ['water_jug'], 'id': 1166, 'def': 'a jug that holds water', 'name': 'water_jug'}, {'frequency': 'r', 'synset': 'water_pistol.n.01', 'synonyms': ['water_gun', 'squirt_gun'], 'id': 1167, 'def': 'plaything consisting of a toy pistol that squirts water', 'name': 'water_gun'}, {'frequency': 'c', 'synset': 'water_scooter.n.01', 'synonyms': ['water_scooter', 'sea_scooter', 'jet_ski'], 'id': 1168, 'def': 'a motorboat resembling a motor scooter (NOT A SURFBOARD OR WATER SKI)', 'name': 'water_scooter'}, {'frequency': 'c', 'synset': 'water_ski.n.01', 'synonyms': ['water_ski'], 'id': 1169, 'def': 'broad ski for skimming over water towed by a speedboat (DO NOT MARK WATER)', 'name': 'water_ski'}, {'frequency': 'c', 'synset': 'water_tower.n.01', 'synonyms': ['water_tower'], 'id': 1170, 'def': 'a large reservoir for water', 'name': 'water_tower'}, {'frequency': 'c', 'synset': 'watering_can.n.01', 'synonyms': ['watering_can'], 'id': 1171, 'def': 'a container with a handle and a spout with a perforated nozzle; used to sprinkle water over plants', 'name': 'watering_can'}, {'frequency': 'f', 'synset': 'watermelon.n.02', 'synonyms': ['watermelon'], 'id': 1172, 'def': 'large oblong or roundish melon with a hard green rind and sweet watery red or occasionally yellowish pulp', 'name': 'watermelon'}, {'frequency': 'f', 'synset': 'weathervane.n.01', 'synonyms': ['weathervane', 'vane_(weathervane)', 'wind_vane'], 'id': 1173, 'def': 'mechanical device attached to an elevated structure; rotates freely to show the direction of the wind', 'name': 'weathervane'}, {'frequency': 'c', 'synset': 'webcam.n.01', 'synonyms': ['webcam'], 'id': 1174, 'def': 'a digital camera designed to take digital photographs and transmit them over the internet', 'name': 'webcam'}, {'frequency': 'c', 'synset': 'wedding_cake.n.01', 'synonyms': ['wedding_cake', 'bridecake'], 'id': 1175, 'def': 'a rich cake with two or more tiers and covered with frosting and decorations; served at a wedding reception', 'name': 'wedding_cake'}, {'frequency': 'c', 'synset': 'wedding_ring.n.01', 'synonyms': ['wedding_ring', 'wedding_band'], 'id': 1176, 'def': 'a ring given to the bride and/or groom at the wedding', 'name': 'wedding_ring'}, {'frequency': 'f', 'synset': 'wet_suit.n.01', 'synonyms': ['wet_suit'], 'id': 1177, 'def': 'a close-fitting garment made of a permeable material; worn in cold water to retain body heat', 'name': 'wet_suit'}, {'frequency': 'f', 'synset': 'wheel.n.01', 'synonyms': ['wheel'], 'id': 1178, 'def': 'a circular frame with spokes (or a solid disc) that can rotate on a shaft or axle', 'name': 'wheel'}, {'frequency': 'c', 'synset': 'wheelchair.n.01', 'synonyms': ['wheelchair'], 'id': 1179, 'def': 'a movable chair mounted on large wheels', 'name': 'wheelchair'}, {'frequency': 'c', 'synset': 'whipped_cream.n.01', 'synonyms': ['whipped_cream'], 'id': 1180, 'def': 'cream that has been beaten until light and fluffy', 'name': 'whipped_cream'}, {'frequency': 'c', 'synset': 'whistle.n.03', 'synonyms': ['whistle'], 'id': 1181, 'def': 'a small wind instrument that produces a whistling sound by blowing into it', 'name': 'whistle'}, {'frequency': 'c', 'synset': 'wig.n.01', 'synonyms': ['wig'], 'id': 1182, 'def': 'hairpiece covering the head and made of real or synthetic hair', 'name': 'wig'}, {'frequency': 'c', 'synset': 'wind_chime.n.01', 'synonyms': ['wind_chime'], 'id': 1183, 'def': 'a decorative arrangement of pieces of metal or glass or pottery that hang together loosely so the wind can cause them to tinkle', 'name': 'wind_chime'}, {'frequency': 'c', 'synset': 'windmill.n.01', 'synonyms': ['windmill'], 'id': 1184, 'def': 'A mill or turbine that is powered by wind', 'name': 'windmill'}, {'frequency': 'c', 'synset': 'window_box.n.01', 'synonyms': ['window_box_(for_plants)'], 'id': 1185, 'def': 'a container for growing plants on a windowsill', 'name': 'window_box_(for_plants)'}, {'frequency': 'f', 'synset': 'windshield_wiper.n.01', 'synonyms': ['windshield_wiper', 'windscreen_wiper', 'wiper_(for_windshield/screen)'], 'id': 1186, 'def': 'a mechanical device that cleans the windshield', 'name': 'windshield_wiper'}, {'frequency': 'c', 'synset': 'windsock.n.01', 'synonyms': ['windsock', 'air_sock', 'air-sleeve', 'wind_sleeve', 'wind_cone'], 'id': 1187, 'def': 'a truncated cloth cone mounted on a mast/pole; shows wind direction', 'name': 'windsock'}, {'frequency': 'f', 'synset': 'wine_bottle.n.01', 'synonyms': ['wine_bottle'], 'id': 1188, 'def': 'a bottle for holding wine', 'name': 'wine_bottle'}, {'frequency': 'c', 'synset': 'wine_bucket.n.01', 'synonyms': ['wine_bucket', 'wine_cooler'], 'id': 1189, 'def': 'a bucket of ice used to chill a bottle of wine', 'name': 'wine_bucket'}, {'frequency': 'f', 'synset': 'wineglass.n.01', 'synonyms': ['wineglass'], 'id': 1190, 'def': 'a glass that has a stem and in which wine is served', 'name': 'wineglass'}, {'frequency': 'f', 'synset': 'winker.n.02', 'synonyms': ['blinder_(for_horses)'], 'id': 1191, 'def': 'blinds that prevent a horse from seeing something on either side', 'name': 'blinder_(for_horses)'}, {'frequency': 'c', 'synset': 'wok.n.01', 'synonyms': ['wok'], 'id': 1192, 'def': 'pan with a convex bottom; used for frying in Chinese cooking', 'name': 'wok'}, {'frequency': 'r', 'synset': 'wolf.n.01', 'synonyms': ['wolf'], 'id': 1193, 'def': 'a wild carnivorous mammal of the dog family, living and hunting in packs', 'name': 'wolf'}, {'frequency': 'c', 'synset': 'wooden_spoon.n.02', 'synonyms': ['wooden_spoon'], 'id': 1194, 'def': 'a spoon made of wood', 'name': 'wooden_spoon'}, {'frequency': 'c', 'synset': 'wreath.n.01', 'synonyms': ['wreath'], 'id': 1195, 'def': 'an arrangement of flowers, leaves, or stems fastened in a ring', 'name': 'wreath'}, {'frequency': 'c', 'synset': 'wrench.n.03', 'synonyms': ['wrench', 'spanner'], 'id': 1196, 'def': 'a hand tool that is used to hold or twist a nut or bolt', 'name': 'wrench'}, {'frequency': 'f', 'synset': 'wristband.n.01', 'synonyms': ['wristband'], 'id': 1197, 'def': 'band consisting of a part of a sleeve that covers the wrist', 'name': 'wristband'}, {'frequency': 'f', 'synset': 'wristlet.n.01', 'synonyms': ['wristlet', 'wrist_band'], 'id': 1198, 'def': 'a band or bracelet worn around the wrist', 'name': 'wristlet'}, {'frequency': 'c', 'synset': 'yacht.n.01', 'synonyms': ['yacht'], 'id': 1199, 'def': 'an expensive vessel propelled by sail or power and used for cruising or racing', 'name': 'yacht'}, {'frequency': 'c', 'synset': 'yogurt.n.01', 'synonyms': ['yogurt', 'yoghurt', 'yoghourt'], 'id': 1200, 'def': 'a custard-like food made from curdled milk', 'name': 'yogurt'}, {'frequency': 'c', 'synset': 'yoke.n.07', 'synonyms': ['yoke_(animal_equipment)'], 'id': 1201, 'def': 'gear joining two animals at the neck; NOT egg yolk', 'name': 'yoke_(animal_equipment)'}, {'frequency': 'f', 'synset': 'zebra.n.01', 'synonyms': ['zebra'], 'id': 1202, 'def': 'any of several fleet black-and-white striped African equines', 'name': 'zebra'}, {'frequency': 'c', 'synset': 'zucchini.n.02', 'synonyms': ['zucchini', 'courgette'], 'id': 1203, 'def': 'small cucumber-shaped vegetable marrow; typically dark green', 'name': 'zucchini'}] # noqa -# fmt: on diff --git a/spaces/carlosalonso/Detection-video/carpeta_deteccion/detectron2/evaluation/cityscapes_evaluation.py b/spaces/carlosalonso/Detection-video/carpeta_deteccion/detectron2/evaluation/cityscapes_evaluation.py deleted file mode 100644 index 9cc7888f0f88ed9b44eae942353a9f4dd4b8782a..0000000000000000000000000000000000000000 --- a/spaces/carlosalonso/Detection-video/carpeta_deteccion/detectron2/evaluation/cityscapes_evaluation.py +++ /dev/null @@ -1,197 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. -import glob -import logging -import numpy as np -import os -import tempfile -from collections import OrderedDict -import torch -from PIL import Image - -from detectron2.data import MetadataCatalog -from detectron2.utils import comm -from detectron2.utils.file_io import PathManager - -from .evaluator import DatasetEvaluator - - -class CityscapesEvaluator(DatasetEvaluator): - """ - Base class for evaluation using cityscapes API. - """ - - def __init__(self, dataset_name): - """ - Args: - dataset_name (str): the name of the dataset. - It must have the following metadata associated with it: - "thing_classes", "gt_dir". - """ - self._metadata = MetadataCatalog.get(dataset_name) - self._cpu_device = torch.device("cpu") - self._logger = logging.getLogger(__name__) - - def reset(self): - self._working_dir = tempfile.TemporaryDirectory(prefix="cityscapes_eval_") - self._temp_dir = self._working_dir.name - # All workers will write to the same results directory - # TODO this does not work in distributed training - assert ( - comm.get_local_size() == comm.get_world_size() - ), "CityscapesEvaluator currently do not work with multiple machines." - self._temp_dir = comm.all_gather(self._temp_dir)[0] - if self._temp_dir != self._working_dir.name: - self._working_dir.cleanup() - self._logger.info( - "Writing cityscapes results to temporary directory {} ...".format(self._temp_dir) - ) - - -class CityscapesInstanceEvaluator(CityscapesEvaluator): - """ - Evaluate instance segmentation results on cityscapes dataset using cityscapes API. - - Note: - * It does not work in multi-machine distributed training. - * It contains a synchronization, therefore has to be used on all ranks. - * Only the main process runs evaluation. - """ - - def process(self, inputs, outputs): - from cityscapesscripts.helpers.labels import name2label - - for input, output in zip(inputs, outputs): - file_name = input["file_name"] - basename = os.path.splitext(os.path.basename(file_name))[0] - pred_txt = os.path.join(self._temp_dir, basename + "_pred.txt") - - if "instances" in output: - output = output["instances"].to(self._cpu_device) - num_instances = len(output) - with open(pred_txt, "w") as fout: - for i in range(num_instances): - pred_class = output.pred_classes[i] - classes = self._metadata.thing_classes[pred_class] - class_id = name2label[classes].id - score = output.scores[i] - mask = output.pred_masks[i].numpy().astype("uint8") - png_filename = os.path.join( - self._temp_dir, basename + "_{}_{}.png".format(i, classes) - ) - - Image.fromarray(mask * 255).save(png_filename) - fout.write( - "{} {} {}\n".format(os.path.basename(png_filename), class_id, score) - ) - else: - # Cityscapes requires a prediction file for every ground truth image. - with open(pred_txt, "w") as fout: - pass - - def evaluate(self): - """ - Returns: - dict: has a key "segm", whose value is a dict of "AP" and "AP50". - """ - comm.synchronize() - if comm.get_rank() > 0: - return - import cityscapesscripts.evaluation.evalInstanceLevelSemanticLabeling as cityscapes_eval - - self._logger.info("Evaluating results under {} ...".format(self._temp_dir)) - - # set some global states in cityscapes evaluation API, before evaluating - cityscapes_eval.args.predictionPath = os.path.abspath(self._temp_dir) - cityscapes_eval.args.predictionWalk = None - cityscapes_eval.args.JSONOutput = False - cityscapes_eval.args.colorized = False - cityscapes_eval.args.gtInstancesFile = os.path.join(self._temp_dir, "gtInstances.json") - - # These lines are adopted from - # https://github.com/mcordts/cityscapesScripts/blob/master/cityscapesscripts/evaluation/evalInstanceLevelSemanticLabeling.py # noqa - gt_dir = PathManager.get_local_path(self._metadata.gt_dir) - groundTruthImgList = glob.glob(os.path.join(gt_dir, "*", "*_gtFine_instanceIds.png")) - assert len( - groundTruthImgList - ), "Cannot find any ground truth images to use for evaluation. Searched for: {}".format( - cityscapes_eval.args.groundTruthSearch - ) - predictionImgList = [] - for gt in groundTruthImgList: - predictionImgList.append(cityscapes_eval.getPrediction(gt, cityscapes_eval.args)) - results = cityscapes_eval.evaluateImgLists( - predictionImgList, groundTruthImgList, cityscapes_eval.args - )["averages"] - - ret = OrderedDict() - ret["segm"] = {"AP": results["allAp"] * 100, "AP50": results["allAp50%"] * 100} - self._working_dir.cleanup() - return ret - - -class CityscapesSemSegEvaluator(CityscapesEvaluator): - """ - Evaluate semantic segmentation results on cityscapes dataset using cityscapes API. - - Note: - * It does not work in multi-machine distributed training. - * It contains a synchronization, therefore has to be used on all ranks. - * Only the main process runs evaluation. - """ - - def process(self, inputs, outputs): - from cityscapesscripts.helpers.labels import trainId2label - - for input, output in zip(inputs, outputs): - file_name = input["file_name"] - basename = os.path.splitext(os.path.basename(file_name))[0] - pred_filename = os.path.join(self._temp_dir, basename + "_pred.png") - - output = output["sem_seg"].argmax(dim=0).to(self._cpu_device).numpy() - pred = 255 * np.ones(output.shape, dtype=np.uint8) - for train_id, label in trainId2label.items(): - if label.ignoreInEval: - continue - pred[output == train_id] = label.id - Image.fromarray(pred).save(pred_filename) - - def evaluate(self): - comm.synchronize() - if comm.get_rank() > 0: - return - # Load the Cityscapes eval script *after* setting the required env var, - # since the script reads CITYSCAPES_DATASET into global variables at load time. - import cityscapesscripts.evaluation.evalPixelLevelSemanticLabeling as cityscapes_eval - - self._logger.info("Evaluating results under {} ...".format(self._temp_dir)) - - # set some global states in cityscapes evaluation API, before evaluating - cityscapes_eval.args.predictionPath = os.path.abspath(self._temp_dir) - cityscapes_eval.args.predictionWalk = None - cityscapes_eval.args.JSONOutput = False - cityscapes_eval.args.colorized = False - - # These lines are adopted from - # https://github.com/mcordts/cityscapesScripts/blob/master/cityscapesscripts/evaluation/evalPixelLevelSemanticLabeling.py # noqa - gt_dir = PathManager.get_local_path(self._metadata.gt_dir) - groundTruthImgList = glob.glob(os.path.join(gt_dir, "*", "*_gtFine_labelIds.png")) - assert len( - groundTruthImgList - ), "Cannot find any ground truth images to use for evaluation. Searched for: {}".format( - cityscapes_eval.args.groundTruthSearch - ) - predictionImgList = [] - for gt in groundTruthImgList: - predictionImgList.append(cityscapes_eval.getPrediction(cityscapes_eval.args, gt)) - results = cityscapes_eval.evaluateImgLists( - predictionImgList, groundTruthImgList, cityscapes_eval.args - ) - ret = OrderedDict() - ret["sem_seg"] = { - "IoU": 100.0 * results["averageScoreClasses"], - "iIoU": 100.0 * results["averageScoreInstClasses"], - "IoU_sup": 100.0 * results["averageScoreCategories"], - "iIoU_sup": 100.0 * results["averageScoreInstCategories"], - } - self._working_dir.cleanup() - return ret diff --git a/spaces/carlosalonso/Detection-video/carpeta_deteccion/detectron2/modeling/poolers.py b/spaces/carlosalonso/Detection-video/carpeta_deteccion/detectron2/modeling/poolers.py deleted file mode 100644 index 3393794507c6504bf6ac1bfae7a1c80a0d81725e..0000000000000000000000000000000000000000 --- a/spaces/carlosalonso/Detection-video/carpeta_deteccion/detectron2/modeling/poolers.py +++ /dev/null @@ -1,263 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. -import math -from typing import List, Optional -import torch -from torch import nn -from torchvision.ops import RoIPool - -from detectron2.layers import ROIAlign, ROIAlignRotated, cat, nonzero_tuple, shapes_to_tensor -from detectron2.structures import Boxes -from detectron2.utils.tracing import assert_fx_safe, is_fx_tracing - -""" -To export ROIPooler to torchscript, in this file, variables that should be annotated with -`Union[List[Boxes], List[RotatedBoxes]]` are only annotated with `List[Boxes]`. - -TODO: Correct these annotations when torchscript support `Union`. -https://github.com/pytorch/pytorch/issues/41412 -""" - -__all__ = ["ROIPooler"] - - -def assign_boxes_to_levels( - box_lists: List[Boxes], - min_level: int, - max_level: int, - canonical_box_size: int, - canonical_level: int, -): - """ - Map each box in `box_lists` to a feature map level index and return the assignment - vector. - - Args: - box_lists (list[Boxes] | list[RotatedBoxes]): A list of N Boxes or N RotatedBoxes, - where N is the number of images in the batch. - min_level (int): Smallest feature map level index. The input is considered index 0, - the output of stage 1 is index 1, and so. - max_level (int): Largest feature map level index. - canonical_box_size (int): A canonical box size in pixels (sqrt(box area)). - canonical_level (int): The feature map level index on which a canonically-sized box - should be placed. - - Returns: - A tensor of length M, where M is the total number of boxes aggregated over all - N batch images. The memory layout corresponds to the concatenation of boxes - from all images. Each element is the feature map index, as an offset from - `self.min_level`, for the corresponding box (so value i means the box is at - `self.min_level + i`). - """ - box_sizes = torch.sqrt(cat([boxes.area() for boxes in box_lists])) - # Eqn.(1) in FPN paper - level_assignments = torch.floor( - canonical_level + torch.log2(box_sizes / canonical_box_size + 1e-8) - ) - # clamp level to (min, max), in case the box size is too large or too small - # for the available feature maps - level_assignments = torch.clamp(level_assignments, min=min_level, max=max_level) - return level_assignments.to(torch.int64) - min_level - - -# script the module to avoid hardcoded device type -@torch.jit.script_if_tracing -def _convert_boxes_to_pooler_format(boxes: torch.Tensor, sizes: torch.Tensor) -> torch.Tensor: - sizes = sizes.to(device=boxes.device) - indices = torch.repeat_interleave( - torch.arange(len(sizes), dtype=boxes.dtype, device=boxes.device), sizes - ) - return cat([indices[:, None], boxes], dim=1) - - -def convert_boxes_to_pooler_format(box_lists: List[Boxes]): - """ - Convert all boxes in `box_lists` to the low-level format used by ROI pooling ops - (see description under Returns). - - Args: - box_lists (list[Boxes] | list[RotatedBoxes]): - A list of N Boxes or N RotatedBoxes, where N is the number of images in the batch. - - Returns: - When input is list[Boxes]: - A tensor of shape (M, 5), where M is the total number of boxes aggregated over all - N batch images. - The 5 columns are (batch index, x0, y0, x1, y1), where batch index - is the index in [0, N) identifying which batch image the box with corners at - (x0, y0, x1, y1) comes from. - When input is list[RotatedBoxes]: - A tensor of shape (M, 6), where M is the total number of boxes aggregated over all - N batch images. - The 6 columns are (batch index, x_ctr, y_ctr, width, height, angle_degrees), - where batch index is the index in [0, N) identifying which batch image the - rotated box (x_ctr, y_ctr, width, height, angle_degrees) comes from. - """ - boxes = torch.cat([x.tensor for x in box_lists], dim=0) - # __len__ returns Tensor in tracing. - sizes = shapes_to_tensor([x.__len__() for x in box_lists]) - return _convert_boxes_to_pooler_format(boxes, sizes) - - -@torch.jit.script_if_tracing -def _create_zeros( - batch_target: Optional[torch.Tensor], - channels: int, - height: int, - width: int, - like_tensor: torch.Tensor, -) -> torch.Tensor: - batches = batch_target.shape[0] if batch_target is not None else 0 - sizes = (batches, channels, height, width) - return torch.zeros(sizes, dtype=like_tensor.dtype, device=like_tensor.device) - - -class ROIPooler(nn.Module): - """ - Region of interest feature map pooler that supports pooling from one or more - feature maps. - """ - - def __init__( - self, - output_size, - scales, - sampling_ratio, - pooler_type, - canonical_box_size=224, - canonical_level=4, - ): - """ - Args: - output_size (int, tuple[int] or list[int]): output size of the pooled region, - e.g., 14 x 14. If tuple or list is given, the length must be 2. - scales (list[float]): The scale for each low-level pooling op relative to - the input image. For a feature map with stride s relative to the input - image, scale is defined as 1/s. The stride must be power of 2. - When there are multiple scales, they must form a pyramid, i.e. they must be - a monotically decreasing geometric sequence with a factor of 1/2. - sampling_ratio (int): The `sampling_ratio` parameter for the ROIAlign op. - pooler_type (string): Name of the type of pooling operation that should be applied. - For instance, "ROIPool" or "ROIAlignV2". - canonical_box_size (int): A canonical box size in pixels (sqrt(box area)). The default - is heuristically defined as 224 pixels in the FPN paper (based on ImageNet - pre-training). - canonical_level (int): The feature map level index from which a canonically-sized box - should be placed. The default is defined as level 4 (stride=16) in the FPN paper, - i.e., a box of size 224x224 will be placed on the feature with stride=16. - The box placement for all boxes will be determined from their sizes w.r.t - canonical_box_size. For example, a box whose area is 4x that of a canonical box - should be used to pool features from feature level ``canonical_level+1``. - - Note that the actual input feature maps given to this module may not have - sufficiently many levels for the input boxes. If the boxes are too large or too - small for the input feature maps, the closest level will be used. - """ - super().__init__() - - if isinstance(output_size, int): - output_size = (output_size, output_size) - assert len(output_size) == 2 - assert isinstance(output_size[0], int) and isinstance(output_size[1], int) - self.output_size = output_size - - if pooler_type == "ROIAlign": - self.level_poolers = nn.ModuleList( - ROIAlign( - output_size, spatial_scale=scale, sampling_ratio=sampling_ratio, aligned=False - ) - for scale in scales - ) - elif pooler_type == "ROIAlignV2": - self.level_poolers = nn.ModuleList( - ROIAlign( - output_size, spatial_scale=scale, sampling_ratio=sampling_ratio, aligned=True - ) - for scale in scales - ) - elif pooler_type == "ROIPool": - self.level_poolers = nn.ModuleList( - RoIPool(output_size, spatial_scale=scale) for scale in scales - ) - elif pooler_type == "ROIAlignRotated": - self.level_poolers = nn.ModuleList( - ROIAlignRotated(output_size, spatial_scale=scale, sampling_ratio=sampling_ratio) - for scale in scales - ) - else: - raise ValueError("Unknown pooler type: {}".format(pooler_type)) - - # Map scale (defined as 1 / stride) to its feature map level under the - # assumption that stride is a power of 2. - min_level = -(math.log2(scales[0])) - max_level = -(math.log2(scales[-1])) - assert math.isclose(min_level, int(min_level)) and math.isclose( - max_level, int(max_level) - ), "Featuremap stride is not power of 2!" - self.min_level = int(min_level) - self.max_level = int(max_level) - assert ( - len(scales) == self.max_level - self.min_level + 1 - ), "[ROIPooler] Sizes of input featuremaps do not form a pyramid!" - assert 0 <= self.min_level and self.min_level <= self.max_level - self.canonical_level = canonical_level - assert canonical_box_size > 0 - self.canonical_box_size = canonical_box_size - - def forward(self, x: List[torch.Tensor], box_lists: List[Boxes]): - """ - Args: - x (list[Tensor]): A list of feature maps of NCHW shape, with scales matching those - used to construct this module. - box_lists (list[Boxes] | list[RotatedBoxes]): - A list of N Boxes or N RotatedBoxes, where N is the number of images in the batch. - The box coordinates are defined on the original image and - will be scaled by the `scales` argument of :class:`ROIPooler`. - - Returns: - Tensor: - A tensor of shape (M, C, output_size, output_size) where M is the total number of - boxes aggregated over all N batch images and C is the number of channels in `x`. - """ - num_level_assignments = len(self.level_poolers) - - if not is_fx_tracing(): - torch._assert( - isinstance(x, list) and isinstance(box_lists, list), - "Arguments to pooler must be lists", - ) - assert_fx_safe( - len(x) == num_level_assignments, - "unequal value, num_level_assignments={}, but x is list of {} Tensors".format( - num_level_assignments, len(x) - ), - ) - assert_fx_safe( - len(box_lists) == x[0].size(0), - "unequal value, x[0] batch dim 0 is {}, but box_list has length {}".format( - x[0].size(0), len(box_lists) - ), - ) - if len(box_lists) == 0: - return _create_zeros(None, x[0].shape[1], *self.output_size, x[0]) - - pooler_fmt_boxes = convert_boxes_to_pooler_format(box_lists) - - if num_level_assignments == 1: - return self.level_poolers[0](x[0], pooler_fmt_boxes) - - level_assignments = assign_boxes_to_levels( - box_lists, self.min_level, self.max_level, self.canonical_box_size, self.canonical_level - ) - - num_channels = x[0].shape[1] - output_size = self.output_size[0] - - output = _create_zeros(pooler_fmt_boxes, num_channels, output_size, output_size, x[0]) - - for level, pooler in enumerate(self.level_poolers): - inds = nonzero_tuple(level_assignments == level)[0] - pooler_fmt_boxes_level = pooler_fmt_boxes[inds] - # Use index_put_ instead of advance indexing, to avoid pytorch/issues/49852 - output.index_put_((inds,), pooler(x[level], pooler_fmt_boxes_level)) - - return output diff --git a/spaces/carlosalonso/Detection-video/carpeta_deteccion/tests/export/test_c10.py b/spaces/carlosalonso/Detection-video/carpeta_deteccion/tests/export/test_c10.py deleted file mode 100644 index 55076abd15beb50b1774f0b5fe399b22d7cc630f..0000000000000000000000000000000000000000 --- a/spaces/carlosalonso/Detection-video/carpeta_deteccion/tests/export/test_c10.py +++ /dev/null @@ -1,25 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. -import unittest - -try: - # Caffe2 used to be included in PyTorch, but since PyTorch 1.10+, - # it is not included in pre-built packages. This is a safety BC check - from detectron2.config import get_cfg - from detectron2.export.c10 import Caffe2RPN - from detectron2.layers import ShapeSpec -except ImportError: - raise unittest.SkipTest( - f"PyTorch does not have Caffe2 support. Skipping all tests in {__name__}" - ) from None - - -class TestCaffe2RPN(unittest.TestCase): - def test_instantiation(self): - cfg = get_cfg() - cfg.MODEL.RPN.BBOX_REG_WEIGHTS = (1, 1, 1, 1, 1) - input_shapes = {"res4": ShapeSpec(channels=256, stride=4)} - rpn = Caffe2RPN(cfg, input_shapes) - assert rpn is not None - cfg.MODEL.RPN.BBOX_REG_WEIGHTS = (10, 10, 5, 5, 1) - with self.assertRaises(AssertionError): - rpn = Caffe2RPN(cfg, input_shapes) diff --git a/spaces/cedpsam/mistral_openorca_lamacpp/README.md b/spaces/cedpsam/mistral_openorca_lamacpp/README.md deleted file mode 100644 index 4d53fa1c9ab0fc8ba4fd8994bff2806cb8bcfdbb..0000000000000000000000000000000000000000 --- a/spaces/cedpsam/mistral_openorca_lamacpp/README.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: Mistral Openorca Lamacpp -emoji: 🏃 -colorFrom: gray -colorTo: blue -sdk: gradio -sdk_version: 3.47.1 -app_file: app.py -pinned: false ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/cfj108/prompthero-openjourney/app.py b/spaces/cfj108/prompthero-openjourney/app.py deleted file mode 100644 index 2193905172b6fb6d868bff88cc8311f491ec13b3..0000000000000000000000000000000000000000 --- a/spaces/cfj108/prompthero-openjourney/app.py +++ /dev/null @@ -1,3 +0,0 @@ -import gradio as gr - -gr.Interface.load("models/prompthero/openjourney").launch() \ No newline at end of file diff --git a/spaces/chasemcdo/hf_localai/pkg/stablediffusion/generate.go b/spaces/chasemcdo/hf_localai/pkg/stablediffusion/generate.go deleted file mode 100644 index cef96e805520315650bd49bee392661f44383343..0000000000000000000000000000000000000000 --- a/spaces/chasemcdo/hf_localai/pkg/stablediffusion/generate.go +++ /dev/null @@ -1,35 +0,0 @@ -//go:build stablediffusion -// +build stablediffusion - -package stablediffusion - -import ( - stableDiffusion "github.com/mudler/go-stable-diffusion" -) - -func GenerateImage(height, width, mode, step, seed int, positive_prompt, negative_prompt, dst, asset_dir string) error { - if height > 512 || width > 512 { - return stableDiffusion.GenerateImageUpscaled( - height, - width, - step, - seed, - positive_prompt, - negative_prompt, - dst, - asset_dir, - ) - } - return stableDiffusion.GenerateImage( - height, - width, - mode, - step, - seed, - positive_prompt, - negative_prompt, - dst, - "", - asset_dir, - ) -} diff --git a/spaces/chiye/background-remover/app.py b/spaces/chiye/background-remover/app.py deleted file mode 100644 index c53c42ae3e0e6ec108301bc6f7dbce2c36684e95..0000000000000000000000000000000000000000 --- a/spaces/chiye/background-remover/app.py +++ /dev/null @@ -1,127 +0,0 @@ -import cv2 -import gradio as gr -import numpy as np -import onnxruntime -import requests -from huggingface_hub import hf_hub_download -from PIL import Image - - -# Get x_scale_factor & y_scale_factor to resize image -def get_scale_factor(im_h, im_w, ref_size=512): - - if max(im_h, im_w) < ref_size or min(im_h, im_w) > ref_size: - if im_w >= im_h: - im_rh = ref_size - im_rw = int(im_w / im_h * ref_size) - elif im_w < im_h: - im_rw = ref_size - im_rh = int(im_h / im_w * ref_size) - else: - im_rh = im_h - im_rw = im_w - - im_rw = im_rw - im_rw % 32 - im_rh = im_rh - im_rh % 32 - - x_scale_factor = im_rw / im_w - y_scale_factor = im_rh / im_h - - return x_scale_factor, y_scale_factor - - -MODEL_PATH = hf_hub_download('nateraw/background-remover-files', 'modnet.onnx', repo_type='dataset') - - -def main(image_path, threshold): - - # read image - im = cv2.imread(image_path) - im = cv2.cvtColor(im, cv2.COLOR_BGR2RGB) - - # unify image channels to 3 - if len(im.shape) == 2: - im = im[:, :, None] - if im.shape[2] == 1: - im = np.repeat(im, 3, axis=2) - elif im.shape[2] == 4: - im = im[:, :, 0:3] - - # normalize values to scale it between -1 to 1 - im = (im - 127.5) / 127.5 - - im_h, im_w, im_c = im.shape - x, y = get_scale_factor(im_h, im_w) - - # resize image - im = cv2.resize(im, None, fx=x, fy=y, interpolation=cv2.INTER_AREA) - - # prepare input shape - im = np.transpose(im) - im = np.swapaxes(im, 1, 2) - im = np.expand_dims(im, axis=0).astype('float32') - - # Initialize session and get prediction - session = onnxruntime.InferenceSession(MODEL_PATH, None) - input_name = session.get_inputs()[0].name - output_name = session.get_outputs()[0].name - result = session.run([output_name], {input_name: im}) - - # refine matte - matte = (np.squeeze(result[0]) * 255).astype('uint8') - matte = cv2.resize(matte, dsize=(im_w, im_h), interpolation=cv2.INTER_AREA) - - # HACK - Could probably just convert this to PIL instead of writing - cv2.imwrite('out.png', matte) - - image = Image.open(image_path) - matte = Image.open('out.png') - - # obtain predicted foreground - image = np.asarray(image) - if len(image.shape) == 2: - image = image[:, :, None] - if image.shape[2] == 1: - image = np.repeat(image, 3, axis=2) - elif image.shape[2] == 4: - image = image[:, :, 0:3] - - b, g, r = cv2.split(image) - - mask = np.asarray(matte) - a = np.ones(mask.shape, dtype='uint8') * 255 - alpha_im = cv2.merge([b, g, r, a], 4) - bg = np.zeros(alpha_im.shape) - new_mask = np.stack([mask, mask, mask, mask], axis=2) - foreground = np.where(new_mask > threshold, alpha_im, bg).astype(np.uint8) - - return Image.fromarray(foreground) - - -title = "MODNet Background Remover" -description = "Gradio demo for MODNet, a model that can remove the background from a given image. To use it, simply upload your image, or click one of the examples to load them. Read more at the links below." -article = "" - -url = "https://huggingface.co/datasets/nateraw/background-remover-files/resolve/main/twitter_profile_pic.jpeg" -image = Image.open(requests.get(url, stream=True).raw) -image.save('twitter_profile_pic.jpg') - -url = "https://upload.wikimedia.org/wikipedia/commons/8/8d/President_Barack_Obama.jpg" -image = Image.open(requests.get(url, stream=True).raw) -image.save('obama.jpg') - -interface = gr.Interface( - fn=main, - inputs=[ - gr.inputs.Image(type='filepath'), - gr.inputs.Slider(minimum=0, maximum=250, default=100, step=5, label='Mask Cutoff Threshold'), - ], - outputs='image', - examples=[['twitter_profile_pic.jpg', 120], ['obama.jpg', 155]], - title=title, - description=description, - article=article, -) - -if __name__ == '__main__': - interface.launch(debug=True) diff --git a/spaces/chuan-hd/law-assistant-chatbot/.venv/lib/python3.11/site-packages/PIL/ImageShow.py b/spaces/chuan-hd/law-assistant-chatbot/.venv/lib/python3.11/site-packages/PIL/ImageShow.py deleted file mode 100644 index 8b1c3f8bb63ea6e6fccba543bdaea0bbd9b03163..0000000000000000000000000000000000000000 --- a/spaces/chuan-hd/law-assistant-chatbot/.venv/lib/python3.11/site-packages/PIL/ImageShow.py +++ /dev/null @@ -1,323 +0,0 @@ -# -# The Python Imaging Library. -# $Id$ -# -# im.show() drivers -# -# History: -# 2008-04-06 fl Created -# -# Copyright (c) Secret Labs AB 2008. -# -# See the README file for information on usage and redistribution. -# -import os -import shutil -import subprocess -import sys -from shlex import quote - -from . import Image - -_viewers = [] - - -def register(viewer, order=1): - """ - The :py:func:`register` function is used to register additional viewers:: - - from PIL import ImageShow - ImageShow.register(MyViewer()) # MyViewer will be used as a last resort - ImageShow.register(MySecondViewer(), 0) # MySecondViewer will be prioritised - ImageShow.register(ImageShow.XVViewer(), 0) # XVViewer will be prioritised - - :param viewer: The viewer to be registered. - :param order: - Zero or a negative integer to prepend this viewer to the list, - a positive integer to append it. - """ - try: - if issubclass(viewer, Viewer): - viewer = viewer() - except TypeError: - pass # raised if viewer wasn't a class - if order > 0: - _viewers.append(viewer) - else: - _viewers.insert(0, viewer) - - -def show(image, title=None, **options): - r""" - Display a given image. - - :param image: An image object. - :param title: Optional title. Not all viewers can display the title. - :param \**options: Additional viewer options. - :returns: ``True`` if a suitable viewer was found, ``False`` otherwise. - """ - for viewer in _viewers: - if viewer.show(image, title=title, **options): - return True - return False - - -class Viewer: - """Base class for viewers.""" - - # main api - - def show(self, image, **options): - """ - The main function for displaying an image. - Converts the given image to the target format and displays it. - """ - - if not ( - image.mode in ("1", "RGBA") - or (self.format == "PNG" and image.mode in ("I;16", "LA")) - ): - base = Image.getmodebase(image.mode) - if image.mode != base: - image = image.convert(base) - - return self.show_image(image, **options) - - # hook methods - - format = None - """The format to convert the image into.""" - options = {} - """Additional options used to convert the image.""" - - def get_format(self, image): - """Return format name, or ``None`` to save as PGM/PPM.""" - return self.format - - def get_command(self, file, **options): - """ - Returns the command used to display the file. - Not implemented in the base class. - """ - raise NotImplementedError - - def save_image(self, image): - """Save to temporary file and return filename.""" - return image._dump(format=self.get_format(image), **self.options) - - def show_image(self, image, **options): - """Display the given image.""" - return self.show_file(self.save_image(image), **options) - - def show_file(self, path, **options): - """ - Display given file. - """ - os.system(self.get_command(path, **options)) # nosec - return 1 - - -# -------------------------------------------------------------------- - - -class WindowsViewer(Viewer): - """The default viewer on Windows is the default system application for PNG files.""" - - format = "PNG" - options = {"compress_level": 1, "save_all": True} - - def get_command(self, file, **options): - return ( - f'start "Pillow" /WAIT "{file}" ' - "&& ping -n 4 127.0.0.1 >NUL " - f'&& del /f "{file}"' - ) - - -if sys.platform == "win32": - register(WindowsViewer) - - -class MacViewer(Viewer): - """The default viewer on macOS using ``Preview.app``.""" - - format = "PNG" - options = {"compress_level": 1, "save_all": True} - - def get_command(self, file, **options): - # on darwin open returns immediately resulting in the temp - # file removal while app is opening - command = "open -a Preview.app" - command = f"({command} {quote(file)}; sleep 20; rm -f {quote(file)})&" - return command - - def show_file(self, path, **options): - """ - Display given file. - """ - subprocess.call(["open", "-a", "Preview.app", path]) - executable = sys.executable or shutil.which("python3") - if executable: - subprocess.Popen( - [ - executable, - "-c", - "import os, sys, time; time.sleep(20); os.remove(sys.argv[1])", - path, - ] - ) - return 1 - - -if sys.platform == "darwin": - register(MacViewer) - - -class UnixViewer(Viewer): - format = "PNG" - options = {"compress_level": 1, "save_all": True} - - def get_command(self, file, **options): - command = self.get_command_ex(file, **options)[0] - return f"({command} {quote(file)}" - - -class XDGViewer(UnixViewer): - """ - The freedesktop.org ``xdg-open`` command. - """ - - def get_command_ex(self, file, **options): - command = executable = "xdg-open" - return command, executable - - def show_file(self, path, **options): - """ - Display given file. - """ - subprocess.Popen(["xdg-open", path]) - return 1 - - -class DisplayViewer(UnixViewer): - """ - The ImageMagick ``display`` command. - This viewer supports the ``title`` parameter. - """ - - def get_command_ex(self, file, title=None, **options): - command = executable = "display" - if title: - command += f" -title {quote(title)}" - return command, executable - - def show_file(self, path, **options): - """ - Display given file. - """ - args = ["display"] - title = options.get("title") - if title: - args += ["-title", title] - args.append(path) - - subprocess.Popen(args) - return 1 - - -class GmDisplayViewer(UnixViewer): - """The GraphicsMagick ``gm display`` command.""" - - def get_command_ex(self, file, **options): - executable = "gm" - command = "gm display" - return command, executable - - def show_file(self, path, **options): - """ - Display given file. - """ - subprocess.Popen(["gm", "display", path]) - return 1 - - -class EogViewer(UnixViewer): - """The GNOME Image Viewer ``eog`` command.""" - - def get_command_ex(self, file, **options): - executable = "eog" - command = "eog -n" - return command, executable - - def show_file(self, path, **options): - """ - Display given file. - """ - subprocess.Popen(["eog", "-n", path]) - return 1 - - -class XVViewer(UnixViewer): - """ - The X Viewer ``xv`` command. - This viewer supports the ``title`` parameter. - """ - - def get_command_ex(self, file, title=None, **options): - # note: xv is pretty outdated. most modern systems have - # imagemagick's display command instead. - command = executable = "xv" - if title: - command += f" -name {quote(title)}" - return command, executable - - def show_file(self, path, **options): - """ - Display given file. - """ - args = ["xv"] - title = options.get("title") - if title: - args += ["-name", title] - args.append(path) - - subprocess.Popen(args) - return 1 - - -if sys.platform not in ("win32", "darwin"): # unixoids - if shutil.which("xdg-open"): - register(XDGViewer) - if shutil.which("display"): - register(DisplayViewer) - if shutil.which("gm"): - register(GmDisplayViewer) - if shutil.which("eog"): - register(EogViewer) - if shutil.which("xv"): - register(XVViewer) - - -class IPythonViewer(Viewer): - """The viewer for IPython frontends.""" - - def show_image(self, image, **options): - ipython_display(image) - return 1 - - -try: - from IPython.display import display as ipython_display -except ImportError: - pass -else: - register(IPythonViewer) - - -if __name__ == "__main__": - if len(sys.argv) < 2: - print("Syntax: python3 ImageShow.py imagefile [title]") - sys.exit() - - with Image.open(sys.argv[1]) as im: - print(show(im, *sys.argv[2:])) diff --git a/spaces/chuan-hd/law-assistant-chatbot/.venv/lib/python3.11/site-packages/anyio/_core/_compat.py b/spaces/chuan-hd/law-assistant-chatbot/.venv/lib/python3.11/site-packages/anyio/_core/_compat.py deleted file mode 100644 index 22d29ab8ac303756047d105dadafcfd5107563ef..0000000000000000000000000000000000000000 --- a/spaces/chuan-hd/law-assistant-chatbot/.venv/lib/python3.11/site-packages/anyio/_core/_compat.py +++ /dev/null @@ -1,217 +0,0 @@ -from __future__ import annotations - -from abc import ABCMeta, abstractmethod -from contextlib import AbstractContextManager -from types import TracebackType -from typing import ( - TYPE_CHECKING, - Any, - AsyncContextManager, - Callable, - ContextManager, - Generator, - Generic, - Iterable, - List, - TypeVar, - Union, - overload, -) -from warnings import warn - -if TYPE_CHECKING: - from ._testing import TaskInfo -else: - TaskInfo = object - -T = TypeVar("T") -AnyDeprecatedAwaitable = Union[ - "DeprecatedAwaitable", - "DeprecatedAwaitableFloat", - "DeprecatedAwaitableList[T]", - TaskInfo, -] - - -@overload -async def maybe_async(__obj: TaskInfo) -> TaskInfo: - ... - - -@overload -async def maybe_async(__obj: DeprecatedAwaitableFloat) -> float: - ... - - -@overload -async def maybe_async(__obj: DeprecatedAwaitableList[T]) -> list[T]: - ... - - -@overload -async def maybe_async(__obj: DeprecatedAwaitable) -> None: - ... - - -async def maybe_async( - __obj: AnyDeprecatedAwaitable[T], -) -> TaskInfo | float | list[T] | None: - """ - Await on the given object if necessary. - - This function is intended to bridge the gap between AnyIO 2.x and 3.x where some functions and - methods were converted from coroutine functions into regular functions. - - Do **not** try to use this for any other purpose! - - :return: the result of awaiting on the object if coroutine, or the object itself otherwise - - .. versionadded:: 2.2 - - """ - return __obj._unwrap() - - -class _ContextManagerWrapper: - def __init__(self, cm: ContextManager[T]): - self._cm = cm - - async def __aenter__(self) -> T: - return self._cm.__enter__() - - async def __aexit__( - self, - exc_type: type[BaseException] | None, - exc_val: BaseException | None, - exc_tb: TracebackType | None, - ) -> bool | None: - return self._cm.__exit__(exc_type, exc_val, exc_tb) - - -def maybe_async_cm( - cm: ContextManager[T] | AsyncContextManager[T], -) -> AsyncContextManager[T]: - """ - Wrap a regular context manager as an async one if necessary. - - This function is intended to bridge the gap between AnyIO 2.x and 3.x where some functions and - methods were changed to return regular context managers instead of async ones. - - :param cm: a regular or async context manager - :return: an async context manager - - .. versionadded:: 2.2 - - """ - if not isinstance(cm, AbstractContextManager): - raise TypeError("Given object is not an context manager") - - return _ContextManagerWrapper(cm) - - -def _warn_deprecation( - awaitable: AnyDeprecatedAwaitable[Any], stacklevel: int = 1 -) -> None: - warn( - f'Awaiting on {awaitable._name}() is deprecated. Use "await ' - f"anyio.maybe_async({awaitable._name}(...)) if you have to support both AnyIO 2.x " - f'and 3.x, or just remove the "await" if you are completely migrating to AnyIO 3+.', - DeprecationWarning, - stacklevel=stacklevel + 1, - ) - - -class DeprecatedAwaitable: - def __init__(self, func: Callable[..., DeprecatedAwaitable]): - self._name = f"{func.__module__}.{func.__qualname__}" - - def __await__(self) -> Generator[None, None, None]: - _warn_deprecation(self) - if False: - yield - - def __reduce__(self) -> tuple[type[None], tuple[()]]: - return type(None), () - - def _unwrap(self) -> None: - return None - - -class DeprecatedAwaitableFloat(float): - def __new__( - cls, x: float, func: Callable[..., DeprecatedAwaitableFloat] - ) -> DeprecatedAwaitableFloat: - return super().__new__(cls, x) - - def __init__(self, x: float, func: Callable[..., DeprecatedAwaitableFloat]): - self._name = f"{func.__module__}.{func.__qualname__}" - - def __await__(self) -> Generator[None, None, float]: - _warn_deprecation(self) - if False: - yield - - return float(self) - - def __reduce__(self) -> tuple[type[float], tuple[float]]: - return float, (float(self),) - - def _unwrap(self) -> float: - return float(self) - - -class DeprecatedAwaitableList(List[T]): - def __init__( - self, - iterable: Iterable[T] = (), - *, - func: Callable[..., DeprecatedAwaitableList[T]], - ): - super().__init__(iterable) - self._name = f"{func.__module__}.{func.__qualname__}" - - def __await__(self) -> Generator[None, None, list[T]]: - _warn_deprecation(self) - if False: - yield - - return list(self) - - def __reduce__(self) -> tuple[type[list[T]], tuple[list[T]]]: - return list, (list(self),) - - def _unwrap(self) -> list[T]: - return list(self) - - -class DeprecatedAsyncContextManager(Generic[T], metaclass=ABCMeta): - @abstractmethod - def __enter__(self) -> T: - pass - - @abstractmethod - def __exit__( - self, - exc_type: type[BaseException] | None, - exc_val: BaseException | None, - exc_tb: TracebackType | None, - ) -> bool | None: - pass - - async def __aenter__(self) -> T: - warn( - f"Using {self.__class__.__name__} as an async context manager has been deprecated. " - f'Use "async with anyio.maybe_async_cm(yourcontextmanager) as foo:" if you have to ' - f'support both AnyIO 2.x and 3.x, or just remove the "async" from "async with" if ' - f"you are completely migrating to AnyIO 3+.", - DeprecationWarning, - ) - return self.__enter__() - - async def __aexit__( - self, - exc_type: type[BaseException] | None, - exc_val: BaseException | None, - exc_tb: TracebackType | None, - ) -> bool | None: - return self.__exit__(exc_type, exc_val, exc_tb) diff --git a/spaces/chuan-hd/law-assistant-chatbot/.venv/lib/python3.11/site-packages/chromadb/test/hnswlib/test_hnswlib.py b/spaces/chuan-hd/law-assistant-chatbot/.venv/lib/python3.11/site-packages/chromadb/test/hnswlib/test_hnswlib.py deleted file mode 100644 index 2039c67096646c73ee4aa43af93af23749b24c81..0000000000000000000000000000000000000000 --- a/spaces/chuan-hd/law-assistant-chatbot/.venv/lib/python3.11/site-packages/chromadb/test/hnswlib/test_hnswlib.py +++ /dev/null @@ -1,67 +0,0 @@ -import os -import shutil -import tempfile -from typing import Generator - -import pytest -from chromadb.db.index.hnswlib import Hnswlib -from chromadb.config import Settings -import uuid -import numpy as np - - -@pytest.fixture(scope="module") -def settings() -> Generator[Settings, None, None]: - save_path = tempfile.gettempdir() + "/tests/hnswlib/" - yield Settings(persist_directory=save_path) - if os.path.exists(save_path): - shutil.rmtree(save_path) - - -def test_count_tracking(settings: Settings) -> None: - hnswlib = Hnswlib("test", settings, {}, 2) - hnswlib._init_index(2) - assert hnswlib._index_metadata["curr_elements"] == 0 - assert hnswlib._index_metadata["total_elements_added"] == 0 - idA, idB = uuid.uuid4(), uuid.uuid4() - - embeddingA = np.random.rand(1, 2) - hnswlib.add([idA], embeddingA.tolist()) - assert ( - hnswlib._index_metadata["curr_elements"] - == hnswlib._index_metadata["total_elements_added"] - == 1 - ) - embeddingB = np.random.rand(1, 2) - hnswlib.add([idB], embeddingB.tolist()) - assert ( - hnswlib._index_metadata["curr_elements"] - == hnswlib._index_metadata["total_elements_added"] - == 2 - ) - hnswlib.delete_from_index(ids=[idA]) - assert hnswlib._index_metadata["curr_elements"] == 1 - assert hnswlib._index_metadata["total_elements_added"] == 2 - hnswlib.delete_from_index(ids=[idB]) - assert hnswlib._index_metadata["curr_elements"] == 0 - assert hnswlib._index_metadata["total_elements_added"] == 2 - - -def test_add_delete_large_amount(settings: Settings) -> None: - # Test adding a large number of records - N = 2000 - D = 512 - large_records = np.random.rand(N, D).astype(np.float32).tolist() - ids = [uuid.uuid4() for _ in range(N)] - hnswlib = Hnswlib("test", settings, {}, N) - hnswlib._init_index(D) - hnswlib.add(ids, large_records) - assert hnswlib._index_metadata["curr_elements"] == N - assert hnswlib._index_metadata["total_elements_added"] == N - - # Test deleting a large number of records by getting a random subset of the ids - ids_to_delete = np.random.choice(np.array(ids), size=100, replace=False).tolist() - hnswlib.delete_from_index(ids_to_delete) - - assert hnswlib._index_metadata["curr_elements"] == N - 100 - assert hnswlib._index_metadata["total_elements_added"] == N diff --git a/spaces/chuan-hd/law-assistant-chatbot/.venv/lib/python3.11/site-packages/docx/enum/shape.py b/spaces/chuan-hd/law-assistant-chatbot/.venv/lib/python3.11/site-packages/docx/enum/shape.py deleted file mode 100644 index 937f30a9fa9a1d2dd495b74823b6acd204ee9531..0000000000000000000000000000000000000000 --- a/spaces/chuan-hd/law-assistant-chatbot/.venv/lib/python3.11/site-packages/docx/enum/shape.py +++ /dev/null @@ -1,22 +0,0 @@ -# encoding: utf-8 - -""" -Enumerations related to DrawingML shapes in WordprocessingML files -""" - -from __future__ import absolute_import, print_function, unicode_literals - - -class WD_INLINE_SHAPE_TYPE(object): - """ - Corresponds to WdInlineShapeType enumeration - http://msdn.microsoft.com/en-us/library/office/ff192587.aspx - """ - CHART = 12 - LINKED_PICTURE = 4 - PICTURE = 3 - SMART_ART = 15 - NOT_IMPLEMENTED = -6 - - -WD_INLINE_SHAPE = WD_INLINE_SHAPE_TYPE diff --git a/spaces/chuan-hd/law-assistant-chatbot/.venv/lib/python3.11/site-packages/fontTools/pens/recordingPen.py b/spaces/chuan-hd/law-assistant-chatbot/.venv/lib/python3.11/site-packages/fontTools/pens/recordingPen.py deleted file mode 100644 index 6c3b6613211d76f0306876dceb6d3945920417f5..0000000000000000000000000000000000000000 --- a/spaces/chuan-hd/law-assistant-chatbot/.venv/lib/python3.11/site-packages/fontTools/pens/recordingPen.py +++ /dev/null @@ -1,179 +0,0 @@ -"""Pen recording operations that can be accessed or replayed.""" -from fontTools.pens.basePen import AbstractPen, DecomposingPen -from fontTools.pens.pointPen import AbstractPointPen - - -__all__ = [ - "replayRecording", - "RecordingPen", - "DecomposingRecordingPen", - "RecordingPointPen", -] - - -def replayRecording(recording, pen): - """Replay a recording, as produced by RecordingPen or DecomposingRecordingPen, - to a pen. - - Note that recording does not have to be produced by those pens. - It can be any iterable of tuples of method name and tuple-of-arguments. - Likewise, pen can be any objects receiving those method calls. - """ - for operator, operands in recording: - getattr(pen, operator)(*operands) - - -class RecordingPen(AbstractPen): - """Pen recording operations that can be accessed or replayed. - - The recording can be accessed as pen.value; or replayed using - pen.replay(otherPen). - - :Example: - - from fontTools.ttLib import TTFont - from fontTools.pens.recordingPen import RecordingPen - - glyph_name = 'dollar' - font_path = 'MyFont.otf' - - font = TTFont(font_path) - glyphset = font.getGlyphSet() - glyph = glyphset[glyph_name] - - pen = RecordingPen() - glyph.draw(pen) - print(pen.value) - """ - - def __init__(self): - self.value = [] - - def moveTo(self, p0): - self.value.append(("moveTo", (p0,))) - - def lineTo(self, p1): - self.value.append(("lineTo", (p1,))) - - def qCurveTo(self, *points): - self.value.append(("qCurveTo", points)) - - def curveTo(self, *points): - self.value.append(("curveTo", points)) - - def closePath(self): - self.value.append(("closePath", ())) - - def endPath(self): - self.value.append(("endPath", ())) - - def addComponent(self, glyphName, transformation): - self.value.append(("addComponent", (glyphName, transformation))) - - def addVarComponent(self, glyphName, transformation, location): - self.value.append(("addVarComponent", (glyphName, transformation, location))) - - def replay(self, pen): - replayRecording(self.value, pen) - - -class DecomposingRecordingPen(DecomposingPen, RecordingPen): - """Same as RecordingPen, except that it doesn't keep components - as references, but draws them decomposed as regular contours. - - The constructor takes a single 'glyphSet' positional argument, - a dictionary of glyph objects (i.e. with a 'draw' method) keyed - by thir name:: - - >>> class SimpleGlyph(object): - ... def draw(self, pen): - ... pen.moveTo((0, 0)) - ... pen.curveTo((1, 1), (2, 2), (3, 3)) - ... pen.closePath() - >>> class CompositeGlyph(object): - ... def draw(self, pen): - ... pen.addComponent('a', (1, 0, 0, 1, -1, 1)) - >>> glyphSet = {'a': SimpleGlyph(), 'b': CompositeGlyph()} - >>> for name, glyph in sorted(glyphSet.items()): - ... pen = DecomposingRecordingPen(glyphSet) - ... glyph.draw(pen) - ... print("{}: {}".format(name, pen.value)) - a: [('moveTo', ((0, 0),)), ('curveTo', ((1, 1), (2, 2), (3, 3))), ('closePath', ())] - b: [('moveTo', ((-1, 1),)), ('curveTo', ((0, 2), (1, 3), (2, 4))), ('closePath', ())] - """ - - # raises KeyError if base glyph is not found in glyphSet - skipMissingComponents = False - - -class RecordingPointPen(AbstractPointPen): - """PointPen recording operations that can be accessed or replayed. - - The recording can be accessed as pen.value; or replayed using - pointPen.replay(otherPointPen). - - :Example: - - from defcon import Font - from fontTools.pens.recordingPen import RecordingPointPen - - glyph_name = 'a' - font_path = 'MyFont.ufo' - - font = Font(font_path) - glyph = font[glyph_name] - - pen = RecordingPointPen() - glyph.drawPoints(pen) - print(pen.value) - - new_glyph = font.newGlyph('b') - pen.replay(new_glyph.getPointPen()) - """ - - def __init__(self): - self.value = [] - - def beginPath(self, identifier=None, **kwargs): - if identifier is not None: - kwargs["identifier"] = identifier - self.value.append(("beginPath", (), kwargs)) - - def endPath(self): - self.value.append(("endPath", (), {})) - - def addPoint( - self, pt, segmentType=None, smooth=False, name=None, identifier=None, **kwargs - ): - if identifier is not None: - kwargs["identifier"] = identifier - self.value.append(("addPoint", (pt, segmentType, smooth, name), kwargs)) - - def addComponent(self, baseGlyphName, transformation, identifier=None, **kwargs): - if identifier is not None: - kwargs["identifier"] = identifier - self.value.append(("addComponent", (baseGlyphName, transformation), kwargs)) - - def addVarComponent( - self, baseGlyphName, transformation, location, identifier=None, **kwargs - ): - if identifier is not None: - kwargs["identifier"] = identifier - self.value.append( - ("addVarComponent", (baseGlyphName, transformation, location), kwargs) - ) - - def replay(self, pointPen): - for operator, args, kwargs in self.value: - getattr(pointPen, operator)(*args, **kwargs) - - -if __name__ == "__main__": - pen = RecordingPen() - pen.moveTo((0, 0)) - pen.lineTo((0, 100)) - pen.curveTo((50, 75), (60, 50), (50, 25)) - pen.closePath() - from pprint import pprint - - pprint(pen.value) diff --git a/spaces/chuan-hd/law-assistant-chatbot/.venv/lib/python3.11/site-packages/fontTools/qu2cu/qu2cu.py b/spaces/chuan-hd/law-assistant-chatbot/.venv/lib/python3.11/site-packages/fontTools/qu2cu/qu2cu.py deleted file mode 100644 index 97a665f63adf88681328a69c5c0a3c6814bf3719..0000000000000000000000000000000000000000 --- a/spaces/chuan-hd/law-assistant-chatbot/.venv/lib/python3.11/site-packages/fontTools/qu2cu/qu2cu.py +++ /dev/null @@ -1,408 +0,0 @@ -# cython: language_level=3 -# distutils: define_macros=CYTHON_TRACE_NOGIL=1 - -# Copyright 2023 Google Inc. All Rights Reserved. -# Copyright 2023 Behdad Esfahbod. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -try: - import cython - - COMPILED = cython.compiled -except (AttributeError, ImportError): - # if cython not installed, use mock module with no-op decorators and types - from fontTools.misc import cython - - COMPILED = False - -from fontTools.misc.bezierTools import splitCubicAtTC -from collections import namedtuple -import math -from typing import ( - List, - Tuple, - Union, -) - - -__all__ = ["quadratic_to_curves"] - - -# Copied from cu2qu -@cython.cfunc -@cython.returns(cython.int) -@cython.locals( - tolerance=cython.double, - p0=cython.complex, - p1=cython.complex, - p2=cython.complex, - p3=cython.complex, -) -@cython.locals(mid=cython.complex, deriv3=cython.complex) -def cubic_farthest_fit_inside(p0, p1, p2, p3, tolerance): - """Check if a cubic Bezier lies within a given distance of the origin. - - "Origin" means *the* origin (0,0), not the start of the curve. Note that no - checks are made on the start and end positions of the curve; this function - only checks the inside of the curve. - - Args: - p0 (complex): Start point of curve. - p1 (complex): First handle of curve. - p2 (complex): Second handle of curve. - p3 (complex): End point of curve. - tolerance (double): Distance from origin. - - Returns: - bool: True if the cubic Bezier ``p`` entirely lies within a distance - ``tolerance`` of the origin, False otherwise. - """ - # First check p2 then p1, as p2 has higher error early on. - if abs(p2) <= tolerance and abs(p1) <= tolerance: - return True - - # Split. - mid = (p0 + 3 * (p1 + p2) + p3) * 0.125 - if abs(mid) > tolerance: - return False - deriv3 = (p3 + p2 - p1 - p0) * 0.125 - return cubic_farthest_fit_inside( - p0, (p0 + p1) * 0.5, mid - deriv3, mid, tolerance - ) and cubic_farthest_fit_inside(mid, mid + deriv3, (p2 + p3) * 0.5, p3, tolerance) - - -@cython.locals( - p0=cython.complex, - p1=cython.complex, - p2=cython.complex, - p1_2_3=cython.complex, -) -def elevate_quadratic(p0, p1, p2): - """Given a quadratic bezier curve, return its degree-elevated cubic.""" - - # https://pomax.github.io/bezierinfo/#reordering - p1_2_3 = p1 * (2 / 3) - return ( - p0, - (p0 * (1 / 3) + p1_2_3), - (p2 * (1 / 3) + p1_2_3), - p2, - ) - - -@cython.cfunc -@cython.locals( - start=cython.int, - n=cython.int, - k=cython.int, - prod_ratio=cython.double, - sum_ratio=cython.double, - ratio=cython.double, - t=cython.double, - p0=cython.complex, - p1=cython.complex, - p2=cython.complex, - p3=cython.complex, -) -def merge_curves(curves, start, n): - """Give a cubic-Bezier spline, reconstruct one cubic-Bezier - that has the same endpoints and tangents and approxmates - the spline.""" - - # Reconstruct the t values of the cut segments - prod_ratio = 1.0 - sum_ratio = 1.0 - ts = [1] - for k in range(1, n): - ck = curves[start + k] - c_before = curves[start + k - 1] - - # |t_(k+1) - t_k| / |t_k - t_(k - 1)| = ratio - assert ck[0] == c_before[3] - ratio = abs(ck[1] - ck[0]) / abs(c_before[3] - c_before[2]) - - prod_ratio *= ratio - sum_ratio += prod_ratio - ts.append(sum_ratio) - - # (t(n) - t(n - 1)) / (t_(1) - t(0)) = prod_ratio - - ts = [t / sum_ratio for t in ts[:-1]] - - p0 = curves[start][0] - p1 = curves[start][1] - p2 = curves[start + n - 1][2] - p3 = curves[start + n - 1][3] - - # Build the curve by scaling the control-points. - p1 = p0 + (p1 - p0) / (ts[0] if ts else 1) - p2 = p3 + (p2 - p3) / ((1 - ts[-1]) if ts else 1) - - curve = (p0, p1, p2, p3) - - return curve, ts - - -@cython.locals( - count=cython.int, - num_offcurves=cython.int, - i=cython.int, - off1=cython.complex, - off2=cython.complex, - on=cython.complex, -) -def add_implicit_on_curves(p): - q = list(p) - count = 0 - num_offcurves = len(p) - 2 - for i in range(1, num_offcurves): - off1 = p[i] - off2 = p[i + 1] - on = off1 + (off2 - off1) * 0.5 - q.insert(i + 1 + count, on) - count += 1 - return q - - -Point = Union[Tuple[float, float], complex] - - -@cython.locals( - cost=cython.int, - is_complex=cython.int, -) -def quadratic_to_curves( - quads: List[List[Point]], - max_err: float = 0.5, - all_cubic: bool = False, -) -> List[Tuple[Point, ...]]: - """Converts a connecting list of quadratic splines to a list of quadratic - and cubic curves. - - A quadratic spline is specified as a list of points. Either each point is - a 2-tuple of X,Y coordinates, or each point is a complex number with - real/imaginary components representing X,Y coordinates. - - The first and last points are on-curve points and the rest are off-curve - points, with an implied on-curve point in the middle between every two - consequtive off-curve points. - - Returns: - The output is a list of tuples of points. Points are represented - in the same format as the input, either as 2-tuples or complex numbers. - - Each tuple is either of length three, for a quadratic curve, or four, - for a cubic curve. Each curve's last point is the same as the next - curve's first point. - - Args: - quads: quadratic splines - - max_err: absolute error tolerance; defaults to 0.5 - - all_cubic: if True, only cubic curves are generated; defaults to False - """ - is_complex = type(quads[0][0]) is complex - if not is_complex: - quads = [[complex(x, y) for (x, y) in p] for p in quads] - - q = [quads[0][0]] - costs = [1] - cost = 1 - for p in quads: - assert q[-1] == p[0] - for i in range(len(p) - 2): - cost += 1 - costs.append(cost) - costs.append(cost) - qq = add_implicit_on_curves(p)[1:] - costs.pop() - q.extend(qq) - cost += 1 - costs.append(cost) - - curves = spline_to_curves(q, costs, max_err, all_cubic) - - if not is_complex: - curves = [tuple((c.real, c.imag) for c in curve) for curve in curves] - return curves - - -Solution = namedtuple("Solution", ["num_points", "error", "start_index", "is_cubic"]) - - -@cython.locals( - i=cython.int, - j=cython.int, - k=cython.int, - start=cython.int, - i_sol_count=cython.int, - j_sol_count=cython.int, - this_sol_count=cython.int, - tolerance=cython.double, - err=cython.double, - error=cython.double, - i_sol_error=cython.double, - j_sol_error=cython.double, - all_cubic=cython.int, - is_cubic=cython.int, - count=cython.int, - p0=cython.complex, - p1=cython.complex, - p2=cython.complex, - p3=cython.complex, - v=cython.complex, - u=cython.complex, -) -def spline_to_curves(q, costs, tolerance=0.5, all_cubic=False): - """ - q: quadratic spline with alternating on-curve / off-curve points. - - costs: cumulative list of encoding cost of q in terms of number of - points that need to be encoded. Implied on-curve points do not - contribute to the cost. If all points need to be encoded, then - costs will be range(1, len(q)+1). - """ - - assert len(q) >= 3, "quadratic spline requires at least 3 points" - - # Elevate quadratic segments to cubic - elevated_quadratics = [ - elevate_quadratic(*q[i : i + 3]) for i in range(0, len(q) - 2, 2) - ] - - # Find sharp corners; they have to be oncurves for sure. - forced = set() - for i in range(1, len(elevated_quadratics)): - p0 = elevated_quadratics[i - 1][2] - p1 = elevated_quadratics[i][0] - p2 = elevated_quadratics[i][1] - if abs(p1 - p0) + abs(p2 - p1) > tolerance + abs(p2 - p0): - forced.add(i) - - # Dynamic-Programming to find the solution with fewest number of - # cubic curves, and within those the one with smallest error. - sols = [Solution(0, 0, 0, False)] - impossible = Solution(len(elevated_quadratics) * 3 + 1, 0, 1, False) - start = 0 - for i in range(1, len(elevated_quadratics) + 1): - best_sol = impossible - for j in range(start, i): - j_sol_count, j_sol_error = sols[j].num_points, sols[j].error - - if not all_cubic: - # Solution with quadratics between j:i - this_count = costs[2 * i - 1] - costs[2 * j] + 1 - i_sol_count = j_sol_count + this_count - i_sol_error = j_sol_error - i_sol = Solution(i_sol_count, i_sol_error, i - j, False) - if i_sol < best_sol: - best_sol = i_sol - - if this_count <= 3: - # Can't get any better than this in the path below - continue - - # Fit elevated_quadratics[j:i] into one cubic - try: - curve, ts = merge_curves(elevated_quadratics, j, i - j) - except ZeroDivisionError: - continue - - # Now reconstruct the segments from the fitted curve - reconstructed_iter = splitCubicAtTC(*curve, *ts) - reconstructed = [] - - # Knot errors - error = 0 - for k, reconst in enumerate(reconstructed_iter): - orig = elevated_quadratics[j + k] - err = abs(reconst[3] - orig[3]) - error = max(error, err) - if error > tolerance: - break - reconstructed.append(reconst) - if error > tolerance: - # Not feasible - continue - - # Interior errors - for k, reconst in enumerate(reconstructed): - orig = elevated_quadratics[j + k] - p0, p1, p2, p3 = tuple(v - u for v, u in zip(reconst, orig)) - - if not cubic_farthest_fit_inside(p0, p1, p2, p3, tolerance): - error = tolerance + 1 - break - if error > tolerance: - # Not feasible - continue - - # Save best solution - i_sol_count = j_sol_count + 3 - i_sol_error = max(j_sol_error, error) - i_sol = Solution(i_sol_count, i_sol_error, i - j, True) - if i_sol < best_sol: - best_sol = i_sol - - if i_sol_count == 3: - # Can't get any better than this - break - - sols.append(best_sol) - if i in forced: - start = i - - # Reconstruct solution - splits = [] - cubic = [] - i = len(sols) - 1 - while i: - count, is_cubic = sols[i].start_index, sols[i].is_cubic - splits.append(i) - cubic.append(is_cubic) - i -= count - curves = [] - j = 0 - for i, is_cubic in reversed(list(zip(splits, cubic))): - if is_cubic: - curves.append(merge_curves(elevated_quadratics, j, i - j)[0]) - else: - for k in range(j, i): - curves.append(q[k * 2 : k * 2 + 3]) - j = i - - return curves - - -def main(): - from fontTools.cu2qu.benchmark import generate_curve - from fontTools.cu2qu import curve_to_quadratic - - tolerance = 0.05 - reconstruct_tolerance = tolerance * 1 - curve = generate_curve() - quadratics = curve_to_quadratic(curve, tolerance) - print( - "cu2qu tolerance %g. qu2cu tolerance %g." % (tolerance, reconstruct_tolerance) - ) - print("One random cubic turned into %d quadratics." % len(quadratics)) - curves = quadratic_to_curves([quadratics], reconstruct_tolerance) - print("Those quadratics turned back into %d cubics. " % len(curves)) - print("Original curve:", curve) - print("Reconstructed curve(s):", curves) - - -if __name__ == "__main__": - main() diff --git a/spaces/chuan-hd/law-assistant-chatbot/.venv/lib/python3.11/site-packages/functorch/experimental/__init__.py b/spaces/chuan-hd/law-assistant-chatbot/.venv/lib/python3.11/site-packages/functorch/experimental/__init__.py deleted file mode 100644 index 655534c2a3756f5c3261580d99dca9387c96eb1d..0000000000000000000000000000000000000000 --- a/spaces/chuan-hd/law-assistant-chatbot/.venv/lib/python3.11/site-packages/functorch/experimental/__init__.py +++ /dev/null @@ -1,5 +0,0 @@ -# PyTorch forward-mode is not mature yet -from torch._functorch.eager_transforms import hessian, jacfwd, jvp -from torch._functorch.vmap import chunk_vmap -from torch._functorch.batch_norm_replacement import replace_all_batch_norm_modules_ -from functorch import functionalize diff --git a/spaces/cihyFjudo/fairness-paper-search/Hot Sexy Voyuer Pics Hindi Sex Kahaniya Sex Vidi Com Avi.md b/spaces/cihyFjudo/fairness-paper-search/Hot Sexy Voyuer Pics Hindi Sex Kahaniya Sex Vidi Com Avi.md deleted file mode 100644 index 90f6b40efc11c048653ebd951417d5cd7f1fffa1..0000000000000000000000000000000000000000 --- a/spaces/cihyFjudo/fairness-paper-search/Hot Sexy Voyuer Pics Hindi Sex Kahaniya Sex Vidi Com Avi.md +++ /dev/null @@ -1,6 +0,0 @@ -

hot sexy voyuer pics Hindi Sex kahaniya Sex vidi com avi


Downloadhttps://tinurli.com/2uwi8r



-
- aaccfb2cb3
-
-
-

diff --git a/spaces/cihyFjudo/fairness-paper-search/O Mundo Sombrio das Altas Apostas em Cartas na Mesa Dublado.md b/spaces/cihyFjudo/fairness-paper-search/O Mundo Sombrio das Altas Apostas em Cartas na Mesa Dublado.md deleted file mode 100644 index e4e005f8f4065a1ac154e879849286ba08983975..0000000000000000000000000000000000000000 --- a/spaces/cihyFjudo/fairness-paper-search/O Mundo Sombrio das Altas Apostas em Cartas na Mesa Dublado.md +++ /dev/null @@ -1,11 +0,0 @@ -
-

Rounders é uma história de um par de escola de preparação amigos, Matt Damon e Edward Norton, que são um par de poker tubarões. Damon's usou seus ganhos para pagar a faculdade de direito e Norton's ido para outras empresas, como roubo de identidade, que pousou-lhe um estiramento na prisão.Damon depois de ser tomadas para a limpeza pelo russo mob cara de John Malkovich tem dado em cima de poker para a faculdade de direito. Norton's terminando o seu trecho em comum e acontece que ele deve Malkovich de alguns pesados dívida. Ele's que necessitam de ajuda, especialmente depois da etapa de disjuntor de Michael Rispoli dá Norton uma amostra do que ele pode esperar. Damon deve Norton bem para não ratting-lhe para fora em alguma escola de preparação golpe que poderia ter ficado com ele expulsos, como o Norton. Escusado será dizer que ele vai voltar para a vida.I'm disposto a apostar (sem trocadilhos) que, devido Rounders saiu logo depois de uma Boa Caça que este foi um projeto que pretende para Damon e Ben Affleck. Eu acho que Ben, provavelmente, mostrou bom senso em pensar que ele não estava muito certo para o papel. Certamente Norton, que reproduz alguns realmente nervoso personagens foi muito melhor para o papel de Lester 'Worm' Murphy.Damon faz tudo certo para si mesmo como o standup Mike McDermott. Ele também porque ele descargas a dívida que tem com o Norton, percebe-se que ele deve seguir o seu sonho também. O que é e como o filme termina eu não't dizer, mas se você tem um sonho, você tem que segui-lo, porque você não't saber se você don't tentar. Além de tudo o Basebol é um olhar para o mundo dos profissionais de jogos de azar. Como Damon diz, mesmo se você jogar é honesto,'s muito mais sorte do que habilidade. Leia o adversário, não as cartas.Rounders foi uma grande carreira continuação do aclamado Boa Caça para Matt Damon. Mesmo se você're não um jogador, por natureza, este filme vai fascinar um.

-

cartas na mesa dublado


Download Zip ○○○ https://tinurli.com/2uwiEW



-

Filmes Online - Assistir Filmes Online - Filmes Online Grátis - Filmes Completos Dublados
O vizer é uma plataforma de site e aplicativo para assistir filmes x series online grátis!O nosso site atualiza todas as séries no dia em legendado e dublado, e como o nosso site é um indexador automático, somos os mais rápidos postadores do Brasil.Vizer não armazena mega filmes e series em nosso site, por isso é completamente dentro da lei. O vizer indexa conteudo encontrado na web automáticamente usando Robots e Inteligência artificial.O uso do vizer é totalmente responsabilidade do usuário. A distribuição de filmes é da parte de plataformas como mystream, fembed entre outros. Qualquer violação de direitos autorais, entre em contato com o distribuidor.Em caso de dúvidas ou reclamações sobre conteúdo, funcionalidade do site, anúncios entre outros, entre em contato com a equipe de suporte.

-

Tudo de Mim
O que eu faria sem seu sarcasmoEstou me arrastando e você está me dispensandoEstou com a cabeça a mil, sem brincadeiraNão posso te forçar a nadaO que está se passando nessa mente lindaEstou passando pelo seu mágico mistérioE estou tão confuso que não sei o que me atingiuMas eu vou ficar bem
Minha cabeça está embaixo da águaMas estou respirando bemVocê é louca e eu estou fora de controle
Porque tudo de mimAma tudo em vocêAma suas curvas e todos os seus limitesTodas as suas perfeitas imperfeiçõesDê tudo de você para mimEu te darei meu tudoVocê é o meu fim e meu começoMesmo quando perco estou ganhandoPorque te dou tudo de mimE você me dá tudo de você oh
Quantas vezes tenho que te dizerQue mesmo quando você está chorando você continua lindaO mundo está te massacrandoEstou por perto a todo o momentoVocê é minha ruína, você é minha musaMinha pior distração, meu ritmo e tristezaNão consigo parar de cantarEstá tocando uma música em minha cabeça para você
Minha cabeça está embaixo da águaMas estou respirando bemVocê é louca e eu estou fora de controle
Porque tudo de mimAma tudo em vocêAma suas curvas e todos os seus limitesTodas as suas perfeitas imperfeiçõesDê tudo de você para mimEu te darei meu tudoVocê é o meu fim e meu começoMesmo quando perco estou ganhandoPorque te dou tudo de mimE você me dá tudo de você ohMe dá tudo de você
As cartas na mesa, estamos mostrando os nossos coraçõesArriscando tudo, apesar de isso ser difícil
Porque tudo de mimAma tudo em vocêAma suas curvas e todos os seus limitesTodas as suas perfeitas imperfeiçõesDê tudo de você para mimEu te darei meu tudoVocê é o meu fim e meu começoMesmo quando perco estou ganhandoPorque te dou tudo de mimE você me dá tudo de você oh
Te dou tudo de mimE você me dá tudo de você ohAll Of Me
What would I do without your smart mouthDrawing me in and you kicking me outGot my head spinning, no kiddingI can't pin you downWhat's going on in that beautiful mindI'm on your magical mystery rideAnd I'm so dizzy, don't know what hit meBut I'll be alright
My head's under waterBut I'm breathing fineYou're crazy and I'm out of my mind
'Cause all of meLoves all of youLove your curves and all your edgesAll your perfect imperfectionsGive your all to meI'll give my all to youYou're my end and my beginningEven when I lose I'm winning'Cause I give you all of meAnd you give me all of you oh
How many times do I have to tell youEven when you're crying you're beautiful tooThe world is beating you downI'm around through every moodYou're my downfall, you're my museMy worst distraction, my rhythm and bluesI can't stop singingIt's ringing, in my head for you
My head's under waterBut I'm breathing fineYou're crazy and I'm out of my mind
'Cause all of meLoves all of youLove your curves and all your edgesAll your perfect imperfectionsGive your all to meI'll give my all to youYou're my end and my beginningEven when I lose I'm winning'Cause I give you all of meAnd you give me all of youGive me all of you
Cards on the table, we're both showing heartsRisking it all, though it's hard
'Cause all of meLoves all of youLove your curves and all your edgesAll your perfect imperfectionsGive your all to meI'll give my all to youYou're my end and my beginningEven when I lose I'm winning'Cause I give you all of meAnd you give me all of you
I give you all of meAnd you give me all of you ohEncontrou algum erro na letra? Por favor, envie uma correção >Compartilhe
esta músicaComentar ÚLTIMAS

  • Jennifer Lopez e Ben Affleck fazem dueto romântico durante festa de fim de ano. Veja!

    -

    Cartas na Mesa, filme completo - Mike McDermott, que também é estudante de direito, é um jogador de cartas de mesmo nunca perder. Quando seu melhor amigo fora da prisão e descobre que ainda deve uma grande quantia de dinheiro a um gangster perigoso, decide jogar, enquanto sua namorada e seu tutor na universidade tinha sido desencorajado. No jogo de póquer que se destina a ajudar o amigo, envolvidos alguns jogadores bastante escuras, incluindo o pérfido Teddy KGB. Você pode assistir Rounders em Português em TV cable ou cinemas com áudio original em Inglês ou dublado em português. Visto na HBO, este filme estreou no cinemas do Brasil em 1998. A edição em Blu-Ray e edição de DVD de filme completo foi vendido algum tempo depois de seu lançamento oficial na cinemas brasileiros.

    -


    Wendel Luís Bezerra da Silva (São Paulo, 18 de junho de 1974) é um ator, dublador, diretor de dublagem, locutor e youtuber brasileiro, na área desde os oito anos de idade. Tem quatro irmãos, dos quais dois também seguem a carreira de dublador, Ulisses e Úrsula Bezerra. Também já escalou seus filhos para papéis de dublagem.

    -

    TRICOLINES ESTAMPADAS

    Você já conhece o tecido tricoline? em 100% algodão é super macio e versátil, sendo a escolha ideal para diversos tipos de costura criativa como patchwork, artesanato, vestuário adulto e infantil, camisaria e decoração no geral.

    Sua variedade em estampas possibilita a criação de lindos conjuntos em composês, ideal na costura dedicada à mesa como jogos americanos, sousplats e guardanapos. Legal, né? Deixe sua criatividade fluir com uma de nossas estampas!

    Composição: 100% Algodão.
    Largura: 1,50m de largura.
    Gramatura: 130 G/M².

    Você gostaria de divulgar seu trabalho? Marque @jlmtecidos em suas criações no instagram para aparecer em nossos stories.

    ATENÇÃO: Variações nas tonalidades das fotos para o tecido real podem ocorrer devido a calibração de cada tela de computador ou celular. Agradecemos a sua compreensão!

    -

    aaccfb2cb3
    -
    -
    \ No newline at end of file diff --git a/spaces/cihyFjudo/fairness-paper-search/Skripta Za Voditelja Brodice Download jaelzandy Master the Skills of Boating with This PDF Document.md b/spaces/cihyFjudo/fairness-paper-search/Skripta Za Voditelja Brodice Download jaelzandy Master the Skills of Boating with This PDF Document.md deleted file mode 100644 index 0e692453d4b13a7fa8cc6abf98cbba74cd0f0b07..0000000000000000000000000000000000000000 --- a/spaces/cihyFjudo/fairness-paper-search/Skripta Za Voditelja Brodice Download jaelzandy Master the Skills of Boating with This PDF Document.md +++ /dev/null @@ -1,6 +0,0 @@ -

    Skripta Za Voditelja Brodice Download jaelzandy


    DOWNLOADhttps://tinurli.com/2uwjQv



    -
    - aaccfb2cb3
    -
    -
    -

    diff --git a/spaces/cloudtheboi/Lofi4All/.pythonlibs/lib/python3.10/site-packages/attr/__init__.py b/spaces/cloudtheboi/Lofi4All/.pythonlibs/lib/python3.10/site-packages/attr/__init__.py deleted file mode 100644 index 7cfa792f744b7e0b4e28a536c0603f142ded6518..0000000000000000000000000000000000000000 --- a/spaces/cloudtheboi/Lofi4All/.pythonlibs/lib/python3.10/site-packages/attr/__init__.py +++ /dev/null @@ -1,132 +0,0 @@ -# SPDX-License-Identifier: MIT - -""" -Classes Without Boilerplate -""" - -from functools import partial -from typing import Callable - -from . import converters, exceptions, filters, setters, validators -from ._cmp import cmp_using -from ._config import get_run_validators, set_run_validators -from ._funcs import asdict, assoc, astuple, evolve, has, resolve_types -from ._make import ( - NOTHING, - Attribute, - Factory, - attrib, - attrs, - fields, - fields_dict, - make_class, - validate, -) -from ._next_gen import define, field, frozen, mutable -from ._version_info import VersionInfo - - -s = attributes = attrs -ib = attr = attrib -dataclass = partial(attrs, auto_attribs=True) # happy Easter ;) - - -class AttrsInstance: - pass - - -__all__ = [ - "Attribute", - "AttrsInstance", - "Factory", - "NOTHING", - "asdict", - "assoc", - "astuple", - "attr", - "attrib", - "attributes", - "attrs", - "cmp_using", - "converters", - "define", - "evolve", - "exceptions", - "field", - "fields", - "fields_dict", - "filters", - "frozen", - "get_run_validators", - "has", - "ib", - "make_class", - "mutable", - "resolve_types", - "s", - "set_run_validators", - "setters", - "validate", - "validators", -] - - -def _make_getattr(mod_name: str) -> Callable: - """ - Create a metadata proxy for packaging information that uses *mod_name* in - its warnings and errors. - """ - - def __getattr__(name: str) -> str: - dunder_to_metadata = { - "__title__": "Name", - "__copyright__": "", - "__version__": "version", - "__version_info__": "version", - "__description__": "summary", - "__uri__": "", - "__url__": "", - "__author__": "", - "__email__": "", - "__license__": "license", - } - if name not in dunder_to_metadata.keys(): - raise AttributeError(f"module {mod_name} has no attribute {name}") - - import sys - import warnings - - if sys.version_info < (3, 8): - from importlib_metadata import metadata - else: - from importlib.metadata import metadata - - if name != "__version_info__": - warnings.warn( - f"Accessing {mod_name}.{name} is deprecated and will be " - "removed in a future release. Use importlib.metadata directly " - "to query for attrs's packaging metadata.", - DeprecationWarning, - stacklevel=2, - ) - - meta = metadata("attrs") - if name == "__license__": - return "MIT" - elif name == "__copyright__": - return "Copyright (c) 2015 Hynek Schlawack" - elif name in ("__uri__", "__url__"): - return meta["Project-URL"].split(" ", 1)[-1] - elif name == "__version_info__": - return VersionInfo._from_version_string(meta["version"]) - elif name == "__author__": - return meta["Author-email"].rsplit(" ", 1)[0] - elif name == "__email__": - return meta["Author-email"].rsplit("<", 1)[1][:-1] - - return meta[dunder_to_metadata[name]] - - return __getattr__ - - -__getattr__ = _make_getattr(__name__) diff --git a/spaces/cloudtheboi/Lofi4All/.pythonlibs/lib/python3.10/site-packages/fontTools/pens/statisticsPen.py b/spaces/cloudtheboi/Lofi4All/.pythonlibs/lib/python3.10/site-packages/fontTools/pens/statisticsPen.py deleted file mode 100644 index 8e00aa44da6a005f9c246f8c8e752a95ee601e0d..0000000000000000000000000000000000000000 --- a/spaces/cloudtheboi/Lofi4All/.pythonlibs/lib/python3.10/site-packages/fontTools/pens/statisticsPen.py +++ /dev/null @@ -1,195 +0,0 @@ -"""Pen calculating area, center of mass, variance and standard-deviation, -covariance and correlation, and slant, of glyph shapes.""" -import math -from fontTools.pens.momentsPen import MomentsPen - -__all__ = ["StatisticsPen"] - - -class StatisticsPen(MomentsPen): - - """Pen calculating area, center of mass, variance and - standard-deviation, covariance and correlation, and slant, - of glyph shapes. - - Note that all the calculated values are 'signed'. Ie. if the - glyph shape is self-intersecting, the values are not correct - (but well-defined). As such, area will be negative if contour - directions are clockwise. Moreover, variance might be negative - if the shapes are self-intersecting in certain ways.""" - - def __init__(self, glyphset=None): - MomentsPen.__init__(self, glyphset=glyphset) - self.__zero() - - def _closePath(self): - MomentsPen._closePath(self) - self.__update() - - def __zero(self): - self.meanX = 0 - self.meanY = 0 - self.varianceX = 0 - self.varianceY = 0 - self.stddevX = 0 - self.stddevY = 0 - self.covariance = 0 - self.correlation = 0 - self.slant = 0 - - def __update(self): - area = self.area - if not area: - self.__zero() - return - - # Center of mass - # https://en.wikipedia.org/wiki/Center_of_mass#A_continuous_volume - self.meanX = meanX = self.momentX / area - self.meanY = meanY = self.momentY / area - - # Var(X) = E[X^2] - E[X]^2 - self.varianceX = varianceX = self.momentXX / area - meanX**2 - self.varianceY = varianceY = self.momentYY / area - meanY**2 - - self.stddevX = stddevX = math.copysign(abs(varianceX) ** 0.5, varianceX) - self.stddevY = stddevY = math.copysign(abs(varianceY) ** 0.5, varianceY) - - # Covariance(X,Y) = ( E[X.Y] - E[X]E[Y] ) - self.covariance = covariance = self.momentXY / area - meanX * meanY - - # Correlation(X,Y) = Covariance(X,Y) / ( stddev(X) * stddev(Y) ) - # https://en.wikipedia.org/wiki/Pearson_product-moment_correlation_coefficient - if stddevX * stddevY == 0: - correlation = float("NaN") - else: - correlation = covariance / (stddevX * stddevY) - self.correlation = correlation if abs(correlation) > 1e-3 else 0 - - slant = covariance / varianceY if varianceY != 0 else float("NaN") - self.slant = slant if abs(slant) > 1e-3 else 0 - - -def _test(glyphset, upem, glyphs, quiet=False): - from fontTools.pens.transformPen import TransformPen - from fontTools.misc.transform import Scale - - wght_sum = 0 - wght_sum_perceptual = 0 - wdth_sum = 0 - slnt_sum = 0 - slnt_sum_perceptual = 0 - for glyph_name in glyphs: - glyph = glyphset[glyph_name] - pen = StatisticsPen(glyphset=glyphset) - transformer = TransformPen(pen, Scale(1.0 / upem)) - glyph.draw(transformer) - - wght_sum += abs(pen.area) - wght_sum_perceptual += abs(pen.area) * glyph.width - wdth_sum += glyph.width - slnt_sum += pen.slant - slnt_sum_perceptual += pen.slant * glyph.width - - if quiet: - continue - - print() - print("glyph:", glyph_name) - - for item in [ - "area", - "momentX", - "momentY", - "momentXX", - "momentYY", - "momentXY", - "meanX", - "meanY", - "varianceX", - "varianceY", - "stddevX", - "stddevY", - "covariance", - "correlation", - "slant", - ]: - print("%s: %g" % (item, getattr(pen, item))) - - if not quiet: - print() - print("font:") - - print("weight: %g" % (wght_sum * upem / wdth_sum)) - print("weight (perceptual): %g" % (wght_sum_perceptual / wdth_sum)) - print("width: %g" % (wdth_sum / upem / len(glyphs))) - slant = slnt_sum / len(glyphs) - print("slant: %g" % slant) - print("slant angle: %g" % -math.degrees(math.atan(slant))) - slant_perceptual = slnt_sum_perceptual / wdth_sum - print("slant (perceptual): %g" % slant_perceptual) - print("slant (perceptual) angle: %g" % -math.degrees(math.atan(slant_perceptual))) - - -def main(args): - """Report font glyph shape geometricsl statistics""" - - if args is None: - import sys - - args = sys.argv[1:] - - import argparse - - parser = argparse.ArgumentParser( - "fonttools pens.statisticsPen", - description="Report font glyph shape geometricsl statistics", - ) - parser.add_argument("font", metavar="font.ttf", help="Font file.") - parser.add_argument("glyphs", metavar="glyph-name", help="Glyph names.", nargs="*") - parser.add_argument( - "-y", - metavar="", - help="Face index into a collection to open. Zero based.", - ) - parser.add_argument( - "-q", "--quiet", action="store_true", help="Only report font-wide statistics." - ) - parser.add_argument( - "--variations", - metavar="AXIS=LOC", - default="", - help="List of space separated locations. A location consist in " - "the name of a variation axis, followed by '=' and a number. E.g.: " - "wght=700 wdth=80. The default is the location of the base master.", - ) - - options = parser.parse_args(args) - - glyphs = options.glyphs - fontNumber = int(options.y) if options.y is not None else 0 - - location = {} - for tag_v in options.variations.split(): - fields = tag_v.split("=") - tag = fields[0].strip() - v = int(fields[1]) - location[tag] = v - - from fontTools.ttLib import TTFont - - font = TTFont(options.font, fontNumber=fontNumber) - if not glyphs: - glyphs = font.getGlyphOrder() - _test( - font.getGlyphSet(location=location), - font["head"].unitsPerEm, - glyphs, - quiet=options.quiet, - ) - - -if __name__ == "__main__": - import sys - - main(sys.argv[1:]) diff --git a/spaces/colakin/video-generater/public/assets/js/browser.min.js b/spaces/colakin/video-generater/public/assets/js/browser.min.js deleted file mode 100644 index f96349691342905a3e41f063a8030f3075198708..0000000000000000000000000000000000000000 --- a/spaces/colakin/video-generater/public/assets/js/browser.min.js +++ /dev/null @@ -1,2 +0,0 @@ -/* browser.js v1.0.1 | @ajlkn | MIT licensed */ -var browser=function(){"use strict";var t={name:null,version:null,os:null,osVersion:null,touch:null,mobile:null,_canUse:null,canUse:function(e){t._canUse||(t._canUse=document.createElement("div"));var n=t._canUse.style,r=e.charAt(0).toUpperCase()+e.slice(1);return e in n||"Moz"+r in n||"Webkit"+r in n||"O"+r in n||"ms"+r in n},init:function(){for(var e=navigator.userAgent,n="other",r=0,i=[["firefox",/Firefox\/([0-9\.]+)/],["bb",/BlackBerry.+Version\/([0-9\.]+)/],["bb",/BB[0-9]+.+Version\/([0-9\.]+)/],["opera",/OPR\/([0-9\.]+)/],["opera",/Opera\/([0-9\.]+)/],["edge",/Edge\/([0-9\.]+)/],["safari",/Version\/([0-9\.]+).+Safari/],["chrome",/Chrome\/([0-9\.]+)/],["ie",/MSIE ([0-9]+)/],["ie",/Trident\/.+rv:([0-9]+)/]],o=0;o - * - * This file is part of FFmpeg. - * - * FFmpeg is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * FFmpeg is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with FFmpeg; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#ifndef AVCODEC_AC3DEC_DATA_H -#define AVCODEC_AC3DEC_DATA_H - -#include - -extern const uint8_t ff_ac3_ungroup_3_in_5_bits_tab[32][3]; - -extern const uint8_t ff_eac3_hebap_tab[64]; -extern const uint8_t ff_eac3_default_spx_band_struct[17]; - -#endif /* AVCODEC_AC3DEC_DATA_H */ diff --git a/spaces/colakin/video-generater/public/ffmpeg/libavcodec/diracdsp.c b/spaces/colakin/video-generater/public/ffmpeg/libavcodec/diracdsp.c deleted file mode 100644 index 284f914f9d477567815946cf31076b38d157ab1b..0000000000000000000000000000000000000000 --- a/spaces/colakin/video-generater/public/ffmpeg/libavcodec/diracdsp.c +++ /dev/null @@ -1,253 +0,0 @@ -/* - * Copyright (C) 2009 David Conrad - * - * This file is part of FFmpeg. - * - * FFmpeg is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * FFmpeg is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with FFmpeg; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#include "config.h" -#include "libavutil/attributes.h" -#include "libavutil/common.h" -#include "diracdsp.h" - -#define FILTER(src, stride) \ - ((21*((src)[ 0*stride] + (src)[1*stride]) \ - -7*((src)[-1*stride] + (src)[2*stride]) \ - +3*((src)[-2*stride] + (src)[3*stride]) \ - -1*((src)[-3*stride] + (src)[4*stride]) + 16) >> 5) - -static void dirac_hpel_filter(uint8_t *dsth, uint8_t *dstv, uint8_t *dstc, const uint8_t *src, - int stride, int width, int height) -{ - int x, y; - - for (y = 0; y < height; y++) { - for (x = -3; x < width+5; x++) - dstv[x] = av_clip_uint8(FILTER(src+x, stride)); - - for (x = 0; x < width; x++) - dstc[x] = av_clip_uint8(FILTER(dstv+x, 1)); - - for (x = 0; x < width; x++) - dsth[x] = av_clip_uint8(FILTER(src+x, 1)); - - src += stride; - dsth += stride; - dstv += stride; - dstc += stride; - } -} - -#define PIXOP_BILINEAR(PFX, OP, WIDTH) \ - static void ff_ ## PFX ## _dirac_pixels ## WIDTH ## _bilinear_c(uint8_t *dst, const uint8_t *src[5], int stride, int h) \ - { \ - int x; \ - const uint8_t *s0 = src[0]; \ - const uint8_t *s1 = src[1]; \ - const uint8_t *s2 = src[2]; \ - const uint8_t *s3 = src[3]; \ - const uint8_t *w = src[4]; \ - \ - while (h--) { \ - for (x = 0; x < WIDTH; x++) { \ - OP(dst[x], (s0[x]*w[0] + s1[x]*w[1] + s2[x]*w[2] + s3[x]*w[3] + 8) >> 4); \ - } \ - \ - dst += stride; \ - s0 += stride; \ - s1 += stride; \ - s2 += stride; \ - s3 += stride; \ - } \ - } - -#define OP_PUT(dst, val) (dst) = (val) -#define OP_AVG(dst, val) (dst) = (((dst) + (val) + 1)>>1) - -PIXOP_BILINEAR(put, OP_PUT, 8) -PIXOP_BILINEAR(put, OP_PUT, 16) -PIXOP_BILINEAR(put, OP_PUT, 32) -PIXOP_BILINEAR(avg, OP_AVG, 8) -PIXOP_BILINEAR(avg, OP_AVG, 16) -PIXOP_BILINEAR(avg, OP_AVG, 32) - -#define op_scale1(x) block[x] = av_clip_uint8( (block[x]*weight + (1<<(log2_denom-1))) >> log2_denom) -#define op_scale2(x) dst[x] = av_clip_uint8( (src[x]*weights + dst[x]*weightd + (1<<(log2_denom-1))) >> log2_denom) - -#define DIRAC_WEIGHT(W) \ - static void weight_dirac_pixels ## W ## _c(uint8_t *block, int stride, int log2_denom, \ - int weight, int h) { \ - int x; \ - while (h--) { \ - for (x = 0; x < W; x++) { \ - op_scale1(x); \ - op_scale1(x+1); \ - } \ - block += stride; \ - } \ - } \ - static void biweight_dirac_pixels ## W ## _c(uint8_t *dst, const uint8_t *src, int stride, int log2_denom, \ - int weightd, int weights, int h) { \ - int x; \ - while (h--) { \ - for (x = 0; x < W; x++) { \ - op_scale2(x); \ - op_scale2(x+1); \ - } \ - dst += stride; \ - src += stride; \ - } \ - } - -DIRAC_WEIGHT(8) -DIRAC_WEIGHT(16) -DIRAC_WEIGHT(32) - -#define ADD_OBMC(xblen) \ - static void add_obmc ## xblen ## _c(uint16_t *dst, const uint8_t *src, int stride, \ - const uint8_t *obmc_weight, int yblen) \ - { \ - int x; \ - while (yblen--) { \ - for (x = 0; x < xblen; x += 2) { \ - dst[x ] += src[x ] * obmc_weight[x ]; \ - dst[x+1] += src[x+1] * obmc_weight[x+1]; \ - } \ - dst += stride; \ - src += stride; \ - obmc_weight += 32; \ - } \ - } - -ADD_OBMC(8) -ADD_OBMC(16) -ADD_OBMC(32) - -static void put_signed_rect_clamped_8bit_c(uint8_t *dst, int dst_stride, const uint8_t *_src, int src_stride, int width, int height) -{ - int x, y; - const int16_t *src = (const int16_t *)_src; - for (y = 0; y < height; y++) { - for (x = 0; x < width; x+=4) { - dst[x ] = av_clip_uint8(src[x ] + 128); - dst[x+1] = av_clip_uint8(src[x+1] + 128); - dst[x+2] = av_clip_uint8(src[x+2] + 128); - dst[x+3] = av_clip_uint8(src[x+3] + 128); - } - dst += dst_stride; - src += src_stride >> 1; - } -} - -#define PUT_SIGNED_RECT_CLAMPED(PX) \ -static void put_signed_rect_clamped_ ## PX ## bit_c(uint8_t *_dst, int dst_stride, const uint8_t *_src, \ - int src_stride, int width, int height) \ -{ \ - int x, y; \ - uint16_t *dst = (uint16_t *)_dst; \ - const int32_t *src = (const int32_t *)_src; \ - for (y = 0; y < height; y++) { \ - for (x = 0; x < width; x+=4) { \ - dst[x ] = av_clip_uintp2(src[x ] + (1U << (PX - 1)), PX); \ - dst[x+1] = av_clip_uintp2(src[x+1] + (1U << (PX - 1)), PX); \ - dst[x+2] = av_clip_uintp2(src[x+2] + (1U << (PX - 1)), PX); \ - dst[x+3] = av_clip_uintp2(src[x+3] + (1U << (PX - 1)), PX); \ - } \ - dst += dst_stride >> 1; \ - src += src_stride >> 2; \ - } \ -} - -PUT_SIGNED_RECT_CLAMPED(10) -PUT_SIGNED_RECT_CLAMPED(12) - -static void add_rect_clamped_c(uint8_t *dst, const uint16_t *src, int stride, - const int16_t *idwt, int idwt_stride, - int width, int height) -{ - int x, y; - - for (y = 0; y < height; y++) { - for (x = 0; x < width; x+=2) { - dst[x ] = av_clip_uint8(((src[x ]+32)>>6) + idwt[x ]); - dst[x+1] = av_clip_uint8(((src[x+1]+32)>>6) + idwt[x+1]); - } - dst += stride; - src += stride; - idwt += idwt_stride; - } -} - -#define DEQUANT_SUBBAND(PX) \ -static void dequant_subband_ ## PX ## _c(uint8_t *src, uint8_t *dst, ptrdiff_t stride, \ - const int qf, const int qs, int tot_v, int tot_h) \ -{ \ - int i, y; \ - for (y = 0; y < tot_v; y++) { \ - PX c, *src_r = (PX *)src, *dst_r = (PX *)dst; \ - for (i = 0; i < tot_h; i++) { \ - c = *src_r++; \ - if (c < 0) c = -((-(unsigned)c*qf + qs) >> 2); \ - else if(c > 0) c = (( (unsigned)c*qf + qs) >> 2); \ - *dst_r++ = c; \ - } \ - src += tot_h << (sizeof(PX) >> 1); \ - dst += stride; \ - } \ -} - -DEQUANT_SUBBAND(int16_t) -DEQUANT_SUBBAND(int32_t) - -#define PIXFUNC(PFX, WIDTH) \ - c->PFX ## _dirac_pixels_tab[WIDTH>>4][0] = ff_ ## PFX ## _dirac_pixels ## WIDTH ## _c; \ - c->PFX ## _dirac_pixels_tab[WIDTH>>4][1] = ff_ ## PFX ## _dirac_pixels ## WIDTH ## _l2_c; \ - c->PFX ## _dirac_pixels_tab[WIDTH>>4][2] = ff_ ## PFX ## _dirac_pixels ## WIDTH ## _l4_c; \ - c->PFX ## _dirac_pixels_tab[WIDTH>>4][3] = ff_ ## PFX ## _dirac_pixels ## WIDTH ## _bilinear_c - -av_cold void ff_diracdsp_init(DiracDSPContext *c) -{ - c->dirac_hpel_filter = dirac_hpel_filter; - c->add_rect_clamped = add_rect_clamped_c; - c->put_signed_rect_clamped[0] = put_signed_rect_clamped_8bit_c; - c->put_signed_rect_clamped[1] = put_signed_rect_clamped_10bit_c; - c->put_signed_rect_clamped[2] = put_signed_rect_clamped_12bit_c; - - c->add_dirac_obmc[0] = add_obmc8_c; - c->add_dirac_obmc[1] = add_obmc16_c; - c->add_dirac_obmc[2] = add_obmc32_c; - - c->weight_dirac_pixels_tab[0] = weight_dirac_pixels8_c; - c->weight_dirac_pixels_tab[1] = weight_dirac_pixels16_c; - c->weight_dirac_pixels_tab[2] = weight_dirac_pixels32_c; - c->biweight_dirac_pixels_tab[0] = biweight_dirac_pixels8_c; - c->biweight_dirac_pixels_tab[1] = biweight_dirac_pixels16_c; - c->biweight_dirac_pixels_tab[2] = biweight_dirac_pixels32_c; - - c->dequant_subband[0] = c->dequant_subband[2] = dequant_subband_int16_t_c; - c->dequant_subband[1] = c->dequant_subband[3] = dequant_subband_int32_t_c; - - PIXFUNC(put, 8); - PIXFUNC(put, 16); - PIXFUNC(put, 32); - PIXFUNC(avg, 8); - PIXFUNC(avg, 16); - PIXFUNC(avg, 32); - -#if ARCH_X86 - ff_diracdsp_init_x86(c); -#endif -} diff --git a/spaces/colakin/video-generater/public/ffmpeg/libavcodec/ivi_dsp.h b/spaces/colakin/video-generater/public/ffmpeg/libavcodec/ivi_dsp.h deleted file mode 100644 index 2704d2b9a540d5b9ed0792dc0f46d0d5c2e46514..0000000000000000000000000000000000000000 --- a/spaces/colakin/video-generater/public/ffmpeg/libavcodec/ivi_dsp.h +++ /dev/null @@ -1,348 +0,0 @@ -/* - * DSP functions for Indeo Video Interactive codecs (Indeo4 and Indeo5) - * - * Copyright (c) 2009-2011 Maxim Poliakovski - * - * This file is part of FFmpeg. - * - * FFmpeg is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * FFmpeg is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with FFmpeg; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ - -/** - * @file - * DSP functions (inverse transforms, motion compensations, wavelet recomposition) - * for Indeo Video Interactive codecs. - */ - -#ifndef AVCODEC_IVI_DSP_H -#define AVCODEC_IVI_DSP_H - -#include -#include - -#include "ivi.h" - -/** - * 5/3 wavelet recomposition filter for Indeo5 - * - * @param[in] plane pointer to the descriptor of the plane being processed - * @param[out] dst pointer to the destination buffer - * @param[in] dst_pitch pitch of the destination buffer - */ -void ff_ivi_recompose53(const IVIPlaneDesc *plane, uint8_t *dst, - const ptrdiff_t dst_pitch); - -/** - * Haar wavelet recomposition filter for Indeo 4 - * - * @param[in] plane pointer to the descriptor of the plane being processed - * @param[out] dst pointer to the destination buffer - * @param[in] dst_pitch pitch of the destination buffer - */ -void ff_ivi_recompose_haar(const IVIPlaneDesc *plane, uint8_t *dst, - const ptrdiff_t dst_pitch); - -/** - * two-dimensional inverse Haar 8x8 transform for Indeo 4 - * - * @param[in] in pointer to the vector of transform coefficients - * @param[out] out pointer to the output buffer (frame) - * @param[in] pitch pitch to move to the next y line - * @param[in] flags pointer to the array of column flags: - * != 0 - non_empty column, 0 - empty one - * (this array must be filled by caller) - */ -void ff_ivi_inverse_haar_8x8(const int32_t *in, int16_t *out, ptrdiff_t pitch, - const uint8_t *flags); -void ff_ivi_inverse_haar_8x1(const int32_t *in, int16_t *out, uint32_t pitch, - const uint8_t *flags); -void ff_ivi_inverse_haar_1x8(const int32_t *in, int16_t *out, uint32_t pitch, - const uint8_t *flags); - -/** - * one-dimensional inverse 8-point Haar transform on rows for Indeo 4 - * - * @param[in] in pointer to the vector of transform coefficients - * @param[out] out pointer to the output buffer (frame) - * @param[in] pitch pitch to move to the next y line - * @param[in] flags pointer to the array of column flags: - * != 0 - non_empty column, 0 - empty one - * (this array must be filled by caller) - */ -void ff_ivi_row_haar8(const int32_t *in, int16_t *out, ptrdiff_t pitch, - const uint8_t *flags); - -/** - * one-dimensional inverse 8-point Haar transform on columns for Indeo 4 - * - * @param[in] in pointer to the vector of transform coefficients - * @param[out] out pointer to the output buffer (frame) - * @param[in] pitch pitch to move to the next y line - * @param[in] flags pointer to the array of column flags: - * != 0 - non_empty column, 0 - empty one - * (this array must be filled by caller) - */ -void ff_ivi_col_haar8(const int32_t *in, int16_t *out, ptrdiff_t pitch, - const uint8_t *flags); - -/** - * two-dimensional inverse Haar 4x4 transform for Indeo 4 - * - * @param[in] in pointer to the vector of transform coefficients - * @param[out] out pointer to the output buffer (frame) - * @param[in] pitch pitch to move to the next y line - * @param[in] flags pointer to the array of column flags: - * != 0 - non_empty column, 0 - empty one - * (this array must be filled by caller) - */ -void ff_ivi_inverse_haar_4x4(const int32_t *in, int16_t *out, ptrdiff_t pitch, - const uint8_t *flags); - -/** - * one-dimensional inverse 4-point Haar transform on rows for Indeo 4 - * - * @param[in] in pointer to the vector of transform coefficients - * @param[out] out pointer to the output buffer (frame) - * @param[in] pitch pitch to move to the next y line - * @param[in] flags pointer to the array of column flags: - * != 0 - non_empty column, 0 - empty one - * (this array must be filled by caller) - */ -void ff_ivi_row_haar4(const int32_t *in, int16_t *out, ptrdiff_t pitch, - const uint8_t *flags); - -/** - * one-dimensional inverse 4-point Haar transform on columns for Indeo 4 - * - * @param[in] in pointer to the vector of transform coefficients - * @param[out] out pointer to the output buffer (frame) - * @param[in] pitch pitch to move to the next y line - * @param[in] flags pointer to the array of column flags: - * != 0 - non_empty column, 0 - empty one - * (this array must be filled by caller) - */ -void ff_ivi_col_haar4(const int32_t *in, int16_t *out, ptrdiff_t pitch, - const uint8_t *flags); - -/** - * DC-only two-dimensional inverse Haar transform for Indeo 4. - * Performing the inverse transform in this case is equivalent to - * spreading DC_coeff >> 3 over the whole block. - * - * @param[in] in pointer to the dc coefficient - * @param[out] out pointer to the output buffer (frame) - * @param[in] pitch pitch to move to the next y line - * @param[in] blk_size transform block size - */ -void ff_ivi_dc_haar_2d(const int32_t *in, int16_t *out, ptrdiff_t pitch, - int blk_size); - -/** - * two-dimensional inverse slant 8x8 transform - * - * @param[in] in pointer to the vector of transform coefficients - * @param[out] out pointer to the output buffer (frame) - * @param[in] pitch pitch to move to the next y line - * @param[in] flags pointer to the array of column flags: - * != 0 - non_empty column, 0 - empty one - * (this array must be filled by caller) - */ -void ff_ivi_inverse_slant_8x8(const int32_t *in, int16_t *out, ptrdiff_t pitch, - const uint8_t *flags); - -/** - * two-dimensional inverse slant 4x4 transform - * - * @param[in] in pointer to the vector of transform coefficients - * @param[out] out pointer to the output buffer (frame) - * @param[in] pitch pitch to move to the next y line - * @param[in] flags pointer to the array of column flags: - * != 0 - non_empty column, 0 - empty one - * (this array must be filled by caller) - */ -void ff_ivi_inverse_slant_4x4(const int32_t *in, int16_t *out, ptrdiff_t pitch, - const uint8_t *flags); - -/** - * DC-only two-dimensional inverse slant transform. - * Performing the inverse slant transform in this case is equivalent to - * spreading (DC_coeff + 1)/2 over the whole block. - * It works much faster than performing the slant transform on a vector of zeroes. - * - * @param[in] in pointer to the dc coefficient - * @param[out] out pointer to the output buffer (frame) - * @param[in] pitch pitch to move to the next y line - * @param[in] blk_size transform block size - */ -void ff_ivi_dc_slant_2d(const int32_t *in, int16_t *out, ptrdiff_t pitch, int blk_size); - -/** - * inverse 1D row slant transform - * - * @param[in] in pointer to the vector of transform coefficients - * @param[out] out pointer to the output buffer (frame) - * @param[in] pitch pitch to move to the next y line - * @param[in] flags pointer to the array of column flags (unused here) - */ -void ff_ivi_row_slant8(const int32_t *in, int16_t *out, ptrdiff_t pitch, - const uint8_t *flags); - -/** - * inverse 1D column slant transform - * - * @param[in] in pointer to the vector of transform coefficients - * @param[out] out pointer to the output buffer (frame) - * @param[in] pitch pitch to move to the next y line - * @param[in] flags pointer to the array of column flags: - * != 0 - non_empty column, 0 - empty one - * (this array must be filled by caller) - */ -void ff_ivi_col_slant8(const int32_t *in, int16_t *out, ptrdiff_t pitch, - const uint8_t *flags); - -/** - * inverse 1D row slant transform - * - * @param[in] in pointer to the vector of transform coefficients - * @param[out] out pointer to the output buffer (frame) - * @param[in] pitch pitch to move to the next y line - * @param[in] flags pointer to the array of column flags (unused here) - */ -void ff_ivi_row_slant4(const int32_t *in, int16_t *out, ptrdiff_t pitch, - const uint8_t *flags); - -/** - * inverse 1D column slant transform - * - * @param[in] in pointer to the vector of transform coefficients - * @param[out] out pointer to the output buffer (frame) - * @param[in] pitch pitch to move to the next y line - * @param[in] flags pointer to the array of column flags: - * != 0 - non_empty column, 0 - empty one - * (this array must be filled by caller) - */ -void ff_ivi_col_slant4(const int32_t *in, int16_t *out, ptrdiff_t pitch, - const uint8_t *flags); - -/** - * DC-only inverse row slant transform - */ -void ff_ivi_dc_row_slant(const int32_t *in, int16_t *out, ptrdiff_t pitch, int blk_size); - -/** - * DC-only inverse column slant transform - */ -void ff_ivi_dc_col_slant(const int32_t *in, int16_t *out, ptrdiff_t pitch, int blk_size); - -/** - * Copy the pixels into the frame buffer. - */ -void ff_ivi_put_pixels_8x8(const int32_t *in, int16_t *out, ptrdiff_t pitch, const uint8_t *flags); - -/** - * Copy the DC coefficient into the first pixel of the block and - * zero all others. - */ -void ff_ivi_put_dc_pixel_8x8(const int32_t *in, int16_t *out, ptrdiff_t pitch, int blk_size); - -/** - * 8x8 block motion compensation with adding delta - * - * @param[in,out] buf pointer to the block in the current frame buffer containing delta - * @param[in] ref_buf pointer to the corresponding block in the reference frame - * @param[in] pitch pitch for moving to the next y line - * @param[in] mc_type interpolation type - */ -void ff_ivi_mc_8x8_delta(int16_t *buf, const int16_t *ref_buf, ptrdiff_t pitch, int mc_type); - -/** - * 4x4 block motion compensation with adding delta - * - * @param[in,out] buf pointer to the block in the current frame buffer containing delta - * @param[in] ref_buf pointer to the corresponding block in the reference frame - * @param[in] pitch pitch for moving to the next y line - * @param[in] mc_type interpolation type - */ -void ff_ivi_mc_4x4_delta(int16_t *buf, const int16_t *ref_buf, ptrdiff_t pitch, int mc_type); - -/** - * motion compensation without adding delta - * - * @param[in,out] buf pointer to the block in the current frame receiving the result - * @param[in] ref_buf pointer to the corresponding block in the reference frame - * @param[in] pitch pitch for moving to the next y line - * @param[in] mc_type interpolation type - */ -void ff_ivi_mc_8x8_no_delta(int16_t *buf, const int16_t *ref_buf, ptrdiff_t pitch, int mc_type); - -/** - * 4x4 block motion compensation without adding delta - * - * @param[in,out] buf pointer to the block in the current frame receiving the result - * @param[in] ref_buf pointer to the corresponding block in the reference frame - * @param[in] pitch pitch for moving to the next y line - * @param[in] mc_type interpolation type - */ -void ff_ivi_mc_4x4_no_delta(int16_t *buf, const int16_t *ref_buf, ptrdiff_t pitch, int mc_type); - -/** - * 8x8 block motion compensation with adding delta - * - * @param[in,out] buf pointer to the block in the current frame buffer containing delta - * @param[in] ref_buf pointer to the corresponding block in the backward reference frame - * @param[in] ref_buf2 pointer to the corresponding block in the forward reference frame - * @param[in] pitch pitch for moving to the next y line - * @param[in] mc_type interpolation type for backward reference - * @param[in] mc_type2 interpolation type for forward reference - */ -void ff_ivi_mc_avg_8x8_delta(int16_t *buf, const int16_t *ref_buf, const int16_t *ref_buf2, ptrdiff_t pitch, int mc_type, int mc_type2); - -/** - * 4x4 block motion compensation with adding delta - * - * @param[in,out] buf pointer to the block in the current frame buffer containing delta - * @param[in] ref_buf pointer to the corresponding block in the backward reference frame - * @param[in] ref_buf2 pointer to the corresponding block in the forward reference frame - * @param[in] pitch pitch for moving to the next y line - * @param[in] mc_type interpolation type for backward reference - * @param[in] mc_type2 interpolation type for forward reference - */ -void ff_ivi_mc_avg_4x4_delta(int16_t *buf, const int16_t *ref_buf, const int16_t *ref_buf2, ptrdiff_t pitch, int mc_type, int mc_type2); - -/** - * motion compensation without adding delta for B-frames - * - * @param[in,out] buf pointer to the block in the current frame receiving the result - * @param[in] ref_buf pointer to the corresponding block in the backward reference frame - * @param[in] ref_buf2 pointer to the corresponding block in the forward reference frame - * @param[in] pitch pitch for moving to the next y line - * @param[in] mc_type interpolation type for backward reference - * @param[in] mc_type2 interpolation type for forward reference - */ -void ff_ivi_mc_avg_8x8_no_delta(int16_t *buf, const int16_t *ref_buf, const int16_t *ref_buf2, ptrdiff_t pitch, int mc_type, int mc_type2); - -/** - * 4x4 block motion compensation without adding delta for B-frames - * - * @param[in,out] buf pointer to the block in the current frame receiving the result - * @param[in] ref_buf pointer to the corresponding block in the backward reference frame - * @param[in] ref_buf2 pointer to the corresponding block in the forward reference frame - * @param[in] pitch pitch for moving to the next y line - * @param[in] mc_type interpolation type for backward reference - * @param[in] mc_type2 interpolation type for forward reference - */ -void ff_ivi_mc_avg_4x4_no_delta(int16_t *buf, const int16_t *ref_buf, const int16_t *ref_buf2, ptrdiff_t pitch, int mc_type, int mc_type2); - -#endif /* AVCODEC_IVI_DSP_H */ diff --git a/spaces/congsaPfin/Manga-OCR/logs/Music Recording Studio APK The Ultimate Guide for Android Users.md b/spaces/congsaPfin/Manga-OCR/logs/Music Recording Studio APK The Ultimate Guide for Android Users.md deleted file mode 100644 index c9eee7921d543997c76b950c83e0064da3d2d839..0000000000000000000000000000000000000000 --- a/spaces/congsaPfin/Manga-OCR/logs/Music Recording Studio APK The Ultimate Guide for Android Users.md +++ /dev/null @@ -1,156 +0,0 @@ - - - - - - - -
    -

    Music Recording Studio APK for Android: How to Turn Your Phone into a Professional Studio

    -

    Do you love making music but don't have access to a professional studio? Do you want to record, edit, and mix your own songs using your Android phone? If so, you might be interested in music recording studio APK for Android.

    -

    music recording studio apk for android


    Download Zip »»» https://urlca.com/2uO6TT



    -

    Music recording studio APK for Android is a type of application that allows you to turn your phone into a mini studio. You can use it to create high-quality music tracks using various features and tools. You can also share your music with others or export it to different formats.

    -

    In this article, we will show you how to choose, install, and use music recording studio APK for Android. We will also give you some tips on how to enhance your music production quality with this app. By the end of this article, you will be able to make amazing music with your phone.

    -

    How to Choose the Best Music Recording App for Android

    -

    There are many music recording apps available for Android devices. However, not all of them are equally good or suitable for your needs. Here are some features to look for in a music recording app:

    -
      -
    • Multi-track recording: This feature allows you to record multiple audio tracks simultaneously or separately and mix them together. This gives you more flexibility and creativity in your music production.
    • -
    • Audio editing: This feature allows you to cut, copy, paste, trim, fade, and adjust the volume and pitch of your audio tracks. You can also apply various effects and filters to enhance your sound quality.
    • -
    • Audio mixing: This feature allows you to balance the levels, panning, and equalization of your audio tracks. You can also add compression, reverb, delay, and other effects to create a professional sound.
    • -
    • Audio exporting and sharing: This feature allows you to save your music files in different formats such as MP3, WAV, OGG, etc. You can also share your music with others via email, social media, or cloud storage.
    • -
    -

    To compare different apps based on ratings, reviews, and price, you can use the Google Play Store or other online sources. You can also check out some YouTube videos or blogs that review music recording apps for Android.

    -

    Some examples of popular and reliable music recording apps for Android are:

    -

    music recording studio app for android free download
    -best music recording studio software for android
    -music recording studio pro apk full version
    -how to set up a music recording studio on android
    -music recording studio lite apk mod
    -music recording studio apk cracked
    -music production studio app for android
    -music recording studio apk latest version
    -music recording studio apk offline
    -music recording studio apk no ads
    -music recording studio apk premium
    -music recording studio apk old version
    -music recording studio apk for android 4.4.2
    -music recording studio apk for android 10
    -music recording studio apk for android 11
    -music recording studio apk for android tv
    -music recording studio apk for android tablet
    -music recording studio apk for android phone
    -music recording studio apk for android emulator
    -music recording studio apk for android oreo
    -music recording studio apk for android pie
    -music recording studio apk for android nougat
    -music recording studio apk for android marshmallow
    -music recording studio apk for android lollipop
    -music recording studio apk for android kitkat
    -download music recording studio apk for android devices
    -install music recording studio apk for android mobiles
    -update music recording studio apk for android phones
    -uninstall music recording studio apk for android tablets
    -review music recording studio apk for android tvs
    -compare music recording studio apps for android
    -best free music recording studio apps for android 2023
    -top rated music recording studio apps for android 2022
    -most downloaded music recording studio apps for android 2021
    -most popular music recording studio apps for android 2020
    -cheapest music recording studio apps for android 2019
    -highest quality music recording studio apps for android 2018
    -easiest to use music recording studio apps for android 2017
    -fastest to download music recording studio apps for android 2016
    -coolest to play with music recording studio apps for android 2015
    -funniest to record with music recording studio apps for android 2014
    -most creative to edit with music recording studio apps for android 2013
    -most professional to mix with music recording studio apps for android 2012
    -most versatile to produce with music recording studio apps for android 2011
    -most advanced to master with music recording studio apps for android 2010
    -most reliable to share with music recording studio apps for android 2009
    -most secure to store with music recording studio apps for android 2008
    -most compatible to sync with music recording studio apps for android 2007

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    NameDescriptionPrice
    BandLabA social music platform that lets you record, edit, and mix your music with millions of other users. You can also access thousands of loops, samples, and instruments.Free
    FL Studio MobileA mobile version of the famous digital audio workstation (DAW) that lets you create and save complete multi-track music projects. You can also use MIDI controllers and external devices.$14.99
    n-Track StudioA powerful DAW that lets you record and playback up to 64 audio tracks and up to 24 MIDI tracks. You can also use virtual instruments, effects, and plugins.$29.99/year or $0.99/month
    Music Maker JAMA fun and easy app that lets you create your own music with hundreds of styles and genres. You can also remix tracks, collaborate with others, and share your music online.Free with in-app purchases
    Walk BandA versatile app that lets you play and record various musical instruments such as piano, guitar, drum, bass, etc. You can also use a multi-track synthesizer and a MIDI keyboard.Free with ads
    -

    How to Install and Use Music Recording Studio APK for Android

    -

    To install and use music recording studio APK for Android, you need to follow these steps:

    -
      -
    1. Download the music recording studio APK file from a trusted source. You can use the links provided in the previous section or search for other sources online. Make sure the file is compatible with your device and has a good reputation.
    2. -
    3. Enable the installation of apps from unknown sources on your device. To do this, go to Settings > Security > Unknown Sources and toggle it on. This will allow you to install apps that are not from the Google Play Store.
    4. -
    5. Locate the downloaded APK file on your device using a file manager app or your browser. Tap on the file and follow the instructions to install it. You may need to grant some permissions and access to your microphone and storage.
    6. -
    7. Launch the app and start creating your music tracks. You can use the app's interface to record, edit, and mix your audio tracks. You can also access various features and tools such as effects, filters, instruments, loops, samples, etc.
    8. -
    9. Save your music files in your preferred format and location. You can also share your music with others via email, social media, or cloud storage.
    10. -
    -

    How to Enhance Your Music Production Quality with Music Recording Studio APK for Android

    -

    To enhance your music production quality with music recording studio APK for Android, you can use these tips:

    -
      -
    • Use a good microphone: If possible, use an external microphone instead of your phone's built-in microphone. This will improve the sound quality and reduce the background noise. You can also use a pop filter or a windscreen to prevent pops and hisses.
    • -
    • Use headphones: Use headphones instead of speakers when recording and mixing your music. This will help you hear the details and nuances of your music better. You can also avoid feedback and distortion that may occur with speakers.
    • -
    • Use a metronome: Use a metronome to keep your tempo and rhythm consistent and accurate. You can also use a click track or a drum loop to guide you. This will make your music sound more professional and polished.
    • -
    • Use a tuner: Use a tuner to tune your instruments and vocals before and during recording. This will ensure that your music is in tune and harmonious. You can also use a pitch correction tool to fix any minor errors or deviations.
    • -
    • Use automation: Use automation to adjust the volume, panning, effects, and other parameters of your audio tracks automatically. This will save you time and effort and create a more dynamic and balanced sound.
    • -
    • Use mastering: Use mastering to finalize your music production and enhance its overall quality. You can use a mastering tool or app to apply compression, equalization, limiting, and other processes to your music. This will make your music sound louder, clearer, and more professional.
    • -
    -

    Conclusion

    -

    Music recording studio APK for Android is a great way to turn your phone into a professional studio. You can use it to record, edit, and mix your own music tracks using various features and tools. You can also share your music with others or export it to different formats.

    -

    To use music recording studio APK for Android, you need to choose the best app for your needs, install it from a trusted source, and grant the necessary permissions and access. You can then create your music tracks using the app's interface and features. You can also enhance your music production quality with some tips and tricks.

    -

    If you love making music and want to unleash your creativity, you should try out music recording studio APK for Android. It is easy, fun, and rewarding. You will be amazed by what you can do with your phone.

    -

    So what are you waiting for? Download music recording studio APK for Android today and start making some awesome music!

    -

    FAQs

    -

    Here are some frequently asked questions about music recording studio APK for Android:

    -
      -
    1. What are some advantages of using music recording studio APK for Android over other apps?
    2. -

      Some advantages of using music recording studio APK for Android over other apps are:

      -
        -
      • You can use it offline without an internet connection.
      • -
      • You can use it on any Android device regardless of the model or version.
      • -
      • You can use it for free or at a low cost compared to other apps.
      • -
      • You can access more features and tools than other apps.
      • -
      • You can customize your music production according to your preferences and style.
      • -
      -
    3. How much storage space do I need to use music recording studio APK for Android?
    4. -

      The amount of storage space you need to use music recording studio APK for Android depends on the size of the app and the number and length of your music files. Generally, you should have at least 1 GB of free space on your device to use the app smoothly. You can also use an external SD card or cloud storage to save your music files. -

    5. Can I use music recording studio APK for Android offline?
    6. -

      Yes, you can use music recording studio APK for Android offline without an internet connection. However, some features and functions may not work properly or at all offline. For example, you may not be able to download or update the app, access online libraries or resources, share or export your music files, or get help or support from the app developers. -

    7. Is music recording studio APK for Android compatible with other devices and platforms?
    8. -

      Music recording studio APK for Android is compatible with most Android devices that have a microphone and storage capability. However, some devices may not support some features or functions of the app due to hardware or software limitations. You can check the compatibility of your device with the app before downloading it from the Google Play Store or other sources.

      -

      Music recording studio APK for Android is not compatible with other devices and platforms such as iOS, Windows, Mac, etc. You cannot use the app on these devices or platforms unless you use an emulator or a converter tool. However, this may affect the performance and quality of the app and your music files. -

    9. How can I get help or support if I have any issues with music recording studio APK for Android?
    10. -

      If you have any issues with music recording studio APK for Android, you can try these solutions:

      -
        -
      • Check the app's settings and preferences and make sure they are correct and suitable for your device and music production.
      • -
      • Restart the app or your device and try again.
      • -
      • Update the app to the latest version and check for any bug fixes or improvements.
      • -
      • Clear the app's cache and data and free up some storage space on your device.
      • -
      • Uninstall and reinstall the app and check for any changes or differences.
      • -
      • Contact the app developers via email, phone, or social media and report your issue or feedback. You can also check their website or blog for any FAQs, tutorials, or guides.
      • -
      -

      I hope this article has helped you learn more about music recording studio APK for Android and how to use it effectively. If you have any questions or comments, please feel free to leave them below. I would love to hear from you.

      -

      Thank you for reading and happy music making!

      401be4b1e0
      -
      -
      \ No newline at end of file diff --git a/spaces/congsaPfin/Manga-OCR/logs/Pokmon UNITE APK Team Up with Trainers from Around the World in this Epic Pokmon Game for Android.md b/spaces/congsaPfin/Manga-OCR/logs/Pokmon UNITE APK Team Up with Trainers from Around the World in this Epic Pokmon Game for Android.md deleted file mode 100644 index 11ced220d4dfd68e2c063325bb70d5869aae56fd..0000000000000000000000000000000000000000 --- a/spaces/congsaPfin/Manga-OCR/logs/Pokmon UNITE APK Team Up with Trainers from Around the World in this Epic Pokmon Game for Android.md +++ /dev/null @@ -1,152 +0,0 @@ - -

      Pokémon UNITE APK: How to Download and Play the Latest Pokémon Game on Your Android Device

      -

      Are you a fan of Pokémon games and want to experience a new way of battling with your favorite creatures? If so, you might want to check out Pokémon UNITE, the latest game from The Pokémon Company that is taking the world by storm.

      -

      What is Pokémon UNITE?

      -

      A brief introduction to the game and its features

      -

      Pokémon UNITE is a 5-on-5 strategic team battle game that was released for Nintendo Switch in July 2021 and for Android devices in September 2021. It is the first Pokémon game that features cross-platform play, meaning that you can team up or compete with players from different devices.

      -

      pokemon unite apk 100 mb


      DOWNLOADhttps://urlca.com/2uOagR



      -

      In this game, you can choose from a variety of Pokémon, each with their own unique abilities and roles, such as Attacker, Defender, Speedster, Supporter, or All-Rounder. You can also customize your Pokémon's appearance with Holowear, which are holographic outfits that use Aeos energy.

      -

      The benefits of playing Pokémon UNITE on your Android device

      -

      Playing Pokémon UNITE on your Android device has several advantages over playing it on Nintendo Switch. For one thing, you can enjoy the game anytime and anywhere, as long as you have a stable internet connection. You can also use touch controls or connect a compatible controller to your device for more convenience.

      -

      Another benefit of playing Pokémon UNITE on your Android device is that you can access more features and content than on Nintendo Switch. For example, you can use voice chat to communicate with your teammates or opponents during matches. You can also participate in special events and missions that are exclusive to mobile users.

      How to download Pokémon UNITE APK?

      -

      The official source of the game and its requirements

      -

      If you want to download Pokémon UNITE APK, you should only do so from the official source, which is the Google Play Store. This way, you can avoid downloading fake or malicious apps that might harm your device or steal your personal information.

      -

      To download Pokémon UNITE APK from the Google Play Store, you need to have an Android device that meets the following requirements:

      -
        -
      • At least 4 GB of RAM
      • -
      • Android 4.4 or higher
      • -
      • A stable internet connection
      • -
      • A Pokémon Trainer Club account or a Nintendo Account
      • -
      -

      The steps to install and launch the game on your Android device

      -

      Once you have confirmed that your device meets the requirements, you can follow these simple steps to install and launch Pokémon UNITE on your Android device:

      -
        -
      1. Open the Google Play Store app on your device and search for Pokémon UNITE.
      2. -
      3. Tap on the game icon and then tap on the Install button. The game will start downloading and installing on your device.
      4. -
      5. After the installation is complete, tap on the Open button to launch the game. You will see a splash screen with the game logo and some loading messages.
      6. -
      7. When prompted, choose your preferred language and accept the terms of service and privacy policy.
      8. -
      9. Log in with your Pokémon Trainer Club account or your Nintendo Account. If you don't have either of these accounts, you can create one for free.
      10. -
      11. Follow the on-screen instructions to create your profile, choose your starter Pokémon, and complete the tutorial.
      12. -
      13. Congratulations! You are now ready to enjoy Pokémon UNITE on your Android device.
      14. -
      -

      The tips to avoid common issues and errors while downloading and playing the game

      -

      While downloading and playing Pokémon UNITE on your Android device, you might encounter some common issues and errors that might affect your gaming experience. Here are some tips to help you avoid or fix them:

      -

      pokemon unite android apk download 100 mb
      -how to install pokemon unite apk in 100 mb
      -pokemon unite apk 100 mb free download
      -pokemon unite apk 100 mb latest version
      -pokemon unite apk 100 mb offline mode
      -pokemon unite apk 100 mb modded
      -pokemon unite apk 100 mb no verification
      -pokemon unite apk 100 mb compatible devices
      -pokemon unite apk 100 mb gameplay
      -pokemon unite apk 100 mb tips and tricks
      -pokemon unite apk 100 mb review
      -pokemon unite apk 100 mb update
      -pokemon unite apk 100 mb error fix
      -pokemon unite apk 100 mb best team
      -pokemon unite apk 100 mb guide
      -pokemon unite apk 100 mb hack
      -pokemon unite apk 100 mb cheats
      -pokemon unite apk 100 mb unlimited coins
      -pokemon unite apk 100 mb features
      -pokemon unite apk 100 mb requirements
      -pokemon unite apk 100 mb size
      -pokemon unite apk 100 mb graphics
      -pokemon unite apk 100 mb sound
      -pokemon unite apk 100 mb controls
      -pokemon unite apk 100 mb settings
      -pokemon unite apk 100 mb support
      -pokemon unite apk 100 mb feedback
      -pokemon unite apk 100 mb rating
      -pokemon unite apk 100 mb comparison
      -pokemon unite apk 100 mb alternatives
      -pokemon unite apk 100 mb pros and cons
      -pokemon unite apk 100 mb strategy
      -pokemon unite apk 100 mb tutorial
      -pokemon unite apk 100 mb walkthrough
      -pokemon unite apk 100 mb characters
      -pokemon unite apk 100 mb skins
      -pokemon unite apk 100 mb items
      -pokemon unite apk 100 mb roles
      -pokemon unite apk 100 mb maps
      -pokemon unite apk 100 mb modes
      -pokemon unite apk 100 mb events
      -pokemon unite apk 100 mb rewards
      -pokemon unite apk 100 mb challenges
      -pokemon unite apk 100 mb missions
      -pokemon unite apk 100 mb achievements
      -pokemon unite apk 100 mb leaderboards
      -pokemon unite apk 100 mb clans
      -pokemon unite apk 100 mb chat

      -
        -
      • If you have trouble downloading or installing the game, make sure you have enough storage space on your device, clear the cache and data of the Google Play Store app, and restart your device.
      • -
      • If you experience lag or connection issues while playing the game, make sure you have a stable internet connection, close any background apps that might consume bandwidth, and use a VPN if you are in a region where the game is not officially supported.
      • -
      • If you encounter any bugs or glitches while playing the game, report them to the developers through the in-game feedback system or their official social media channels. You can also check for updates or reinstall the game if necessary.
      • -

      How to play Pokémon UNITE?

      -

      The basics of the gameplay and the controls

      -

      Pokémon UNITE is a game that requires teamwork, strategy, and skill. The main mode of the game is Unite Battle, where two teams of five players each compete to score more points than the other team by collecting and depositing Aeos energy in the opponent's goal zones.

      -

      To play Pokémon UNITE on your Android device, you can use either touch controls or a compatible controller. The touch controls are simple and intuitive: you can move your Pokémon by dragging the virtual joystick on the left side of the screen, and you can use your basic attacks and moves by tapping the buttons on the right side of the screen. You can also adjust the settings and customize the layout of the touch controls according to your preference.

      -

      If you prefer to use a controller, you can connect one to your device via Bluetooth or USB. You can use the left stick to move your Pokémon, the right stick to aim your moves, and the face buttons to activate your moves. You can also access the menu, signals, and quick-chat messages by using the directional pad and the shoulder buttons. You can check the full list of controller commands in the game settings.

      -

      The different modes and maps of the game

      -

      Pokémon UNITE offers different modes and maps for you to enjoy. The main mode is Unite Battle, which has three sub-modes: Standard, Quick, and Ranked. Each sub-mode has different rules, durations, and rewards.

      - - - - - - - - - - - - - - - - - - - - - - - - - -
      Sub-modeRulesDurationRewards
      StandardTwo teams of five players each compete on a map with three lanes and five goal zones per team. The team with more points at the end of the match wins.10 minutesAeos Coins, Aeos Tickets, Item Enhancers, Fashion Tickets, Unite Licenses, Holowear Tickets
      QuickTwo teams of four players each compete on a map with two lanes and two goal zones per team. The team with more points at the end of the match or the first team to score a certain number of points wins.5 minutesAeos Coins, Aeos Tickets, Item Enhancers, Fashion Tickets
      RankedTwo teams of five players each compete on a map with three lanes and five goal zones per team. The team with more points at the end of the match wins. Players are matched based on their performance rating and can earn or lose points depending on the outcome of the match.10 minutesAeos Coins, Aeos Tickets, Item Enhancers, Fashion Tickets, Unite Licenses, Holowear Tickets, Performance Points
      -

      In addition to Unite Battle, there are also other modes that you can play for fun or practice. These include:

      -
        -
      • Tutorial: A mode where you can learn the basics of the game and try out different Pokémon.
      • -
      • Practice: A mode where you can play against AI opponents or with your friends in custom matches.
      • -
      • Events: A mode where you can participate in special challenges and missions that change periodically.
      • -
      • Spectate: A mode where you can watch live or recorded matches of other players.
      • -
      -

      The best strategies and tips to win in Unite Battles

      -

      To win in Unite Battles, you need to work as a team and use your Pokémon's strengths and abilities wisely. Here are some strategies and tips that can help you improve your skills and performance:

      -
        -
      • Choose a Pokémon that suits your playstyle and role. For example, if you like to deal damage from a distance, you might want to choose an Attacker like Pikachu or Cinderace. If you like to protect your teammates and block enemies, you might want to choose a Defender like Snorlax or Crustle.
      • -
      • Coordinate with your teammates and communicate with them using signals, quick-chat messages, or voice chat. For example, you can signal when you need help, when you want to attack or retreat, or when you want to use your Unite Move.
      • -
      • Pay attention to the map and the timer. You can see where your teammates, enemies, wild Pokémon, goal zones, and power-ups are on the map. You can also see how much time is left in the match and when special events like Zapdos or Drednaw will appear.
      • -
      • Balance between scoring points and defeating enemies. You need to score points to win the match, but you also need to defeat enemies to prevent them from scoring or interrupting you. You can also gain experience and level up by defeating enemies and wild Pokémon, which will make your Pokémon stronger and unlock new moves.
      • -
      • Use your moves and items effectively. You can choose from different moves for your Pokémon as you level up, and you can also equip them with items that can boost their stats or give them special effects. You can also use battle items like potions or eject buttons to help you in combat. You can change your moves and items before each match in the preparation screen.
      • -
      • Use your Unite Move at the right time. Your Unite Move is a powerful move that can turn the tide of the battle, but it has a long cooldown time. You should use it when you have a clear advantage, such as when you are outnumbering or outleveling your enemies, or when you are contesting a key objective like Zapdos or the final stretch.
      • -
      -

      Conclusion

      -

      Pokémon UNITE is a fun and exciting game that lets you enjoy the thrill of Pokémon battles in a new way. You can download and play the game on your Android device by following the steps and tips in this article. You can also explore the different modes and maps of the game, and learn how to play better with your Pokémon and your teammates.

      -

      If you are ready to join the millions of players who are already playing Pokémon UNITE, you can download the game from the Google Play Store today. You can also visit the official website or follow the official social media channels for more information and updates about the game.

      -

      What are you waiting for? Unite with your friends and have fun with Pokémon UNITE!

      -

      FAQs

      -

      Q: Is Pokémon UNITE free to play?

      -

      A: Yes, Pokémon UNITE is a free-to-start game with optional in-game purchases.

      -

      Q: Can I play Pokémon UNITE with my friends?

      -

      A: Yes, you can team up with your friends or other players from around the world in 5-on-5 Unite Battles. You can also communicate with them using signals, quick-chat messages, or voice chat.

      -

      Q: What are the minimum requirements for playing Pokémon UNITE on Android?

      -

      A: According to the official website, you need an Android device with at least 4 GB of RAM, Android 4.4 or higher, and a stable internet connection. You also need a Pokémon Trainer Club account or a Nintendo Account to sync your progress between devices.

      -

      Q: How can I get more Pokémon and Holowear in Pokémon UNITE?

      -

      A: You can get more Pokémon and Holowear by using Aeos Coins, Aeos Gems, or Aeos Tickets. These are the in-game currencies that you can earn by playing the game or by making real-money purchases. You can also get some Pokémon and Holowear by completing missions and events.

      -

      Q: What are Unite Moves and how do I use them?

      -

      A: Unite Moves are powerful moves that are unique to each Pokémon. They can only be used in Unite Battles, and they have a long cooldown time. You can activate your Unite Move by tapping the hexagon icon on the right side of the screen when it is fully charged.

      401be4b1e0
      -
      -
      \ No newline at end of file diff --git a/spaces/contluForse/HuggingGPT/assets/Download Flames of War Barbarossa PDF and Experience the Epic Campaign of WWII.md b/spaces/contluForse/HuggingGPT/assets/Download Flames of War Barbarossa PDF and Experience the Epic Campaign of WWII.md deleted file mode 100644 index a6f17a1b774adfee1fc3c5d1accf7fac28278733..0000000000000000000000000000000000000000 --- a/spaces/contluForse/HuggingGPT/assets/Download Flames of War Barbarossa PDF and Experience the Epic Campaign of WWII.md +++ /dev/null @@ -1,7 +0,0 @@ -
      -

      From here you should head straight to My Account using the navigation buttons at the bottom of the page. Here you can set up an account to make it easier to keep track what you have purchased, and if you change your device you can just log in and download your purchases.

      -

      Once you have found a something you like the look of, you can either press the red button (this will either have a price, or be labelled Free in some cases), or you can tap on the book cover to view some more information. Inside this preview you can tap the book cover again to download a small book preview.

      -

      flames of war barbarossa pdf download


      Download Ziphttps://ssurll.com/2uzxh8



      -

      Learn about over 1,000 camps and ghettos in Volumes I-III of this encyclopedia, which are available as a free PDF download. This reference provides text, photographs, charts, maps, and extensive indexes.

      aaccfb2cb3
      -
      -
      \ No newline at end of file diff --git a/spaces/coreml-community/ControlNet-v1-1-Annotators-cpu/annotator/mmpkg/mmcv/runner/builder.py b/spaces/coreml-community/ControlNet-v1-1-Annotators-cpu/annotator/mmpkg/mmcv/runner/builder.py deleted file mode 100644 index 77c96ba0b2f30ead9da23f293c5dc84dd3e4a74f..0000000000000000000000000000000000000000 --- a/spaces/coreml-community/ControlNet-v1-1-Annotators-cpu/annotator/mmpkg/mmcv/runner/builder.py +++ /dev/null @@ -1,24 +0,0 @@ -# Copyright (c) OpenMMLab. All rights reserved. -import copy - -from ..utils import Registry - -RUNNERS = Registry('runner') -RUNNER_BUILDERS = Registry('runner builder') - - -def build_runner_constructor(cfg): - return RUNNER_BUILDERS.build(cfg) - - -def build_runner(cfg, default_args=None): - runner_cfg = copy.deepcopy(cfg) - constructor_type = runner_cfg.pop('constructor', - 'DefaultRunnerConstructor') - runner_constructor = build_runner_constructor( - dict( - type=constructor_type, - runner_cfg=runner_cfg, - default_args=default_args)) - runner = runner_constructor() - return runner diff --git a/spaces/coreml-community/ControlNet-v1-1-Annotators-cpu/annotator/oneformer/detectron2/data/transforms/__init__.py b/spaces/coreml-community/ControlNet-v1-1-Annotators-cpu/annotator/oneformer/detectron2/data/transforms/__init__.py deleted file mode 100644 index e91c6cdfacd6992a7a1e80c7d2e4b38b2cf7dcde..0000000000000000000000000000000000000000 --- a/spaces/coreml-community/ControlNet-v1-1-Annotators-cpu/annotator/oneformer/detectron2/data/transforms/__init__.py +++ /dev/null @@ -1,14 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. -from fvcore.transforms.transform import Transform, TransformList # order them first -from fvcore.transforms.transform import * -from .transform import * -from .augmentation import * -from .augmentation_impl import * - -__all__ = [k for k in globals().keys() if not k.startswith("_")] - - -from annotator.oneformer.detectron2.utils.env import fixup_module_metadata - -fixup_module_metadata(__name__, globals(), __all__) -del fixup_module_metadata diff --git a/spaces/daarumadx/bot/src/loader/http.py b/spaces/daarumadx/bot/src/loader/http.py deleted file mode 100644 index 389124b4d9bb26f0870a4f5af2abca164a5d36b2..0000000000000000000000000000000000000000 --- a/spaces/daarumadx/bot/src/loader/http.py +++ /dev/null @@ -1,34 +0,0 @@ -import os -import re -import tempfile - -from utils import dl_file, read_image -from loader import Loader - - -regex_url = re.compile( - r'^(?:http)s?://' # http:// or https:// - r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' # domain... - r'localhost|' # localhost... - r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ip - r'(?::\d+)?' # optional port - r'(?:/?|[/?]\S+)$', re.IGNORECASE) - - -class HTTPLoader(Loader): - """ Abstract Loader Class """ - @staticmethod - def run(uri): - """ - Run the loader ressource - :return: image - """ - _, tmp_path = tempfile.mkstemp() - dl_file(uri, tmp_path) - img = read_image(tmp_path) - os.remove(tmp_path) - return img - - @staticmethod - def uri_validator(uri): - return regex_url.match(uri) diff --git a/spaces/daddyjin/TalkingFaceGeneration/Demo_TFR_Pirenderer/src/face3d/models/arcface_torch/utils/plot.py b/spaces/daddyjin/TalkingFaceGeneration/Demo_TFR_Pirenderer/src/face3d/models/arcface_torch/utils/plot.py deleted file mode 100644 index ccc588e5c01ca550b69c385aeb3fd139c59fb88a..0000000000000000000000000000000000000000 --- a/spaces/daddyjin/TalkingFaceGeneration/Demo_TFR_Pirenderer/src/face3d/models/arcface_torch/utils/plot.py +++ /dev/null @@ -1,72 +0,0 @@ -# coding: utf-8 - -import os -from pathlib import Path - -import matplotlib.pyplot as plt -import numpy as np -import pandas as pd -from menpo.visualize.viewmatplotlib import sample_colours_from_colourmap -from prettytable import PrettyTable -from sklearn.metrics import roc_curve, auc - -image_path = "/data/anxiang/IJB_release/IJBC" -files = [ - "./ms1mv3_arcface_r100/ms1mv3_arcface_r100/ijbc.npy" -] - - -def read_template_pair_list(path): - pairs = pd.read_csv(path, sep=' ', header=None).values - t1 = pairs[:, 0].astype(np.int) - t2 = pairs[:, 1].astype(np.int) - label = pairs[:, 2].astype(np.int) - return t1, t2, label - - -p1, p2, label = read_template_pair_list( - os.path.join('%s/meta' % image_path, - '%s_template_pair_label.txt' % 'ijbc')) - -methods = [] -scores = [] -for file in files: - methods.append(file.split('/')[-2]) - scores.append(np.load(file)) - -methods = np.array(methods) -scores = dict(zip(methods, scores)) -colours = dict( - zip(methods, sample_colours_from_colourmap(methods.shape[0], 'Set2'))) -x_labels = [10 ** -6, 10 ** -5, 10 ** -4, 10 ** -3, 10 ** -2, 10 ** -1] -tpr_fpr_table = PrettyTable(['Methods'] + [str(x) for x in x_labels]) -fig = plt.figure() -for method in methods: - fpr, tpr, _ = roc_curve(label, scores[method]) - roc_auc = auc(fpr, tpr) - fpr = np.flipud(fpr) - tpr = np.flipud(tpr) # select largest tpr at same fpr - plt.plot(fpr, - tpr, - color=colours[method], - lw=1, - label=('[%s (AUC = %0.4f %%)]' % - (method.split('-')[-1], roc_auc * 100))) - tpr_fpr_row = [] - tpr_fpr_row.append("%s-%s" % (method, "IJBC")) - for fpr_iter in np.arange(len(x_labels)): - _, min_index = min( - list(zip(abs(fpr - x_labels[fpr_iter]), range(len(fpr))))) - tpr_fpr_row.append('%.2f' % (tpr[min_index] * 100)) - tpr_fpr_table.add_row(tpr_fpr_row) -plt.xlim([10 ** -6, 0.1]) -plt.ylim([0.3, 1.0]) -plt.grid(linestyle='--', linewidth=1) -plt.xticks(x_labels) -plt.yticks(np.linspace(0.3, 1.0, 8, endpoint=True)) -plt.xscale('log') -plt.xlabel('False Positive Rate') -plt.ylabel('True Positive Rate') -plt.title('ROC on IJB') -plt.legend(loc="lower right") -print(tpr_fpr_table) diff --git a/spaces/declare-lab/tango/diffusers/tests/pipelines/versatile_diffusion/__init__.py b/spaces/declare-lab/tango/diffusers/tests/pipelines/versatile_diffusion/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/spaces/deeplearning/audioldm-text-to-audio-generation/audioldm/clap/training/scheduler.py b/spaces/deeplearning/audioldm-text-to-audio-generation/audioldm/clap/training/scheduler.py deleted file mode 100644 index 7151ffbab25a113673b7627027b443b27f22cb0f..0000000000000000000000000000000000000000 --- a/spaces/deeplearning/audioldm-text-to-audio-generation/audioldm/clap/training/scheduler.py +++ /dev/null @@ -1,24 +0,0 @@ -import numpy as np - - -def assign_learning_rate(optimizer, new_lr): - for param_group in optimizer.param_groups: - param_group["lr"] = new_lr - - -def _warmup_lr(base_lr, warmup_length, step): - return base_lr * (step + 1) / warmup_length - - -def cosine_lr(optimizer, base_lr, warmup_length, steps): - def _lr_adjuster(step): - if step < warmup_length: - lr = _warmup_lr(base_lr, warmup_length, step) - else: - e = step - warmup_length - es = steps - warmup_length - lr = 0.5 * (1 + np.cos(np.pi * e / es)) * base_lr - assign_learning_rate(optimizer, lr) - return lr - - return _lr_adjuster diff --git a/spaces/deepwisdom/MetaGPT/metagpt/provider/metagpt_llm_api.py b/spaces/deepwisdom/MetaGPT/metagpt/provider/metagpt_llm_api.py deleted file mode 100644 index c27e7132da336336c608d79d606111fff7c75538..0000000000000000000000000000000000000000 --- a/spaces/deepwisdom/MetaGPT/metagpt/provider/metagpt_llm_api.py +++ /dev/null @@ -1,33 +0,0 @@ -# -*- coding: utf-8 -*- -""" -@Time : 2023/8/30 -@Author : mashenquan -@File : metagpt_llm_api.py -@Desc : MetaGPT LLM related APIs -""" - -import openai - -from metagpt.config import CONFIG -from metagpt.provider import OpenAIGPTAPI -from metagpt.provider.openai_api import RateLimiter - - -class MetaGPTLLMAPI(OpenAIGPTAPI): - """MetaGPT LLM api""" - - def __init__(self): - self.__init_openai() - self.llm = openai - self.model = CONFIG.METAGPT_API_MODEL - self.auto_max_tokens = False - RateLimiter.__init__(self, rpm=self.rpm) - - def __init_openai(self, *args, **kwargs): - openai.api_key = CONFIG.METAGPT_API_KEY - if CONFIG.METAGPT_API_BASE: - openai.api_base = CONFIG.METAGPT_API_BASE - if CONFIG.METAGPT_API_TYPE: - openai.api_type = CONFIG.METAGPT_API_TYPE - openai.api_version = CONFIG.METAGPT_API_VERSION - self.rpm = int(CONFIG.RPM) if CONFIG.RPM else 10 diff --git "a/spaces/derful/Chatgpt-academic/crazy_functions/\346\211\271\351\207\217\346\200\273\347\273\223PDF\346\226\207\346\241\243.py" "b/spaces/derful/Chatgpt-academic/crazy_functions/\346\211\271\351\207\217\346\200\273\347\273\223PDF\346\226\207\346\241\243.py" deleted file mode 100644 index a98507cd27906a94ee14183dbe87fc93efd0a40b..0000000000000000000000000000000000000000 --- "a/spaces/derful/Chatgpt-academic/crazy_functions/\346\211\271\351\207\217\346\200\273\347\273\223PDF\346\226\207\346\241\243.py" +++ /dev/null @@ -1,99 +0,0 @@ -from predict import predict_no_ui -from toolbox import CatchException, report_execption, write_results_to_file, predict_no_ui_but_counting_down -fast_debug = False - - -def 解析PDF(api, file_manifest, project_folder, top_p, temperature, chatbot, history, systemPromptTxt): - import time, glob, os, fitz - print('begin analysis on:', file_manifest) - for index, fp in enumerate(file_manifest): - with fitz.open(fp) as doc: - file_content = "" - for page in doc: - file_content += page.get_text() - print(file_content) - - prefix = "接下来请你逐文件分析下面的论文文件,概括其内容" if index==0 else "" - i_say = prefix + f'请对下面的文章片段用中文做一个概述,文件名是{os.path.relpath(fp, project_folder)},文章内容是 ```{file_content}```' - i_say_show_user = prefix + f'[{index}/{len(file_manifest)}] 请对下面的文章片段做一个概述: {os.path.abspath(fp)}' - chatbot.append((i_say_show_user, "[Local Message] waiting gpt response.")) - print('[1] yield chatbot, history') - yield chatbot, history, '正常' - - if not fast_debug: - msg = '正常' - # ** gpt request ** - gpt_say = yield from predict_no_ui_but_counting_down(api, i_say, i_say_show_user, chatbot, top_p, temperature, history=[]) # 带超时倒计时 - - print('[2] end gpt req') - chatbot[-1] = (i_say_show_user, gpt_say) - history.append(i_say_show_user); history.append(gpt_say) - print('[3] yield chatbot, history') - yield chatbot, history, msg - print('[4] next') - if not fast_debug: time.sleep(2) - - all_file = ', '.join([os.path.relpath(fp, project_folder) for index, fp in enumerate(file_manifest)]) - i_say = f'根据以上你自己的分析,对全文进行概括,用学术性语言写一段中文摘要,然后再写一段英文摘要(包括{all_file})。' - chatbot.append((i_say, "[Local Message] waiting gpt response.")) - yield chatbot, history, '正常' - - if not fast_debug: - msg = '正常' - # ** gpt request ** - gpt_say = yield from predict_no_ui_but_counting_down(api, i_say, i_say, chatbot, top_p, temperature, history=history) # 带超时倒计时 - - chatbot[-1] = (i_say, gpt_say) - history.append(i_say); history.append(gpt_say) - yield chatbot, history, msg - res = write_results_to_file(history) - chatbot.append(("完成了吗?", res)) - yield chatbot, history, msg - - -@CatchException -def 批量总结PDF文档(api, txt, top_p, temperature, chatbot, history, systemPromptTxt, WEB_PORT): - import glob, os - - # 基本信息:功能、贡献者 - chatbot.append([ - "函数插件功能?", - "批量总结PDF文档。函数插件贡献者: ValeriaWong"]) - yield chatbot, history, '正常' - - # 尝试导入依赖,如果缺少依赖,则给出安装建议 - try: - import fitz - except: - report_execption(chatbot, history, - a = f"解析项目: {txt}", - b = f"导入软件依赖失败。使用该模块需要额外依赖,安装方法```pip install --upgrade pymupdf```。") - yield chatbot, history, '正常' - return - - # 清空历史,以免输入溢出 - history = [] - - # 检测输入参数,如没有给定输入参数,直接退出 - if os.path.exists(txt): - project_folder = txt - else: - if txt == "": txt = '空空如也的输入栏' - report_execption(chatbot, history, a = f"解析项目: {txt}", b = f"找不到本地项目或无权访问: {txt}") - yield chatbot, history, '正常' - return - - # 搜索需要处理的文件清单 - file_manifest = [f for f in glob.glob(f'{project_folder}/**/*.pdf', recursive=True)] # + \ - # [f for f in glob.glob(f'{project_folder}/**/*.tex', recursive=True)] + \ - # [f for f in glob.glob(f'{project_folder}/**/*.cpp', recursive=True)] + \ - # [f for f in glob.glob(f'{project_folder}/**/*.c', recursive=True)] - - # 如果没找到任何文件 - if len(file_manifest) == 0: - report_execption(chatbot, history, a = f"解析项目: {txt}", b = f"找不到任何.tex或.pdf文件: {txt}") - yield chatbot, history, '正常' - return - - # 开始正式执行任务 - yield from 解析PDF(api, file_manifest, project_folder, top_p, temperature, chatbot, history, systemPromptTxt) diff --git a/spaces/dhansmair/flamingo-tiny-cap/README.md b/spaces/dhansmair/flamingo-tiny-cap/README.md deleted file mode 100644 index aa34117f13a5ae56df7bcea73940d1950ff81d24..0000000000000000000000000000000000000000 --- a/spaces/dhansmair/flamingo-tiny-cap/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: Flamingo Tiny Image Captioning -emoji: 🦩🖼️💬 -colorFrom: purple -colorTo: green -sdk: gradio -sdk_version: 3.1.7 -app_file: app.py -pinned: true -license: mit ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/diacanFperku/AutoGPT/APK MANIA Full App Backup Share Pro V15.5.0 APK Free Download __FULL__.md b/spaces/diacanFperku/AutoGPT/APK MANIA Full App Backup Share Pro V15.5.0 APK Free Download __FULL__.md deleted file mode 100644 index 3280f1d4bef7fb8cc237f61cef069baa40aa6b78..0000000000000000000000000000000000000000 --- a/spaces/diacanFperku/AutoGPT/APK MANIA Full App Backup Share Pro V15.5.0 APK Free Download __FULL__.md +++ /dev/null @@ -1,27 +0,0 @@ -
      -

      APK MANIA Full App Backup Share Pro v15.5.0 APK Free Download

      -

      Are you looking for a simple and powerful app to backup and share your apps with your friends? If yes, then APK MANIA Full App Backup Share Pro is the app for you. This app allows you to backup your apps to your SD card or cloud storage, and share them with anyone via email, Bluetooth, Wi-Fi Direct, or any other app that supports file sharing. You can also restore your apps from the backup anytime you want.

      -

      APK MANIA Full App Backup Share Pro is not just a backup app, but also a full-featured app manager. You can view the details of your apps, such as version, size, permissions, activities, services, etc. You can also uninstall, clear data, clear cache, or move your apps to SD card with one tap. You can also batch select multiple apps for backup, share, or uninstall.

      -

      APK MANIA Full App Backup Share Pro v15.5.0 APK Free Download


      Download Filehttps://gohhs.com/2uFTpE



      -

      APK MANIA Full App Backup Share Pro is compatible with Android 4.0 and above. It supports both rooted and non-rooted devices. It also supports backup of split APKs and app bundles. It does not require any internet connection or registration to use.

      -

      APK MANIA Full App Backup Share Pro is a premium app that costs $2.99 on Google Play Store. However, you can download it for free from the link below. Just click on the download button and enjoy this amazing app.

      -Download APK MANIA Full App Backup Share Pro v15.5.0 APK - -

      Why should you use APK MANIA Full App Backup Share Pro? There are many reasons to use this app. First of all, it can help you save your storage space by backing up your apps to external sources. You can also free up your RAM by uninstalling or moving your apps to SD card. Secondly, it can help you protect your apps from accidental deletion or corruption. You can always restore your apps from the backup in case of any problem. Thirdly, it can help you share your apps with your friends or family easily. You can send your apps via any method you prefer, without any size limit or restriction.

      -

      How to use APK MANIA Full App Backup Share Pro? Using this app is very easy and intuitive. You just need to open the app and grant the necessary permissions. Then, you will see a list of all your installed apps on the main screen. You can select any app or multiple apps by tapping on them. Then, you can choose to backup, share, uninstall, or manage your apps from the menu at the bottom. You can also access the settings and help options from the menu at the top right corner.

      -

      What are the features of APK MANIA Full App Backup Share Pro? This app has many features that make it stand out from other backup and share apps. Some of the features are:

      -
        -
      • Backup and restore apps to SD card or cloud storage (Google Drive, Dropbox, OneDrive)
      • -
      • Share apps via email, Bluetooth, Wi-Fi Direct, or any other app that supports file sharing
      • -
      • View app details such as version, size, permissions, activities, services, etc.
      • -
      • Uninstall, clear data, clear cache, or move apps to SD card with one tap
      • -
      • Batch select multiple apps for backup, share, or uninstall
      • -
      • Support backup of split APKs and app bundles
      • -
      • Compatible with Android 4.0 and above
      • -
      • Support both rooted and non-rooted devices
      • -
      • No internet connection or registration required
      • -
      • Premium app with no ads or in-app purchases
      • -

      -

      d5da3c52bf
      -
      -
      \ No newline at end of file diff --git a/spaces/diacanFperku/AutoGPT/HACK Ashampoo Core Tuner 2 V2.01 Portable By Speedzodiac !!LINK!!.md b/spaces/diacanFperku/AutoGPT/HACK Ashampoo Core Tuner 2 V2.01 Portable By Speedzodiac !!LINK!!.md deleted file mode 100644 index 33a4faf5d0b08d9e0186111a9f9e912a4a0a5b03..0000000000000000000000000000000000000000 --- a/spaces/diacanFperku/AutoGPT/HACK Ashampoo Core Tuner 2 V2.01 Portable By Speedzodiac !!LINK!!.md +++ /dev/null @@ -1,13 +0,0 @@ -

      HACK Ashampoo Core Tuner 2 V2.01 Portable By Speedzodiac


      DOWNLOAD ✵✵✵ https://gohhs.com/2uFUYd



      - -ivermectin otc ivermectin for man where to buy – ivermectin cream 1% ... .com/stories/3271254- hack-ashampoo-core-tuner-2-v2-01-portable -by-speedzodiac ... 2 days back ... -Andrej Petrov4 months ago. -Hi, please tell me, how much does ivermectin cost? -It's just that prices vary everywhere on the Internet and ... -ivermectin otc ivermectin for man where to buy – ivermectin cream 1% ... .com/stories/3271254- hack-ashampoo-core-tuner-2-v2-01-portable-by-speedzodiac ... -2 days back ... -Just on the Internet everywhere different prices and ... 2 days. back ... -Andrej Petrov4 months ago. 8a78ff9644
      -
      -
      -

      diff --git a/spaces/digitalxingtong/Nailv-read-Bert-Vits2/monotonic_align/__init__.py b/spaces/digitalxingtong/Nailv-read-Bert-Vits2/monotonic_align/__init__.py deleted file mode 100644 index a323673bb16070d6d0fffddb939b657d0915ff1b..0000000000000000000000000000000000000000 --- a/spaces/digitalxingtong/Nailv-read-Bert-Vits2/monotonic_align/__init__.py +++ /dev/null @@ -1,20 +0,0 @@ -from numpy import zeros, int32, float32 -from torch import from_numpy - -from .core import maximum_path_jit - - -def maximum_path(neg_cent, mask): - """ numba optimized version. - neg_cent: [b, t_t, t_s] - mask: [b, t_t, t_s] - """ - device = neg_cent.device - dtype = neg_cent.dtype - neg_cent = neg_cent.data.cpu().numpy().astype(float32) - path = zeros(neg_cent.shape, dtype=int32) - - t_t_max = mask.sum(1)[:, 0].data.cpu().numpy().astype(int32) - t_s_max = mask.sum(2)[:, 0].data.cpu().numpy().astype(int32) - maximum_path_jit(path, neg_cent, t_t_max, t_s_max) - return from_numpy(path).to(device=device, dtype=dtype) \ No newline at end of file diff --git a/spaces/digitalxingtong/Un-Bert-Vits2/train_ms.py b/spaces/digitalxingtong/Un-Bert-Vits2/train_ms.py deleted file mode 100644 index 5d109003d40497ea4493e7c73f47c1eb7370a81e..0000000000000000000000000000000000000000 --- a/spaces/digitalxingtong/Un-Bert-Vits2/train_ms.py +++ /dev/null @@ -1,402 +0,0 @@ -import os -import json -import argparse -import itertools -import math -import torch -import shutil -from torch import nn, optim -from torch.nn import functional as F -from torch.utils.data import DataLoader -from torch.utils.tensorboard import SummaryWriter -import torch.multiprocessing as mp -import torch.distributed as dist -from torch.nn.parallel import DistributedDataParallel as DDP -from torch.cuda.amp import autocast, GradScaler -from tqdm import tqdm -import logging -logging.getLogger('numba').setLevel(logging.WARNING) -import commons -import utils -from data_utils import ( - TextAudioSpeakerLoader, - TextAudioSpeakerCollate, - DistributedBucketSampler -) -from models import ( - SynthesizerTrn, - MultiPeriodDiscriminator, - DurationDiscriminator, -) -from losses import ( - generator_loss, - discriminator_loss, - feature_loss, - kl_loss -) -from mel_processing import mel_spectrogram_torch, spec_to_mel_torch -from text.symbols import symbols - -torch.backends.cudnn.benchmark = True -torch.backends.cuda.matmul.allow_tf32 = True -torch.backends.cudnn.allow_tf32 = True -torch.set_float32_matmul_precision('medium') -global_step = 0 - - -def main(): - """Assume Single Node Multi GPUs Training Only""" - assert torch.cuda.is_available(), "CPU training is not allowed." - - n_gpus = torch.cuda.device_count() - os.environ['MASTER_ADDR'] = 'localhost' - os.environ['MASTER_PORT'] = '65280' - - hps = utils.get_hparams() - if not hps.cont: - shutil.copy('./pretrained_models/D_0.pth','./logs/OUTPUT_MODEL/D_0.pth') - shutil.copy('./pretrained_models/G_0.pth','./logs/OUTPUT_MODEL/G_0.pth') - shutil.copy('./pretrained_models/DUR_0.pth','./logs/OUTPUT_MODEL/DUR_0.pth') - mp.spawn(run, nprocs=n_gpus, args=(n_gpus, hps,)) - - -def run(rank, n_gpus, hps): - global global_step - if rank == 0: - logger = utils.get_logger(hps.model_dir) - logger.info(hps) - utils.check_git_hash(hps.model_dir) - writer = SummaryWriter(log_dir=hps.model_dir) - writer_eval = SummaryWriter(log_dir=os.path.join(hps.model_dir, "eval")) - - dist.init_process_group(backend= 'gloo' if os.name == 'nt' else 'nccl', init_method='env://', world_size=n_gpus, rank=rank) - torch.manual_seed(hps.train.seed) - torch.cuda.set_device(rank) - - train_dataset = TextAudioSpeakerLoader(hps.data.training_files, hps.data) - train_sampler = DistributedBucketSampler( - train_dataset, - hps.train.batch_size, - [32, 300, 400, 500, 600, 700, 800, 900, 1000], - num_replicas=n_gpus, - rank=rank, - shuffle=True) - collate_fn = TextAudioSpeakerCollate() - train_loader = DataLoader(train_dataset, num_workers=2, shuffle=False, pin_memory=True, - collate_fn=collate_fn, batch_sampler=train_sampler) - if rank == 0: - eval_dataset = TextAudioSpeakerLoader(hps.data.validation_files, hps.data) - eval_loader = DataLoader(eval_dataset, num_workers=0, shuffle=False, - batch_size=1, pin_memory=True, - drop_last=False, collate_fn=collate_fn) - if "use_noise_scaled_mas" in hps.model.keys() and hps.model.use_noise_scaled_mas == True: - print("Using noise scaled MAS for VITS2") - use_noise_scaled_mas = True - mas_noise_scale_initial = 0.01 - noise_scale_delta = 2e-6 - else: - print("Using normal MAS for VITS1") - use_noise_scaled_mas = False - mas_noise_scale_initial = 0.0 - noise_scale_delta = 0.0 - if "use_duration_discriminator" in hps.model.keys() and hps.model.use_duration_discriminator == True: - print("Using duration discriminator for VITS2") - use_duration_discriminator = True - net_dur_disc = DurationDiscriminator( - hps.model.hidden_channels, - hps.model.hidden_channels, - 3, - 0.1, - gin_channels=hps.model.gin_channels if hps.data.n_speakers != 0 else 0, - ).cuda(rank) - if "use_spk_conditioned_encoder" in hps.model.keys() and hps.model.use_spk_conditioned_encoder == True: - if hps.data.n_speakers == 0: - raise ValueError("n_speakers must be > 0 when using spk conditioned encoder to train multi-speaker model") - use_spk_conditioned_encoder = True - else: - print("Using normal encoder for VITS1") - use_spk_conditioned_encoder = False - - net_g = SynthesizerTrn( - len(symbols), - hps.data.filter_length // 2 + 1, - hps.train.segment_size // hps.data.hop_length, - n_speakers=hps.data.n_speakers, - mas_noise_scale_initial = mas_noise_scale_initial, - noise_scale_delta = noise_scale_delta, - **hps.model).cuda(rank) - - freeze_enc = getattr(hps.model, "freeze_enc", False) - if freeze_enc: - print("freeze encoder !!!") - for param in net_g.enc_p.parameters(): - param.requires_grad = False - - net_d = MultiPeriodDiscriminator(hps.model.use_spectral_norm).cuda(rank) - optim_g = torch.optim.AdamW( - filter(lambda p: p.requires_grad, net_g.parameters()), - hps.train.learning_rate, - betas=hps.train.betas, - eps=hps.train.eps) - optim_d = torch.optim.AdamW( - net_d.parameters(), - hps.train.learning_rate, - betas=hps.train.betas, - eps=hps.train.eps) - if net_dur_disc is not None: - optim_dur_disc = torch.optim.AdamW( - net_dur_disc.parameters(), - hps.train.learning_rate, - betas=hps.train.betas, - eps=hps.train.eps) - else: - optim_dur_disc = None - net_g = DDP(net_g, device_ids=[rank], find_unused_parameters=True) - net_d = DDP(net_d, device_ids=[rank], find_unused_parameters=True) - if net_dur_disc is not None: - net_dur_disc = DDP(net_dur_disc, device_ids=[rank], find_unused_parameters=True) - - pretrain_dir = None - if pretrain_dir is None: - try: - if net_dur_disc is not None: - _, optim_dur_disc, _, epoch_str = utils.load_checkpoint(utils.latest_checkpoint_path(hps.model_dir, "DUR_*.pth"), net_dur_disc, optim_dur_disc, skip_optimizer=not hps.cont) - _, optim_g, _, epoch_str = utils.load_checkpoint(utils.latest_checkpoint_path(hps.model_dir, "G_*.pth"), net_g, - optim_g, skip_optimizer=not hps.cont) - _, optim_d, _, epoch_str = utils.load_checkpoint(utils.latest_checkpoint_path(hps.model_dir, "D_*.pth"), net_d, - optim_d, skip_optimizer=not hps.cont) - - epoch_str = max(epoch_str, 1) - global_step = (epoch_str - 1) * len(train_loader) - except Exception as e: - print(e) - epoch_str = 1 - global_step = 0 - else: - _, _, _, epoch_str = utils.load_checkpoint(utils.latest_checkpoint_path(pretrain_dir, "G_*.pth"), net_g, - optim_g, True) - _, _, _, epoch_str = utils.load_checkpoint(utils.latest_checkpoint_path(pretrain_dir, "D_*.pth"), net_d, - optim_d, True) - - - - scheduler_g = torch.optim.lr_scheduler.ExponentialLR(optim_g, gamma=hps.train.lr_decay, last_epoch=epoch_str - 2) - scheduler_d = torch.optim.lr_scheduler.ExponentialLR(optim_d, gamma=hps.train.lr_decay, last_epoch=epoch_str - 2) - if net_dur_disc is not None: - scheduler_dur_disc = torch.optim.lr_scheduler.ExponentialLR(optim_dur_disc, gamma=hps.train.lr_decay, last_epoch=epoch_str-2) - else: - scheduler_dur_disc = None - scaler = GradScaler(enabled=hps.train.fp16_run) - - for epoch in range(epoch_str, hps.train.epochs + 1): - if rank == 0: - train_and_evaluate(rank, epoch, hps, [net_g, net_d, net_dur_disc], [optim_g, optim_d, optim_dur_disc], [scheduler_g, scheduler_d, scheduler_dur_disc], scaler, [train_loader, eval_loader], logger, [writer, writer_eval]) - else: - train_and_evaluate(rank, epoch, hps, [net_g, net_d, net_dur_disc], [optim_g, optim_d, optim_dur_disc], [scheduler_g, scheduler_d, scheduler_dur_disc], scaler, [train_loader, None], None, None) - scheduler_g.step() - scheduler_d.step() - if net_dur_disc is not None: - scheduler_dur_disc.step() - - -def train_and_evaluate(rank, epoch, hps, nets, optims, schedulers, scaler, loaders, logger, writers): - net_g, net_d, net_dur_disc = nets - optim_g, optim_d, optim_dur_disc = optims - scheduler_g, scheduler_d, scheduler_dur_disc = schedulers - train_loader, eval_loader = loaders - if writers is not None: - writer, writer_eval = writers - - train_loader.batch_sampler.set_epoch(epoch) - global global_step - - net_g.train() - net_d.train() - if net_dur_disc is not None: - net_dur_disc.train() - for batch_idx, (x, x_lengths, spec, spec_lengths, y, y_lengths, speakers, tone, language, bert) in tqdm(enumerate(train_loader)): - if net_g.module.use_noise_scaled_mas: - current_mas_noise_scale = net_g.module.mas_noise_scale_initial - net_g.module.noise_scale_delta * global_step - net_g.module.current_mas_noise_scale = max(current_mas_noise_scale, 0.0) - x, x_lengths = x.cuda(rank, non_blocking=True), x_lengths.cuda(rank, non_blocking=True) - spec, spec_lengths = spec.cuda(rank, non_blocking=True), spec_lengths.cuda(rank, non_blocking=True) - y, y_lengths = y.cuda(rank, non_blocking=True), y_lengths.cuda(rank, non_blocking=True) - speakers = speakers.cuda(rank, non_blocking=True) - tone = tone.cuda(rank, non_blocking=True) - language = language.cuda(rank, non_blocking=True) - bert = bert.cuda(rank, non_blocking=True) - - with autocast(enabled=hps.train.fp16_run): - y_hat, l_length, attn, ids_slice, x_mask, z_mask, \ - (z, z_p, m_p, logs_p, m_q, logs_q), (hidden_x, logw, logw_) = net_g(x, x_lengths, spec, spec_lengths, speakers, tone, language, bert) - mel = spec_to_mel_torch( - spec, - hps.data.filter_length, - hps.data.n_mel_channels, - hps.data.sampling_rate, - hps.data.mel_fmin, - hps.data.mel_fmax) - y_mel = commons.slice_segments(mel, ids_slice, hps.train.segment_size // hps.data.hop_length) - y_hat_mel = mel_spectrogram_torch( - y_hat.squeeze(1), - hps.data.filter_length, - hps.data.n_mel_channels, - hps.data.sampling_rate, - hps.data.hop_length, - hps.data.win_length, - hps.data.mel_fmin, - hps.data.mel_fmax - ) - - y = commons.slice_segments(y, ids_slice * hps.data.hop_length, hps.train.segment_size) # slice - - # Discriminator - y_d_hat_r, y_d_hat_g, _, _ = net_d(y, y_hat.detach()) - with autocast(enabled=False): - loss_disc, losses_disc_r, losses_disc_g = discriminator_loss(y_d_hat_r, y_d_hat_g) - loss_disc_all = loss_disc - if net_dur_disc is not None: - y_dur_hat_r, y_dur_hat_g = net_dur_disc(hidden_x.detach(), x_mask.detach(), logw.detach(), logw_.detach()) - with autocast(enabled=False): - # TODO: I think need to mean using the mask, but for now, just mean all - loss_dur_disc, losses_dur_disc_r, losses_dur_disc_g = discriminator_loss(y_dur_hat_r, y_dur_hat_g) - loss_dur_disc_all = loss_dur_disc - optim_dur_disc.zero_grad() - scaler.scale(loss_dur_disc_all).backward() - scaler.unscale_(optim_dur_disc) - grad_norm_dur_disc = commons.clip_grad_value_(net_dur_disc.parameters(), None) - scaler.step(optim_dur_disc) - - optim_d.zero_grad() - scaler.scale(loss_disc_all).backward() - scaler.unscale_(optim_d) - grad_norm_d = commons.clip_grad_value_(net_d.parameters(), None) - scaler.step(optim_d) - - with autocast(enabled=hps.train.fp16_run): - # Generator - y_d_hat_r, y_d_hat_g, fmap_r, fmap_g = net_d(y, y_hat) - if net_dur_disc is not None: - y_dur_hat_r, y_dur_hat_g = net_dur_disc(hidden_x, x_mask, logw, logw_) - with autocast(enabled=False): - loss_dur = torch.sum(l_length.float()) - loss_mel = F.l1_loss(y_mel, y_hat_mel) * hps.train.c_mel - loss_kl = kl_loss(z_p, logs_q, m_p, logs_p, z_mask) * hps.train.c_kl - - loss_fm = feature_loss(fmap_r, fmap_g) - loss_gen, losses_gen = generator_loss(y_d_hat_g) - loss_gen_all = loss_gen + loss_fm + loss_mel + loss_dur + loss_kl - if net_dur_disc is not None: - loss_dur_gen, losses_dur_gen = generator_loss(y_dur_hat_g) - loss_gen_all += loss_dur_gen - optim_g.zero_grad() - scaler.scale(loss_gen_all).backward() - scaler.unscale_(optim_g) - grad_norm_g = commons.clip_grad_value_(net_g.parameters(), None) - scaler.step(optim_g) - scaler.update() - - if rank == 0: - if global_step % hps.train.log_interval == 0: - lr = optim_g.param_groups[0]['lr'] - losses = [loss_disc, loss_gen, loss_fm, loss_mel, loss_dur, loss_kl] - logger.info('Train Epoch: {} [{:.0f}%]'.format( - epoch, - 100. * batch_idx / len(train_loader))) - logger.info([x.item() for x in losses] + [global_step, lr]) - - scalar_dict = {"loss/g/total": loss_gen_all, "loss/d/total": loss_disc_all, "learning_rate": lr, - "grad_norm_d": grad_norm_d, "grad_norm_g": grad_norm_g} - scalar_dict.update( - {"loss/g/fm": loss_fm, "loss/g/mel": loss_mel, "loss/g/dur": loss_dur, "loss/g/kl": loss_kl}) - scalar_dict.update({"loss/g/{}".format(i): v for i, v in enumerate(losses_gen)}) - scalar_dict.update({"loss/d_r/{}".format(i): v for i, v in enumerate(losses_disc_r)}) - scalar_dict.update({"loss/d_g/{}".format(i): v for i, v in enumerate(losses_disc_g)}) - - image_dict = { - "slice/mel_org": utils.plot_spectrogram_to_numpy(y_mel[0].data.cpu().numpy()), - "slice/mel_gen": utils.plot_spectrogram_to_numpy(y_hat_mel[0].data.cpu().numpy()), - "all/mel": utils.plot_spectrogram_to_numpy(mel[0].data.cpu().numpy()), - "all/attn": utils.plot_alignment_to_numpy(attn[0, 0].data.cpu().numpy()) - } - utils.summarize( - writer=writer, - global_step=global_step, - images=image_dict, - scalars=scalar_dict) - - if global_step % hps.train.eval_interval == 0: - evaluate(hps, net_g, eval_loader, writer_eval) - utils.save_checkpoint(net_g, optim_g, hps.train.learning_rate, epoch, - os.path.join(hps.model_dir, "G_{}.pth".format(global_step))) - utils.save_checkpoint(net_d, optim_d, hps.train.learning_rate, epoch, - os.path.join(hps.model_dir, "D_{}.pth".format(global_step))) - if net_dur_disc is not None: - utils.save_checkpoint(net_dur_disc, optim_dur_disc, hps.train.learning_rate, epoch, os.path.join(hps.model_dir, "DUR_{}.pth".format(global_step))) - keep_ckpts = getattr(hps.train, 'keep_ckpts', 5) - if keep_ckpts > 0: - utils.clean_checkpoints(path_to_models=hps.model_dir, n_ckpts_to_keep=keep_ckpts, sort_by_time=True) - - - global_step += 1 - - if rank == 0: - logger.info('====> Epoch: {}'.format(epoch)) - - - -def evaluate(hps, generator, eval_loader, writer_eval): - generator.eval() - image_dict = {} - audio_dict = {} - print("Evaluating ...") - with torch.no_grad(): - for batch_idx, (x, x_lengths, spec, spec_lengths, y, y_lengths, speakers, tone, language, bert) in enumerate(eval_loader): - x, x_lengths = x.cuda(), x_lengths.cuda() - spec, spec_lengths = spec.cuda(), spec_lengths.cuda() - y, y_lengths = y.cuda(), y_lengths.cuda() - speakers = speakers.cuda() - bert = bert.cuda() - tone = tone.cuda() - language = language.cuda() - for use_sdp in [True, False]: - y_hat, attn, mask, *_ = generator.module.infer(x, x_lengths, speakers, tone, language, bert, y=spec, max_len=1000, sdp_ratio=0.0 if not use_sdp else 1.0) - y_hat_lengths = mask.sum([1, 2]).long() * hps.data.hop_length - - mel = spec_to_mel_torch( - spec, - hps.data.filter_length, - hps.data.n_mel_channels, - hps.data.sampling_rate, - hps.data.mel_fmin, - hps.data.mel_fmax) - y_hat_mel = mel_spectrogram_torch( - y_hat.squeeze(1).float(), - hps.data.filter_length, - hps.data.n_mel_channels, - hps.data.sampling_rate, - hps.data.hop_length, - hps.data.win_length, - hps.data.mel_fmin, - hps.data.mel_fmax - ) - image_dict.update({ - f"gen/mel_{batch_idx}": utils.plot_spectrogram_to_numpy(y_hat_mel[0].cpu().numpy()) - }) - audio_dict.update({ - f"gen/audio_{batch_idx}_{use_sdp}": y_hat[0, :, :y_hat_lengths[0]] - }) - image_dict.update({f"gt/mel_{batch_idx}": utils.plot_spectrogram_to_numpy(mel[0].cpu().numpy())}) - audio_dict.update({f"gt/audio_{batch_idx}": y[0, :, :y_lengths[0]]}) - - utils.summarize( - writer=writer_eval, - global_step=global_step, - images=image_dict, - audios=audio_dict, - audio_sampling_rate=hps.data.sampling_rate - ) - generator.train() - -if __name__ == "__main__": - main() diff --git a/spaces/digitalxingtong/Xingtong-Longread-Bert-VITS2/README.md b/spaces/digitalxingtong/Xingtong-Longread-Bert-VITS2/README.md deleted file mode 100644 index e6cd6f7fccf0a8d1b5740b471b0fbc2eaa5114ab..0000000000000000000000000000000000000000 --- a/spaces/digitalxingtong/Xingtong-Longread-Bert-VITS2/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: AI星瞳 长文本专用(小王子 版本) -emoji: 🌟 -colorFrom: red -colorTo: indigo -sdk: gradio -sdk_version: 3.36.1 -app_file: app.py -pinned: false -license: mit ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference \ No newline at end of file diff --git a/spaces/dineshreddy/WALT/mmdet/models/roi_heads/mask_heads/scnet_mask_head.py b/spaces/dineshreddy/WALT/mmdet/models/roi_heads/mask_heads/scnet_mask_head.py deleted file mode 100644 index 983a2d9db71a3b2b4980996725fdafb0b412b413..0000000000000000000000000000000000000000 --- a/spaces/dineshreddy/WALT/mmdet/models/roi_heads/mask_heads/scnet_mask_head.py +++ /dev/null @@ -1,27 +0,0 @@ -from mmdet.models.builder import HEADS -from mmdet.models.utils import ResLayer, SimplifiedBasicBlock -from .fcn_mask_head import FCNMaskHead - - -@HEADS.register_module() -class SCNetMaskHead(FCNMaskHead): - """Mask head for `SCNet `_. - - Args: - conv_to_res (bool, optional): if True, change the conv layers to - ``SimplifiedBasicBlock``. - """ - - def __init__(self, conv_to_res=True, **kwargs): - super(SCNetMaskHead, self).__init__(**kwargs) - self.conv_to_res = conv_to_res - if conv_to_res: - assert self.conv_kernel_size == 3 - self.num_res_blocks = self.num_convs // 2 - self.convs = ResLayer( - SimplifiedBasicBlock, - self.in_channels, - self.conv_out_channels, - self.num_res_blocks, - conv_cfg=self.conv_cfg, - norm_cfg=self.norm_cfg) diff --git a/spaces/dorkai/text-generation-webui-main/css/chat_style-wpp.css b/spaces/dorkai/text-generation-webui-main/css/chat_style-wpp.css deleted file mode 100644 index a54a10734c0c14a1abe3ecd7fdb89602bc362dec..0000000000000000000000000000000000000000 --- a/spaces/dorkai/text-generation-webui-main/css/chat_style-wpp.css +++ /dev/null @@ -1,86 +0,0 @@ -.chat { - margin-left: auto; - margin-right: auto; - max-width: 800px; - height: calc(100vh - 306px); - overflow-y: auto; - padding-right: 20px; - display: flex; - flex-direction: column-reverse; - word-break: break-word; - overflow-wrap: anywhere; -} - -.message { - padding-bottom: 25px; - font-size: 15px; - font-family: Helvetica, Arial, sans-serif; - line-height: 1.428571429; -} - -.text-you { - background-color: #d9fdd3; - border-radius: 15px; - padding: 10px; - padding-top: 5px; - float: right; -} - -.text-bot { - background-color: #f2f2f2; - border-radius: 15px; - padding: 10px; - padding-top: 5px; -} - -.dark .text-you { - background-color: #005c4b; - color: #111b21; -} - -.dark .text-bot { - background-color: #1f2937; - color: #111b21; -} - -.text-bot p, .text-you p { - margin-top: 5px; -} - -.message-body {} - -.message-body img { - max-width: 300px; - max-height: 300px; - border-radius: 20px; -} - -.message-body p { - margin-bottom: 0 !important; - font-size: 15px !important; - line-height: 1.428571429 !important; -} - -.message-body li { - margin-top: 0.5em !important; - margin-bottom: 0.5em !important; -} - -.message-body li > p { - display: inline !important; -} - -.message-body code { - overflow-x: auto; -} -.message-body :not(pre) > code { - white-space: normal !important; -} - -.dark .message-body p em { - color: rgb(138, 138, 138) !important; -} - -.message-body p em { - color: rgb(110, 110, 110) !important; -} \ No newline at end of file diff --git a/spaces/dorkai/text-generation-webui-main/extensions/multimodal/pipelines/llava/llava.py b/spaces/dorkai/text-generation-webui-main/extensions/multimodal/pipelines/llava/llava.py deleted file mode 100644 index ad80016572eecd10f930b1c6279122c792f3df62..0000000000000000000000000000000000000000 --- a/spaces/dorkai/text-generation-webui-main/extensions/multimodal/pipelines/llava/llava.py +++ /dev/null @@ -1,139 +0,0 @@ -import logging -import time -from abc import abstractmethod -from typing import List, Tuple - -import torch -from extensions.multimodal.abstract_pipeline import AbstractMultimodalPipeline -from huggingface_hub import hf_hub_download -from modules import shared -from modules.text_generation import encode -from PIL import Image -from transformers import CLIPImageProcessor, CLIPVisionModel - - -class LLaVA_v0_Pipeline(AbstractMultimodalPipeline): - CLIP_REPO = "openai/clip-vit-large-patch14" - - def __init__(self, params: dict) -> None: - super().__init__() - self.clip_device = self._get_device("vision_device", params) - self.clip_dtype = self._get_dtype("vision_bits", params) - self.projector_device = self._get_device("projector_device", params) - self.projector_dtype = self._get_dtype("projector_bits", params) - self.image_processor, self.vision_tower, self.mm_projector = self._load_models() - - def _load_models(self): - start_ts = time.time() - - logging.info(f"LLaVA - Loading CLIP from {LLaVA_v0_Pipeline.CLIP_REPO} as {self.clip_dtype} on {self.clip_device}...") - image_processor = CLIPImageProcessor.from_pretrained(LLaVA_v0_Pipeline.CLIP_REPO, torch_dtype=self.clip_dtype) - vision_tower = CLIPVisionModel.from_pretrained(LLaVA_v0_Pipeline.CLIP_REPO, torch_dtype=self.clip_dtype).to(self.clip_device) - - logging.info(f"LLaVA - Loading projector from {self.llava_projector_repo()} as {self.projector_dtype} on {self.projector_device}...") - projector_path = hf_hub_download(self.llava_projector_repo(), self.llava_projector_filename()) - mm_projector = torch.nn.Linear(*self.llava_projector_shape()) - projector_data = torch.load(projector_path) - mm_projector.weight = torch.nn.Parameter(projector_data['model.mm_projector.weight'].to(dtype=self.projector_dtype), False) - mm_projector.bias = torch.nn.Parameter(projector_data['model.mm_projector.bias'].to(dtype=self.projector_dtype), False) - mm_projector = mm_projector.to(self.projector_device) - - logging.info(f"LLaVA supporting models loaded, took {time.time() - start_ts:.2f} seconds") - return image_processor, vision_tower, mm_projector - - @staticmethod - def image_start() -> str: - return "" - - @staticmethod - def image_end() -> str: - return "" - - @staticmethod - def num_image_embeds() -> int: - return 256 - - @staticmethod - def embed_tokens(input_ids: torch.Tensor) -> torch.Tensor: - return shared.model.model.embed_tokens(input_ids).to(shared.model.device, dtype=shared.model.dtype) - - @staticmethod - def placeholder_embeddings() -> torch.Tensor: - return LLaVA_v0_Pipeline.embed_tokens(encode(""*256, add_bos_token=False)[0]) - - def embed_images(self, images: List[Image.Image]) -> torch.Tensor: - images = self.image_processor(images, return_tensors='pt')['pixel_values'] - images = images.to(self.clip_device, dtype=self.clip_dtype) - - with torch.no_grad(): - image_forward_outs = self.vision_tower(images, output_hidden_states=True) - select_hidden_state_layer = -2 - select_hidden_state = image_forward_outs.hidden_states[select_hidden_state_layer] - image_features = select_hidden_state[:, 1:].to(self.projector_device, dtype=self.projector_dtype) - image_features = self.mm_projector(image_features) - return image_features.to(shared.model.device, dtype=shared.model.dtype) - - @staticmethod - @abstractmethod - def llava_projector_repo() -> str: - pass - - @staticmethod - @abstractmethod - def llava_projector_filename() -> str: - pass - - @staticmethod - @abstractmethod - def llava_projector_shape() -> Tuple[int, int]: - pass - - -class LLaVA_v0_13B_Pipeline(LLaVA_v0_Pipeline): - def __init__(self, params: dict) -> None: - super().__init__(params) - - @staticmethod - def name() -> str: - return "llava-13b" - - @staticmethod - def placeholder_token_id() -> int: - return 32000 - - @staticmethod - def llava_projector_shape() -> Tuple[int, int]: - return (1024, 5120) - - @staticmethod - def llava_projector_filename() -> str: - return "mm_projector.bin" - - @staticmethod - def llava_projector_repo() -> str: - return "liuhaotian/LLaVA-13b-delta-v0" - - -class LLaVA_v0_7B_Pipeline(LLaVA_v0_Pipeline): - def __init__(self, params: dict) -> None: - super().__init__(params) - - @staticmethod - def name() -> str: - return "llava-7b" - - @staticmethod - def placeholder_token_id() -> int: - return 32001 - - @staticmethod - def llava_projector_shape() -> Tuple[int, int]: - return (1024, 4096) - - @staticmethod - def llava_projector_filename() -> str: - return "mm_projector.bin" - - @staticmethod - def llava_projector_repo() -> str: - return "liuhaotian/LLaVA-7b-delta-v0" diff --git a/spaces/dperales/Fraud_Detection_Pycaret/app.py b/spaces/dperales/Fraud_Detection_Pycaret/app.py deleted file mode 100644 index 9d29e88e4f202757076fa4f1bbed207376adf428..0000000000000000000000000000000000000000 --- a/spaces/dperales/Fraud_Detection_Pycaret/app.py +++ /dev/null @@ -1,330 +0,0 @@ -import os -import pandas as pd -import numpy as np -import seaborn as sns -import matplotlib.pyplot as plt -import matplotlib as mpl -import pycaret -import streamlit as st -from streamlit_option_menu import option_menu -import PIL -from PIL import Image -from PIL import ImageColor -from PIL import ImageDraw -from PIL import ImageFont - -def main(): - st.set_page_config(layout="wide") - - hide_streamlit_style = """ - - """ - st.markdown(hide_streamlit_style, unsafe_allow_html=True) - - with st.sidebar: - image = Image.open('itaca_logo.png') - st.image(image, width=150) #,use_column_width=True) - page = option_menu(menu_title='Menu', - menu_icon="robot", - options=["Clustering Analysis", - "Anomaly Detection"], - icons=["chat-dots", - "key"], - default_index=0 - ) - - # Additional section below the option menu - # st.markdown("---") # Add a separator line - st.header("Settings") - - num_lines = st.number_input("% of lines to be processed:", min_value=0, max_value=100, value=100) - graph_select = st.checkbox("Show Graphics", value= True) - feat_imp_select = st.checkbox("Feature Importance", value= False) - - # Define the options for the dropdown list - numclusters = [2, 3, 4, 5, 6] - selected_clusters = st.slider("Choose a number of clusters", min_value=2, max_value=10, value=4) - - p_remove_multicollinearity = st.checkbox("Remove Multicollinearity", value=False) - p_multicollinearity_threshold = st.slider("Choose multicollinearity thresholds", min_value=0.0, max_value=1.0, value=0.9) - # p_remove_outliers = st.checkbox("Remove Outliers", value=False) - # p_outliers_method = st.selectbox ("Choose an Outlier Method", ["iforest", "ee", "lof"]) - p_transformation = st.checkbox("Choose Power Transform", value = False) - p_normalize = st.checkbox("Choose Normalize", value = False) - p_pca = st.checkbox("Choose PCA", value = False) - p_pca_method = st.selectbox ("Choose a PCA Method", ["linear", "kernel", "incremental"]) - - st.title('ITACA Insurance Core AI Module') - - #col1, col2 = st.columns(2) - - if page == "Clustering Analysis": - #with col1: - st.header('Clustering Analysis') - - st.write( - """ - """ - ) - # import pycaret unsupervised models - from pycaret.clustering import setup, create_model, assign_model, pull, plot_model - # import ClusteringExperiment - from pycaret.clustering import ClusteringExperiment - - # Display the list of CSV files - directory = "./" - all_files = os.listdir(directory) - # Filter files to only include CSV files - csv_files = [file for file in all_files if file.endswith(".csv")] - # Select a CSV file from the list - selected_csv = st.selectbox("Select a CSV file from the list", ["None"] + csv_files) - - # Upload the CSV file - uploaded_file = st.file_uploader("Choose a CSV file", type="csv") - - # Define the unsupervised model - clusteringmodel = ['kmeans', 'ap', 'meanshift', 'sc', 'hclust', 'dbscan', 'optics', 'birch'] - selected_model = st.selectbox("Choose a clustering model", clusteringmodel) - - # Read and display the CSV file - if selected_csv != "None" or uploaded_file is not None: - if uploaded_file: - try: - delimiter = ',' - insurance_claims = pd.read_csv (uploaded_file, sep=delimiter) - except ValueError: - delimiter = '|' - insurance_claims = pd.read_csv (uploaded_file, sep=delimiter, encoding='latin-1') - else: - insurance_claims = pd.read_csv(selected_csv) - - num_rows = int(insurance_claims.shape[0]*(num_lines)/100) - insurance_claims_reduced = insurance_claims.head(num_rows) - st.write("Rows to be processed: " + str(num_rows)) - - all_columns = insurance_claims_reduced.columns.tolist() - selected_columns = st.multiselect("Choose columns", all_columns, default=all_columns) - insurance_claims_reduced = insurance_claims_reduced[selected_columns].copy() - - with st.expander("Inference Description", expanded=True): - insurance_claims_reduced.describe().T - - with st.expander("Head Map", expanded=True): - cat_col = insurance_claims_reduced.select_dtypes(include=['object']).columns - num_col = insurance_claims_reduced.select_dtypes(exclude=['object']).columns - - # insurance_claims[num_col].hist(bins=15, figsize=(20, 15), layout=(5, 4)) - # Calculate the correlation matrix - corr_matrix = insurance_claims_reduced[num_col].corr() - # Create a Matplotlib figure - fig, ax = plt.subplots(figsize=(12, 8)) - # Create a heatmap using seaborn - #st.header("Heat Map") - sns.heatmap(corr_matrix, annot=True, cmap='coolwarm', fmt='.2f', ax=ax) - # Set the title for the heatmap - ax.set_title('Correlation Heatmap') - # Display the heatmap in Streamlit - st.pyplot(fig) - - if st.button("Prediction"): - #insurance_claims_reduced = insurance_claims_reduced[selected_columns].copy() - - s = setup(insurance_claims_reduced, session_id = 123, remove_multicollinearity=p_remove_multicollinearity, multicollinearity_threshold=p_multicollinearity_threshold, - # remove_outliers=p_remove_outliers, outliers_method=p_outliers_method, - transformation=p_transformation, - normalize=p_normalize, pca=p_pca, pca_method=p_pca_method) - exp_clustering = ClusteringExperiment() - # init setup on exp - exp_clustering.setup(insurance_claims_reduced, session_id = 123) - - with st.spinner("Analyzing..."): - #with col2: - #st.markdown("



      ", unsafe_allow_html=True) - # train kmeans model - cluster_model = create_model(selected_model, num_clusters = selected_clusters) - - cluster_model_2 = assign_model(cluster_model) - # Calculate summary statistics for each cluster - cluster_summary = cluster_model_2.groupby('Cluster').agg(['count', 'mean', 'median', 'min', 'max', - 'std', 'var', 'sum', ('quantile_25', lambda x: x.quantile(0.25)), - ('quantile_75', lambda x: x.quantile(0.75)), 'skew']) - - with st.expander("Cluster Summary", expanded=False): - #st.header("Cluster Summary") - cluster_summary - - with st.expander("Model Assign", expanded=False): - #st.header("Assign Model") - cluster_model_2 - - # all_metrics = get_metrics() - # all_metrics - - with st.expander("Clustering Metrics", expanded=False): - #st.header("Clustering Metrics") - cluster_results = pull() - cluster_results - - with st.expander("Clustering Plots", expanded=False): - if graph_select: - #st.header("Clustering Plots") - # plot pca cluster plot - plot_model(cluster_model, plot = 'cluster', display_format = 'streamlit') - - if selected_model != 'ap': - plot_model(cluster_model, plot = 'tsne', display_format = 'streamlit') - - if selected_model not in ('ap', 'meanshift', 'dbscan', 'optics'): - plot_model(cluster_model, plot = 'elbow', display_format = 'streamlit') - - if selected_model not in ('ap', 'meanshift', 'sc', 'hclust', 'dbscan', 'optics'): - plot_model(cluster_model, plot = 'silhouette', display_format = 'streamlit') - - if selected_model not in ('ap', 'sc', 'hclust', 'dbscan', 'optics', 'birch'): - plot_model(cluster_model, plot = 'distance', display_format = 'streamlit') - - if selected_model != 'ap': - plot_model(cluster_model, plot = 'distribution', display_format = 'streamlit') - - with st.expander("Feature Importance", expanded=False): - # Create a Classification Model to extract feature importance - if graph_select and feat_imp_select: - #st.header("Feature Importance") - from pycaret.classification import setup, create_model, get_config - s = setup(cluster_model_2, target = 'Cluster') - lr = create_model('lr') - - # this is how you can recreate the table - feat_imp = pd.DataFrame({'Feature': get_config('X_train').columns, 'Value' : abs(lr.coef_[0])}).sort_values(by='Value', ascending=False) - # sort by feature importance value and filter top 10 - feat_imp = feat_imp.sort_values(by='Value', ascending=False).head(10) - # Display the filtered table in Streamlit - # st.dataframe(feat_imp) - # Display the filtered table as a bar chart in Streamlit - st.bar_chart(feat_imp.set_index('Feature')) - - elif page == "Anomaly Detection": - #with col1: - st.header('Anomaly Detection') - - st.write( - """ - """ - ) - - # import pycaret anomaly - from pycaret.anomaly import setup, create_model, assign_model, pull, plot_model - # import AnomalyExperiment - from pycaret.anomaly import AnomalyExperiment - - # Display the list of CSV files - directory = "./" - all_files = os.listdir(directory) - # Filter files to only include CSV files - csv_files = [file for file in all_files if file.endswith(".csv")] - # Select a CSV file from the list - selected_csv = st.selectbox("Select a CSV file from the list", ["None"] + csv_files) - - # Upload the CSV file - uploaded_file = st.file_uploader("Choose a CSV file", type="csv") - - # Define the unsupervised model - anomalymodel = ['abod', 'cluster', 'cof', 'iforest', 'histogram', 'knn', 'lof', 'svm', 'pca', 'mcd', 'sod', 'sos'] - selected_model = st.selectbox("Choose an anomaly model", anomalymodel) - - # Read and display the CSV file - if selected_csv != "None" or uploaded_file is not None: - if uploaded_file: - try: - delimiter = ',' - insurance_claims = pd.read_csv (uploaded_file, sep=delimiter) - except ValueError: - delimiter = '|' - insurance_claims = pd.read_csv (uploaded_file, sep=delimiter, encoding='latin-1') - else: - insurance_claims = pd.read_csv(selected_csv) - - num_rows = int(insurance_claims.shape[0]*(num_lines)/100) - insurance_claims_reduced = insurance_claims.head(num_rows) - st.write("Rows to be processed: " + str(num_rows)) - - all_columns = insurance_claims_reduced.columns.tolist() - selected_columns = st.multiselect("Choose columns", all_columns, default=all_columns) - insurance_claims_reduced = insurance_claims_reduced[selected_columns].copy() - - with st.expander("Inference Description", expanded=True): - insurance_claims_reduced.describe().T - - with st.expander("Head Map", expanded=True): - cat_col = insurance_claims_reduced.select_dtypes(include=['object']).columns - num_col = insurance_claims_reduced.select_dtypes(exclude=['object']).columns - - # insurance_claims[num_col].hist(bins=15, figsize=(20, 15), layout=(5, 4)) - # Calculate the correlation matrix - corr_matrix = insurance_claims_reduced[num_col].corr() - # Create a Matplotlib figure - fig, ax = plt.subplots(figsize=(12, 8)) - # Create a heatmap using seaborn - #st.header("Heat Map") - sns.heatmap(corr_matrix, annot=True, cmap='coolwarm', fmt='.2f', ax=ax) - # Set the title for the heatmap - ax.set_title('Correlation Heatmap') - # Display the heatmap in Streamlit - st.pyplot(fig) - - if st.button("Prediction"): - - s = setup(insurance_claims_reduced, session_id = 123, remove_multicollinearity=p_remove_multicollinearity, multicollinearity_threshold=p_multicollinearity_threshold, - # remove_outliers=p_remove_outliers, outliers_method=p_outliers_method, - transformation=p_transformation, - normalize=p_normalize, pca=p_pca, pca_method=p_pca_method) - - exp_anomaly = AnomalyExperiment() - # init setup on exp - exp_anomaly.setup(insurance_claims_reduced, session_id = 123) - - with st.spinner("Analyzing..."): - #with col2: - #st.markdown("



      ", unsafe_allow_html=True) - # train model - anomaly_model = create_model(selected_model) - - with st.expander("Assign Model", expanded=False): - #st.header("Assign Model") - anomaly_model_2 = assign_model(anomaly_model) - anomaly_model_2 - - with st.expander("Anomaly Metrics", expanded=False): - #st.header("Anomaly Metrics") - anomaly_results = pull() - anomaly_results - - with st.expander("Anomaly Plots", expanded=False): - if graph_select: - # plot - #st.header("Anomaly Plots") - plot_model(anomaly_model, plot = 'tsne', display_format = 'streamlit') - plot_model(anomaly_model, plot = 'umap', display_format = 'streamlit') - - with st.expander("Feature Importance", expanded=False): - if graph_select and feat_imp_select: - # Create a Classification Model to extract feature importance - #st.header("Feature Importance") - from pycaret.classification import setup, create_model, get_config - s = setup(anomaly_model_2, target = 'Anomaly') - lr = create_model('lr') - # this is how you can recreate the table - feat_imp = pd.DataFrame({'Feature': get_config('X_train').columns, 'Value' : abs(lr.coef_[0])}).sort_values(by='Value', ascending=False) - # sort by feature importance value and filter top 10 - feat_imp = feat_imp.sort_values(by='Value', ascending=False).head(10) - # Display the filtered table in Streamlit - # st.dataframe(feat_imp) - # Display the filtered table as a bar chart in Streamlit - st.bar_chart(feat_imp.set_index('Feature')) -try: - main() -except Exception as e: - st.sidebar.error(f"An error occurred: {e}") \ No newline at end of file diff --git a/spaces/dylanebert/gaussian-viewer/public/_app/immutable/nodes/1.8eb04061.js b/spaces/dylanebert/gaussian-viewer/public/_app/immutable/nodes/1.8eb04061.js deleted file mode 100644 index a2a0db429b2eaa5b90fce340555e6532dc67efee..0000000000000000000000000000000000000000 --- a/spaces/dylanebert/gaussian-viewer/public/_app/immutable/nodes/1.8eb04061.js +++ /dev/null @@ -1 +0,0 @@ -import{s as x,n as _,e as S}from"../chunks/scheduler.8b74b908.js";import{S as j,i as q,g as f,m as d,s as y,h as g,j as h,n as v,f as u,c as C,a as m,x as $,o as E}from"../chunks/index.c146e4e6.js";import{d as H}from"../chunks/singletons.6b4734db.js";const P=()=>{const s=H;return{page:{subscribe:s.page.subscribe},navigating:{subscribe:s.navigating.subscribe},updated:s.updated}},k={subscribe(s){return P().page.subscribe(s)}};function w(s){var b;let t,r=s[0].status+"",o,n,i,c=((b=s[0].error)==null?void 0:b.message)+"",l;return{c(){t=f("h1"),o=d(r),n=y(),i=f("p"),l=d(c)},l(e){t=g(e,"H1",{});var a=h(t);o=v(a,r),a.forEach(u),n=C(e),i=g(e,"P",{});var p=h(i);l=v(p,c),p.forEach(u)},m(e,a){m(e,t,a),$(t,o),m(e,n,a),m(e,i,a),$(i,l)},p(e,[a]){var p;a&1&&r!==(r=e[0].status+"")&&E(o,r),a&1&&c!==(c=((p=e[0].error)==null?void 0:p.message)+"")&&E(l,c)},i:_,o:_,d(e){e&&(u(t),u(n),u(i))}}}function z(s,t,r){let o;return S(s,k,n=>r(0,o=n)),[o]}let F=class extends j{constructor(t){super(),q(this,t,z,w,x,{})}};export{F as component}; diff --git a/spaces/elvis-d/tweet-sentiment-analysis.GRADIO/app.py b/spaces/elvis-d/tweet-sentiment-analysis.GRADIO/app.py deleted file mode 100644 index a125e022fdd9da28b7bf47a13fe8837482a94d9c..0000000000000000000000000000000000000000 --- a/spaces/elvis-d/tweet-sentiment-analysis.GRADIO/app.py +++ /dev/null @@ -1,48 +0,0 @@ -from scipy.special import softmax - -from transformers import AutoModelForSequenceClassification -from transformers import TFAutoModelForSequenceClassification -from transformers import AutoTokenizer, AutoConfig -from transformers import pipeline - -import gradio as gr - -# Requirements -model_path = "elvis-d/elvis_roberta" -tokenizer = AutoTokenizer.from_pretrained('bert-base-cased') -config = AutoConfig.from_pretrained(model_path) -model = AutoModelForSequenceClassification.from_pretrained(model_path) - -# Preprocess text (username and link placeholders) -def preprocess(text): - new_text = [] - for t in text.split(" "): - t = '@user' if t.startswith('@') and len(t) > 1 else t - t = 'http' if t.startswith('http') else t - new_text.append(t) - return " ".join(new_text) - - -def sentiment_analysis(text): - text = preprocess(text) - - # PyTorch-based models - encoded_input = tokenizer(text, return_tensors='pt') - output = model(**encoded_input) - scores_ = output[0][0].detach().numpy() - scores_ = softmax(scores_) - - # Format output dict of scores - labels = ['Negative', 'Neutral', 'Positive'] - scores = {l:float(s) for (l,s) in zip(labels, scores_) } - - return scores - -demo = gr.Interface( - fn=sentiment_analysis, - inputs=gr.Textbox(placeholder="Write your tweet here..."), - outputs="label", - interpretation="default", - examples=[["This is wonderful!"]]) - -demo.launch() \ No newline at end of file diff --git a/spaces/ennet/ChatDev/online_log/static/replay.html b/spaces/ennet/ChatDev/online_log/static/replay.html deleted file mode 100644 index deb6256bae0292bd2fcc6f03675637f0379393c1..0000000000000000000000000000000000000000 --- a/spaces/ennet/ChatDev/online_log/static/replay.html +++ /dev/null @@ -1,116 +0,0 @@ - - - - - - - - - chatdev demo - - - - - -
      -
      - -

      - Communicative Agents for Software Development

      -
      -
      - chatdev-company - - -
      -
      -
      - -
      -
      -
      -
      -
      -
      -
      -
      -

      Task:

      -
      -
      -
      -
      - - -
      -
      -
      - -
      - -

      -
      -
      - -

      -
      - -
      - -

      -
      -
      - -

      -
      -
      - -

      -
      -
      - -

      -
      -
      - -

      -
      -
      - -

      -
      - -
      - -

      -
      -
      - -

      -
      -
      - -

      -
      -
      - -

      -
      -
      - -

      -
      -
      - -

      -
      - -
      - -
      -
      - - - - - \ No newline at end of file diff --git a/spaces/eson/tokenizer-arena/vocab/belle_7b_2m/__init__.py b/spaces/eson/tokenizer-arena/vocab/belle_7b_2m/__init__.py deleted file mode 100644 index 6c642fcef637b0352dbec44f6b2aa85d53bf25de..0000000000000000000000000000000000000000 --- a/spaces/eson/tokenizer-arena/vocab/belle_7b_2m/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ - -import os -from transformers import AutoTokenizer - -CURRENT_DIR = os.path.dirname(os.path.abspath(__file__)) -TOKENIZER_DIR = os.path.join(CURRENT_DIR, "belle-7b-2m") - -tokenizer = AutoTokenizer.from_pretrained(TOKENIZER_DIR) \ No newline at end of file diff --git a/spaces/eson/tokenizer-arena/vocab/gpt_nexo_20b/test_tokenizer_HF.py b/spaces/eson/tokenizer-arena/vocab/gpt_nexo_20b/test_tokenizer_HF.py deleted file mode 100644 index 988fe983bef052c0272ffc98afdab1b68fb315cd..0000000000000000000000000000000000000000 --- a/spaces/eson/tokenizer-arena/vocab/gpt_nexo_20b/test_tokenizer_HF.py +++ /dev/null @@ -1,38 +0,0 @@ -""" -最简单的tokenizer -""" - - -import json -from vocab.gpt_nexo_20b.tokenizer.tokenizer import HFTokenizer - -tokenizer = HFTokenizer("20B_tokenizer.json") - - -print("vocab_size with added_tokens:", tokenizer.vocab_size) - -vocab = tokenizer.vocab - -def test_single_token(): - """ - 单个字符的编码(一个字符可能会编码成多个id) - """ - for word in "中国解决方法黑白侗鸩,。!?;": - encoding = tokenizer.tokenize(word) - for token_id in encoding: - decode_str = tokenizer.detokenize([token_id]) # 特殊字符解码后会统一变成 �,对应 "\ufffd" - # token = tokenizer.tokenizer.id_to_token(token_id) - print(word, token_id, decode_str, json.dumps(decode_str), ) - # print(word, token_id, decode_str, json.dumps(decode_str), token, json.dumps(token)) - - -def test_encode(): - text = "中国解决方法黑白侗鸩,。!?;一个人去哪里 一 个" - encoding = tokenizer.tokenize(text) - for token_id in encoding: - decode_str = tokenizer.detokenize([token_id]) # 特殊字符解码后会统一变成 �,对应 "\ufffd" - token = tokenizer.tokenizer.id_to_token(token_id) - print(token_id, decode_str, json.dumps(decode_str), token, json.dumps(token)) - - -test_encode() diff --git a/spaces/facebook/MaskCut/style.css b/spaces/facebook/MaskCut/style.css deleted file mode 100644 index c4739b4ea5fc35e774a049e3dacc443f7f0eac19..0000000000000000000000000000000000000000 --- a/spaces/facebook/MaskCut/style.css +++ /dev/null @@ -1,3 +0,0 @@ -h1 { - text-align: center; -} diff --git a/spaces/falterWliame/Face_Mask_Detection/CS GO Mac Cheat Trigger Bhop ESP Aimbot And More NO VAC LINK.md b/spaces/falterWliame/Face_Mask_Detection/CS GO Mac Cheat Trigger Bhop ESP Aimbot And More NO VAC LINK.md deleted file mode 100644 index 0ae664d686ea57f9896f5e3ef61a0aef7db8a574..0000000000000000000000000000000000000000 --- a/spaces/falterWliame/Face_Mask_Detection/CS GO Mac Cheat Trigger Bhop ESP Aimbot And More NO VAC LINK.md +++ /dev/null @@ -1,11 +0,0 @@ -
      -

      It doesn't matter if you have a bot in your team, you can hack any other person's aimbot and skills system. The team's bot will then take care of the bot restriction and help you cheat and hack the other player easier than you could have done otherwise.

      -

      CS GO Mac Cheat Trigger, Bhop, ESP, Aimbot, and more NO VAC


      Download File 🔗 https://urlca.com/2uDdVv



      -

      Features: ESP (Extra Sensory Perception), Triggerbot, Install / Uninstall, Keyboard shortcuts, Keyboard setting. More idea from Themppnalls. ESP stands for Extra Sensory Perception. ESP is considered anything that gives extra information visually. Showing player positions. Showing player health.

      -

      Requirements: Python 2.7, Pygame 1.9.2, PyOpenGL 3.3.0 (32bit, 64bit), PyYAML 3.11 (32bit, 64bit), Pygame Zero 2.0.5 (32bit, 64bit), Pyglet 1.3.4 (32bit, 64bit), OpenGL 16.0.1 (32bit, 64bit), PyQt 4.10.2 (32bit, 64bit). ESP-Triggerbot by tixy. ESP-Triggerbot: ESP (Extra Sensory Perception), Triggerbot, Install / Uninstall, Keyboard shortcuts, Keyboard setting.

      -

      Trust me this is not a cracked or Working version it's. Merely an external. Proves JVM cheats are viable on native games, and demonstrates the longevity against. Valorant undetected cheat (Wallhack, ESP, Aimbot and more!) .

      -

      XDA Developers was founded by developers, for developers. It is now a valuable resource for people who want to make the most of their mobile devices, from customizing the look and feel to adding new functionality.

      -

      -

      Developers and regular people both use XDA Developers. Your contributions will help keep developers' work accessible to all. We challenge you to make the most of this resource by signing up and giving back to XDA.Terms of use: https://www. XDA Developers provides a social experience for developers and regular people to share and discover the latest and greatest content across mobile, wearable, the Internet of Things, and more. Downloads: https://developers. xda-developers. com/tracker/stats/download- stats-download-namespace-tracker-community-your-feedback/
      Contributors: https://developers. xda-developers. com/tracker/contributors/

      899543212b
      -
      -
      \ No newline at end of file diff --git a/spaces/falterWliame/Face_Mask_Detection/Libro Lenguajes De Programacion Principios Y Practica Kenneth C Louden Rapidshare Checkedl __FULL__.md b/spaces/falterWliame/Face_Mask_Detection/Libro Lenguajes De Programacion Principios Y Practica Kenneth C Louden Rapidshare Checkedl __FULL__.md deleted file mode 100644 index a9acc0a7b441ec16b5e20fcef02fd1d0b252a68c..0000000000000000000000000000000000000000 --- a/spaces/falterWliame/Face_Mask_Detection/Libro Lenguajes De Programacion Principios Y Practica Kenneth C Louden Rapidshare Checkedl __FULL__.md +++ /dev/null @@ -1,12 +0,0 @@ -

      Libro Lenguajes De Programacion Principios Y Practica Kenneth C Louden Rapidshare Checkedl


      Download 🗸🗸🗸 https://urlca.com/2uDbWF



      -
      -A look at the new features of the new science. This book is an introduction to software design principles, techniques, and practice. This book is a resource for practicing programmers and developers, students, academic scholars, and for anyone interested in software practice or research. This book presents a foundation for software development practice and more specifically software design. In the first part of the book the topics of design thinking, software architecture and patterns and practices in software development are discussed. The second part deals with software design topics such as low-level design, design guidelines, principles and rules for developing software, the importance of code documentation and good code reviews. In the last part, the real world examples and problems that might be encountered when working with different technologies and development methodologies are discussed. This book is a resource for practicing programmers and developers, students, academic scholars, and for anyone interested in software practice or research. This book presents a foundation for software development practice and more specifically software design. In the first part of the book the topics of design thinking, software architecture and patterns and practices in software development are discussed. The second part deals with software design topics such as low-level design, design guidelines, principles and rules for developing software, the importance of code documentation and good code reviews. In the last part, the real world examples and problems that might be encountered when working with different technologies and development methodologies are discussed..Reading Time: 4 minutes - -You will be happy to know that in the past few weeks we have discovered several successful viruses and have managed to catch them in the act and get an early warning. In the most serious instance, one virus had penetrated the systems of the server of a large U.S. bank and caused $24 million in losses. While the problem was immediately resolved, it showed us that the security of our companies and personal systems is still weak. - -Let’s look at some of the recent issues and how they impacted the Internet and us personally. - -First was the ransoms for the film maker, who had previously made anti-Islamic videos, and his wife. Their video was uploaded to YouTube and rapidly became viral – reaching over 2 million views in a few days. It was very likely that the attackers hacked into their system and used their own access to upload the video. This was an excellent show of how easy it is to access sensitive data and a perfect illustration of how complex passwords really are. Even if you have a long and complex password, a keylogger would easily steal it 4fefd39f24
      -
      -
      -

      diff --git a/spaces/fatiXbelha/sd/CSR Classics Mod Apk 3.1.0 Drive Your Dream Car with Unlimited Money and Gold.md b/spaces/fatiXbelha/sd/CSR Classics Mod Apk 3.1.0 Drive Your Dream Car with Unlimited Money and Gold.md deleted file mode 100644 index 9cc9dc9ece2ac1f22325d4386e39e8067723e7d2..0000000000000000000000000000000000000000 --- a/spaces/fatiXbelha/sd/CSR Classics Mod Apk 3.1.0 Drive Your Dream Car with Unlimited Money and Gold.md +++ /dev/null @@ -1,107 +0,0 @@ - -

      CSR Classics Mod APK 3.1.0: A Review

      -

      If you are a fan of racing games, you might have heard of CSR Classics, a popular game that lets you race with classic cars from different eras. But did you know that there is a modded version of this game that gives you unlimited money, gold, and fuel? In this article, we will review CSR Classics Mod APK 3.1.0, a hacked version of the game that offers many benefits and features. We will also show you how to download and install it on your Android device, how to play it, and some tips and tricks to make the most out of it.

      -

      csr classics mod apk 3.1.0


      Downloadhttps://urllie.com/2uNGdU



      -

      What is CSR Classics?

      -

      CSR Classics is a racing game developed by NaturalMotionGames Ltd, the makers of CSR Racing and CSR Racing 2. It was released in 2013 for iOS and Android devices. The game features over 50 classic cars from different manufacturers, such as Ford, Chevrolet, BMW, Mercedes-Benz, Jaguar, Aston Martin, and more. You can customize your cars with different paint jobs, decals, wheels, and upgrades. You can also compete with other players online or offline in various modes, such as drag races, ladder races, crew battles, regulation races, and more.

      -

      What is CSR Classics Mod APK?

      -

      CSR Classics Mod APK is a modified version of the original game that gives you access to unlimited resources and features. With this modded version, you can enjoy the following benefits:

      -
        -
      • Unlimited money: You can buy any car or upgrade without worrying about the cost.
      • -
      • Unlimited gold: You can use gold to speed up your progress or unlock premium features.
      • -
      • Unlimited fuel: You can race as much as you want without running out of fuel.
      • -
      • All cars unlocked: You can choose any car from the garage without completing any requirements.
      • -
      • No ads: You can play the game without any interruptions or distractions.
      • -
      -

      However, there are also some drawbacks to using this modded version:

      -
        -
      • Possible ban: You might get banned from the online mode if you use this modded version.
      • -
      • Possible virus: You might get infected with malware or viruses if you download this modded version from an untrusted source.
      • -
      • Possible compatibility issues: You might encounter some bugs or glitches if you use this modded version on an incompatible device or OS.
      • -
      -

      How to download and install CSR Classics Mod APK?

      -

      If you want to try out CSR Classics Mod APK 3.1.0, you need to follow these steps:

      -
        -
      1. Download the modded version from a trusted source. You can use this link to download it safely.
      2. -
      3. Enable unknown sources on your device. Go to Settings > Security > Unknown Sources and toggle it on.
      4. -
      5. Locate the downloaded file on your device and tap on it to install it.
      6. -
      7. Wait for the installation to finish and launch the game.
      8. -
      9. Enjoy unlimited money, gold, fuel, and cars!
      10. -
      -

      What are the benefits of CSR Classics Mod APK?

      -

      As we mentioned earlier, CSR Classics Mod APK offers many benefits that can enhance your gaming experience. Here are some of them:

      -
    BenefitExplanation
    More fun and excitementYou can enjoy racing with any car you want, without worrying about the cost or the fuel. You can also challenge other players online or offline with your modded cars.
    More customization and personalizationYou can customize your cars with different paint jobs, decals, wheels, and upgrades. You can also use gold to unlock premium features, such as super nitrous, mechanic, and gas station.
    More variety and diversityYou can choose from over 50 classic cars from different manufacturers, such as Ford, Chevrolet, BMW, Mercedes-Benz, Jaguar, Aston Martin, and more. You can also race in different modes, such as drag races, ladder races, crew battles, regulation races, and more.
    -

    How to play CSR Classics Mod APK?

    -

    Playing CSR Classics Mod APK is similar to playing the original game. Here are some basic steps to get you started:

    -

    csr classics mod apk unlimited money and gold
    -csr classics mod apk latest version download
    -csr classics mod apk android 1
    -csr classics mod apk revdl
    -csr classics mod apk offline
    -csr classics mod apk obb
    -csr classics mod apk hack
    -csr classics mod apk free shopping
    -csr classics mod apk data
    -csr classics mod apk rexdl
    -csr classics mod apk no root
    -csr classics mod apk 2023
    -csr classics mod apk all cars unlocked
    -csr classics mod apk unlimited everything
    -csr classics mod apk old version
    -csr classics mod apk pure
    -csr classics mod apk ios
    -csr classics mod apk online
    -csr classics mod apk unlimited nitro
    -csr classics mod apk unlimited fuel
    -csr classics mod apk andropalace
    -csr classics mod apk android republic
    -csr classics mod apk blackmod
    -csr classics mod apk cheat
    -csr classics mod apk download for pc
    -csr classics mod apk download apkpure
    -csr classics mod apk download uptodown
    -csr classics mod apk for android 10
    -csr classics mod apk for android 11
    -csr classics mod apk for android 9.0 pie
    -csr classics mod apk gamestechy
    -csr classics mod apk happymod
    -csr classics mod apk highly compressed
    -csr classics mod apk ihackedit
    -csr classics mod apk lenov.ru
    -csr classics mod apk mirror
    -csr classics mod apk mob.org
    -csr classics mod apk platinmods
    -csr classics mod apk premium unlocked features free download latest version 2023 updated working link no ads no virus no malware no survey no human verification no root required no password required no login required no signup required no subscription required no payment required no credit card required no debit card required no paypal required no bitcoin required no gift card required no in app purchases required no jailbreak required no lucky patcher required no game guardian required no sb game hacker required no freedom required no xmodgames required no creehack required no leoplay card required no game killer required no gamecih required no root explorer required no es file explorer required no zarchiver required no rar required no zip required no 7zip required no winrar required no winzip required

    -
      -
    1. Select a car from the garage. You can choose any car you want, as they are all unlocked.
    2. -
    3. Customize your car with different paint jobs, decals, wheels, and upgrades. You can use money or gold to buy them.
    4. -
    5. Select a mode from the map. You can choose from drag races, ladder races, crew battles, regulation races, and more.
    6. -
    7. Race against your opponent. You can use the gas pedal to accelerate and the shift button to change gears. You can also use the nitrous button to boost your speed.
    8. -
    9. Win the race and earn rewards. You can earn money, gold, respect points, and trophies.
    10. -
    -

    Tips and tricks for CSR Classics Mod APK

    -

    If you want to improve your skills and performance in CSR Classics Mod APK, you can follow these tips and tricks:

    -
      -
    • Shift at the right time. You can use the green light on the dashboard to know when to shift. Shifting at the right time will give you a perfect start and a perfect shift bonus.
    • -
    • Use nitrous wisely. You can use nitrous to boost your speed and overtake your opponent. However, you should not use it too early or too late, as it might waste your nitrous or slow you down.
    • -
    • Upgrade your car regularly. You can upgrade your car's engine, turbo, intake, exhaust, tires, weight reduction, and gearbox. Upgrading your car will improve its performance and stats.
    • -
    • Choose the right car for each mode. You can choose from different classes of cars, such as C (Classic), B (Vintage), A (Muscle), S (Sports), and R (Super). Each class has its own strengths and weaknesses. For example, C-class cars are good for drag races, while R-class cars are good for crew battles.
    • -
    • Watch videos to earn extra rewards. You can watch videos to earn extra money, gold, fuel, or respect points. You can also watch videos to skip wait times or retry races.
    • -
    -

    FAQs about CSR Classics Mod APK

    -

    Here are some frequently asked questions and answers about CSR Classics Mod APK:

    -
      -
    1. Q: Is CSR Classics Mod APK safe to use?
      A: Yes, CSR Classics Mod APK is safe to use if you download it from a trusted source. However, you should be careful when using it online, as you might get banned by the game developers.
    2. -
    3. Q: Is CSR Classics Mod APK compatible with my device?
      A: CSR Classics Mod APK is compatible with most Android devices that have Android 4.0 or higher. However, you might encounter some compatibility issues if you use it on an incompatible device or OS.
    4. -
    5. Q: How do I update CSR Classics Mod APK?
      A: You can update CSR Classics Mod APK by downloading the latest version from the same source where you downloaded it before. However, you should backup your data before updating it, as you might lose your progress or settings.
    6. -
    7. Q: How do I uninstall CSR Classics Mod APK?
      A: You can uninstall CSR Classics Mod APK by following these steps:
      - Go to Settings > Apps > CSR Classics.
      - Tap on Uninstall and confirm.
      - Delete the modded file from your device.
      - Restart your device.
    8. -
    9. Q: Where can I get more information about CSR Classics Mod APK?
      A: You can get more information about CSR Classics Mod APK by visiting this website, where you can find more details, reviews, screenshots, and videos of the modded version.
    10. -
    -

    Conclusion

    -

    CSR Classics Mod APK 3.1.0 is a hacked version of the popular racing game CSR Classics that gives you unlimited money, gold, fuel, and cars. It also removes ads and unlocks all cars. You can download and install it on your Android device by following the steps we provided in this article. You can also play it with ease by following the tips and tricks we shared. However, you should be aware of the risks and drawbacks of using this modded version, such as possible ban, virus, or compatibility issues. If you want to enjoy racing with classic cars without any limitations, you can try out CSR Classics Mod APK 3.1.0 today!

    401be4b1e0
    -
    -
    \ No newline at end of file diff --git a/spaces/fatiXbelha/sd/Como Relembrar os Anos 70 80 e 90 com o Flash Back Download Grtis das Mais Tocadas.md b/spaces/fatiXbelha/sd/Como Relembrar os Anos 70 80 e 90 com o Flash Back Download Grtis das Mais Tocadas.md deleted file mode 100644 index 7929ed3c34522ddfdf7b96b466fa15a8e9e28bb3..0000000000000000000000000000000000000000 --- a/spaces/fatiXbelha/sd/Como Relembrar os Anos 70 80 e 90 com o Flash Back Download Grtis das Mais Tocadas.md +++ /dev/null @@ -1,144 +0,0 @@ - -

    Flash Back Anos 70 80 90 Download: How to Enjoy the Best Music of the Past

    -

    Do you love listening to oldies but goodies? Do you want to relive the golden days of music with the best songs from the 70s, 80s, and 90s? If so, you are not alone. Millions of people around the world are fans of Flash Back Anos 70 80 90, a term that refers to the music that marked these decades. In this article, we will tell you everything you need to know about Flash Back Anos 70 80 90, why it is still popular today, and how you can download it for free.

    -

    What is Flash Back Anos 70 80 90?

    -

    Flash Back Anos 70 80 90 is a Portuguese expression that literally means "flashback years 70, 80, and 90". It is used to describe the music that was popular in these decades, especially in Brazil and other Latin American countries. The term was coined in the late 90s and early 2000s, when radio stations, TV shows, and nightclubs started to play these songs again, creating a wave of nostalgia among listeners.

    -

    flash back anos 70 80 90 download


    Download File >>>>> https://urllie.com/2uNI1v



    -

    The meaning and origin of the term

    -

    The word "flashback" comes from the English language and means "a sudden and vivid memory of a past event". It is often used in psychology to refer to traumatic memories that resurface in the present. However, in this context, it has a positive connotation, as it implies a pleasant and nostalgic reminiscence of the past. The word "anos" means "years" in Portuguese, and the numbers indicate the decades that are being remembered.

    -

    The genres and artists that defined the era

    -

    The music of Flash Back Anos 70 80 90 covers a wide range of genres and styles, from rock to disco, from pop to funk, from soul to new wave. Some of the most iconic artists of this period include:

    -
      -
    • The Beatles, The Rolling Stones, Led Zeppelin, Pink Floyd, Queen, ABBA, Elton John, David Bowie, Bob Dylan, Bob Marley, and many others from the rock scene.
    • -
    • Bee Gees, Donna Summer, Gloria Gaynor, Village People, Kool & The Gang, Chic, Earth Wind & Fire, Michael Jackson, Madonna, Prince, Whitney Houston, and many others from the disco and pop scene.
    • -
    • James Brown, Marvin Gaye, Stevie Wonder, Aretha Franklin, Diana Ross, Lionel Richie, Barry White, Al Green, George Benson, Sade, and many others from the soul and funk scene.
    • -
    • The Police, Blondie, Duran Duran, Depeche Mode, U2, The Cure, The Smiths, New Order, Pet Shop Boys, Eurythmics, and many others from the new wave scene.
    • -
    -

    Of course, this is not an exhaustive list, as there are many more artists and genres that contributed to the richness and diversity of Flash Back Anos 70 80 90 music.

    -

    Why Flash Back Anos 70 80 90 is still popular today?

    -

    Flash Back Anos 70 80 90 music has not lost its charm and appeal over time. In fact, it has gained more fans and followers as time goes by. There are several reasons why this music is still popular today:

    The nostalgia factor and the emotional connection

    -

    One of the main reasons why people love Flash Back Anos 70 80 90 music is because it reminds them of their childhood, adolescence, or young adulthood. These songs evoke memories of happy times, special moments, and important events in their lives. They also create a sense of belonging and identity, as they reflect the culture and values of their generation. For many people, Flash Back Anos 70 80 90 music is more than just music, it is a part of their history and personality.

    -

    The quality and diversity of the music

    -

    Another reason why Flash Back Anos 70 80 90 music is still popular today is because it is simply good music. The songs are well-written, well-produced, well-performed, and well-recorded. They have catchy melodies, meaningful lyrics, and expressive vocals. They also have a variety of rhythms, instruments, and sounds that make them interesting and enjoyable to listen to. Whether you want to dance, sing, relax, or have fun, you can find a Flash Back Anos 70 80 90 song that suits your mood and taste.

    -

    flash back anos 70 80 90 balada g4
    -flash back anos 70 80 90 cd completo
    -flash back anos 70 80 90 dvd video
    -flash back anos 70 80 90 melhores músicas
    -flash back anos 70 80 90 archive.org
    -flash back anos 70 80 90 eletro funk
    -flash back anos 70 80 90 som automotivo
    -flash back anos 70 80 90 free download
    -flash back anos 70 80 90 public domain
    -flash back anos 70 80 90 internet archive
    -flash back anos 70 80 90 eletro house
    -flash back anos 70 80 90 funk dance
    -flash back anos 70 80 90 música eletrônica
    -flash back anos 70 80 90 ouvir online
    -flash back anos 70 80 90 baixar grátis
    -flash back anos 70 80 90 volume 3
    -flash back anos 70 80 90 vítor hugo
    -flash back anos 70 80 90 mjtv
    -flash back anos 70 80 90 english language
    -flash back anos 70 80 eletro mix
    -flash back anos 70 eletro remix
    -flash back anos retro hits
    -flashback disco music download
    -flashback dance classics download
    -flashback pop rock download
    -flashback internacional download
    -flashback nacional download
    -flashback romântico download
    -flashback love songs download
    -flashback hits collection download
    -flashback mp3 download free
    -flashback zip download free
    -flashback rar download free
    -flashback torrent download free
    -flashback mega download free
    -flashback mediafire download free
    -flashback drive download free
    -flashback youtube playlist download free
    -flashback spotify playlist download free
    -flashback deezer playlist download free

    -

    The influence and legacy of the music

    -

    A third reason why Flash Back Anos 70 80 90 music is still popular today is because it has influenced and inspired many other artists and genres that came after it. The music of Flash Back Anos 70 80 90 has left a mark on the musical landscape, as it has shaped the sound and style of many contemporary musicians. Some examples of artists who have been influenced by Flash Back Anos 70 80 90 music are Bruno Mars, Adele, Ed Sheeran, Lady Gaga, Coldplay, Beyoncé, and many others. The music of Flash Back Anos 70 80 90 has also paved the way for new genres such as hip hop, rap, electronic, indie, alternative, and many others.

    -

    How to download Flash Back Anos 70 80 90 music for free?

    -

    If you are a fan of Flash Back Anos 70 80 90 music and you want to download it for free, you might be wondering how to do it safely and legally. There are many websites and apps that offer free downloads of music, but not all of them are reliable and trustworthy. Some of them might contain viruses, malware, or spyware that can harm your device or compromise your privacy. Some of them might also violate the intellectual property rights of the artists and the record labels that own the music.

    -

    The legal and ethical issues of downloading music

    -

    Before you download any music for free, you should be aware of the legal and ethical issues involved. Downloading music for free without the permission of the artists or the record labels is considered piracy, which is illegal in most countries. Piracy can result in fines, lawsuits, or even jail time for the offenders. Piracy can also hurt the artists and the music industry, as it reduces their income and their incentive to create new music.

    -

    Therefore, you should respect the rights and the work of the artists and the record labels that produce the music that you love. You should only download music for free if you have the consent of the artists or the record labels, or if the music is in the public domain or under a creative commons license.

    The best websites and apps to download music

    -

    If you want to download Flash Back Anos 70 80 90 music for free legally and safely, you should use reputable and reliable websites and apps that offer free downloads of music. Some of the best websites and apps to download music are:

    -
      -
    • Spotify: Spotify is one of the most popular and widely used music streaming services in the world. It offers a free plan that allows you to listen to millions of songs online, with some ads and limitations. You can also download up to 10,000 songs for offline listening, as long as you have an active internet connection every 30 days.
    • -
    • YouTube Music: YouTube Music is another popular and widely used music streaming service in the world. It offers a free plan that allows you to listen to millions of songs and videos online, with some ads and limitations. You can also download songs for offline listening, as long as you have a YouTube Premium subscription.
    • -
    • SoundCloud: SoundCloud is one of the largest and most diverse online audio platforms in the world. It offers a free plan that allows you to listen to millions of songs and podcasts online, with some ads and limitations. You can also download some songs for offline listening, as long as the artists or the record labels have enabled the download option.
    • -
    • Jamendo: Jamendo is one of the largest and most diverse online platforms for independent music in the world. It offers a free plan that allows you to listen to and download thousands of songs online, without any ads or limitations. All the songs on Jamendo are under a creative commons license, which means you can use them for personal or commercial purposes, as long as you give credit to the artists.
    • -
    -

    The tips and tricks to optimize your download experience

    -

    If you want to download Flash Back Anos 70 80 90 music for free, you should follow some tips and tricks to optimize your download experience. Some of them are:

    -
      -
    • Use a fast and stable internet connection to avoid interruptions and delays.
    • -
    • Use a secure and updated browser or app to avoid viruses, malware, or spyware.
    • -
    • Use a reputable and reliable antivirus or firewall software to protect your device and your privacy.
    • -
    • Use a good quality headphone or speaker to enjoy the sound and the quality of the music.
    • -
    • Use a suitable format and bitrate for your device and your preference. The most common formats are MP3, WAV, FLAC, AAC, OGG, etc. The higher the bitrate, the better the quality, but also the larger the file size.
    • -
    • Use a proper file name and folder for your music files to organize them easily and find them quickly.
    • -
    • Use a backup service or device to store your music files safely and securely.
    • -
    -

    Conclusion

    -

    Flash Back Anos 70 80 90 is a term that refers to the music that was popular in the 70s, 80s, and 90s, especially in Brazil and other Latin American countries. It is still popular today because it evokes nostalgia, emotion, quality, diversity, influence, and legacy. If you want to download Flash Back Anos 70 80 90 music for free, you should use reputable and reliable websites and apps that offer free downloads of music legally and safely. You should also follow some tips and tricks to optimize your download experience.

    -

    FAQs

    -

    Here are some frequently asked questions about Flash Back Anos 70 80 90:

    -
      -
    1. What are some of the best Flash Back Anos 70 80 90 songs?
    2. -

      There are many great Flash Back Anos 70 80 90 songs, but some of the most famous ones are:

      -
        -
      • "Staying Alive" by Bee Gees
      • -
      • "Bohemian Rhapsody" by Queen
      • -
      • "Thriller" by Michael Jackson
      • -
      • "Like a Virgin" by Madonna
      • -
      • "Every Breath You Take" by The Police
      • -
      • "I Will Always Love You" by Whitney Houston
      • -
      • "Don't Stop Believin'" by Journey
      • -
      • "Livin' la Vida Loca" by Ricky Martin
      • -
      • "Smells Like Teen Spirit" by Nirvana
      • -
      • "I Want It That Way" by Backstreet Boys
      • -
      -

      Of course, this is not an exhaustive list, as there are many more Flash Back Anos 70 80 90 songs that you can discover and enjoy.

      -
    3. Where can I listen to Flash Back Anos 70 80 90 music online?
    4. -

      There are many online platforms where you can listen to Flash Back Anos 70 80 90 music online, such as:

      -
        -
      • Spotify: Spotify has a large collection of Flash Back Anos 70 80 90 music playlists that you can browse and play for free.
      • -
      • YouTube: YouTube has a large collection of Flash Back Anos 70 80 90 music videos that you can watch and listen to for free.
      • -
      • Radio Flashback FM: Radio Flashback FM is a Brazilian online radio station that plays only Flash Back Anos 70 80 90 music 24/7.
      • -
      • Flashback Radio: Flashback Radio is an American online radio station that plays the best of the 70s, 80s, and 90s music.
      • -
      -
    5. How can I create my own Flash Back Anos 70 80 90 music playlist?
    6. -

      If you want to create your own Flash Back Anos 70 80 90 music playlist, you can follow these steps:

      -
        -
      1. Choose a platform where you want to create your playlist, such as Spotify, YouTube, or SoundCloud.
      2. -
      3. Search for the songs that you want to include in your playlist, using keywords such as "Flash Back Anos 70 80 90", "70s music", "80s music", or "90s music".
      4. -
      5. Select the songs that you like and add them to your playlist, using the option "Add to playlist" or "Create playlist".
      6. -
      7. Name your playlist and customize it with a description and a cover image.
      8. -
      9. Share your playlist with your friends and family, using the option "Share" or "Copy link".
      10. -
      -
    7. What are some of the benefits of listening to Flash Back Anos 70 80 90 music?
    8. -

      Listening to Flash Back Anos 70 80 90 music can have many benefits for your health and well-being, such as:

      -
        -
      • It can boost your mood and make you feel happier, as it triggers the release of dopamine and serotonin in your brain.
      • -
      • It can reduce your stress and anxiety, as it lowers your cortisol levels and blood pressure.
      • -
      • It can improve your memory and cognition, as it stimulates your hippocampus and prefrontal cortex.
      • -
      • It can enhance your creativity and productivity, as it activates your right brain hemisphere and increases your focus.
      • -
      • It can strengthen your social bonds and communication skills, as it fosters empathy and cooperation.
      • -
      -
    9. What are some of the challenges of listening to Flash Back Anos 70 80 90 music?
    10. -

      Listening to Flash Back Anos 70 80 90 music can also have some challenges or drawbacks, such as:

      -
        -
      • It can make you feel old and out of touch, as it reminds you of how much time has passed and how much things have changed.
      • -
      • It can make you feel sad and nostalgic, as it reminds you of the people and places that you miss or have lost.
      • -
      • It can make you feel bored and repetitive, as it exposes you to the same songs and artists over and over again.
      • -
      • It can make you feel isolated and disconnected, as it prevents you from exploring new music and cultures.
      • -
      • It can make you feel guilty and unethical, as it involves downloading music illegally or without paying the artists.
      • -

      401be4b1e0
      -
      -
      \ No newline at end of file diff --git a/spaces/fatiXbelha/sd/Download All of Us Are Dead S01 in Hindi English Korean Netflix Zombie Series.md b/spaces/fatiXbelha/sd/Download All of Us Are Dead S01 in Hindi English Korean Netflix Zombie Series.md deleted file mode 100644 index 2fb7444ab0e123a5975c85cab6fd0e7a0cf6db7d..0000000000000000000000000000000000000000 --- a/spaces/fatiXbelha/sd/Download All of Us Are Dead S01 in Hindi English Korean Netflix Zombie Series.md +++ /dev/null @@ -1,83 +0,0 @@ -
      -

      All of Us Are Dead Season 1 Download in Hindi Filmyzilla

      -

      If you are a fan of zombie horror thrillers, you might have heard of the Korean series All of Us Are Dead, which is based on a popular webtoon of the same name. The series premiered on Netflix in January 2022 and has received rave reviews from critics and viewers alike. But what if you want to watch the series in Hindi, your native language? Is there a way to download All of Us Are Dead season 1 in Hindi from Filmyzilla, a notorious movie piracy website? In this article, we will answer these questions and more.

      -

      all of us are dead season 1 download in hindi filmyzilla


      DOWNLOADhttps://urllie.com/2uNAiT



      -

      What is All of Us Are Dead?

      -

      Synopsis

      -

      All of Us Are Dead is a zombie horror thriller series that follows a group of high school students who are trapped inside their school when a zombie virus outbreak occurs. They must fight their way out or turn into one of the rabid infected. Meanwhile, the outside world is also plunged into chaos as the military tries to contain the situation.

      -

      Cast and crew

      -

      The series stars Park Ji-hu, Yoon Chan-young, Cho Yi-hyun, Lomon, Yoo In-soo, Lee You-mi, Kim Byong-chul, Lee Kyoo-hyung, and Jeon Bae-soo as the main characters. The series is created by Lee JQ, Chun Sung-il, and Kim Nam-su, who also serve as executive producers. The series is directed by Lee Eung-bok, Kim Nam-su, and Kim Seong-hun.

      -

      Reception

      -

      All of Us Are Dead has received positive reviews from critics and viewers for its gripping storyline, intense action scenes, realistic effects, and stellar performances. The series has a rating of 7.5 out of 10 on IMDb and 8.4 out of 10 on MyDramaList. The series has also been renewed for a second season by Netflix, which shows its popularity and demand.

      -

      How to download All of Us Are Dead Season 1 in Hindi?

      -

      Why do people want to watch All of Us Are Dead in Hindi?

      -

      Many people prefer to watch movies and shows in their native language for various reasons. Some may find it easier to understand and enjoy the content without subtitles or dubbing. Some may feel more connected to the characters and emotions when they hear them speak their own language. Some may simply like the sound and feel of their own language better than others.

      -

      For these reasons, many people in India want to watch All of Us Are Dead in Hindi, which is one of the most widely spoken languages in the country. However, Netflix does not offer Hindi dubbing or subtitles for this series, which means that they have to either watch it in Korean with English subtitles or look for other sources to download it in Hindi.

      -

      All of Us Are Dead S01 Hindi Dubbed Web-DL 720p
      -All of Us Are Dead Season 1 Episode 12 Hindi Dubbed (ORG) | K Drama
      -All of Us Are Dead Jigeum Uri Hakgyoneun Hindi + English + Korean
      -All of Us Are Dead Netflix Series Download in Hindi 480p & 1080p HD
      -All of Us Are Dead Korean Zombie Drama Hindi Dubbed Free Download
      -All of Us Are Dead S01 E08 720p Hindi English MSubs Streaming Online
      -All of Us Are Dead Season 1 Complete Multi-Audio Hindi + English + Korean
      -All of Us Are Dead Jigeum Uri Hakgyoneun Season 1 Hindi Dubbed Download
      -All of Us Are Dead Netflix Original Series Hindi Dubbed Watch Online
      -All of Us Are Dead Korean Zombie Series Download in Hindi Filmywap
      -All of Us Are Dead Season 1 Episode 1 Hindi Dubbed (ORG) | K Drama
      -All of Us Are Dead S01 E01 720p Hindi English MSubs Free Download
      -All of Us Are Dead Season 1 Full Episodes Download in Hindi 720p & 480p
      -All of Us Are Dead Jigeum Uri Hakgyoneun Netflix Series Hindi Dubbed
      -All of Us Are Dead Korean Zombie Drama Watch Online in Hindi HD Quality
      -All of Us Are Dead S01 E12 720p Hindi English MSubs Borrow and Streaming
      -All of Us Are Dead Season 1 Multi-Audio Hindi + English + Korean Web-DL
      -All of Us Are Dead Jigeum Uri Hakgyoneun Season 1 Download in Hindi 1080p
      -All of Us Are Dead Netflix Original Series Download in Hindi Filmyzilla
      -All of Us Are Dead Korean Zombie Series Watch Online in Hindi Filmywap
      -All of Us Are Dead Season 1 Episode 2 Hindi Dubbed (ORG) | K Drama
      -All of Us Are Dead S01 E02 720p Hindi English MSubs Streaming Online
      -All of Us Are Dead Season 1 Full Episodes Watch Online in Hindi 720p & 480p
      -All of Us Are Dead Jigeum Uri Hakgyoneun Netflix Series Watch Online in Hindi
      -All of Us Are Dead Korean Zombie Drama Download in Hindi HD Quality
      -All of Us Are Dead S01 E10 720p Hindi English MSubs Free Download
      -All of Us Are Dead Season 1 Multi-Audio Hindi + English + Korean Download
      -All of Us Are Dead Jigeum Uri Hakgyoneun Season 1 Watch Online in Hindi 1080p
      -All of Us Are Dead Netflix Original Series Watch Online in Hindi Filmyzilla
      -All of Us Are Dead Korean Zombie Series Download in Hindi Filmy4wap

      -

      Is it legal and safe to download All of Us Are Dead from Filmyzilla?

      -

      Filmyzilla is a movie piracy website that illegally provides leaked and pirated movies for free. The website has a huge library of movies of different genres and categories. One can find the latest movies, Bollywood movies, dubbed movies, Telugu Movies, Tamil Movies, Hollywood Movies, Web Series, and a lot more.

      -

      However, downloading movies from Filmyzilla is not legal or safe. It is a violation of the Indian Copyright Act of 1957, which prohibits the unauthorized reproduction, distribution , transmission, or display of any copyrighted work without the permission of the owner. It can result in legal action, fines, or imprisonment for the offenders. Downloading movies from Filmyzilla is also not safe for your device and data. The website may contain malware, viruses, spyware, or other harmful software that can infect your device and compromise your security and privacy. The website may also redirect you to other malicious websites or pop-ups that can steal your personal information, such as your bank details, passwords, or identity. Therefore, it is not advisable to download All of Us Are Dead season 1 in Hindi from Filmyzilla or any other similar website. You may end up risking your legal status, device health, and data security.

      -

      What are the alternatives to Filmyzilla?

      -

      If you want to watch All of Us Are Dead season 1 in Hindi legally and safely, you have some alternatives to Filmyzilla. Here are some of them:

      -
        -
      • The best and most reliable option is to watch the series on Netflix with English subtitles. Netflix is a streaming platform that offers high-quality content with a subscription fee. You can enjoy the series without any interruption, ads, or malware. You can also support the creators and actors of the series by watching it on Netflix.
      • -
      • Another option is to use a VPN service to access Netflix from another country that offers Hindi dubbing or subtitles for the series. A VPN is a virtual private network that allows you to change your IP address and location online. You can use a VPN to bypass geo-restrictions and access content that is not available in your region. However, you should be careful while choosing a VPN service, as some of them may not be trustworthy or secure. You should also check the Netflix terms of service before using a VPN, as some of them may prohibit the use of VPNs.
      • -
      • A third option is to wait for the official release of the series in Hindi by Netflix or any other authorized platform. This may take some time, but it will ensure that you watch the series legally and safely. You will also get to enjoy the series in high quality and with proper synchronization.
      • -
      -

      Conclusion

      -

      Summary of the main points

      -

      In this article, we have discussed the following points:

      -
        -
      • All of Us Are Dead is a Korean zombie horror thriller series that is based on a webtoon and premiered on Netflix in January 2022.
      • -
      • The series has received positive reviews from critics and viewers for its storyline, action, effects, and performances.
      • -
      • Many people in India want to watch the series in Hindi, but Netflix does not offer Hindi dubbing or subtitles for it.
      • -
      • Downloading the series from Filmyzilla or any other movie piracy website is not legal or safe. It can result in legal action, fines, imprisonment, malware infection, data theft, or device damage.
      • -
      • The alternatives to Filmyzilla are watching the series on Netflix with English subtitles, using a VPN service to access Netflix from another country that offers Hindi dubbing or subtitles, or waiting for the official release of the series in Hindi by Netflix or any other authorized platform.
      • -
      -

      Recommendation for the viewers

      -

      We recommend that you watch All of Us Are Dead season 1 legally and safely on Netflix with English subtitles. This way, you can enjoy the series without any hassle, risk, or guilt. You can also appreciate the original language and culture of the series and learn some Korean words along the way. If you really want to watch the series in Hindi, you can either use a VPN service or wait for the official release in Hindi by Netflix or any other authorized platform.

      -

      FAQs

      -

      Here are some frequently asked questions about All of Us Are Dead season 1 download in Hindi Filmyzilla:

      -
        -
      1. How many episodes are there in All of Us Are Dead season 1?
      2. -

        All of Us Are Dead season 1 has 12 episodes, each ranging from 40 to 60 minutes.

        -
      3. Is All of Us Are Dead based on a true story?
      4. -

        No, All of Us Are Dead is not based on a true story. It is based on a webtoon by Joo Dong-geun called Now at Our School, which was published from 2009 to 2011.

        -
      5. Will there be a season 2 of All of Us Are Dead?Yes, there will be a season 2 of All of Us Are Dead. Netflix has confirmed the renewal of the series in February 2022. The production of the second season is expected to begin in the second half of 2022.

        -
      6. Where can I read the webtoon Now at Our School?
      7. -

        You can read the webtoon Now at Our School on Naver Webtoon, a digital comics platform. The webtoon is available in Korean and English languages. You can also find fan translations of the webtoon in other languages on various websites and forums.

        -
      8. What are some other Korean zombie series or movies that I can watch?
      9. -

        Some other Korean zombie series or movies that you can watch are Kingdom, Sweet Home, Train to Busan, #Alive, Rampant, and The Odd Family: Zombie on Sale.

        -
      -

      I hope you found this article helpful and informative. If you have any questions or feedback, please leave a comment below. Thank you for reading!

      197e85843d
      -
      -
      \ No newline at end of file diff --git a/spaces/fclong/summary/fengshen/examples/classification/finetune_classification_bert-3.9B_cmnli.sh b/spaces/fclong/summary/fengshen/examples/classification/finetune_classification_bert-3.9B_cmnli.sh deleted file mode 100644 index da10752cff77be9462d17cbb45882543a5e0ed48..0000000000000000000000000000000000000000 --- a/spaces/fclong/summary/fengshen/examples/classification/finetune_classification_bert-3.9B_cmnli.sh +++ /dev/null @@ -1,161 +0,0 @@ -#!/bin/bash -#SBATCH --job-name=slurm-test # create a short name for your job -#SBATCH --nodes=1 # node count -#SBATCH --ntasks=2 # total number of tasks across all nodes -#SBATCH --cpus-per-task=16 # cpu-cores per task (>1 if multi-threaded tasks) -#SBATCH --mem-per-cpu=8G # memory per cpu-core (4G is default) -#SBATCH --gres=gpu:2 # number of gpus per node -#SBATCH --mail-type=ALL # send email when job begins, ends or failed etc. - - -export TORCH_EXTENSIONS_DIR=/cognitive_comp/yangping/cache/torch_extendsions - -BERT_NAME=bert-3.9B - -TASK=cmnli -TEXTA_NAME=sentence1 -TEXTB_NAME=sentence2 -LABEL_NAME=label -ID_NAME=id - - -BATCH_SIZE=16 -VAL_BATCH_SIZE=56 -ZERO_STAGE=2 - - -ROOT_PATH=cognitive_comp -DATA_DIR=/$ROOT_PATH/yangping/data/ChineseCLUE_DATA/${TASK}_public/ -PRETRAINED_MODEL_PATH=/$ROOT_PATH/yangping/pretrained_model/$BERT_NAME/ - - -CHECKPOINT_PATH=/$ROOT_PATH/yangping/checkpoints/fengshen-finetune/$TASK/ -DEFAULT_ROOT_DIR=/cognitive_comp/yangping/nlp/fengshen/fengshen/scripts/log/$TASK/$BERT_NAME/ -OUTPUT_PATH=/$ROOT_PATH/yangping/nlp/modelevaluation/output/${TASK}_predict.json - - -config_json="./ds_config.json" -# Deepspeed figures out GAS dynamically from dynamic GBS via set_train_batch_size() -# reduce_bucket_size: hidden_size*hidden_size -# stage3_prefetch_bucket_size: 0.9 * hidden_size * hidden_size -# stage3_param_persistence_threshold: 10 * hidden_size - -cat < $config_json -{ - "train_micro_batch_size_per_gpu": $BATCH_SIZE, - "steps_per_print": 100, - "gradient_clipping": 1.0, - "zero_optimization": { - "stage": 3, - "offload_optimizer": { - "device": "cpu", - "pin_memory": true - }, - "offload_param": { - "device": "cpu", - "pin_memory": true - }, - "overlap_comm": true, - "contiguous_gradients": true, - "sub_group_size": 1e9, - "reduce_bucket_size": 6553600, - "stage3_prefetch_bucket_size": 5898240, - "stage3_param_persistence_threshold": 25600, - "stage3_max_live_parameters": 1e9, - "stage3_max_reuse_distance": 1e9, - "stage3_gather_fp16_weights_on_model_save": true - }, - "optimizer": { - "type": "Adam", - "params": { - "lr": 1e-6, - "betas": [ - 0.9, - 0.95 - ], - "eps": 1e-8, - "weight_decay": 1e-3 - } - }, - "scheduler": { - "type": "WarmupLR", - "params":{ - "warmup_min_lr": 5e-8, - "warmup_max_lr": 1e-6 - } - }, - "zero_allow_untested_optimizer": false, - "fp16": { - "enabled": true, - "loss_scale": 0, - "loss_scale_window": 1000, - "hysteresis": 2, - "min_loss_scale": 1 - }, - "activation_checkpointing": { - "partition_activations": false, - "contiguous_memory_optimization": false - }, - "wall_clock_breakdown": false -} -EOT - -export PL_DEEPSPEED_CONFIG_PATH=$config_json - - -DATA_ARGS="\ - --data_dir $DATA_DIR \ - --train_data train.json \ - --valid_data dev.json \ - --test_data test.json \ - --train_batchsize $BATCH_SIZE \ - --valid_batchsize $VAL_BATCH_SIZE \ - --max_length 128 \ - --texta_name $TEXTA_NAME \ - --textb_name $TEXTB_NAME \ - --label_name $LABEL_NAME \ - --id_name $ID_NAME \ - " - -MODEL_ARGS="\ - --learning_rate 0.000001 \ - --weight_decay 0.001 \ - --warmup 0.001 \ - --num_labels 3 \ - " - -MODEL_CHECKPOINT_ARGS="\ - --monitor val_acc \ - --save_top_k 3 \ - --mode max \ - --every_n_train_steps 100 \ - --save_weights_only True \ - --dirpath $CHECKPOINT_PATH \ - --filename model-{epoch:02d}-{val_acc:.4f} \ - " -TRAINER_ARGS="\ - --max_epochs 7 \ - --gpus 2 \ - --strategy deepspeed_stage_3 \ - --precision 16 \ - --gradient_clip_val 0.1 \ - --check_val_every_n_epoch 1 \ - --val_check_interval 100 \ - --default_root_dir $DEFAULT_ROOT_DIR \ - " - -options=" \ - --pretrained_model_path $PRETRAINED_MODEL_PATH \ - --output_save_path $OUTPUT_PATH \ - $DATA_ARGS \ - $MODEL_ARGS \ - $MODEL_CHECKPOINT_ARGS \ - $TRAINER_ARGS \ - " - -DOCKER_PATH=/$ROOT_PATH/yangping/containers/pytorch21_06_py3_docker_image.sif -SCRIPT_PATH=/$ROOT_PATH/yangping/nlp/fengshen/fengshen/examples/finetune_classification.py - -# python3 $SCRIPT_PATH $options -srun singularity exec --nv -B /cognitive_comp/:/cognitive_comp/ $DOCKER_PATH python3 $SCRIPT_PATH $options - diff --git a/spaces/fclong/summary/fengshen/examples/pretrain_t5/pretrain_randeng_t5_large.sh b/spaces/fclong/summary/fengshen/examples/pretrain_t5/pretrain_randeng_t5_large.sh deleted file mode 100644 index a91d7082a4c945fe78a2fb0ce99be7c7d9a02745..0000000000000000000000000000000000000000 --- a/spaces/fclong/summary/fengshen/examples/pretrain_t5/pretrain_randeng_t5_large.sh +++ /dev/null @@ -1,132 +0,0 @@ -#!/bin/bash -#SBATCH --job-name=randeng_t5_large -#SBATCH --nodes=2 -#SBATCH --ntasks-per-node=8 -#SBATCH --gres=gpu:8 # number of gpus -#SBATCH --cpus-per-task=30 # cpu-cores per task (>1 if multi-threaded tasks) -#SBATCH -o %x-%j.log -#SBATCH -e %x-%j.err - -set -x -e - -echo "START TIME: $(date)" -MICRO_BATCH_SIZE=8 -ROOT_DIR=/cognitive_comp/ganruyi/experiments/randeng_t5_large_v2/ -if [ ! -d ${ROOT_DIR} ];then - mkdir ${ROOT_DIR} - echo ${ROOT_DIR} created!!!!!!!!!!!!!! -else - echo ${ROOT_DIR} exist!!!!!!!!!!!!!!! -fi - -ZERO_STAGE=1 - -config_json="$ROOT_DIR/ds_config.randeng_t5_large_pretrain.$SLURM_JOBID.json" -export MASTER_PORT=$[RANDOM%10000+30000] - -cat < $config_json -{ - "train_micro_batch_size_per_gpu": ${MICRO_BATCH_SIZE}, - "steps_per_print": 100, - "gradient_clipping": 1.0, - "zero_optimization": { - "stage": $ZERO_STAGE, - "contiguous_gradients": false, - "overlap_comm": true, - "reduce_scatter": true, - "reduce_bucket_size": 50000000, - "allgather_bucket_size": 500000000 - }, - "optimizer": { - "type": "Adam", - "params": { - "lr": 1e-4, - "weight_decay": 1e-2 - } - }, - "scheduler": { - "params": { - "warmup_max_lr": 1e-04, - "warmup_min_lr": 1e-05, - "total_num_steps": 100000, - "warmup_num_steps" : 10000 - }, - "type": "WarmupDecayLR" - }, - "zero_allow_untested_optimizer": false, - "fp16": { - "enabled": true, - "loss_scale": 0, - "loss_scale_window": 1000, - "hysteresis": 2, - "min_loss_scale": 1 - }, - "activation_checkpointing": { - "partition_activations": false, - "contiguous_memory_optimization": false - }, - "wall_clock_breakdown": false -} -EOT - -export PL_DEEPSPEED_CONFIG_PATH=$config_json -export TORCH_EXTENSIONS_DIR=/cognitive_comp/ganruyi/tmp/torch_extendsions -# strategy=ddp -strategy=deepspeed_stage_1 - -TRAINER_ARGS=" - --max_epochs 1 \ - --gpus 8 \ - --num_nodes 2 \ - --strategy ${strategy} \ - --default_root_dir $ROOT_DIR \ - --dirpath $ROOT_DIR/ckpt \ - --save_top_k 3 \ - --every_n_train_steps 1000000 \ - --monitor train_loss \ - --mode min \ - --save_last \ - --val_check_interval 0.01 \ - --preprocessing_num_workers 20 \ -" -# --accumulate_grad_batches 8 \ -DATA_DIR=wudao_180g_t5_tokenized_512 - -DATA_ARGS=" - --train_batchsize $MICRO_BATCH_SIZE \ - --valid_batchsize $MICRO_BATCH_SIZE \ - --train_data ${DATA_DIR} \ - --train_split_size 0.999 \ - --max_seq_length 512 \ -" - -MODEL_ARGS=" - --pretrained_model_path /cognitive_comp/ganruyi/hf_models/google/mt5-large \ - --new_vocab_path /cognitive_comp/ganruyi/hf_models/t5_cn_small/sentencepiece_cn.model \ - --keep_tokens_path /cognitive_comp/ganruyi/hf_models/t5_cn_small/sentencepiece_cn_keep_tokens.json \ -" -# --ckpt_path /cognitive_comp/ganruyi/experiments/randeng_t5_large/ckpt/last.ckpt \ - -SCRIPTS_PATH=/cognitive_comp/ganruyi/Fengshenbang-LM/fengshen/examples/pretrain_t5/pretrain_t5.py - -export CMD=" \ - $SCRIPTS_PATH \ - $TRAINER_ARGS \ - $MODEL_ARGS \ - $DATA_ARGS \ - " - -echo $CMD -# source activate base -# python $CMD -# srun --nodes=1 --gres=gpu:8 --ntasks-per-node=8 --cpus-per-task=30 --jobid=171866 -e %x-%j.err -o %x-%j.log python $CMD - -SINGULARITY_PATH=/cognitive_comp/ganruyi/pytorch21_06_py3_docker_image_v2.sif -srun --jobid=172781 --job-name=randeng_t5_large --nodes=2 --gres=gpu:8 --ntasks-per-node=8 --cpus-per-task=30 -e randeng_t5_large-%j.err -o randeng_t5_large-%j.log singularity exec --nv -B /cognitive_comp/:/cognitive_comp/ $SINGULARITY_PATH bash -c '/home/ganruyi/anaconda3/bin/python $CMD' - - -# to debug - add echo (it exits and prints what it would have launched) -#run_cmd="$PY_LAUNCHER $CMD" -# salloc --nodes=1 --gres=gpu:2 --cpus-per-gpu=20 -t 24:00:00 -# clear; srun singularity exec --nv -B /cognitive_comp/:/cognitive_comp/ $SINGULARITY_PATH bash -c '/home/ganruyi/anaconda3/bin/python $CMD' -# clear; srun singularity exec --nv -B /cognitive_comp/:/cognitive_comp/ $SINGULARITY_PATH bash -c '/home/ganruyi/anaconda3/bin/python -u -m debugpy --listen 192.168.190.2:53005 --wait-for-client $CMD' \ No newline at end of file diff --git a/spaces/fclong/summary/fengshen/models/PPVAE/__init__.py b/spaces/fclong/summary/fengshen/models/PPVAE/__init__.py deleted file mode 100644 index a92b6a8083d4f23a890ebe0c8635a94d0328fcea..0000000000000000000000000000000000000000 --- a/spaces/fclong/summary/fengshen/models/PPVAE/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# coding=utf-8 -# Copyright 2022 IDEA-CCNL The HuggingFace Inc. team. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -""" PyTorch PPVAE model. """ diff --git a/spaces/fengmuxi/ChatGpt-Web/app/components/chat-list.tsx b/spaces/fengmuxi/ChatGpt-Web/app/components/chat-list.tsx deleted file mode 100644 index 8b88c2fc3e9d145803eef4bab2090a036d30d364..0000000000000000000000000000000000000000 --- a/spaces/fengmuxi/ChatGpt-Web/app/components/chat-list.tsx +++ /dev/null @@ -1,158 +0,0 @@ -import DeleteIcon from "../icons/delete.svg"; - -import styles from "./home.module.scss"; -import { - DragDropContext, - Droppable, - Draggable, - OnDragEndResponder, -} from "@hello-pangea/dnd"; - -import { useChatStore } from "../store"; - -import Locale from "../locales"; -import { useNavigate } from "react-router-dom"; -import { Path } from "../constant"; -import { MaskAvatar } from "./mask"; -import { Mask } from "../store/mask"; -import { useRef, useEffect } from "react"; - -export function ChatItem(props: { - onClick?: () => void; - onDelete?: () => void; - title: string; - count: number; - time: string; - selected: boolean; - id: number; - index: number; - narrow?: boolean; - mask: Mask; -}) { - const draggableRef = useRef(null); - useEffect(() => { - if (props.selected && draggableRef.current) { - draggableRef.current?.scrollIntoView({ - block: "center", - }); - } - }, [props.selected]); - return ( - - {(provided) => ( -
      { - draggableRef.current = ele; - provided.innerRef(ele); - }} - {...provided.draggableProps} - {...provided.dragHandleProps} - title={`${props.title}\n${Locale.ChatItem.ChatItemCount( - props.count, - )}`} - > - {props.narrow ? ( -
      -
      - -
      -
      - {props.count} -
      -
      - ) : ( - <> -
      {props.title}
      -
      -
      - {Locale.ChatItem.ChatItemCount(props.count)} -
      -
      - {new Date(props.time).toLocaleString()} -
      -
      - - )} - -
      - -
      -
      - )} -
      - ); -} - -export function ChatList(props: { narrow?: boolean }) { - const [sessions, selectedIndex, selectSession, moveSession] = useChatStore( - (state) => [ - state.sessions, - state.currentSessionIndex, - state.selectSession, - state.moveSession, - ], - ); - const chatStore = useChatStore(); - const navigate = useNavigate(); - - const onDragEnd: OnDragEndResponder = (result) => { - const { destination, source } = result; - if (!destination) { - return; - } - - if ( - destination.droppableId === source.droppableId && - destination.index === source.index - ) { - return; - } - - moveSession(source.index, destination.index); - }; - - return ( - - - {(provided) => ( -
      - {sessions.map((item, i) => ( - { - navigate(Path.Chat); - selectSession(i); - }} - onDelete={() => { - if (!props.narrow || confirm(Locale.Home.DeleteChat)) { - chatStore.deleteSession(i); - } - }} - narrow={props.narrow} - mask={item.mask} - /> - ))} - {provided.placeholder} -
      - )} -
      -
      - ); -} diff --git a/spaces/feregVcuzo/sanity-test-midi/checkpoint/1234 Player Indir Play with Your Friends on the Same Device with Simple One Touch Controls.md b/spaces/feregVcuzo/sanity-test-midi/checkpoint/1234 Player Indir Play with Your Friends on the Same Device with Simple One Touch Controls.md deleted file mode 100644 index 8b69ee7891def5f4cfcf292420e3f40b6897d9f8..0000000000000000000000000000000000000000 --- a/spaces/feregVcuzo/sanity-test-midi/checkpoint/1234 Player Indir Play with Your Friends on the Same Device with Simple One Touch Controls.md +++ /dev/null @@ -1,148 +0,0 @@ -
      -

      1234 Player Indir: A Review of the Best Free Multiplayer Games App

      -

      If you are looking for a fun and easy way to play games with your friends, family, or even by yourself, you should check out 1234 Player Indir. This app is a collection of singleplayer and local multiplayer games that you can play on your Android or iOS device. It features 30 different minigames that you can enjoy with up to four players on the same device. Whether you like action, puzzle, racing, or sports games, you will find something to suit your mood and style in this app. In this article, we will review what 1234 Player Indir is, why you should download it, how to install it, some of the most popular minigames in it, and some tips and tricks for playing it.

      -

      1234 player indir


      Download Filehttps://gohhs.com/2uPu46



      -

      What is 1234 Player Indir?

      -

      1234 Player Indir is a casual game app that offers a variety of minigames for one, two, three, or four players. You can play these games on the same device using simple one touch controls. The app is compatible with Android and iOS devices, so you can play it on your smartphone or tablet.

      -

      A collection of singleplayer and local multiplayer games

      -

      The app contains 30 different minigames that you can play by yourself or with your friends. These games range from classic arcade games like Snake and Pinball, to modern games like Tank Battle and Soccer Challenge. You can also play some unique games like Sumo Wrestling, Chicken Run, and Feed the Pigeon. Each game has its own rules, objectives, and challenges that will keep you entertained for hours.

      -

      Compatible with Android and iOS devices

      -

      You can download and play 1234 Player Indir on any Android or iOS device that supports the app. The app has a small size of around 100 MB, so it won't take up much space on your device. The app also runs smoothly and does not require an internet connection to play. You can enjoy the game offline anytime, anywhere.

      -

      Features 30 different minigames to play

      -

      The app offers a wide range of minigames for different tastes and preferences. You can choose from action, puzzle, racing, sports, and more genres. You can also switch between different minigames as you like, or stick to your favorites. You can also customize the game settings, such as the number of players, the difficulty level, and the game duration. Here is a table that shows some of the minigames available in the app and their descriptions:

      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
      MinigameDescription
      Snake ArenaGrow your snake and avoid your opponents. The last snake standing wins.
      Tank BattleShoot your enemies and dodge their bullets. The last tank standing wins.
      Soccer ChallengeScore a goal in one touch soccer. The player with the most goals wins.
      Sumo WrestlingPush your opponent out of the ring. The last wrestler standing wins.
      Chicken RunAvoid the obstacles and collect the eggs. The player with the most eggs wins.
      Feed the PigeonThrow bread crumbs to the pigeons. The player who feeds the most pigeons wins.
      PinballBounce the ball and hit the targets. The player with the highest score wins.
      Rally DriftersRace against your opponents and drift around the corners. The first player to finish three laps wins.
      -

      Why You Should Download 1234 Player Indir

      -

      1234 Player Indir is a great app for multiplayer gaming. It offers a lot of benefits and advantages that make it worth downloading and playing. Here are some of the reasons why you should download 1234 Player Indir:

      -

      2 3 4 player mini games download
      -1234 player games for android
      -1234 player apk indir
      -2 3 4 player games app store
      -1234 player oyunları indir
      -Stickman party 2 3 4 mini games
      -1234 player games for iphone
      -2 3 4 player games online
      -1234 player mod apk indir
      -2 3 4 player games for ipad
      -1234 player games for pc
      -Stickman party 2 3 4 mini games download
      -1234 player oyunu indir
      -2 3 4 player games free
      -1234 player pro apk indir
      -Stickman party 2 3 4 mini games apk
      -1234 player games for ios
      -2 3 4 player games unblocked
      -1234 player uygulaması indir
      -Stickman party 2 3 4 mini games app store
      -1234 player games for mac
      -Stickman party multiplayer games
      -Best multiplayer games for android offline
      -Local multiplayer games for android
      -Multiplayer mini games for pc
      -Offline multiplayer games for ios
      -Multiplayer mini games online free
      -Offline multiplayer games for ipad
      -Multiplayer mini games for mac
      -Offline multiplayer games for iphone
      -Multiplayer mini games download free
      -Offline multiplayer games for android apk
      -Multiplayer mini games app store free
      -Offline multiplayer games for ios and android
      -Multiplayer mini games unblocked at school
      -Offline multiplayer games for android and ios free download
      -Multiplayer mini games apk mod unlimited money
      -Offline multiplayer games for android and pc via hotspot
      -Multiplayer mini games minecraft server ip address
      -Offline multiplayer games for android bluetooth controller support
      -Multiplayer mini games roblox codes wiki fandom
      -Offline multiplayer games for android using wifi direct
      -Multiplayer mini games fortnite creative map codes
      -Offline multiplayer games for android without internet
      -Multiplayer mini games steam free to play
      -Offline multiplayer games for android tablet
      -Multiplayer mini games switch best
      -Offline multiplayer games for android reddit

      -

      Simple and fun gameplay for all ages

      -

      The app is designed to be easy and fun to play for anyone, regardless of their age or skill level. The games are simple to understand and control, but also challenging and addictive. You can have fun playing by yourself, or with your friends and family. The app is suitable for kids, teens, adults, and even seniors who want to have some fun.

      -

      Play with up to four friends on the same device

      -

      The app allows you to play with up to four players on the same device, using split-screen mode. This means that you don't need any extra devices, controllers, or internet connection to play multiplayer games. You can just use your smartphone or tablet as a console and enjoy playing with your friends on the same screen. This is a great way to bond with your friends, have some friendly competition, or just have a good time.

      -

      Challenge yourself and others in the 4 Player Cup mode

      -

      The app also features a 4 Player Cup mode, where you can compete against other players in a tournament of four minigames. You can choose from three difficulty levels: easy, medium, or hard. You can also choose from three cup types: bronze, silver, or gold. The higher the difficulty and cup type, the harder the games will be. You can play this mode by yourself or with up to three other players. The player who wins the most games in the cup will be crowned as the champion.

      -

      How to Download and Install 1234 Player Indir

      -

      If you are interested in downloading and installing 1234 Player Indir, you can follow these simple steps:

      -

      Visit the Google Play Store or the App Store

      -

      The app is available for free on both Android and iOS platforms. You can visit the Google Play Store or the App Store on your device and search for 2 3 4 Player Mini Games or 2 3 4 Player Games. These are the official names of the app on each platform.

      -

      Search for 2 3 4 Player Mini Games or 2 3 4 Player Games

      -

      Once you find the app on your device's store, you can tap on it to see more details about it. You can read the description, see the screenshots, watch the video, check the ratings and reviews, and more. You can also see if your device is compatible with the app and if it meets the minimum requirements.

      -

      Tap on Install and enjoy the game

      -

      If you decide to download and install 1234 Player Indir, you can simply tap on Install and wait for it to finish downloading and installing on your device. This may take a few minutes depending on your device and internet speed. Once the app is installed, you can open it and start playing the game. You can choose from singleplayer or multiplayer mode, select the minigames you want to play, and have fun.

      -

      Some of the Most Popular Minigames in 1234 Player Indir

      -

      1234 Player Indir has 30 different minigames that you can play by yourself or with your friends. Each minigame has its own theme, graphics, sound effects, and gameplay. Some of the minigames are more popular than others, based on the ratings and reviews of the users. Here are some of the most popular minigames in 1234 Player Indir:

      -

      Snake Arena: Grow your snake and avoid your opponents

      -

      This minigame is based on the classic Snake game, where you have to control a snake and eat dots to grow longer. The twist is that you have to avoid colliding with your own tail or with other snakes. The last snake standing wins the game. You can play this game with up to four players on the same device, using different colors and shapes for your snakes. You can also adjust the speed and size of the snakes, as well as the number of dots on the screen.

      -

      Tank Battle: Shoot your enemies and dodge their bullets

      -

      This minigame is based on the classic Tank game, where you have to control a tank and shoot your enemies. The twist is that you have to dodge their bullets as well as the obstacles on the map. The last tank standing wins the game. You can play this game with up to four players on the same device, using different colors and types of tanks. You can also choose from different maps, such as desert, forest, city, or space.

      -

      Soccer Challenge: Score a goal in one touch soccer

      -

      This minigame is based on the popular sport of soccer, where you have to score a goal by kicking a ball into a net. The twist is that you only have one touch to do so, and you have to aim carefully and time your kick well. The player with the most goals wins the game. You can play this game with up to four players on the same device, using different colors and shapes for your players. You can also choose from different fields, such as grass, sand, ice, or lava.

      -

      Sumo Wrestling: Push your opponent out of the ring

      -

      This minigame is based on the traditional sport of sumo wrestling, where you have to push your opponent out of a circular ring. The twist is that you have to use your finger to swipe and tap on the screen to move your wrestler. The last wrestler standing wins the game. You can play this game with up to four players on the same device, using different colors and sizes for your wrestlers. You can also choose from different rings, such as wood, stone, metal, or water.

      -

      Tips and Tricks for Playing 1234 Player Indir

      -

      1234 Player Indir is a fun and easy game to play, but it can also be challenging and competitive if you want to win more games and beat your friends. Here are some tips and tricks for playing 1234 Player Indir:

      -

      Use the one touch, one button controls wisely

      -

      The app uses simple one touch, one button controls for all the minigames. This means that you only need to tap or swipe on the screen to play. However, this also means that you need to be careful and precise with your movements. You don't want to tap too fast or too slow, or swipe too far or too short. You also want to avoid accidental touches or swipes that might ruin your game. Practice makes perfect, so try to get used to the controls and find the best way to play each minigame.

      -

      Experiment with different minigames and find your favorites

      -

      The app offers a wide range of minigames for different tastes and preferences. You might like some minigames more than others, depending on your mood and style. You might also find some minigames easier or harder than others, depending on your skill level and experience. Don't be afraid to experiment with different minigames and find your favorites. You can also switch between different minigames as you like, or stick to your favorites.

      -

      Invite your friends and family to join the fun

      -

      The app is designed for multiplayer gaming, so it is more fun if you invite your friends and family to join you. You can play with up to four players on the same device, using split-screen mode. This means that you don t need any extra devices, controllers, or internet connection to play multiplayer games. You can just use your smartphone or tablet as a console and enjoy playing with your friends on the same screen. This is a great way to bond with your friends, have some friendly competition, or just have a good time.

      -

      Conclusion

      -

      1234 Player Indir is a great app for multiplayer gaming. It offers a variety of minigames for different tastes and preferences. It is easy to download, install, and play on any device. It is also fun and simple to play for all ages. You can play by yourself or with up to four friends on the same device. You can also challenge yourself and others in the 4 Player Cup mode. If you are looking for a fun and easy way to play games with your friends, family, or even by yourself, you should check out 1234 Player Indir.

      -

      FAQs

      -

      Here are some of the frequently asked questions about 1234 Player Indir:

      -

      Is 1234 Player Indir free?

      -

      Yes, 1234 Player Indir is free to download and play on both Android and iOS devices. However, the app contains ads that may interrupt your gameplay. You can remove the ads by purchasing the premium version of the app for a small fee.

      -

      How many minigames are there in 1234 Player Indir?

      -

      There are 30 different minigames in 1234 Player Indir, ranging from action, puzzle, racing, sports, and more genres. You can choose from singleplayer or multiplayer mode, select the minigames you want to play, and customize the game settings.

      -

      How many players can play 1234 Player Indir on the same device?

      -

      You can play 1234 Player Indir with up to four players on the same device, using split-screen mode. You don't need any extra devices, controllers, or internet connection to play multiplayer games. You can just use your smartphone or tablet as a console and enjoy playing with your friends on the same screen.

      -

      What is the 4 Player Cup mode in 1234 Player Indir?

      -

      The 4 Player Cup mode is a tournament mode where you can compete against other players in a series of four minigames. You can choose from three difficulty levels: easy, medium, or hard. You can also choose from three cup types: bronze, silver, or gold. The higher the difficulty and cup type, the harder the games will be. You can play this mode by yourself or with up to three other players. The player who wins the most games in the cup will be crowned as the champion.

      -

      How can I contact the developers of 1234 Player Indir?

      -

      If you have any questions, feedback, suggestions, or issues with 1234 Player Indir, you can contact the developers of the app by emailing them at support@betterworldgames.com. You can also visit their website at www.betterworldgames.com for more information about their other games and apps.

      401be4b1e0
      -
      -
      \ No newline at end of file diff --git a/spaces/feregVcuzo/sanity-test-midi/checkpoint/Candy Crush Saga for PC How to Install and Play this Legendary Puzzle Game.md b/spaces/feregVcuzo/sanity-test-midi/checkpoint/Candy Crush Saga for PC How to Install and Play this Legendary Puzzle Game.md deleted file mode 100644 index ef9f8dce4ff2ee68edd02ad3f32411a869dc5a2e..0000000000000000000000000000000000000000 --- a/spaces/feregVcuzo/sanity-test-midi/checkpoint/Candy Crush Saga for PC How to Install and Play this Legendary Puzzle Game.md +++ /dev/null @@ -1,102 +0,0 @@ - -

      How to Download Candy Crush Saga on Your PC

      -

      Candy Crush Saga is one of the most popular and addictive games in the world. It is a match 3 puzzle game where you have to swap and match candies of the same color to clear levels and earn rewards. You can also play with your friends and compete for the highest score. But did you know that you can also play Candy Crush Saga on your PC? In this article, we will show you how to download and install Candy Crush Saga on your Windows PC using two different methods. Whether you want to enjoy the game on a bigger screen, use easier controls, or sync your progress across devices, we have you covered.

      -

      how can i download candy crush saga on my pc


      Download File ○○○ https://gohhs.com/2uPvtz



      -

      What is Candy Crush Saga?

      -

      A popular match 3 puzzle game

      -

      Candy Crush Saga is a game developed by King, a leading mobile game developer. It was released in 2012 and has since become one of the most played games of all time. The game has over a trillion levels, each with different goals and challenges. You have to match at least three candies of the same color to clear them from the board and create special candies that have extra effects. You also have to deal with obstacles like chocolate, jelly, licorice, and more. The game is fun, colorful, and satisfying to play.

      -

      Available on multiple platforms

      -

      Candy Crush Saga is not only available on mobile devices, but also on other platforms like Facebook, Windows 10, and web browsers. You can play the game online or offline, as long as you have an internet connection to sync your progress. You can also connect your game to your Facebook account and see how your friends are doing. You can send and receive lives, boosters, and messages from your friends. You can also join events and competitions for extra rewards.

      -

      Why play Candy Crush Saga on your PC?

      -

      Bigger screen and better graphics

      -

      One of the main reasons to play Candy Crush Saga on your PC is that you can enjoy the game on a larger screen with better graphics. You can see more details and colors of the candies and the backgrounds. You can also adjust the resolution and quality settings to suit your preferences. Playing on a bigger screen can also help you spot matches and combos more easily.

      -

      How to install Candy Crush Saga on Windows 10 PC
      -Candy Crush Saga PC download free full version
      -Candy Crush Saga for PC - Play online or offline
      -Download Candy Crush Saga from Microsoft Store app
      -Candy Crush Saga on PC with BlueStacks emulator
      -How to switch and match candies in Candy Crush Saga PC
      -Candy Crush Saga PC game features and tips
      -How to sync Candy Crush Saga between PC and mobile devices
      -Candy Crush Saga PC system requirements and compatibility
      -How to solve puzzles and win levels in Candy Crush Saga PC
      -How to get free boosters and rewards in Candy Crush Saga PC
      -Candy Crush Saga PC update and new levels
      -How to contact Candy Crush Saga support for PC issues
      -How to uninstall Candy Crush Saga from PC
      -How to play Candy Crush Saga with friends on PC
      -How to join the Candy Crush Saga club on PC
      -How to access the Candy Kingdom in Candy Crush Saga PC
      -How to enable in-app purchases in Candy Crush Saga PC
      -How to disable ads in Candy Crush Saga PC
      -How to change the language in Candy Crush Saga PC
      -How to play Candy Crush Soda Saga on PC
      -How to play Candy Crush Jelly Saga on PC
      -How to play Candy Crush Friends Saga on PC
      -How to transfer Candy Crush Saga progress from PC to another device
      -How to backup and restore Candy Crush Saga data on PC
      -How to fix Candy Crush Saga not loading or crashing on PC
      -How to improve the performance of Candy Crush Saga on PC
      -How to customize the settings of Candy Crush Saga on PC
      -How to earn achievements and badges in Candy Crush Saga PC
      -How to participate in challenges and events in Candy Crush Saga PC
      -How to use the Daily Booster Wheel in Candy Crush Saga PC
      -How to clear the jelly and collect the ingredients in Candy Crush Saga PC
      -How to beat the chocolate and other obstacles in Candy Crush Saga PC
      -How to use the power-ups and special candies in Candy Crush Saga PC
      -How to create candy combos and cascades in Candy Crush Saga PC
      -How to unlock new episodes and worlds in Candy Crush Saga PC
      -How to find your friends and send them lives in Candy Crush Saga PC
      -How to connect your Facebook account to Candy Crush Saga PC
      -How to play offline mode in Candy Crush Saga PC
      -How to watch videos and trailers of Candy Crush Saga on PC
      -How to learn more about the characters and story of Candy Crush Saga PC
      -How to follow the official social media accounts of Candy Crush Saga on PC
      -How to read the reviews and ratings of Candy Crush Saga on PC
      -How to share your feedback and suggestions for Candy Crush Saga on PC
      -How to report a bug or problem in Candy Crush Saga on PC
      -How to respect the terms of service and privacy policy of Candy Crush Saga on PC
      -How to exercise your Do Not Sell My Data rights for Candy Crush Saga on PC

      -

      Easier controls and faster performance

      -

      Another reason to play Candy Crush Saga on your PC is that you can use easier controls and experience faster performance. Instead of using your fingers to swipe and tap on the screen, you can use your mouse and keyboard to drag and drop candies. You can also use hotkeys and shortcuts to access menus and options. Playing on a PC can also reduce lagging and crashing issues that may occur on some mobile devices.

      -

      Sync your progress across devices

      -

      A third reason to play Candy Crush Saga on your PC is that you can sync your progress across devices. You don't have to worry about losing your data or starting over if you switch from one device to another. As long as you log in with the same account, you can continue where you left off on any device. You can also access all your lives, boosters, gold bars, and other items that you have collected or purchased on any device.

      -

      How to download Candy Crush Saga on your PC?

      -

      There are two main methods to download and install Candy Crush Saga on your PC. The first method is using an Android emulator, which is a software that allows you to run Android apps on your PC. The second method is using the Microsoft Store, which is a digital distribution platform for Windows 10 apps. We will explain both methods in detail below.

      -

      Method 1: Using Bluestacks emulator

      -

      Bluestacks is one of the most popular and trusted Android emulators for PC. It is free, easy to use, and compatible with most Android apps and games. Here are the steps to download and install Candy Crush Saga on your PC using Bluestacks:

      -

      Step 1: Download and install Bluestacks

      -

      Go to the official website of Bluestacks and click on the download button. The file size is about 500 MB, so it may take some time depending on your internet speed. Once the download is complete, run the installer and follow the instructions to install Bluestacks on your PC. You may need to grant some permissions and restart your PC during the process.

      -

      Step 2: Log in to your Google account

      -

      After installing Bluestacks, launch it and log in to your Google account. This will allow you to access the Google Play Store and sync your data with your Android device. If you don't have a Google account, you can create one for free.

      -

      Step 3: Search for Candy Crush Saga in the Google Play Store

      -

      On the home screen of Bluestacks, click on the Google Play Store icon. In the search bar, type "Candy Crush Saga" and hit enter. You will see a list of results, with Candy Crush Saga being the first one. Click on it to open its page.

      -

      Step 4: Install and launch Candy Crush Saga

      -

      On the page of Candy Crush Saga, click on the install button. The game will start downloading and installing automatically. Once the installation is done, you can click on the open button to launch the game. You can also find the game icon on the home screen of Bluestacks or in the app drawer.

      -

      Method 2: Using Microsoft Store

      -

      If you don't want to use an emulator, you can also download and install Candy Crush Saga on your PC using the Microsoft Store. This method only works for Windows 10 users. Here are the steps to follow:

      -

      Step 1: Open Microsoft Store on your PC

      -

      On your Windows 10 PC, click on the start menu and type "Microsoft Store". Click on the app icon to open it. You can also access it from the taskbar or the desktop.

      -

      Step 2: Search for Candy Crush Saga in the apps section

      -

      In the Microsoft Store, click on the apps section on the top menu. In the search bar, type "Candy Crush Saga" and hit enter. You will see a list of results, with Candy Crush Saga being the first one. Click on it to open its page.

      -

      Step 3: Get and install Candy Crush Saga

      -

      On the page of Candy Crush Saga, click on the get button. The game will start downloading and installing automatically. You may need to sign in with your Microsoft account if you haven't already.

      -

      Step 4: Open and play Candy Crush Saga

      -

      Once the installation is done, you can click on the play button to launch the game. You can also find the game icon on the start menu or on your desktop.

      -

      Conclusion

      -

      Candy Crush Saga is a fun and addictive game that you can play on your PC as well as your mobile device. You can download and install it on your PC using either an Android emulator like Bluestacks or the Microsoft Store. Both methods are easy and safe to follow. Playing Candy Crush Saga on your PC can give you a better gaming experience with a bigger screen, easier controls, faster performance, and synced progress. So what are you waiting for? Download Candy Crush Saga on your PC today and enjoy crushing candies!

      -

      FAQs

      -
        -
      • Q: Is Candy Crush Saga free to play?
      • -
      • A: Yes, Candy Crush Saga is free to play, but it also offers in-app purchases for extra lives, boosters, gold bars, and other items.
      • -
      • Q: How do I update Candy Crush Saga on my PC?
      • -
      • A: If A: If you downloaded Candy Crush Saga from the Google Play Store using Bluestacks, you can update it by opening the Google Play Store app on Bluestacks and clicking on the menu icon on the top left corner. Then, click on "My apps & games" and find Candy Crush Saga in the list of installed apps. If there is an update available, you will see an update button next to it. Click on it to download and install the latest version of the game. If you downloaded Candy Crush Saga from the Microsoft Store, you can update it by opening the Microsoft Store app on your PC and clicking on the menu icon on the top right corner. Then, click on "Downloads and updates" and find Candy Crush Saga in the list of installed apps. If there is an update available, you will see an update button next to it. Click on it to download and install the latest version of the game.
      • -
      • Q: How do I save my progress in Candy Crush Saga on my PC?
      • -
      • A: To save your progress in Candy Crush Saga on your PC, you need to connect your game to your Facebook account or your King account. You can do this by clicking on the settings icon on the bottom left corner of the game screen and choosing "Connect" or "Log in". This will allow you to sync your progress across devices and access your data anytime.
      • -
      • Q: How do I uninstall Candy Crush Saga from my PC?
      • -
      • A: To uninstall Candy Crush Saga from your PC, you need to follow different steps depending on how you downloaded it. If you downloaded it from the Google Play Store using Bluestacks, you can uninstall it by opening Bluestacks and clicking on the menu icon on the top left corner. Then, click on "My apps & games" and find Candy Crush Saga in the list of installed apps. Right-click on it and choose "Uninstall". Confirm your choice and wait for the process to finish. If you downloaded it from the Microsoft Store, you can uninstall it by opening the start menu and typing "Candy Crush Saga". Right-click on the app icon and choose "Uninstall". Confirm your choice and wait for the process to finish.
      • -
      • Q: How do I contact the support team of Candy Crush Saga?
      • -
      • A: To contact the support team of Candy Crush Saga, you can visit their official website and click on "Support" at the bottom of the page. You can also access their help center by clicking on the settings icon on the bottom left corner of the game screen and choosing "Help center". You can find answers to common questions, report a problem, or send feedback.
      • -

      197e85843d
      -
      -
      \ No newline at end of file diff --git a/spaces/feregVcuzo/sanity-test-midi/checkpoint/Coin Master Cheat APK Get Free Spins and Coins in Minutes.md b/spaces/feregVcuzo/sanity-test-midi/checkpoint/Coin Master Cheat APK Get Free Spins and Coins in Minutes.md deleted file mode 100644 index 9def0bdcbbeb72948956647d18160713d52dd538..0000000000000000000000000000000000000000 --- a/spaces/feregVcuzo/sanity-test-midi/checkpoint/Coin Master Cheat APK Get Free Spins and Coins in Minutes.md +++ /dev/null @@ -1,108 +0,0 @@ -
      -

      Coin Master Unlimited Free Spins APK: How to Get It and Why You Need It

      -

      If you are a fan of Coin Master, you probably know how addictive and fun this game can be. You also know how frustrating it can be when you run out of free spins and have to wait for hours or even days to get more. But what if we told you that there is a way to get unlimited free spins without spending any money or breaking any rules? Yes, you heard that right. In this article, we will tell you everything you need to know about Coin Master Unlimited Free Spins APK, a modded version of the game that lets you enjoy unlimited free spins anytime you want. We will also tell you how to get it, how to use it, and what are the risks and drawbacks of using it. So, without further ado, let's get started!

      -

      coin master unlimited free spins apk


      Download File ===> https://gohhs.com/2uPnX5



      -

      What is Coin Master?

      -

      Coin Master is a popular casual game that combines slot machine, card collection, and base building elements. The game was released in 2010 by Moon Active, an Israeli game developer, and has since gained millions of fans worldwide. The game is available for both Android and iOS devices, as well as Facebook.

      -

      The main goal of the game is to build and upgrade your village by spinning a slot machine and using the coins and other rewards you get from it. You can also attack and raid other players' villages to steal their coins and resources. Moreover, you can collect cards and complete sets to unlock new villages and themes. The game has hundreds of levels and villages to explore, each with its own unique design and challenges.

      -

      What are free spins and why are they important?

      -

      Free spins are the most essential resource in Coin Master. They allow you to spin the slot machine and get coins, shields, attacks, raids, or other bonuses. You can use these rewards to build and upgrade your village, as well as defend it from other players' attacks.

      -

      You can get free spins in several ways in Coin Master. You can get five free spins every hour, up to a maximum of 50 per day. You can also get free spins by inviting friends, watching ads, completing events, joining tournaments, or claiming daily links. However, these methods are limited and often not enough to satisfy your needs. That's why many players look for alternative ways to get more free spins without spending real money.

      -

      coin master mod apk unlimited spins and coins
      -coin master hack apk free spins and coins
      -coin master cheats apk unlimited spins 2023
      -coin master free spins generator apk download
      -coin master unlimited spins apk latest version
      -coin master modded apk with free spins
      -coin master spin hack apk no verification
      -coin master free coins and spins apk 2023
      -coin master unlimited spins glitch apk
      -coin master spin link apk download free
      -coin master mod menu apk unlimited spins
      -coin master free spin and coin links apk
      -coin master unlimited spins online apk
      -coin master hack tool v1.9 apk free download
      -coin master free daily spins apk 2023
      -coin master unlimited spins and coins apk ios
      -coin master mod apk 2023 free spins
      -coin master spin generator apk without human verification
      -coin master free spins today daily links apk
      -coin master unlimited coins and spins mod apk
      -coin master hack version download apk free spins
      -coin master cheat engine apk unlimited spins 2023
      -coin master free spin codes apk download
      -coin master unlimited spins app download apk
      -coin master modded version apk with free spins
      -coin master spin glitch 2023 apk download
      -coin master free coins and spins link 2023 apk
      -coin master unlimited spins offline apk
      -coin master hack online generator apk free download
      -coin master free daily spin and coins rewards apk 2023

      -

      How to get unlimited free spins with Coin Master APK?

      -

      One of the most popular and effective ways to get unlimited free spins in Coin Master is by using Coin Master APK, a modded version of the game that gives you access to unlimited free spins and other features. Coin Master APK is not an official app from Moon Active, but rather a modified one created by third-party developers. By using this app, you can bypass the limitations of the original game and enjoy unlimited free spins anytime you want.

      -

      The advantages of using Coin Master APK over other methods

      -

      There are many advantages of using Coin Master APK over other methods of getting free spins in Coin Master. Some of them are:

      -
        -
      • You don't have to spend any money or use any cheats or hacks that might harm your account or device.
      • -
      • You don't have to wait for hours or days to get more free spins. You can get as many as you want whenever you want.
      • -
      • You don't have to rely on unreliable sources or links that might not work or contain viruses.
      • -
      • You can enjoy other features and benefits that the original game does not offer, such as unlimited coins, shields, attacks, raids, cards, and more.
      • -
      • You can have more fun and excitement playing the game without any restrictions or limitations.
      • -
      -

      How to download and install Coin Master APK on your device

      -

      Downloading and installing Coin Master APK on your device is very easy and simple. Just follow these steps:

      -
        -
      1. Go to a trusted and reliable website that offers Coin Master APK download links. You can search for them on Google or use the link we provide below.
      2. -
      3. Click on the download button and wait for the file to be downloaded on your device.
      4. -
      5. Once the file is downloaded, go to your device settings and enable the option to install apps from unknown sources. This will allow you to install Coin Master APK on your device.
      6. -
      7. Locate the downloaded file on your device and tap on it to start the installation process.
      8. -
      9. Follow the instructions on the screen and wait for the installation to be completed.
      10. -
      11. Once the installation is done, you can launch the app and enjoy unlimited free spins and other features.
      12. -
      -

      How to use Coin Master APK to get unlimited free spins

      -

      Using Coin Master APK to get unlimited free spins is very easy and simple. Just follow these steps:

      -
        -
      1. Launch the app and log in with your Facebook account or create a new one. This will sync your progress and data with the original game.
      2. -
      3. Once you are in the game, you will see that you have unlimited free spins available. You can use them as you wish without any limits or restrictions.
      4. -
      5. You can also access other features and benefits that Coin Master APK offers, such as unlimited coins, shields, attacks, raids, cards, and more. You can use them to build and upgrade your village, collect cards, and unlock new levels and themes.
      6. -
      7. You can also play with your friends and other players online, as well as join tournaments and events. You can enjoy the same gameplay and experience as the original game, but with more fun and excitement.
      8. -
      -

      What are the risks and drawbacks of using Coin Master APK?

      -

      While using Coin Master APK has many advantages, it also has some risks and drawbacks that you should be aware of before using it. Some of them are:

      -

      The possible consequences of using a modded version of the game

      -

      Using a modded version of the game means that you are violating the terms and conditions of Moon Active, the developer of Coin Master. This could result in some serious consequences, such as:

      -
        -
      • Your account could be banned or suspended by Moon Active for using an unauthorized app. This could mean losing all your progress and data in the game.
      • -
      • Your device could be detected by Moon Active's anti-cheat system and blocked from accessing the game servers. This could prevent you from playing the game online or offline.
      • -
      • Your device could be flagged by Google Play or Apple Store for using a modded app. This could affect your ability to download or update other apps from these platforms.
      • -

      How to avoid getting banned or losing your progress

      -

      If you want to use Coin Master APK without risking your account or device, you should follow some precautions and tips, such as:

      -
        -
      • Use a VPN service to hide your IP address and location from Moon Active's servers. This will make it harder for them to detect and ban you.
      • -
      • Use a secondary or fake Facebook account to log in to Coin Master APK. This will prevent your main account from being linked to the modded app.
      • -
      • Do not use Coin Master APK excessively or abusively. This will avoid raising suspicion and attracting attention from Moon Active or other players.
      • -
      • Do not brag or boast about using Coin Master APK on social media or in-game chat. This will avoid exposing yourself and inviting reports from other players.
      • -
      • Do not update Coin Master APK from unknown sources or websites. This will avoid installing malware or viruses on your device.
      • -
      -

      How to protect your device from malware and viruses

      -

      Using a modded app also means that you are exposing your device to potential malware and viruses that could harm your device or steal your personal information. To protect your device from these threats, you should follow some security measures, such as:

      -
        -
      • Download Coin Master APK only from trusted and reliable websites that offer safe and secure download links. You can use the link we provide below or search for them on Google.
      • -
      • Scan the downloaded file with a reputable antivirus or anti-malware software before installing it on your device. This will detect and remove any malicious code or program that might be hidden in the file.
      • -
      • Backup your device data regularly and store it on a cloud service or an external storage device. This will help you recover your data in case of any loss or damage caused by malware or viruses.
      • -
      • Keep your device updated with the latest software and security patches. This will fix any vulnerabilities or bugs that might be exploited by malware or viruses.
      • -
      -

      Conclusion

      -

      Coin Master is a fun and addictive game that can keep you entertained for hours. However, if you want to enjoy the game without any limitations or restrictions, you might want to try Coin Master Unlimited Free Spins APK, a modded version of the game that gives you access to unlimited free spins and other features. By using this app, you can build and upgrade your village, collect cards, and unlock new levels and themes without spending any money or waiting for hours. However, you should also be aware of the risks and drawbacks of using this app, such as getting banned, losing your progress, or harming your device. Therefore, you should follow some precautions and tips to avoid these consequences and protect your device from malware and viruses. We hope this article has helped you understand everything you need to know about Coin Master Unlimited Free Spins APK. If you have any questions or comments, feel free to leave them below. And if you are ready to download and install Coin Master APK on your device, click on the link below and enjoy unlimited free spins!

      -

      Frequently Asked Questions

      -

      Here are some of the most common questions that people ask about Coin Master Unlimited Free Spins APK:

      - - - - - - - -
      QuestionAnswer
      Is Coin Master APK safe to use?Coin Master APK is generally safe to use if you download it from a trusted and reliable website that offers safe and secure download links. However, you should always scan the downloaded file with an antivirus or anti-malware software before installing it on your device.
      Is Coin Master APK legal to use?Coin Master APK is not legal to use as it violates the terms and conditions of Moon Active, the developer of Coin Master. By using this app, you are breaking the rules of the game and risking your account and device.
      Will I get banned for using Coin Master APK?You might get banned for using Coin Master APK if Moon Active detects that you are using an unauthorized app. This could result in losing all your progress and data in the game. To avoid getting banned, you should follow some precautions and tips that we mentioned above.
      Can I play online with Coin Master APK?You can play online with Coin Master APK as long as you are not detected by Moon Active's anti-cheat system. You can also play with your friends and other players online, as well as join tournaments and events.
      Can I update Coin Master APK?You can update Coin Master APK if there is a new version available from the same website that you downloaded it from. However, you should not update Coin Master APK from unknown sources or websites, as they might contain malware or viruses that could harm your device.

      401be4b1e0
      -
      -
      \ No newline at end of file diff --git a/spaces/fffiloni/Image-to-MusicGen/tests/utils/__init__.py b/spaces/fffiloni/Image-to-MusicGen/tests/utils/__init__.py deleted file mode 100644 index 0952fcc3f57e34b3747962e9ebd6fc57aeea63fa..0000000000000000000000000000000000000000 --- a/spaces/fffiloni/Image-to-MusicGen/tests/utils/__init__.py +++ /dev/null @@ -1,5 +0,0 @@ -# Copyright (c) Meta Platforms, Inc. and affiliates. -# All rights reserved. -# -# This source code is licensed under the license found in the -# LICENSE file in the root directory of this source tree. diff --git a/spaces/fracapuano/NebulOS/nas.py b/spaces/fracapuano/NebulOS/nas.py deleted file mode 100644 index 3214f7462aed596f453b8679b7d153af200eec2f..0000000000000000000000000000000000000000 --- a/spaces/fracapuano/NebulOS/nas.py +++ /dev/null @@ -1,79 +0,0 @@ -from src.search import GeneticSearch -from src.hw_nats_fast_interface import HW_NATS_FastInterface -from src.utils import DEVICES, union_of_dicts -import numpy as np -import argparse -import json - -def parse_args()->object: - """Args function. - Returns: - (object): args parser - """ - parser = argparse.ArgumentParser() - # this selects the dataset to be considered for the search - parser.add_argument( - "--dataset", - default="cifar10", - type=str, - help="Dataset to be considered. One in ['cifar10', 'cifar100', 'ImageNet16-120'].s", - choices=["cifar10", "cifar100", "ImageNet16-120"] - ) - # this selects the target device to be considered for the search - parser.add_argument( - "--device", - default="edgegpu", - type=str, - help="Device to be considered. One in ['edgegpu', 'eyeriss', 'fpga'].", - choices=["edgegpu", "eyeriss", "fpga"] - ) - # when this flag is triggered, the search is hardware-agnostic (penalized with FLOPS and params) - parser.add_argument("--device-agnostic", action="store_true", help="Flag to trigger hardware-agnostic search.") - - parser.add_argument("--n-generations", default=50, type=int, help="Number of generations to let the genetic algorithm run.") - parser.add_argument("--n-runs", default=30, type=int, help="Number of runs used to compute the average test accuracy.") - - parser.add_argument("--performance-weight", default=0.65, type=float, help="Weight of the performance metric in the fitness function.") - parser.add_argument("--hardware-weight", default=0.35, type=float, help="Weight of the hardware metric in the fitness function.") - - return parser.parse_args() - -def main(): - # parse arguments - args = parse_args() - - dataset = args.dataset - device = args.device if args.device in DEVICES else None - n_generations = args.n_generations - n_runs = args.n_runs - performance_weight, hardware_weight = args.performance_weight, args.hardware_weight - - if performance_weight + hardware_weight > 1.0 + 1e-6: - error_msg = f""" - Performance weight: {performance_weight}, Hardware weight: {hardware_weight} (they sum up to {performance_weight + hardware_weight}). - The sum of the weights must be less than 1. - """ - raise ValueError(error_msg) - - nebulos_chunks = [] - for i in range(4): # the number of chunks is 4 in this case - with open(f"data/nebuloss_{i+1}.json", "r") as f: - nebulos_chunks.append(json.load(f)) - - searchspace_dict = union_of_dicts(nebulos_chunks) - - # initialize the search space given dataset and device - searchspace_interface = HW_NATS_FastInterface(datapath=searchspace_dict, device=args.device, dataset=args.dataset) - search = GeneticSearch( - searchspace=searchspace_interface, - fitness_weights=np.array([performance_weight, hardware_weight]) - ) - # this perform the actual architecture search - results = search.solve(max_generations=n_generations) - - print(f'{dataset}-{device.upper() if device is not None else device}') - print(results[0].genotype, results[0].genotype_to_idx["/".join(results[0].genotype)], results[1]) - print() - -if __name__=="__main__": - main() diff --git a/spaces/g4f/freegpt-webui/g4f/Provider/Providers/Weuseing.py b/spaces/g4f/freegpt-webui/g4f/Provider/Providers/Weuseing.py deleted file mode 100644 index ba79e8b9c2573418720495a20d4c1c8d5a6ca7e9..0000000000000000000000000000000000000000 --- a/spaces/g4f/freegpt-webui/g4f/Provider/Providers/Weuseing.py +++ /dev/null @@ -1,29 +0,0 @@ -import requests -import os -import json -from ...typing import sha256, Dict, get_type_hints - -url = 'https://api.gptplus.one' -model = ['gpt-3.5-turbo', 'gpt-3.5-turbo-16k', 'gpt-3.5-turbo-16k-0613', 'gpt-3.5-turbo-0613'] -supports_stream = True -needs_auth = False - -def _create_completion(model: str, messages: list, stream: bool, temperature: float = 0.7, **kwargs): - headers = { - 'Content-Type': 'application/json', - 'Accept': '*/*', - 'Accept-Language': 'ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7,ja;q=0.6,zh-TW;q=0.5,zh;q=0.4', - } - data = { - 'messages': messages, - 'model': model, - } - response = requests.post('https://api.gptplus.one/chat-process', json=data, stream=True) - print(response) - - for token in response.iter_content(chunk_size=None): - yield (token.decode('utf-8')) - - -params = f'g4f.Providers.{os.path.basename(__file__)[:-3]} supports: ' + \ - '(%s)' % ', '.join([f"{name}: {get_type_hints(_create_completion)[name].__name__}" for name in _create_completion.__code__.co_varnames[:_create_completion.__code__.co_argcount]]) diff --git a/spaces/gagan3012/summarization/blog/blog.md b/spaces/gagan3012/summarization/blog/blog.md deleted file mode 100644 index 6dfcc38e2861e998051a9b0eeb359adb70cd424e..0000000000000000000000000000000000000000 --- a/spaces/gagan3012/summarization/blog/blog.md +++ /dev/null @@ -1,123 +0,0 @@ -# Machine Summarization – An Open Data Science Project -## TL;DR -We built a machine learning model that summarizes text. It only makes sense that we’ll let it summarize what this article is about. -## Model generated summary of the Article: - -Deep Learning technology can be used for learning tasks related to language, such as translation, classification, entity recognition or in this case, summarization . We wanted to build a project that could be easily reproduced and customized, to make it usable for the community . The package for text summarization is available to be downloaded as a package . Using DAGHub allows us to track and manage metrics for all the different runs..In a sense, this is a template for more summarization projects. The code for training the model has been written in pytorch lightning. The script allows us to train T5, mT5 and byT5 models as well. - -To add to this auto-summary – Two additional interesting aspects of the project are: -- It is easily customizable – changing datasets and model architectures is made to be easy, which means that you can easily adapt it to your needs. -- It integrates many of the best open source tools all in one – DVC, MLflow, HuggingFace, and Streamlit. This is an example of an end to end open source stack and workflow, which means it can be applicable to many other ML projects. -# Task Introduction – Machine Summarization -Natural Language Processing is one of the key areas where Machine Learning has been very effective. In fact, whereas NLP traditionally required a lot of human intervention, today, this is no longer true. Specifically, Deep Learning technology can be used for learning tasks related to language, such as translation, classification, entity recognition or in this case, summarization. - -Borrowing the definition of the task from this excellent article by Luís Gonçalves: -> Summarization is the task of condensing a piece of text to a shorter version, reducing the size of the initial text while at the same time preserving key informational elements and the meaning of content. Since manual text summarization is a time expensive and generally laborious task, the automatization of the task is gaining increasing popularity and therefore constitutes a strong motivation for academic research. - -> There are important applications for text summarization in various NLP related tasks such as text classification, question answering, legal texts summarization, news summarization, and headline generation. Moreover, the generation of summaries can be integrated into these systems as an intermediate stage which helps to reduce the length of the document. - - -## The Challenge – Making it easy to modify datasets and models -Typically when we are building or fine tuning a model for summarisation we need to load the model, download the data, write a fine tuning script and then we need to define our pipeline. The whole process is very intensive and often results are not reproducible by others using the pipeline. In a traditional git repository it is hard to keep track of large datasets and models which makes it even harder to track models. - -There was not a ready to use pipeline that could be easily modified with different datasets to train the same model (or the ability to customize the model, for that matter). Each time we had to change a dataset or use a different split of the dataset we would have to re-run all the steps of the pipeline which would further take up resources on the system. - -Usually, if you wanted to build a custom summarization model, you had to do all of the work we describe above from scratch, but we wanted to build a project that could be easily reproduced and customized, to make it usable for the community. In a sense, this is a template for more summarization projects - - -We even created a package for text summarization which is available to for being downloaded using `pip`: - -``` -pip install t5s - -``` - -Once we download the package we can use the training pipeline. But before we get into how the package works, let’s start by explaining what each stage of the pipeline does. - - -## The Pipeline – Providing structure to our project -The first stage of our pipeline is to download data from the Hugging Face hub. Here for training we have used the `CNN_dailymail` dataset. In order to download the dataset we use the parameter files called `data_params.yml` which defines the datasets and the split that we would like to train our data on. We run the `download_data` stage which downloads the data and then stores it as raw data which we will then process. - -Once the raw data is saved we move on to processing the data using our script to process the raw data. We change the column names and modify the data to work with our training script. Now the data is also split into three different files: `train.csv`, `validation.csv` and `test.csv` which represent training, validation and test sets, respectively. - -Now we can move on to training the model. The code for training the model has been written in pytorch lightning. The script allows us to train `T5`, `mT5` and `byT5` models as well. All the script parameters can be controlled using the `model_params.yml` file. The training stage returns the model that can be saved and also the training metrics which are logged using MLflow and DAGsHub. - -Next we need to evaluate the model that has been created and to do so we need to use the rouge metric which uses the test datasets to evaluate the model. ROUGE, or Recall-Oriented Understudy for Gisting Evaluation, is a set of metrics and a software package used for evaluating automatic summarization and machine translation software in natural language processing. The metrics compare an automatically produced summary or translation against a reference or a set of references (human-produced) summary or translation. The evaluation metrics are also saved using DAGsHub. Once we commit all the models to git we can evaluate our models from the DAGsHub repo. - - - - -We can also visualise and test the results of the model using a streamlit app which can be accessed using Hugging Face spaces. We also have the option of running the upload script and uploading the model to Hugging Face Hub too. - -## The hard part – making things reproducible and customizable -One of the biggest challenges that we faced in this project was to build a data pipeline that was reproducible and was easy to evaluate. Using DAGsHub has made this possible. DAGsHub allows us to track and manage metrics for all the different runs and allows us to have a reproducible pipeline. Logging metrics to DAGsHub is as easy as committing files to a git repo one push and we are ready to analyse the run. - -In order to use the DAGsHub logger with pytorch lightning we had to make a few changes in the logging system in our code. Since pytorch lightning is a live project and it’s always improving we need to find better ways to have real time logging. We tried using multiple logging services that can be used in the pipeline on demand too. We have implemented Weights and Biases, tensorboard and MLFlow logging. We found that MLFlow is the best logging method here because of its seamless integration with DAGsHub. -## The `t5s` package – wrapping it up nicely -In order to run the pipeline we have setup a CLI application that will help us run the pipeline - -To install the pipeline we need to first install t5s using: - -``` -pip install t5s -``` - -Now, we need to clone the repo containing the code. -``` -t5s clone -``` - -We would then have to create the required directories to run the pipeline - -``` -t5s dirs -``` - -To define the parameters for a run we’ll use the following command: -``` -t5s start [-d DATASET] [-s SPLIT] [-n NAME] [-mt MODEL_TYPE] - [-m MODEL_NAME] [-e EPOCHS] [-lr LEARNING_RATE] - [-b BATCH_SIZE] -``` -This will set all the necessary parameters, in order to automate the rest of the process, including data and model retrieval, and setting of hyperparameters for the training step. - -Then we need to pull the model we chose from our DVC repo: - -``` -t5s pull -``` - -Now to run the training pipeline we can run: - -``` -t5s run -``` - -Before pushing make sure that the DVC remote is setup correctly: - -``` -dvc remote modify origin url https://dagshub.com/{user_name}/summarization.dvc -dvc remote modify origin --local auth basic -dvc remote modify origin --local user {user_name} -dvc remote modify origin --local password {your_token} -``` -Finally to push the model to DVC - -``` -t5s push -``` - -To push this model to Hugging Face Hub for inference you can run: - -``` -t5s upload -``` - -Finally, if we would like to test the model and visualise the results we can run: - -``` -t5s visualize -``` -This will open our Streamlit app, which in turn will let us try out our model with some custom examples. -## Summary -In conclusion, we have built a machine summarisation pipeline that is reproducible and reusable. This project is unique because it combines a lot of open source tools like DAGsHub, DVC, PyTorch Lightning, HuggingFace Hub and Streamlit to build the model. We would love for you to try out our Machine Summarisation project yourself, and to give us feedback. It would really help us to prioritize future features, so please vote on or create issues! If you'd like to take a more active part, we have some good first issues ideas that you can start with. We'll be happy to provide guidance on the best way to do so. diff --git a/spaces/gotiQspiryo/whisper-ui/examples/Free Adobe Premiere Pro Cs5 Templates To Download ((NEW)).md b/spaces/gotiQspiryo/whisper-ui/examples/Free Adobe Premiere Pro Cs5 Templates To Download ((NEW)).md deleted file mode 100644 index 972f18a67484a9842bf93770fe15482a8810796f..0000000000000000000000000000000000000000 --- a/spaces/gotiQspiryo/whisper-ui/examples/Free Adobe Premiere Pro Cs5 Templates To Download ((NEW)).md +++ /dev/null @@ -1,36 +0,0 @@ -

      free adobe premiere pro cs5 templates to download


      Download Ziphttps://urlgoal.com/2uyN5O



      - -  Make sure you download and enjoy the templates before the offer ends.  The deadline for the $50 Free Premiere Pro Templates Offer is December 1, 2019. - -Prepare for the Premiere Pro Competitions by downloading free projects that cover Premiere Pro, from animation, to film, and all-around.  You'll get ideas and examples of what you can do to stand out.[Family relationships, family conflicts and violence: from a phenomenological perspective]. - -The work explains the meaning of violence in an interpersonal context from a phenomenological perspective. It was conducted a qualitative and exploratory research based on discourse analysis that allowed to understand the meaning of the phenomenon from the perspective of the subject of the study. The data were collected through semi-structured interviews with 20 women who were users of the Primary Health Care Center of Alagoas, who agreed to participate in the study. From the analysis of the discourse it was possible to verify that the family relationships are placed in the context of intersubjective conflict and the intersubjective violence; that the family violence has an impact on the dynamics of the family relationships; that the lived experience of violence at home comprises aspects of collective violence, and of gender violence.Q: - -How do I save data in Firefox via JavaScript? - -I've seen this question asked a bunch of times, and I've searched a lot of answers to no avail. I am trying to save data in Firefox via Javascript, and save data in a cookie. - -Here's my Javascript so far, I have no idea if it's even even close, and I want to make it save a string instead of a number: - -function saveData() - - if (document.getElementById("textfield").value) - - var item = document.getElementById("textfield").value; - - document.getElementById("out").innerHTML = item; - - document.getElementById("save").innerHTML = "Save"; - - - - - -And here's my html: - - - - Untitled 1 4fefd39f24
      -
      -
      -

      diff --git a/spaces/gradio/HuBERT/examples/wav2vec/unsupervised/kaldi_self_train/st/path.sh b/spaces/gradio/HuBERT/examples/wav2vec/unsupervised/kaldi_self_train/st/path.sh deleted file mode 100644 index 1a6fb5f891b55d9fd978cfe54565f112f7eedce7..0000000000000000000000000000000000000000 --- a/spaces/gradio/HuBERT/examples/wav2vec/unsupervised/kaldi_self_train/st/path.sh +++ /dev/null @@ -1,5 +0,0 @@ -export KALDI_ROOT=`pwd`/../../.. -export PATH=$PWD/utils/:$KALDI_ROOT/tools/openfst/bin:$PWD:$PATH -[ ! -f $KALDI_ROOT/tools/config/common_path.sh ] && echo >&2 "The standard file $KALDI_ROOT/tools/config/common_path.sh is not present -> Exit!" && exit 1 -. $KALDI_ROOT/tools/config/common_path.sh -export LC_ALL=C diff --git a/spaces/gradio/main_note_main/README.md b/spaces/gradio/main_note_main/README.md deleted file mode 100644 index 863b80cae687cc8ceec6338db4c7742d2c6711cb..0000000000000000000000000000000000000000 --- a/spaces/gradio/main_note_main/README.md +++ /dev/null @@ -1,12 +0,0 @@ - ---- -title: main_note_main -emoji: 🔥 -colorFrom: indigo -colorTo: indigo -sdk: gradio -sdk_version: 4.1.2 -app_file: run.py -pinned: false -hf_oauth: true ---- diff --git a/spaces/gradio/zip_to_json/README.md b/spaces/gradio/zip_to_json/README.md deleted file mode 100644 index 4894aca01f335da15cca7c44d4b62fb8a02ff830..0000000000000000000000000000000000000000 --- a/spaces/gradio/zip_to_json/README.md +++ /dev/null @@ -1,12 +0,0 @@ - ---- -title: zip_to_json -emoji: 🔥 -colorFrom: indigo -colorTo: indigo -sdk: gradio -sdk_version: 4.1.2 -app_file: run.py -pinned: false -hf_oauth: true ---- diff --git a/spaces/gsaivinay/Llama-2-13B-GGML-UI/components/Chat/ErrorMessageDiv.tsx b/spaces/gsaivinay/Llama-2-13B-GGML-UI/components/Chat/ErrorMessageDiv.tsx deleted file mode 100644 index 11b868f98b4eda7eb215a911f59c4b42951a654c..0000000000000000000000000000000000000000 --- a/spaces/gsaivinay/Llama-2-13B-GGML-UI/components/Chat/ErrorMessageDiv.tsx +++ /dev/null @@ -1,28 +0,0 @@ -import { IconCircleX } from '@tabler/icons-react'; -import { FC } from 'react'; - -import { ErrorMessage } from '@/types/error'; - -interface Props { - error: ErrorMessage; -} - -export const ErrorMessageDiv: FC = ({ error }) => { - return ( -
      -
      - -
      -
      {error.title}
      - {error.messageLines.map((line, index) => ( -
      - {' '} - {line}{' '} -
      - ))} -
      - {error.code ? Code: {error.code} : ''} -
      -
      - ); -}; diff --git a/spaces/guetLzy/Real-ESRGAN-Demo/tests/test_discriminator_arch.py b/spaces/guetLzy/Real-ESRGAN-Demo/tests/test_discriminator_arch.py deleted file mode 100644 index c56a40c7743630aa63b3e99bca8dc1a85949c4c5..0000000000000000000000000000000000000000 --- a/spaces/guetLzy/Real-ESRGAN-Demo/tests/test_discriminator_arch.py +++ /dev/null @@ -1,19 +0,0 @@ -import torch - -from realesrgan.archs.discriminator_arch import UNetDiscriminatorSN - - -def test_unetdiscriminatorsn(): - """Test arch: UNetDiscriminatorSN.""" - - # model init and forward (cpu) - net = UNetDiscriminatorSN(num_in_ch=3, num_feat=4, skip_connection=True) - img = torch.rand((1, 3, 32, 32), dtype=torch.float32) - output = net(img) - assert output.shape == (1, 1, 32, 32) - - # model init and forward (gpu) - if torch.cuda.is_available(): - net.cuda() - output = net(img.cuda()) - assert output.shape == (1, 1, 32, 32) diff --git a/spaces/habash/WizardLM-WizardCoder-15B-V1.0/app.py b/spaces/habash/WizardLM-WizardCoder-15B-V1.0/app.py deleted file mode 100644 index b950a0dc3c9037b8db001411736515bf668d4f57..0000000000000000000000000000000000000000 --- a/spaces/habash/WizardLM-WizardCoder-15B-V1.0/app.py +++ /dev/null @@ -1,3 +0,0 @@ -import gradio as gr - -gr.Interface.load("models/WizardLM/WizardCoder-15B-V1.0").launch() \ No newline at end of file diff --git a/spaces/hamacojr/SAM-CAT-Seg/open_clip/src/training/precision.py b/spaces/hamacojr/SAM-CAT-Seg/open_clip/src/training/precision.py deleted file mode 100644 index a63b92256518d13afd57261df1568e26b1622201..0000000000000000000000000000000000000000 --- a/spaces/hamacojr/SAM-CAT-Seg/open_clip/src/training/precision.py +++ /dev/null @@ -1,12 +0,0 @@ -import torch -from contextlib import suppress - - -def get_autocast(precision): - if precision == 'amp': - return torch.cuda.amp.autocast - elif precision == 'amp_bfloat16' or precision == 'amp_bf16': - # amp_bfloat16 is more stable than amp float16 for clip training - return lambda: torch.cuda.amp.autocast(dtype=torch.bfloat16) - else: - return suppress diff --git a/spaces/hamacojr/SAM-CAT-Seg/open_clip/tests/test_num_shards.py b/spaces/hamacojr/SAM-CAT-Seg/open_clip/tests/test_num_shards.py deleted file mode 100644 index 70ca8feccd6ff5be4b04a5d9da7b47ab99e36fa3..0000000000000000000000000000000000000000 --- a/spaces/hamacojr/SAM-CAT-Seg/open_clip/tests/test_num_shards.py +++ /dev/null @@ -1,20 +0,0 @@ -import pytest - -from training.data import get_dataset_size - -@pytest.mark.parametrize( - "shards,expected_size", - [ - ('/path/to/shard.tar', 1), - ('/path/to/shard_{000..000}.tar', 1), - ('/path/to/shard_{000..009}.tar', 10), - ('/path/to/shard_{000..009}_{000..009}.tar', 100), - ('/path/to/shard.tar::/path/to/other_shard_{000..009}.tar', 11), - ('/path/to/shard_{000..009}.tar::/path/to/other_shard_{000..009}.tar', 20), - (['/path/to/shard.tar'], 1), - (['/path/to/shard.tar', '/path/to/other_shard.tar'], 2), - ] -) -def test_num_shards(shards, expected_size): - _, size = get_dataset_size(shards) - assert size == expected_size, f'Expected {expected_size} for {shards} but found {size} instead.' diff --git a/spaces/haoheliu/AudioLDM_48K_Text-to-HiFiAudio_Generation/share_btn.py b/spaces/haoheliu/AudioLDM_48K_Text-to-HiFiAudio_Generation/share_btn.py deleted file mode 100644 index 86324c585bb934534ad238e4879ec8d7449424f4..0000000000000000000000000000000000000000 --- a/spaces/haoheliu/AudioLDM_48K_Text-to-HiFiAudio_Generation/share_btn.py +++ /dev/null @@ -1,74 +0,0 @@ -community_icon_html = """""" - -loading_icon_html = """""" - -share_js = """async () => { - async function uploadFile(file){ - const UPLOAD_URL = 'https://huggingface.co/uploads'; - const response = await fetch(UPLOAD_URL, { - method: 'POST', - headers: { - 'Content-Type': file.type, - 'X-Requested-With': 'XMLHttpRequest', - }, - body: file, /// <- File inherits from Blob - }); - const url = await response.text(); - return url; - } - async function getInputVideoFile(videoEl){ - const res = await fetch(videoEl.src); - const blob = await res.blob(); - const videoId = Date.now() % 200; - const fileName = `sd-perception-${{videoId}}.mp4`; - return new File([blob], fileName, { type: 'video/mp4' }); - } - - async function audioToBase64(audioFile) { - return new Promise((resolve, reject) => { - let reader = new FileReader(); - reader.readAsDataURL(audioFile); - reader.onload = () => resolve(reader.result); - reader.onerror = error => reject(error); - - }); - } - const gradioEl = document.querySelector("gradio-app").shadowRoot || document.querySelector('body > gradio-app'); - const inputPromptEl = gradioEl.querySelector('#prompt-in input').value; - const outputVideoEl = gradioEl.querySelector('#output-video video'); - - let titleTxt = `Text-to-Audio: ${inputPromptEl}`; - - const shareBtnEl = gradioEl.querySelector('#share-btn'); - const shareIconEl = gradioEl.querySelector('#share-btn-share-icon'); - const loadingIconEl = gradioEl.querySelector('#share-btn-loading-icon'); - if(!outputVideoEl){ - return; - }; - shareBtnEl.style.pointerEvents = 'none'; - shareIconEl.style.display = 'none'; - loadingIconEl.style.removeProperty('display'); - const outputVideo = await getInputVideoFile(outputVideoEl); - const urlOutputVideo = await uploadFile(outputVideo); - - const descriptionMd = ` -##### ${inputPromptEl} - -${urlOutputVideo} -`; - const params = new URLSearchParams({ - title: titleTxt, - description: descriptionMd, - }); - const paramsStr = params.toString(); - window.open(`https://huggingface.co/spaces/haoheliu/AudioLDM_48K_Text-to-HiFiAudio_Generation/discussions/new?${paramsStr}`, '_blank'); - shareBtnEl.style.removeProperty('pointer-events'); - shareIconEl.style.removeProperty('display'); - loadingIconEl.style.display = 'none'; -}""" diff --git a/spaces/hasibzunair/fifa-tryon-demo/Self-Correction-Human-Parsing-for-ACGPN/mhp_extension/detectron2/projects/PointRend/point_rend/__init__.py b/spaces/hasibzunair/fifa-tryon-demo/Self-Correction-Human-Parsing-for-ACGPN/mhp_extension/detectron2/projects/PointRend/point_rend/__init__.py deleted file mode 100644 index 4020fe0a287f87cb3bd2487b5b40b7e1e2647aa8..0000000000000000000000000000000000000000 --- a/spaces/hasibzunair/fifa-tryon-demo/Self-Correction-Human-Parsing-for-ACGPN/mhp_extension/detectron2/projects/PointRend/point_rend/__init__.py +++ /dev/null @@ -1,6 +0,0 @@ -# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved -from .config import add_pointrend_config -from .coarse_mask_head import CoarseMaskHead -from .roi_heads import PointRendROIHeads -from .dataset_mapper import SemSegDatasetMapper -from .semantic_seg import PointRendSemSegHead diff --git a/spaces/hasibzunair/fifa-tryon-demo/data/image_folder.py b/spaces/hasibzunair/fifa-tryon-demo/data/image_folder.py deleted file mode 100644 index 90d58ea2abb19d564cfae0e0685553227bdcab28..0000000000000000000000000000000000000000 --- a/spaces/hasibzunair/fifa-tryon-demo/data/image_folder.py +++ /dev/null @@ -1,76 +0,0 @@ -############################################################################### -import torch.utils.data as data -from PIL import Image -import os - -IMG_EXTENSIONS = [ - '.jpg', '.JPG', '.jpeg', '.JPEG', - '.png', '.PNG', '.ppm', '.PPM', '.bmp', '.BMP', '.tiff' -] - - -def is_image_file(filename): - return any(filename.endswith(extension) for extension in IMG_EXTENSIONS) - - -def make_dataset(dir): - images = [] - assert os.path.isdir(dir), '%s is not a valid directory' % dir - - f = dir.split('/')[-1].split('_')[-1] - print(dir, f) - dirs = os.listdir(dir) - for img in dirs: - - path = os.path.join(dir, img) - # print(path) - images.append(path) - return images - - -def make_dataset_test(dir): - images = [] - assert os.path.isdir(dir), '%s is not a valid directory' % dir - - f = dir.split('/')[-1].split('_')[-1] - names = os.listdir(dir) - for i in range(len([name for name in os.listdir(dir) if os.path.isfile(os.path.join(dir, name))])): - img = names[i] - path = os.path.join(dir, img) - # print(path) - images.append(path) - return images - - -def default_loader(path): - return Image.open(path).convert('RGB') - - -class ImageFolder(data.Dataset): - - def __init__(self, root, transform=None, return_paths=False, - loader=default_loader): - imgs = make_dataset(root) - if len(imgs) == 0: - raise(RuntimeError("Found 0 images in: " + root + "\n" - "Supported image extensions are: " + - ",".join(IMG_EXTENSIONS))) - - self.root = root - self.imgs = imgs - self.transform = transform - self.return_paths = return_paths - self.loader = loader - - def __getitem__(self, index): - path = self.imgs[index] - img = self.loader(path) - if self.transform is not None: - img = self.transform(img) - if self.return_paths: - return img, path - else: - return img - - def __len__(self): - return len(self.imgs) diff --git a/spaces/hhalim/EleutherAI-gpt-j-6B/README.md b/spaces/hhalim/EleutherAI-gpt-j-6B/README.md deleted file mode 100644 index ebcba1b62c5c4a86ac3795bc2eb5f96b10b1b7fd..0000000000000000000000000000000000000000 --- a/spaces/hhalim/EleutherAI-gpt-j-6B/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: EleutherAI Gpt J 6B -emoji: 😻 -colorFrom: indigo -colorTo: gray -sdk: gradio -sdk_version: 3.17.0 -app_file: app.py -pinned: false -license: mit ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/huggingface/Model_Cards_Writing_Tool/lets_combine.md b/spaces/huggingface/Model_Cards_Writing_Tool/lets_combine.md deleted file mode 100644 index 6f744ad1aa0d1541f492b1dccbbdbb9e27fb0554..0000000000000000000000000000000000000000 --- a/spaces/huggingface/Model_Cards_Writing_Tool/lets_combine.md +++ /dev/null @@ -1 +0,0 @@ -'
      Click to expand \n\n# Model Details\n## Model Description\n Provide a longer summary of what this model is. \n- **Developed by:** {{ developers | default("More information needed", true)}}- **Shared by [Optional]:** {{ shared_by | default("More information needed", true)}}- **Model type:** Language model- **Language(s) (NLP):** {{ language | default("More information needed", true)}}- **License:** {{ license | default("More information needed", true)}}- **Related Models:** {{ related_models | default("More information needed", true)}} - **Parent Model:** {{ parent_model | default("More information needed", true)}}- **Resources for more information:** {{ more_resources | default("More information needed", true)}}
      \n# Uses\n Address questions around how the model is intended to be used, including the foreseeable users of the model and those affected by the model. \n## Direct Use\n This section is for the model use without fine-tuning or plugging into a larger ecosystem/app. \n## Downstream Use [Optional]\n This section is for the model use when fine-tuned for a task, or when plugged into a larger ecosystem/app \n## Out-of-Scope Use\n This section addresses misuse, malicious use, and uses that the model will not work well for. ' \ No newline at end of file diff --git a/spaces/hyxue/HiFiFace-inference-demo/arcface_torch/README.md b/spaces/hyxue/HiFiFace-inference-demo/arcface_torch/README.md deleted file mode 100644 index 8d391f63684dd1f47900dc6449a5e22fa25e3da3..0000000000000000000000000000000000000000 --- a/spaces/hyxue/HiFiFace-inference-demo/arcface_torch/README.md +++ /dev/null @@ -1,218 +0,0 @@ -# Distributed Arcface Training in Pytorch - -The "arcface_torch" repository is the official implementation of the ArcFace algorithm. It supports distributed and sparse training with multiple distributed training examples, including several memory-saving techniques such as mixed precision training and gradient checkpointing. It also supports training for ViT models and datasets including WebFace42M and Glint360K, two of the largest open-source datasets. Additionally, the repository comes with a built-in tool for converting to ONNX format, making it easy to submit to MFR evaluation systems. - -[![PWC](https://img.shields.io/endpoint.svg?url=https://paperswithcode.com/badge/killing-two-birds-with-one-stone-efficient/face-verification-on-ijb-c)](https://paperswithcode.com/sota/face-verification-on-ijb-c?p=killing-two-birds-with-one-stone-efficient) -[![PWC](https://img.shields.io/endpoint.svg?url=https://paperswithcode.com/badge/killing-two-birds-with-one-stone-efficient/face-verification-on-ijb-b)](https://paperswithcode.com/sota/face-verification-on-ijb-b?p=killing-two-birds-with-one-stone-efficient) -[![PWC](https://img.shields.io/endpoint.svg?url=https://paperswithcode.com/badge/killing-two-birds-with-one-stone-efficient/face-verification-on-agedb-30)](https://paperswithcode.com/sota/face-verification-on-agedb-30?p=killing-two-birds-with-one-stone-efficient) -[![PWC](https://img.shields.io/endpoint.svg?url=https://paperswithcode.com/badge/killing-two-birds-with-one-stone-efficient/face-verification-on-cfp-fp)](https://paperswithcode.com/sota/face-verification-on-cfp-fp?p=killing-two-birds-with-one-stone-efficient) - -## Requirements - -To avail the latest features of PyTorch, we have upgraded to version 1.12.0. - -- Install [PyTorch](https://pytorch.org/get-started/previous-versions/) (torch>=1.12.0). -- (Optional) Install [DALI](https://docs.nvidia.com/deeplearning/dali/user-guide/docs/), our doc for [install_dali.md](docs/install_dali.md). -- `pip install -r requirement.txt`. - -## How to Training - -To train a model, execute the `train.py` script with the path to the configuration files. The sample commands provided below demonstrate the process of conducting distributed training. - -### 1. To run on one GPU: - -```shell -python train_v2.py configs/ms1mv3_r50_onegpu -``` - -Note: -It is not recommended to use a single GPU for training, as this may result in longer training times and suboptimal performance. For best results, we suggest using multiple GPUs or a GPU cluster. - - -### 2. To run on a machine with 8 GPUs: - -```shell -torchrun --nproc_per_node=8 train.py configs/ms1mv3_r50 -``` - -### 3. To run on 2 machines with 8 GPUs each: - -Node 0: - -```shell -torchrun --nproc_per_node=8 --nnodes=2 --node_rank=0 --master_addr="ip1" --master_port=12581 train.py configs/wf42m_pfc02_16gpus_r100 -``` - -Node 1: - -```shell -torchrun --nproc_per_node=8 --nnodes=2 --node_rank=1 --master_addr="ip1" --master_port=12581 train.py configs/wf42m_pfc02_16gpus_r100 -``` - -### 4. Run ViT-B on a machine with 24k batchsize: - -```shell -torchrun --nproc_per_node=8 train_v2.py configs/wf42m_pfc03_40epoch_8gpu_vit_b -``` - - -## Download Datasets or Prepare Datasets -- [MS1MV2](https://github.com/deepinsight/insightface/tree/master/recognition/_datasets_#ms1m-arcface-85k-ids58m-images-57) (87k IDs, 5.8M images) -- [MS1MV3](https://github.com/deepinsight/insightface/tree/master/recognition/_datasets_#ms1m-retinaface) (93k IDs, 5.2M images) -- [Glint360K](https://github.com/deepinsight/insightface/tree/master/recognition/partial_fc#4-download) (360k IDs, 17.1M images) -- [WebFace42M](docs/prepare_webface42m.md) (2M IDs, 42.5M images) -- [Your Dataset, Click Here!](docs/prepare_custom_dataset.md) - -Note: -If you want to use DALI for data reading, please use the script 'scripts/shuffle_rec.py' to shuffle the InsightFace style rec before using it. -Example: - -`python scripts/shuffle_rec.py ms1m-retinaface-t1` - -You will get the "shuffled_ms1m-retinaface-t1" folder, where the samples in the "train.rec" file are shuffled. - - -## Model Zoo - -- The models are available for non-commercial research purposes only. -- All models can be found in here. -- [Baidu Yun Pan](https://pan.baidu.com/s/1CL-l4zWqsI1oDuEEYVhj-g): e8pw -- [OneDrive](https://1drv.ms/u/s!AswpsDO2toNKq0lWY69vN58GR6mw?e=p9Ov5d) - -### Performance on IJB-C and [**ICCV2021-MFR**](https://github.com/deepinsight/insightface/blob/master/challenges/mfr/README.md) - -ICCV2021-MFR testset consists of non-celebrities so we can ensure that it has very few overlap with public available face -recognition training set, such as MS1M and CASIA as they mostly collected from online celebrities. -As the result, we can evaluate the FAIR performance for different algorithms. - -For **ICCV2021-MFR-ALL** set, TAR is measured on all-to-all 1:1 protocal, with FAR less than 0.000001(e-6). The -globalised multi-racial testset contains 242,143 identities and 1,624,305 images. - - -#### 1. Training on Single-Host GPU - -| Datasets | Backbone | **MFR-ALL** | IJB-C(1E-4) | IJB-C(1E-5) | log | -|:---------------|:--------------------|:------------|:------------|:------------|:------------------------------------------------------------------------------------------------------------------------------------| -| MS1MV2 | mobilefacenet-0.45G | 62.07 | 93.61 | 90.28 | [click me](https://raw.githubusercontent.com/anxiangsir/insightface_arcface_log/master/ms1mv2_mbf/training.log) | -| MS1MV2 | r50 | 75.13 | 95.97 | 94.07 | [click me](https://raw.githubusercontent.com/anxiangsir/insightface_arcface_log/master/ms1mv2_r50/training.log) | -| MS1MV2 | r100 | 78.12 | 96.37 | 94.27 | [click me](https://raw.githubusercontent.com/anxiangsir/insightface_arcface_log/master/ms1mv2_r100/training.log) | -| MS1MV3 | mobilefacenet-0.45G | 63.78 | 94.23 | 91.33 | [click me](https://raw.githubusercontent.com/anxiangsir/insightface_arcface_log/master/ms1mv3_mbf/training.log) | -| MS1MV3 | r50 | 79.14 | 96.37 | 94.47 | [click me](https://raw.githubusercontent.com/anxiangsir/insightface_arcface_log/master/ms1mv3_r50/training.log) | -| MS1MV3 | r100 | 81.97 | 96.85 | 95.02 | [click me](https://raw.githubusercontent.com/anxiangsir/insightface_arcface_log/master/ms1mv3_r100/training.log) | -| Glint360K | mobilefacenet-0.45G | 70.18 | 95.04 | 92.62 | [click me](https://raw.githubusercontent.com/anxiangsir/insightface_arcface_log/master/glint360k_mbf/training.log) | -| Glint360K | r50 | 86.34 | 97.16 | 95.81 | [click me](https://raw.githubusercontent.com/anxiangsir/insightface_arcface_log/master/glint360k_r50/training.log) | -| Glint360k | r100 | 89.52 | 97.55 | 96.38 | [click me](https://raw.githubusercontent.com/anxiangsir/insightface_arcface_log/master/glint360k_r100/training.log) | -| WF4M | r100 | 89.87 | 97.19 | 95.48 | [click me](https://raw.githubusercontent.com/anxiangsir/insightface_arcface_log/master/wf4m_r100/training.log) | -| WF12M-PFC-0.2 | r100 | 94.75 | 97.60 | 95.90 | [click me](https://raw.githubusercontent.com/anxiangsir/insightface_arcface_log/master/wf12m_pfc02_r100/training.log) | -| WF12M-PFC-0.3 | r100 | 94.71 | 97.64 | 96.01 | [click me](https://raw.githubusercontent.com/anxiangsir/insightface_arcface_log/master/wf12m_pfc03_r100/training.log) | -| WF12M | r100 | 94.69 | 97.59 | 95.97 | [click me](https://raw.githubusercontent.com/anxiangsir/insightface_arcface_log/master/wf12m_r100/training.log) | -| WF42M-PFC-0.2 | r100 | 96.27 | 97.70 | 96.31 | [click me](https://raw.githubusercontent.com/anxiangsir/insightface_arcface_log/master/wf42m_pfc02_r100/training.log) | -| WF42M-PFC-0.2 | ViT-T-1.5G | 92.04 | 97.27 | 95.68 | [click me](https://raw.githubusercontent.com/anxiangsir/insightface_arcface_log/master/wf42m_pfc02_40epoch_8gpu_vit_t/training.log) | -| WF42M-PFC-0.3 | ViT-B-11G | 97.16 | 97.91 | 97.05 | [click me](https://raw.githubusercontent.com/anxiangsir/insightface_arcface_log/master/pfc03_wf42m_vit_b_8gpu/training.log) | - -#### 2. Training on Multi-Host GPU - -| Datasets | Backbone(bs*gpus) | **MFR-ALL** | IJB-C(1E-4) | IJB-C(1E-5) | Throughout | log | -|:-----------------|:------------------|:------------|:------------|:------------|:-----------|:-------------------------------------------------------------------------------------------------------------------------------------------| -| WF42M-PFC-0.2 | r50(512*8) | 93.83 | 97.53 | 96.16 | ~5900 | [click me](https://raw.githubusercontent.com/anxiangsir/insightface_arcface_log/master/webface42m_r50_bs4k_pfc02/training.log) | -| WF42M-PFC-0.2 | r50(512*16) | 93.96 | 97.46 | 96.12 | ~11000 | [click me](https://raw.githubusercontent.com/anxiangsir/insightface_arcface_log/master/webface42m_r50_lr01_pfc02_bs8k_16gpus/training.log) | -| WF42M-PFC-0.2 | r50(128*32) | 94.04 | 97.48 | 95.94 | ~17000 | click me | -| WF42M-PFC-0.2 | r100(128*16) | 96.28 | 97.80 | 96.57 | ~5200 | click me | -| WF42M-PFC-0.2 | r100(256*16) | 96.69 | 97.85 | 96.63 | ~5200 | [click me](https://raw.githubusercontent.com/anxiangsir/insightface_arcface_log/master/webface42m_r100_bs4k_pfc02/training.log) | -| WF42M-PFC-0.0018 | r100(512*32) | 93.08 | 97.51 | 95.88 | ~10000 | click me | -| WF42M-PFC-0.2 | r100(128*32) | 96.57 | 97.83 | 96.50 | ~9800 | click me | - -`r100(128*32)` means backbone is r100, batchsize per gpu is 128, the number of gpus is 32. - - - -#### 3. ViT For Face Recognition - -| Datasets | Backbone(bs) | FLOPs | **MFR-ALL** | IJB-C(1E-4) | IJB-C(1E-5) | Throughout | log | -|:--------------|:--------------|:------|:------------|:------------|:------------|:-----------|:-----------------------------------------------------------------------------------------------------------------------------| -| WF42M-PFC-0.3 | r18(128*32) | 2.6 | 79.13 | 95.77 | 93.36 | - | click me | -| WF42M-PFC-0.3 | r50(128*32) | 6.3 | 94.03 | 97.48 | 95.94 | - | click me | -| WF42M-PFC-0.3 | r100(128*32) | 12.1 | 96.69 | 97.82 | 96.45 | - | click me | -| WF42M-PFC-0.3 | r200(128*32) | 23.5 | 97.70 | 97.97 | 96.93 | - | click me | -| WF42M-PFC-0.3 | VIT-T(384*64) | 1.5 | 92.24 | 97.31 | 95.97 | ~35000 | click me | -| WF42M-PFC-0.3 | VIT-S(384*64) | 5.7 | 95.87 | 97.73 | 96.57 | ~25000 | [click me](https://raw.githubusercontent.com/anxiangsir/insightface_arcface_log/master/pfc03_wf42m_vit_s_64gpu/training.log) | -| WF42M-PFC-0.3 | VIT-B(384*64) | 11.4 | 97.42 | 97.90 | 97.04 | ~13800 | [click me](https://raw.githubusercontent.com/anxiangsir/insightface_arcface_log/master/pfc03_wf42m_vit_b_64gpu/training.log) | -| WF42M-PFC-0.3 | VIT-L(384*64) | 25.3 | 97.85 | 98.00 | 97.23 | ~9406 | [click me](https://raw.githubusercontent.com/anxiangsir/insightface_arcface_log/master/pfc03_wf42m_vit_l_64gpu/training.log) | - -`WF42M` means WebFace42M, `PFC-0.3` means negivate class centers sample rate is 0.3. - -#### 4. Noisy Datasets - -| Datasets | Backbone | **MFR-ALL** | IJB-C(1E-4) | IJB-C(1E-5) | log | -|:-------------------------|:---------|:------------|:------------|:------------|:---------| -| WF12M-Flip(40%) | r50 | 43.87 | 88.35 | 80.78 | click me | -| WF12M-Flip(40%)-PFC-0.1* | r50 | 80.20 | 96.11 | 93.79 | click me | -| WF12M-Conflict | r50 | 79.93 | 95.30 | 91.56 | click me | -| WF12M-Conflict-PFC-0.3* | r50 | 91.68 | 97.28 | 95.75 | click me | - -`WF12M` means WebFace12M, `+PFC-0.1*` denotes additional abnormal inter-class filtering. - - - -## Speed Benchmark -
      - - -**Arcface-Torch** is an efficient tool for training large-scale face recognition training sets. When the number of classes in the training sets exceeds one million, the partial FC sampling strategy maintains the same accuracy while providing several times faster training performance and lower GPU memory utilization. The partial FC is a sparse variant of the model parallel architecture for large-scale face recognition, utilizing a sparse softmax that dynamically samples a subset of class centers for each training batch. During each iteration, only a sparse portion of the parameters are updated, leading to a significant reduction in GPU memory requirements and computational demands. With the partial FC approach, it is possible to train sets with up to 29 million identities, the largest to date. Furthermore, the partial FC method supports multi-machine distributed training and mixed precision training. - - - -More details see -[speed_benchmark.md](docs/speed_benchmark.md) in docs. - -> 1. Training Speed of Various Parallel Techniques (Samples per Second) on a Tesla V100 32GB x 8 System (Higher is Optimal) - -`-` means training failed because of gpu memory limitations. - -| Number of Identities in Dataset | Data Parallel | Model Parallel | Partial FC 0.1 | -|:--------------------------------|:--------------|:---------------|:---------------| -| 125000 | 4681 | 4824 | 5004 | -| 1400000 | **1672** | 3043 | 4738 | -| 5500000 | **-** | **1389** | 3975 | -| 8000000 | **-** | **-** | 3565 | -| 16000000 | **-** | **-** | 2679 | -| 29000000 | **-** | **-** | **1855** | - -> 2. GPU Memory Utilization of Various Parallel Techniques (MB per GPU) on a Tesla V100 32GB x 8 System (Lower is Optimal) - -| Number of Identities in Dataset | Data Parallel | Model Parallel | Partial FC 0.1 | -|:--------------------------------|:--------------|:---------------|:---------------| -| 125000 | 7358 | 5306 | 4868 | -| 1400000 | 32252 | 11178 | 6056 | -| 5500000 | **-** | 32188 | 9854 | -| 8000000 | **-** | **-** | 12310 | -| 16000000 | **-** | **-** | 19950 | -| 29000000 | **-** | **-** | 32324 | - - -## Citations - -``` -@inproceedings{deng2019arcface, - title={Arcface: Additive angular margin loss for deep face recognition}, - author={Deng, Jiankang and Guo, Jia and Xue, Niannan and Zafeiriou, Stefanos}, - booktitle={Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition}, - pages={4690--4699}, - year={2019} -} -@inproceedings{An_2022_CVPR, - author={An, Xiang and Deng, Jiankang and Guo, Jia and Feng, Ziyong and Zhu, XuHan and Yang, Jing and Liu, Tongliang}, - title={Killing Two Birds With One Stone: Efficient and Robust Training of Face Recognition CNNs by Partial FC}, - booktitle={Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR)}, - month={June}, - year={2022}, - pages={4042-4051} -} -@inproceedings{zhu2021webface260m, - title={Webface260m: A benchmark unveiling the power of million-scale deep face recognition}, - author={Zhu, Zheng and Huang, Guan and Deng, Jiankang and Ye, Yun and Huang, Junjie and Chen, Xinze and Zhu, Jiagang and Yang, Tian and Lu, Jiwen and Du, Dalong and Zhou, Jie}, - booktitle={Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition}, - pages={10492--10502}, - year={2021} -} -``` diff --git a/spaces/inamXcontru/PoeticTTS/Descarga gratis Sonido de Valencia 1990 al 1999 El sonido que marc una generacin.md b/spaces/inamXcontru/PoeticTTS/Descarga gratis Sonido de Valencia 1990 al 1999 El sonido que marc una generacin.md deleted file mode 100644 index 2239bfd099ff5f79ce07eb453fc379a2091196df..0000000000000000000000000000000000000000 --- a/spaces/inamXcontru/PoeticTTS/Descarga gratis Sonido de Valencia 1990 al 1999 El sonido que marc una generacin.md +++ /dev/null @@ -1,6 +0,0 @@ -
      -

      Related Tags: Guitar Spell, Guitar Spell song, Guitar Spell MP3 song, Guitar Spell MP3, download Guitar Spell song, Guitar Spell song, Sonido De Valencia 1990-1999 Guitar Spell song, Guitar Spell song by DJ Sylvan, Guitar Spell song download, download Guitar Spell MP3 song

      -

      sonido de valencia 1990 al 1999 descargar


      Download ✫✫✫ https://gohhs.com/2uz30b



      -

      ALONSO TAPIA, J.; Carriedo, N. y Mateos, M. (1992). Evaluación de la supervisión y regulación de la comprensión. La batería SURCO. Madrid. MEC-CIDE. [ Links ] ALONSO TAPIA, J. Y CARRIEDO, N. (1996). Problemas de comprensión lectora: evaluación e intervención. En C. Monereo e I. Solé (Coords.), El asesoramiento psicopedagógico: una perspectiva profesional y constructivista. Madrid: Alianza Psicología. [ Links ] AUSUBEL, D. P.; Novack, J. D. y Hanesian, H. (1978). Educational Psychology, New York. Traducción castellana: Psicología Educativa México: Trillas. (1983). [ Links ] BORKOWSKI, J., Weyhing, R. S. y Carr, L. A. (1998). Effects of attributional retraining on strategy-based reading comprehension inlearning disabled students. Journal of Educational Psychology, 80, 46-53. [ Links ] CABANACH, R. Y VALLE, A. (1998). Características afectivomotivacionales de los estudiantes con dificultades de aprendizaje. En V. Santiuste y J. Beltrán (coord..), Dificultades de Aprendizaje. Madrid: Síntesis. [ Links ] CUETOS, F. (1993). Psicología de la lectura. Madrid: Escuela Española. [ Links ]CUETOS, F., Rodríguez, B. y Ruano, E. (1996). PROLEC. Procesos Lectores. Madrid: TEA. [ Links ] CUETOS, F., Rodríguez, B. y Ruano, E. (2001). PROLEC.- SE Procesos Lectores. Madrid: TEA. [ Links ] CSIKSZENTMIHALYI, M. (2003). Fluir. Barcelona: Kairós. [ Links ] DE VEGA, M., Carreiras, M., Gutierrez-Calvo, Alonso- Quecuty, Mª. L. (1990). Lectura y comprensión. Una perspectiva cognitiva. Madrid: Alianza. [ Links ] GARCÍA MADRUGA, J. A., Martín, A., Luque, L. y Santamaría, C. (1995). Comprensión y adquisición de conocimientos a partir de textos. Madrid: Siglo XXI. [ Links ] GARCÍA MADRUGA, J. A., Elosúa, M. R., Gutiérrez, F., Luque, J. L. y Gárate, M. (1999). Comprensión lectora y memoria operativa. Aspectos evolutivos e instruccionales. Barcelona: Paidós. [ Links ] GARCÍA VIDAL, J. YMANJÓN, D. G. (2000). Dificultades de aprendizaje e intervención psicopedagógica. Madrid: EOS. [ Links ] GONZÁLEZ, A. (2004). Estrategias de comprensión lectora. Madrid: Síntesis. [ Links ] GONZÁLEZ-PIENDA, J.A. Y NÚÑEZ, J.C. (Coord.) (1998). Dificultades del aprendizaje escolar. Madrid: Pirámide. [ Links ] KIRK, S. Y GALLAGHER, J. (1986). Educating Exceptional Children. Boston M.A.: Hougton Miflin Co. [ Links ] MARTÍN, E. (1999). Metacognición y estrategias de aprendizaje. En Pozo, J. I. y C. Monereo (Coords.) El aprendizaje estratégico, pp: 111-122. Madrid: Santillana. [ Links ] MARTÍN, E. (1999). Estrategias de aprendizaje y asesoramiento psicopedagógico. En Pozo, J. I. y C. Monereo (Coords.). El aprendizaje estratégico, pp: 339-356. Madrid: Santillana. [ Links ] MARTÍN, E. (1999). Enseñar a pensar a través del currículo. En Coll, C.; A. Marchesi, y J. Palacios (Comps.), Desarrollo psicológico y educación. Trastornos del desarrollo y necesidades educativas especiales, pp: 439-467. Madrid: Alianza. [ Links ] MARTÍN, E. (2002). CCL. Instrumento de medida de la competencia para la comprensión lectora. Madrid: CEPE. [ Links ] MCKOON, G. Y RATCLIFF, R. (1998). Memory-based language processing: psycholinguístic research in the 1990s. Annual Review of Psychology, 49, 25-42. [ Links ] MERCER, C. D. (1991a). Dificultades de Aprendizaje 1. Barcelona: CEAC. [ Links ] MERCER, C. D. (1991b). Dificultades de Aprendizaje. Trastornos específicos y tratamiento. Barcelona: CEAC. [ Links ] MEYER, B. J. F. (1984). Text dimensions and cognitive processing. En H. Mandl; N. L. Stein y T. Trabasso (Eds.). Learning and comprehension of texts. Hillsdale. N.J: LEA. [ Links ] MIRANDA, A. (1987). Introducción a las dificultades de aprendizaje. Valencia. Promolibro (Nuev. Ed. 1996). [ Links ] MIRANDA, A. (1988). Dificultades en el aprendizaje de la lectura, escritura y cálculo. Valencia: Promolibro. [ Links ] MIRANDA, A., Arlandis, P. y Soriano, M. (1997). Instrucción en estrategias y entrenamiento atribucional: efectos sobre la resolución de problemas y el autoconcepto de los estudiantes con dificultades de aprendizaje. Infancia y Aprendizaje, 80, 37-52. [ Links ] MIRANDA, A., García, R. y Jara, P. (2001). Acceso al léxico y comprensión lectora en los distintos subtipos de niños con trastornos por déficit de atención con hiperactividad. Revista de Neurología Clínica, 2 (1), 125. [ Links ]MIRANDA, A. Y PRESENTACIÓN,Mª J. (1997). Intervención psicoeducativa con los alumnos inatentos, impulsivos e hiperactivos y dificultades de aprendizaje, en J.N. García (dir.), Instrucción, Aprendizaje y Dificultades, pp: 317-352. Barcelona: LUB. [ Links ] MIRANDA CASAS, A.; Vidal-Abarca Gámez, E.; Soriano Ferrer, M. (2000). Evaluación e intervención psicoeducativa en dificultades de aprendizaje. Madrid: Pirámide. [ Links ] MORAIS, J. (1994). L´art de lire. Paris: Odile Jacobs. [ Links ] MOUSTY, PH Y COLS. (1985). Los respectivos roles de las manos en la lectura Braille. Paris: Prensa Universitaria de Francia. [ Links ] NOLAN, C. Y. Y KEDERIS, J. C. (1969). Perceptual factors in braille word recognition. American foundation for the blind. Research series, nº 20. [ Links ] OCHAÍTA, E. Y ROSA, A. (1988). Lectura braille y procesamiento de la información táctil. Madrid: INSERSO. [ Links ] ONCE (2005). Lectura y escritura Braille. Documentación interna. Madrid. [ Links ] ORTON, S. T. (1937): Reading, wrinting and speech problems in children. New York: Norton. [ Links ] ORTONY, A., Clore, G.L. y Collins, A. (1996). The cognitive structure of emotions. Nueva York: Cambridge University Press. (Traducción en castellano en Siglo XXI. Madrid) (1998). [ Links ] PARKER, J. D., Summerfeldt, L. J., Hogan, M. J. y Msjestki, S. A. (2004). Emotional intelligence in academic perfomance and deviant behavior at school. Personality and individual differences, 36, (2), 277-293. [ Links ] RUMELHART, D. E. (1981). Schemata: the buildong bocks of cognition. En R. Spiro. B. Bruce y W. Brewer (Eds.). Theoretical issues in reading comprehension. Hillsdale. NJ: Erlbaum. [ Links ] RUMELHART, D. Y MCCLELLAND, J. L. (1982). An interactive activation modelo of context effects in letter perception. Psychological Review, 89, p. 60-95. [ Links ] RUMELHART, D. E. Y ORTONY, D. A. (1977). The representation of know ledge in memory. En A. C. Anderson, R. J. Spiro y W. E. Montague (Eds.). Schooling and the acquisition of knowledge. Hillsdale, NJ: Erlbaum. Traducción castellana de E. Rubí y S. Tarrat en Infancia y Aprendizaje, 1982, 19/29, 115-158. [ Links ] RUMELHART, D. E. Y NORMAN, D. A. (1978). "Accretion, tunning and restructuring; three modes of learning." en J. W. Cotton - R. Klatzky (eds.): Semantics factors in cognition. Hillsdale, NJ: LEA. [ Links ] SALOVEY, P, MAYER, J. D. Y CARUSO, D. (2002). The positive psychology of emotional intelligence. C.R. Snyder y S. J. Lopez (Eds.), The handbook of positive psycchology, pp. 159- 171. New York: Oxford University Press. [ Links ] SMITH, C. A. Y LAZARUS, R.S. (1993). Appraisal components, core relational themes, and the emotions. Cognition and Emotion, 7, 233-269. [ Links ] SOLÉ, I. (1994). Estrategias de Lectura. Barcelona: Graó. [ Links ] VALLÉS, A. (1993). Taller de Comprensión Lectora, 2 vols. Valencia: Promolibro. [ Links ] VALLÉS, A. (1994). Técnicas de velocidad y comprensión lectoras. Madrid: Escuela Española. [ Links ] VALLÉS, A. Y VALLÉS C. (1996). Comprensión Lectora 1 y 2. Programa cognitivo y metacognitivo para la comprensión de textos escritos. Madrid: Escuela Española. [ Links ] VALLÉS, A. (1998). PROESMETA. Programa de estrategias metacognitivas para el aprendizaje. Valencia: Promolibro. [ Links ] VALLÉS, A. (1998). Dificultades de aprendizaje e intervención psicopedagógica. Valencia: Promolibro. [ Links ] VALLÉS, A. (2000). Necesidades educativas de los alumnos ciegos y deficientes visuales. En VV.AA. Aspectos evolutivos y educativos de la ceguera y deficiencia visual. Vol. I.Madrid: ONCE. [ Links ] VALLÉS, A. Y VALLÉS, C. (2005). Comprensión Lectora y Estudio. Intervención psicopedagógica. Valencia: Promolibrio. [ Links ] WALLSTEN, T. H. Y LAMBERT, R. M. (1981). Visual braille and print reading as a function of display field size, Boletín de la sociedad de Psiconomía, 17. [ Links ]

      aaccfb2cb3
      -
      -
      \ No newline at end of file diff --git a/spaces/inplisQlawa/anything-midjourney-v4-1/Adobe Acrobat 7.0 Professional Authorization Code Keygen !!HOT!!l.md b/spaces/inplisQlawa/anything-midjourney-v4-1/Adobe Acrobat 7.0 Professional Authorization Code Keygen !!HOT!!l.md deleted file mode 100644 index f40ba5aeef2364163590d9a98e9390812f28bc89..0000000000000000000000000000000000000000 --- a/spaces/inplisQlawa/anything-midjourney-v4-1/Adobe Acrobat 7.0 Professional Authorization Code Keygen !!HOT!!l.md +++ /dev/null @@ -1,76 +0,0 @@ -

      Adobe Acrobat 7.0 Professional Authorization Code Keygenl


      DOWNLOAD ✶✶✶ https://urlin.us/2uEwb3



      -
      -env file on the server with the key and secret. - -Credentials check is success. - -A: - -Open the terminal and install: - -sudo apt-get install git - -then follow this link - -import Component from '@angular/core'; - -@Component( - - selector: 'app-root', - - templateUrl: './app.component.html', - - styleUrls: ['./app.component.css'] - -) - -export class AppComponent - - title = 'CRUD-App'; - - gridColumns = [ - - - - title: 'Name', - - field: 'name' - - , - - title: 'Age', - - field: 'age' - - title: 'Birthdate', - - field: 'birthdate' - - title: 'Height', - - field: 'height' - - title: 'Weight', - - field: 'weight' - - title: 'Sport', - - field:'sport' - - title: 'FavoriteColor', - - field: 'favoriteColor' - - - - ]; - -} - -[Relationship between changes in cardiac function and myocardial metabolism and adenine nucleotides in heart failure]. - -In order to explore the possible mechanism for the impaired cardiac function and hemodynamics in the patients with chronic heart failure (CHF), this study was performed to study the changes of cardiac function and adenine nucleotides of myocardium in rats with CHF induced by aorto-caval fistula (ACF). The results showed that myocardial energy metabolism and adenine nucleotides were significantly impaired in rats with CHF. These changes were correlated with the severity of cardiac dysfunction.Evaluation of clinical examinations 4fefd39f24
      -
      -
      -

      diff --git a/spaces/inplisQlawa/anything-midjourney-v4-1/Alibaba Aur 41 Chor Movie Video Song Free Download __LINK__.md b/spaces/inplisQlawa/anything-midjourney-v4-1/Alibaba Aur 41 Chor Movie Video Song Free Download __LINK__.md deleted file mode 100644 index ab54071d51f75cf50a1ab04c888288c4234043b6..0000000000000000000000000000000000000000 --- a/spaces/inplisQlawa/anything-midjourney-v4-1/Alibaba Aur 41 Chor Movie Video Song Free Download __LINK__.md +++ /dev/null @@ -1,6 +0,0 @@ -

      Alibaba Aur 41 Chor Movie Video Song Free Download


      Downloadhttps://urlin.us/2uEysM



      - -8 cm) 1095 carbon steel clip. ftypisom isomiso2avc1mp41 † moovlmvhd è Y ... Saaf safai ki kami se bhi infection aur bukhar ka khatra hota hai. ... 30 Saal hai 1 saal se Dr. 3,871 ka bar products are offered for sale by suppliers on Alibaba. ... Tham Ke Baras Male MP3 Song by Kumar Sanu from the movie Pyar Ka Bukhar ... 4d29de3e1b
      -
      -
      -

      diff --git a/spaces/inplisQlawa/anything-midjourney-v4-1/CAREUEYES 1.1.24.3 NEW! Cracked Portable Key.md b/spaces/inplisQlawa/anything-midjourney-v4-1/CAREUEYES 1.1.24.3 NEW! Cracked Portable Key.md deleted file mode 100644 index cf2ecbd62f36a356f33d5b936df77ce92710b3ae..0000000000000000000000000000000000000000 --- a/spaces/inplisQlawa/anything-midjourney-v4-1/CAREUEYES 1.1.24.3 NEW! Cracked Portable Key.md +++ /dev/null @@ -1,6 +0,0 @@ -

      CAREUEYES 1.1.24.3 Cracked Portable Key


      DOWNLOADhttps://urlin.us/2uEvC0



      - -Ummy Video Downloader 1.10.10.3 Crack Full License Key 2020 [Latest] Ummy Video ... v2.2; Download TeamViewer Portable 14.0.13488.0; Download CSI DETAILING V3.1; ... CareUEyes 1.1.24.3 Crack Latest Version Full Free Download. 1fdad05405
      -
      -
      -

      diff --git a/spaces/inplisQlawa/anything-midjourney-v4-1/DeadSpaceHighlyCompressedonly350MB.md b/spaces/inplisQlawa/anything-midjourney-v4-1/DeadSpaceHighlyCompressedonly350MB.md deleted file mode 100644 index 658faf79792287704bbc9a5c3ec55261413111fc..0000000000000000000000000000000000000000 --- a/spaces/inplisQlawa/anything-midjourney-v4-1/DeadSpaceHighlyCompressedonly350MB.md +++ /dev/null @@ -1,34 +0,0 @@ -

      DeadSpaceHighlyCompressedonly350MB


      DOWNLOAD >> https://urlin.us/2uEyhe



      - -‎Dead Space 2 HD.e‎Dead Space: Ep.‎Dead Space: Infestation ‎Dead Space: Extraction.‎Dead Space: Retribution. - -Play full with title Dead Space 5 full and free movie streaming in best quality. Play full with title Dead Space 5 free an fun at here. Right now, you could see that hundreds a large number of people looking for free Dead Space 5 movie and watch it on their sweat residence with internet connection. Always be happy, you can easily reach tens of thousands of happy members whom became sick and tired of waiting for dvds in the mail, and now you can watch at no cost Dead Space 5. You will get new online movie, and acquire it free of charge in our own site. It really is fast, easy, free and furthermore to look at. Enjoy now Dead Space 5 on-line movie with out downloading. You can view online movie streaming with HD top quality in 92 Min length. Observe trailer movie and as well full movie of Dead Space 5 go through the button below to look at these film.Zygomaxillaris - -Zygomaxillaris is a genus of leaf beetles in the subfamily Eumolpinae. It is known from the Afrotropical and Oriental regions. - -Description - -Species of Zygomaxillaris are mostly black or very dark brown in color. The head is almost always white, while the pronotum has a yellowish shine. - -References - -Category:Eumolpinae - -Category:Chrysomelidae genera - -Category:Beetles of Africa - -Category:Taxa named by Édouard MénétriesJames D. M. Baxter - -James D. M. Baxter (born 1962) is a British computer scientist who studies Algorithms and data structures. He is a Professor of Computer Science and Mathematics at the University of Oxford. He is currently also a Fellow of All Souls College, Oxford. - -Education - -Baxter completed an MA in Mathematics and Computer Science at Trinity College, Oxford. He obtained his PhD in Mathematics at the University of Oxford under the supervision of Oded Goldreich and Mark Noy in 1996. - -Research - -Baxter's early work is in algorithmic game theory, specifically on network congestion games. He also works on permutation groups, operator algebras and properties of matrix spaces. He has made significant contributions to the design and analysis 4fefd39f24
      -
      -
      -

      diff --git a/spaces/inplisQlawa/anything-midjourney-v4-1/Nagios Xi Crack Torrent ((INSTALL)).md b/spaces/inplisQlawa/anything-midjourney-v4-1/Nagios Xi Crack Torrent ((INSTALL)).md deleted file mode 100644 index 9d72766780d67cce2da8b9eae5240d0fde4df856..0000000000000000000000000000000000000000 --- a/spaces/inplisQlawa/anything-midjourney-v4-1/Nagios Xi Crack Torrent ((INSTALL)).md +++ /dev/null @@ -1,6 +0,0 @@ -

      nagios xi crack torrent


      Download File ··· https://urlin.us/2uEypo



      - -Serial Key Generator is a program that helps developers generate serial numbers for applications. You can generate serial keys using a specified number of columns ... Read more "Serial Key Generator is a program that helps developers generate serial numbers for applications. You can generate serial keys using a specified number of key columns. The generated keys can be exported and imported into another application. You can also generate keys for applications written in Java. Serial Key is a free program that offers everything you would expect from a good key generator and is ad-free. 8a78ff9644
      -
      -
      -

      diff --git a/spaces/inreVtussa/clothingai/Examples/(SDDM909) SOD.md b/spaces/inreVtussa/clothingai/Examples/(SDDM909) SOD.md deleted file mode 100644 index 8b35a3bf4c8ad2bec4e809c626a0e17fda77728a..0000000000000000000000000000000000000000 --- a/spaces/inreVtussa/clothingai/Examples/(SDDM909) SOD.md +++ /dev/null @@ -1,6 +0,0 @@ -

      (SDDM909) SOD


      DOWNLOADhttps://tiurll.com/2uCkwJ



      - -[SDDM-909] 極エロダンス×騎乗位ファック; 素人. 系列作:. 番號:SDDM-909. SOD · 辣妹,舞蹈,企劃,騎乘位; 2006/7/6. 107394 0 0. Video Player is loading. 4d29de3e1b
      -
      -
      -

      diff --git a/spaces/inreVtussa/clothingai/Examples/Advanced Pdf Password Recovery 1.31 Download BEST.md b/spaces/inreVtussa/clothingai/Examples/Advanced Pdf Password Recovery 1.31 Download BEST.md deleted file mode 100644 index b93867751fc07346f16b8c984d8970d800377971..0000000000000000000000000000000000000000 --- a/spaces/inreVtussa/clothingai/Examples/Advanced Pdf Password Recovery 1.31 Download BEST.md +++ /dev/null @@ -1,140 +0,0 @@ -
      -

      How to Download and Use Advanced PDF Password Recovery 1.31

      - -

      If you have ever encountered a PDF file that is password-protected and you don't know the password, you might have felt frustrated and helpless. Maybe you need to access some important information, edit or print the document, or copy some text or images from it. But without the password, you are locked out of the PDF file and can't do anything with it.

      -

      Advanced Pdf Password Recovery 1.31 Download


      Download Zip ✫✫✫ https://tiurll.com/2uCjLb



      - -

      Fortunately, there is a solution for this problem: Advanced PDF Password Recovery 1.31. This is a powerful software that can help you unlock any PDF file, regardless of the encryption type or the password complexity. In this article, we will show you how to download and use this software to recover or remove passwords from PDF files quickly and efficiently.

      - -

      What is Advanced PDF Password Recovery 1.31?

      - -

      Advanced PDF Password Recovery 1.31 is a program that enables you to get access to password-protected PDF files created with all versions of Adobe Acrobat or any other PDF application. It can recover or instantly remove passwords that protect or lock PDF documents, allowing you to open, view, edit, print and copy them without any restrictions.

      - -

      The program supports various encryption types and password recovery methods, such as:

      - -
        -
      • 40-bit RC4 encryption
      • -
      • 128-bit RC4 encryption
      • -
      • 128-bit AES encryption
      • -
      • 256-bit AES encryption
      • -
      • Thunder Tables® technology (patented)
      • -
      • Dictionary attack
      • -
      • Brute force attack
      • -
      • Mask attack
      • -
      • Key search attack
      • -
      - -

      The program can also handle PDF files that have printing, copying and editing restrictions, as well as PDF files that have user passwords (passwords to open) and owner passwords (passwords to change permissions).

      - -

      How to Download Advanced PDF Password Recovery 1.31?

      - -

      If you want to download Advanced PDF Password Recovery 1.31, you can follow these simple steps:

      - -
        -
      1. Go to the official website of Elcomsoft Co.Ltd., the developer of the software: https://www.elcomsoft.com/apdfpr.html
      2. -
      3. Choose the edition of the software that suits your needs: Standard Edition ($49), Professional Edition ($99) or Enterprise Edition ($399). You can also download a free trial version that has some limitations.
      4. -
      5. Click on the "Buy now" or "Download free trial version" button and follow the instructions to complete the purchase or registration process.
      6. -
      7. After you receive the confirmation email with the download link and the license key, click on the link and save the setup file (apdfpr_setup_en.msi) on your computer.
      8. -
      9. Run the setup file and follow the installation wizard to install the software on your computer.
      10. -
      - -

      How to Use Advanced PDF Password Recovery 1.31?

      - -

      If you want to use Advanced PDF Password Recovery 1.31, you can follow these simple steps:

      -

      - -
        -
      1. Launch the software and select the PDF file that you want to unlock by clicking on the "Open" button or dragging and dropping it into the program window.
      2. -
      3. Select the type of attack that you want to use to recover or remove the password from the PDF file. You can choose from four options: Thunder Tables®, Dictionary Attack, Brute Force Attack or Key Search Attack.
      4. -
      5. If you choose Thunder Tables®, you will need to download a precomputed hash table file (apdfpr.ttb) from the website and place it in the same folder as the program. This option can break 40-bit encryption in under a minute.
      6. -
      7. If you choose Dictionary Attack, Brute Force Attack or Key Search Attack, you will need to configure some settings for each option, such as specifying a dictionary file, a mask pattern, a character set, a password length range, etc.
      8. -
      9. Click on the "Start" button and wait for the program to find or remove the password from the PDF file. Depending on the encryption type and password complexity, this process may take from a few seconds to several hours or days.
      10. -
      11. When the program finishes its work, it will display a message with the password (if found) or inform you that the password has been removed (if not found). You can then open, view, edit, print and copy the unlocked PDF file without any restrictions.
      12. -
      - -

      Conclusion

      - -

      Advanced PDF Password Recovery 1.31 is a great software that can help you unlock any PDF file, regardless of the encryption type or password complexity. It can recover or instantly remove passwords that protect or lock PDF documents, allowing you to open, view, edit, print and copy them without any restrictions.

      - -

      If you want to download and use this software, you can visit the official website of Elcomsoft Co.Ltd., choose the edition of the software that suits your needs, purchase or register for a free trial version, download and install the software on your computer, select

      -

      Why Choose Advanced PDF Password Recovery 1.31?

      - -

      There are many reasons why you should choose Advanced PDF Password Recovery 1.31 over other similar software. Here are some of them:

      - -
        -
      • It is fast and reliable. It can unlock any PDF file in a matter of seconds or minutes, depending on the encryption type and password complexity. It can also handle large and complex PDF files without any problems.
      • -
      • It is easy to use. It has a simple and intuitive interface that allows you to select the PDF file, choose the attack type and start the recovery process with just a few clicks. It also has a help file and a user manual that explain how to use the software and its features.
      • -
      • It is versatile and flexible. It can recover or remove passwords from PDF files created with all versions of Adobe Acrobat or any other PDF application. It can also support various encryption types and password recovery methods, such as Thunder Tables®, Dictionary Attack, Brute Force Attack, Mask Attack and Key Search Attack.
      • -
      • It is safe and secure. It does not damage or modify the original PDF file in any way. It only recovers or removes the password and leaves the rest of the file intact. It also does not contain any viruses, malware or spyware that could harm your computer or your privacy.
      • -
      - -

      What are the System Requirements for Advanced PDF Password Recovery 1.31?

      - -

      If you want to install and run Advanced PDF Password Recovery 1.31, you need to have a computer that meets the following system requirements:

      - -
        -
      • Operating system: Windows XP/XP Professional/Vista/7/8/10/11 (32-bit or 64-bit)
      • -
      • Processor: Pentium II or higher
      • -
      • Memory: 256 MB RAM or more
      • -
      • Disk space: 30 MB free hard disk space or more
      • -
      • Video card: Any video card with DirectX 8 support
      • -
      • Internet connection: Required for online activation and updates
      • -
      - -

      If you want to use Thunder Tables® technology, you also need to have a precomputed hash table file (apdfpr.ttb) that is about 400 MB in size.

      - -

      Conclusion

      - -

      Advanced PDF Password Recovery 1.31 is a great software that can help you unlock any PDF file, regardless of the encryption type or password complexity. It can recover or instantly remove passwords that protect or lock PDF documents, allowing you to open, view, edit, print and copy them without any restrictions.

      - -

      If you want to download and use this software, you can visit the official website of Elcomsoft Co.Ltd., choose the edition of the software that suits your needs, purchase or register for a free trial version, download and install the software on your computer, select -

      What are the Advantages and Disadvantages of Advanced PDF Password Recovery 1.31?

      - -

      Like any software, Advanced PDF Password Recovery 1.31 has its advantages and disadvantages. Here are some of them:

      - -

      Advantages

      - -
        -
      • It can unlock any PDF file, regardless of the encryption type or password complexity.
      • -
      • It can recover or instantly remove passwords that protect or lock PDF documents, allowing you to open, view, edit, print and copy them without any restrictions.
      • -
      • It can handle large and complex PDF files without any problems.
      • -
      • It has a simple and intuitive interface that allows you to select the PDF file, choose the attack type and start the recovery process with just a few clicks.
      • -
      • It has a help file and a user manual that explain how to use the software and its features.
      • -
      • It supports various encryption types and password recovery methods, such as Thunder Tables®, Dictionary Attack, Brute Force Attack, Mask Attack and Key Search Attack.
      • -
      • It does not damage or modify the original PDF file in any way. It only recovers or removes the password and leaves the rest of the file intact.
      • -
      • It does not contain any viruses, malware or spyware that could harm your computer or your privacy.
      • -
      - -

      Disadvantages

      - -
        -
      • It is not free. You have to pay $49 for the Standard Edition, $99 for the Professional Edition or $399 for the Enterprise Edition. You can also download a free trial version that has some limitations.
      • -
      • It requires an internet connection for online activation and updates.
      • -
      • It may take a long time to recover or remove passwords from PDF files that have strong encryption or complex passwords.
      • -
      • It may not work with PDF files that are protected using Digital Rights Management (DRM) technology or any third-party security plug-ins such as FileOpen (FOPN_fLock).
      • -
      - -

      Frequently Asked Questions about Advanced PDF Password Recovery 1.31

      - -

      If you have any questions about Advanced PDF Password Recovery 1.31, you may find the answers in this section. Here are some of the most frequently asked questions about this software:

      - -

      Q: How can I download Advanced PDF Password Recovery 1.31?

      - -

      A: You can download Advanced PDF Password Recovery 1.31 from the official website of Elcomsoft Co.Ltd., by choosing the edition of the software that suits your needs, purchasing or registering for a free trial version, downloading and installing the software on your computer.

      - -

      Q: How can I use Advanced PDF Password Recovery 1.31?

      - -

      A: You can use Advanced PDF Password Recovery 1.31 by launching the software and selecting the PDF file that you want to unlock by clicking on the "Open" button or dragging and dropping it into the program window, selecting the type of attack that you want to use to recover or remove the password from the PDF file, clicking on the "Start" button and waiting for the program to find or remove the password from the PDF file.

      - -

      Q: What are Thunder Tables®?

      - -

      A: Thunder Tables® are a patented technology that can break 40-bit encryption in under a minute. They are precomputed hash table files that contain all possible encryption keys for 40-bit encrypted PDF files. You need to download a Thunder Table file (apdfpr.ttb) from -

      Conclusion

      - -

      Advanced PDF Password Recovery 1.31 is a great software that can help you unlock any PDF file, regardless of the encryption type or password complexity. It can recover or instantly remove passwords that protect or lock PDF documents, allowing you to open, view, edit, print and copy them without any restrictions.

      - -

      If you want to download and use this software, you can visit the official website of Elcomsoft Co.Ltd., choose the edition of the software that suits your needs, purchase or register for a free trial version, download and install the software on your computer, select the PDF file that you want to unlock, choose the attack type and start the recovery process with just a few clicks.

      - -

      We hope that this article was useful and informative for you. If you have any questions or feedback about Advanced PDF Password Recovery 1.31 or any other topics related to PDF security and password recovery, please feel free to contact us or leave a comment below. Thank you for your attention!

      3cee63e6c2
      -
      -
      \ No newline at end of file diff --git a/spaces/isotope21/Musicgen/app.py b/spaces/isotope21/Musicgen/app.py deleted file mode 100644 index dd195ad7fbc99e8fc11d52bb9b99c715f40c736b..0000000000000000000000000000000000000000 --- a/spaces/isotope21/Musicgen/app.py +++ /dev/null @@ -1,435 +0,0 @@ -# Copyright (c) Meta Platforms, Inc. and affiliates. -# All rights reserved. - -# This source code is licensed under the license found in the -# LICENSE file in the root directory of this source tree. - -# Updated to account for UI changes from https://github.com/rkfg/audiocraft/blob/long/app.py -# also released under the MIT license. - -import argparse -from concurrent.futures import ProcessPoolExecutor -import os -from pathlib import Path -import subprocess as sp -from tempfile import NamedTemporaryFile -import time -import typing as tp -import warnings - -import torch -import gradio as gr - -from audiocraft.data.audio_utils import convert_audio -from audiocraft.data.audio import audio_write -from audiocraft.models import MusicGen, MultiBandDiffusion - - -MODEL = None # Last used model -IS_BATCHED = "facebook/MusicGen" in os.environ.get('SPACE_ID', '') -print(IS_BATCHED) -MAX_BATCH_SIZE = 12 -BATCHED_DURATION = 15 -INTERRUPTING = False -MBD = None -# We have to wrap subprocess call to clean a bit the log when using gr.make_waveform -_old_call = sp.call - - -def _call_nostderr(*args, **kwargs): - # Avoid ffmpeg vomiting on the logs. - kwargs['stderr'] = sp.DEVNULL - kwargs['stdout'] = sp.DEVNULL - _old_call(*args, **kwargs) - - -sp.call = _call_nostderr -# Preallocating the pool of processes. -pool = ProcessPoolExecutor(4) -pool.__enter__() - - -def interrupt(): - global INTERRUPTING - INTERRUPTING = True - - -class FileCleaner: - def __init__(self, file_lifetime: float = 3600): - self.file_lifetime = file_lifetime - self.files = [] - - def add(self, path: tp.Union[str, Path]): - self._cleanup() - self.files.append((time.time(), Path(path))) - - def _cleanup(self): - now = time.time() - for time_added, path in list(self.files): - if now - time_added > self.file_lifetime: - if path.exists(): - path.unlink() - self.files.pop(0) - else: - break - - -file_cleaner = FileCleaner() - - -def make_waveform(*args, **kwargs): - # Further remove some warnings. - be = time.time() - with warnings.catch_warnings(): - warnings.simplefilter('ignore') - out = gr.make_waveform(*args, **kwargs) - print("Make a video took", time.time() - be) - return out - - -def load_model(version='facebook/musicgen-melody'): - global MODEL - print("Loading model", version) - if MODEL is None or MODEL.name != version: - MODEL = MusicGen.get_pretrained(version) - - -def load_diffusion(): - global MBD - if MBD is None: - print("loading MBD") - MBD = MultiBandDiffusion.get_mbd_musicgen() - - -def _do_predictions(texts, melodies, duration, progress=False, **gen_kwargs): - MODEL.set_generation_params(duration=duration, **gen_kwargs) - print("new batch", len(texts), texts, [None if m is None else (m[0], m[1].shape) for m in melodies]) - be = time.time() - processed_melodies = [] - target_sr = 32000 - target_ac = 1 - for melody in melodies: - if melody is None: - processed_melodies.append(None) - else: - sr, melody = melody[0], torch.from_numpy(melody[1]).to(MODEL.device).float().t() - if melody.dim() == 1: - melody = melody[None] - melody = melody[..., :int(sr * duration)] - melody = convert_audio(melody, sr, target_sr, target_ac) - processed_melodies.append(melody) - - if any(m is not None for m in processed_melodies): - outputs = MODEL.generate_with_chroma( - descriptions=texts, - melody_wavs=processed_melodies, - melody_sample_rate=target_sr, - progress=progress, - return_tokens=USE_DIFFUSION - ) - else: - outputs = MODEL.generate(texts, progress=progress, return_tokens=USE_DIFFUSION) - if USE_DIFFUSION: - outputs_diffusion = MBD.tokens_to_wav(outputs[1]) - outputs = torch.cat([outputs[0], outputs_diffusion], dim=0) - outputs = outputs.detach().cpu().float() - pending_videos = [] - out_wavs = [] - for output in outputs: - with NamedTemporaryFile("wb", suffix=".wav", delete=False) as file: - audio_write( - file.name, output, MODEL.sample_rate, strategy="loudness", - loudness_headroom_db=16, loudness_compressor=True, add_suffix=False) - pending_videos.append(pool.submit(make_waveform, file.name)) - out_wavs.append(file.name) - file_cleaner.add(file.name) - out_videos = [pending_video.result() for pending_video in pending_videos] - for video in out_videos: - file_cleaner.add(video) - print("batch finished", len(texts), time.time() - be) - print("Tempfiles currently stored: ", len(file_cleaner.files)) - return out_videos, out_wavs - - -def predict_batched(texts, melodies): - max_text_length = 512 - texts = [text[:max_text_length] for text in texts] - load_model('facebook/musicgen-melody') - res = _do_predictions(texts, melodies, BATCHED_DURATION) - return res - - -def predict_full(model, decoder, text, melody, duration, topk, topp, temperature, cfg_coef, progress=gr.Progress()): - global INTERRUPTING - global USE_DIFFUSION - INTERRUPTING = False - if temperature < 0: - raise gr.Error("Temperature must be >= 0.") - if topk < 0: - raise gr.Error("Topk must be non-negative.") - if topp < 0: - raise gr.Error("Topp must be non-negative.") - - topk = int(topk) - if decoder == "MultiBand_Diffusion": - USE_DIFFUSION = True - load_diffusion() - else: - USE_DIFFUSION = False - load_model(model) - - def _progress(generated, to_generate): - progress((min(generated, to_generate), to_generate)) - if INTERRUPTING: - raise gr.Error("Interrupted.") - MODEL.set_custom_progress_callback(_progress) - - videos, wavs = _do_predictions( - [text], [melody], duration, progress=True, - top_k=topk, top_p=topp, temperature=temperature, cfg_coef=cfg_coef) - if USE_DIFFUSION: - return videos[0], wavs[0], videos[1], wavs[1] - return videos[0], wavs[0], None, None - - -def toggle_audio_src(choice): - if choice == "mic": - return gr.update(source="microphone", value=None, label="Microphone") - else: - return gr.update(source="upload", value=None, label="File") - - -def toggle_diffusion(choice): - if choice == "MultiBand_Diffusion": - return [gr.update(visible=True)] * 2 - else: - return [gr.update(visible=False)] * 2 - - -def ui_full(launch_kwargs): - with gr.Blocks() as interface: - gr.Markdown( - """ - Music-GEN - - Creative MUSIC-AI Mozart - - """ - ) - with gr.Row(): - with gr.Column(): - with gr.Row(): - text = gr.Text(label="Input Text", interactive=True) - with gr.Column(): - radio = gr.Radio(["file", "mic"], value="file", - label="Condition on a melody (optional) File or Mic") - melody = gr.Audio(source="upload", type="numpy", label="File", - interactive=True, elem_id="melody-input") - with gr.Row(): - submit = gr.Button("Submit") - # Adapted from https://github.com/rkfg/audiocraft/blob/long/app.py, MIT license. - _ = gr.Button("Interrupt").click(fn=interrupt, queue=False) - with gr.Row(): - model = gr.Radio(["facebook/musicgen-melody", "facebook/musicgen-medium", "facebook/musicgen-small", - "facebook/musicgen-large"], - label="Model", value="facebook/musicgen-melody", interactive=True) - with gr.Row(): - decoder = gr.Radio(["Default", "MultiBand_Diffusion"], - label="Decoder", value="Default", interactive=True) - with gr.Row(): - duration = gr.Slider(minimum=1, maximum=120, value=10, label="Duration", interactive=True) - with gr.Row(): - topk = gr.Number(label="Top-k", value=250, interactive=True) - topp = gr.Number(label="Top-p", value=0, interactive=True) - temperature = gr.Number(label="Temperature", value=1.0, interactive=True) - cfg_coef = gr.Number(label="Classifier Free Guidance", value=3.0, interactive=True) - with gr.Column(): - output = gr.Video(label="Generated Music") - # audio_output = gr.Audio(label="Generated Music (wav)", type='filepath') - diffusion_output = gr.Video(label="MultiBand Diffusion Decoder") - audio_diffusion = gr.Audio(label="MultiBand Diffusion Decoder (wav)", type='filepath') - submit.click(toggle_diffusion, decoder, [diffusion_output, audio_diffusion], queue=False, - show_progress=False).then(predict_full, inputs=[model, decoder, text, melody, duration, topk, topp, - temperature, cfg_coef], - outputs=[output, diffusion_output, audio_diffusion]) - # outputs=[output, audio_output, diffusion_output, audio_diffusion]) - radio.change(toggle_audio_src, radio, [melody], queue=False, show_progress=False) - - gr.Examples( - fn=predict_full, - examples=[ - [], - [], - [], - [], - [], - [], - ], - inputs=[text, melody, model, decoder], - outputs=[output] - ) - gr.Markdown( - # """ - # ### More details - # - # The model will generate a short music extract based on the description you provided. - # The model can generate up to 30 seconds of audio in one pass. It is now possible - # to extend the generation by feeding back the end of the previous chunk of audio. - # This can take a long time, and the model might lose consistency. The model might also - # decide at arbitrary positions that the song ends. - # - # **WARNING:** Choosing long durations will take a long time to generate (2min might take ~10min). - # An overlap of 12 seconds is kept with the previously generated chunk, and 18 "new" seconds - # are generated each time. - # - # We present 4 model variations: - # 1. facebook/musicgen-melody -- a music generation model capable of generating music condition - # on text and melody inputs. **Note**, you can also use text only. - # 2. facebook/musicgen-small -- a 300M transformer decoder conditioned on text only. - # 3. facebook/musicgen-medium -- a 1.5B transformer decoder conditioned on text only. - # 4. facebook/musicgen-large -- a 3.3B transformer decoder conditioned on text only. - # - # We also present two way of decoding the audio tokens - # 1. Use the default GAN based compression model - # 2. Use MultiBand Diffusion from (paper linknano ) - # - # When using `facebook/musicgen-melody`, you can optionally provide a reference audio from - # which a broad melody will be extracted. The model will then try to follow both - # the description and melody provided. - # - # You can also use your own GPU or a Google Colab by following the instructions on our repo. - # See [github.com/facebookresearch/audiocraft](https://github.com/facebookresearch/audiocraft) - # for more details. - # """ - ) - - interface.queue().launch(**launch_kwargs) - - -def ui_batched(launch_kwargs): - with gr.Blocks() as demo: - gr.Markdown( - """ - # MusicGen - - This is the demo for [MusicGen](https://github.com/facebookresearch/audiocraft), - a simple and controllable model for music generation - presented at: ["Simple and Controllable Music Generation"](https://huggingface.co/papers/2306.05284). -
      - - Duplicate Space - for longer sequences, more control and no queue.

      - """ - ) - with gr.Row(): - with gr.Column(): - with gr.Row(): - text = gr.Text(label="Describe your music", lines=2, interactive=True) - with gr.Column(): - radio = gr.Radio(["file", "mic"], value="file", - label="Condition on a melody (optional) File or Mic") - melody = gr.Audio(source="upload", type="numpy", label="File", - interactive=True, elem_id="melody-input") - with gr.Row(): - submit = gr.Button("Generate") - with gr.Column(): - output = gr.Video(label="Generated Music") - audio_output = gr.Audio(label="Generated Music (wav)", type='filepath') - submit.click(predict_batched, inputs=[text, melody], - outputs=[output, audio_output], batch=True, max_batch_size=MAX_BATCH_SIZE) - radio.change(toggle_audio_src, radio, [melody], queue=False, show_progress=False) - gr.Examples( - fn=predict_batched, - examples=[ - [ - "An 80s driving pop song with heavy drums and synth pads in the background", - "./assets/bach.mp3", - ], - [ - "A cheerful country song with acoustic guitars", - "./assets/bolero_ravel.mp3", - ], - [ - "90s rock song with electric guitar and heavy drums", - None, - ], - [ - "a light and cheerly EDM track, with syncopated drums, aery pads, and strong emotions bpm: 130", - "./assets/bach.mp3", - ], - [ - "lofi slow bpm electro chill with organic samples", - None, - ], - ], - inputs=[text, melody], - outputs=[output] - ) - gr.Markdown(""" - ### More details - - The model will generate 12 seconds of audio based on the description you provided. - You can optionally provide a reference audio from which a broad melody will be extracted. - The model will then try to follow both the description and melody provided. - All samples are generated with the `melody` model. - - You can also use your own GPU or a Google Colab by following the instructions on our repo. - - See [github.com/facebookresearch/audiocraft](https://github.com/facebookresearch/audiocraft) - for more details. - """) - - demo.queue(max_size=8 * 4).launch(**launch_kwargs) - - -if __name__ == "__main__": - parser = argparse.ArgumentParser() - parser.add_argument( - '--listen', - type=str, - default='0.0.0.0' if 'SPACE_ID' in os.environ else '127.0.0.1', - help='IP to listen on for connections to Gradio', - ) - parser.add_argument( - '--username', type=str, default='', help='Username for authentication' - ) - parser.add_argument( - '--password', type=str, default='', help='Password for authentication' - ) - parser.add_argument( - '--server_port', - type=int, - default=0, - help='Port to run the server listener on', - ) - parser.add_argument( - '--inbrowser', action='store_true', help='Open in browser' - ) - parser.add_argument( - '--share', action='store_true', help='Share the gradio UI' - ) - - args = parser.parse_args() - - launch_kwargs = {} - launch_kwargs['server_name'] = args.listen - - if args.username and args.password: - launch_kwargs['auth'] = (args.username, args.password) - if args.server_port: - launch_kwargs['server_port'] = args.server_port - if args.inbrowser: - launch_kwargs['inbrowser'] = args.inbrowser - if args.share: - launch_kwargs['share'] = args.share - - # Show the interface - if IS_BATCHED: - global USE_DIFFUSION - USE_DIFFUSION = False - ui_batched(launch_kwargs) - else: - ui_full(launch_kwargs) - diff --git a/spaces/jackli888/stable-diffusion-webui/extensions/deforum/scripts/deforum_helpers/src/film_interpolation/film_util.py b/spaces/jackli888/stable-diffusion-webui/extensions/deforum/scripts/deforum_helpers/src/film_interpolation/film_util.py deleted file mode 100644 index e510758e53ced0af433fc14f63bf9b504e256544..0000000000000000000000000000000000000000 --- a/spaces/jackli888/stable-diffusion-webui/extensions/deforum/scripts/deforum_helpers/src/film_interpolation/film_util.py +++ /dev/null @@ -1,161 +0,0 @@ -"""Various utilities used in the film_net frame interpolator model.""" -from typing import List, Optional - -import cv2 -import numpy as np -import torch -from torch import nn -from torch.nn import functional as F - - -def pad_batch(batch, align): - height, width = batch.shape[1:3] - height_to_pad = (align - height % align) if height % align != 0 else 0 - width_to_pad = (align - width % align) if width % align != 0 else 0 - - crop_region = [height_to_pad >> 1, width_to_pad >> 1, height + (height_to_pad >> 1), width + (width_to_pad >> 1)] - batch = np.pad(batch, ((0, 0), (height_to_pad >> 1, height_to_pad - (height_to_pad >> 1)), - (width_to_pad >> 1, width_to_pad - (width_to_pad >> 1)), (0, 0)), mode='constant') - return batch, crop_region - - -def load_image(path, align=64): - image = cv2.cvtColor(cv2.imread(path), cv2.COLOR_BGR2RGB).astype(np.float32) / np.float32(255) - image_batch, crop_region = pad_batch(np.expand_dims(image, axis=0), align) - return image_batch, crop_region - - -def build_image_pyramid(image: torch.Tensor, pyramid_levels: int = 3) -> List[torch.Tensor]: - """Builds an image pyramid from a given image. - - The original image is included in the pyramid and the rest are generated by - successively halving the resolution. - - Args: - image: the input image. - options: film_net options object - - Returns: - A list of images starting from the finest with options.pyramid_levels items - """ - - pyramid = [] - for i in range(pyramid_levels): - pyramid.append(image) - if i < pyramid_levels - 1: - image = F.avg_pool2d(image, 2, 2) - return pyramid - - -def warp(image: torch.Tensor, flow: torch.Tensor) -> torch.Tensor: - """Backward warps the image using the given flow. - - Specifically, the output pixel in batch b, at position x, y will be computed - as follows: - (flowed_y, flowed_x) = (y+flow[b, y, x, 1], x+flow[b, y, x, 0]) - output[b, y, x] = bilinear_lookup(image, b, flowed_y, flowed_x) - - Note that the flow vectors are expected as [x, y], e.g. x in position 0 and - y in position 1. - - Args: - image: An image with shape BxHxWxC. - flow: A flow with shape BxHxWx2, with the two channels denoting the relative - offset in order: (dx, dy). - Returns: - A warped image. - """ - flow = -flow.flip(1) - - dtype = flow.dtype - device = flow.device - - # warped = tfa_image.dense_image_warp(image, flow) - # Same as above but with pytorch - ls1 = 1 - 1 / flow.shape[3] - ls2 = 1 - 1 / flow.shape[2] - - normalized_flow2 = flow.permute(0, 2, 3, 1) / torch.tensor( - [flow.shape[2] * .5, flow.shape[3] * .5], dtype=dtype, device=device)[None, None, None] - normalized_flow2 = torch.stack([ - torch.linspace(-ls1, ls1, flow.shape[3], dtype=dtype, device=device)[None, None, :] - normalized_flow2[..., 1], - torch.linspace(-ls2, ls2, flow.shape[2], dtype=dtype, device=device)[None, :, None] - normalized_flow2[..., 0], - ], dim=3) - - warped = F.grid_sample(image, normalized_flow2, - mode='bilinear', padding_mode='border', align_corners=False) - return warped.reshape(image.shape) - - -def multiply_pyramid(pyramid: List[torch.Tensor], - scalar: torch.Tensor) -> List[torch.Tensor]: - """Multiplies all image batches in the pyramid by a batch of scalars. - - Args: - pyramid: Pyramid of image batches. - scalar: Batch of scalars. - - Returns: - An image pyramid with all images multiplied by the scalar. - """ - # To multiply each image with its corresponding scalar, we first transpose - # the batch of images from BxHxWxC-format to CxHxWxB. This can then be - # multiplied with a batch of scalars, then we transpose back to the standard - # BxHxWxC form. - return [image * scalar for image in pyramid] - - -def flow_pyramid_synthesis( - residual_pyramid: List[torch.Tensor]) -> List[torch.Tensor]: - """Converts a residual flow pyramid into a flow pyramid.""" - flow = residual_pyramid[-1] - flow_pyramid: List[torch.Tensor] = [flow] - for residual_flow in residual_pyramid[:-1][::-1]: - level_size = residual_flow.shape[2:4] - flow = F.interpolate(2 * flow, size=level_size, mode='bilinear') - flow = residual_flow + flow - flow_pyramid.insert(0, flow) - return flow_pyramid - - -def pyramid_warp(feature_pyramid: List[torch.Tensor], - flow_pyramid: List[torch.Tensor]) -> List[torch.Tensor]: - """Warps the feature pyramid using the flow pyramid. - - Args: - feature_pyramid: feature pyramid starting from the finest level. - flow_pyramid: flow fields, starting from the finest level. - - Returns: - Reverse warped feature pyramid. - """ - warped_feature_pyramid = [] - for features, flow in zip(feature_pyramid, flow_pyramid): - warped_feature_pyramid.append(warp(features, flow)) - return warped_feature_pyramid - - -def concatenate_pyramids(pyramid1: List[torch.Tensor], - pyramid2: List[torch.Tensor]) -> List[torch.Tensor]: - """Concatenates each pyramid level together in the channel dimension.""" - result = [] - for features1, features2 in zip(pyramid1, pyramid2): - result.append(torch.cat([features1, features2], dim=1)) - return result - - -def conv(in_channels, out_channels, size, activation: Optional[str] = 'relu'): - # Since PyTorch doesn't have an in-built activation in Conv2d, we use a - # Sequential layer to combine Conv2d and Leaky ReLU in one module. - _conv = nn.Conv2d( - in_channels=in_channels, - out_channels=out_channels, - kernel_size=size, - padding='same') - if activation is None: - return _conv - assert activation == 'relu' - return nn.Sequential( - _conv, - nn.LeakyReLU(.2) - ) diff --git a/spaces/jackli888/stable-diffusion-webui/extensions/deforum/scripts/deforum_helpers/src/rife/rife_new_gen/RIFE_HDv3.py b/spaces/jackli888/stable-diffusion-webui/extensions/deforum/scripts/deforum_helpers/src/rife/rife_new_gen/RIFE_HDv3.py deleted file mode 100644 index e51408af7e574bc4c8b03739cda0bacd73cd0081..0000000000000000000000000000000000000000 --- a/spaces/jackli888/stable-diffusion-webui/extensions/deforum/scripts/deforum_helpers/src/rife/rife_new_gen/RIFE_HDv3.py +++ /dev/null @@ -1,108 +0,0 @@ -import os, sys -import torch -import torch.nn as nn -import numpy as np -from torch.optim import AdamW -import torch.optim as optim -import itertools -from ..model.warplayer import warp -from torch.nn.parallel import DistributedDataParallel as DDP -from .IFNet_HDv3 import * -import torch.nn.functional as F -from ..model.loss import * -sys.path.append('../../') -from deforum_helpers.general_utils import checksum - -device = torch.device("cuda" if torch.cuda.is_available() else "cpu") - -class Model: - def __init__(self, local_rank=-1): - self.flownet = IFNet() - self.device() - self.optimG = AdamW(self.flownet.parameters(), lr=1e-6, weight_decay=1e-4) - self.epe = EPE() - self.version = 3.9 - # self.vgg = VGGPerceptualLoss().to(device) - self.sobel = SOBEL() - if local_rank != -1: - self.flownet = DDP(self.flownet, device_ids=[local_rank], output_device=local_rank) - - def train(self): - self.flownet.train() - - def eval(self): - self.flownet.eval() - - def device(self): - self.flownet.to(device) - - def load_model(self, path, rank, deforum_models_path): - - download_rife_model(path, deforum_models_path) - - def convert(param): - if rank == -1: - return { - k.replace("module.", ""): v - for k, v in param.items() - if "module." in k - } - else: - return param - if rank <= 0: - if torch.cuda.is_available(): - self.flownet.load_state_dict(convert(torch.load(os.path.join(deforum_models_path,'{}.pkl').format(path))), False) - else: - self.flownet.load_state_dict(convert(torch.load(os.path.join(deforum_models_path,'{}.pkl').format(path), map_location ='cpu')), False) - - def inference(self, img0, img1, timestep=0.5, scale=1.0): - imgs = torch.cat((img0, img1), 1) - scale_list = [8/scale, 4/scale, 2/scale, 1/scale] - flow, mask, merged = self.flownet(imgs, timestep, scale_list) - return merged[3] - - def update(self, imgs, gt, learning_rate=0, mul=1, training=True, flow_gt=None): - for param_group in self.optimG.param_groups: - param_group['lr'] = learning_rate - img0 = imgs[:, :3] - img1 = imgs[:, 3:] - if training: - self.train() - else: - self.eval() - scale = [8, 4, 2, 1] - flow, mask, merged = self.flownet(torch.cat((imgs, gt), 1), scale=scale, training=training) - loss_l1 = (merged[3] - gt).abs().mean() - loss_smooth = self.sobel(flow[3], flow[3]*0).mean() - # loss_vgg = self.vgg(merged[2], gt) - if training: - self.optimG.zero_grad() - loss_G = loss_l1 + loss_cons + loss_smooth * 0.1 - loss_G.backward() - self.optimG.step() - else: - flow_teacher = flow[2] - return merged[3], { - 'mask': mask, - 'flow': flow[3][:, :2], - 'loss_l1': loss_l1, - 'loss_cons': loss_cons, - 'loss_smooth': loss_smooth, - } - -def download_rife_model(path, deforum_models_path): - options = {'RIFE46': ( - 'af6f0b4bed96dea2c9f0624b449216c7adfaf7f0b722fba0c8f5c6e20b2ec39559cf33f3d238d53b160c22f00c6eaa47dc54a6e4f8aa4f59a6e4a9e90e1a808a', - "https://github.com/hithereai/Practical-RIFE/releases/download/rife46/RIFE46.pkl"), - 'RIFE43': ('ed660f58708ee369a0b3855f64d2d07a6997d949f33067faae51d740123c5ee015901cc57553594f2df8ec08131a1c5f7c883c481eac0f9addd84379acea90c8', - "https://github.com/hithereai/Practical-RIFE/releases/download/rife43/RIFE43.pkl"), - 'RIFE40': ('0baf0bed23597cda402a97a80a7d14c26a9ed797d2fc0790aac93b19ca5b0f50676ba07aa9f8423cf061ed881ece6e67922f001ea402bfced83ef67675142ce7', - "https://github.com/hithereai/Practical-RIFE/releases/download/rife40/RIFE40.pkl")} - if path in options: - target_file = f"{path}.pkl" - target_path = os.path.join(deforum_models_path, target_file) - if not os.path.exists(target_path): - from basicsr.utils.download_util import load_file_from_url - load_file_from_url(options[path][1], deforum_models_path) - if checksum(target_path) != options[path][0]: - raise Exception(f"Error while downloading {target_file}. Please download from here: {options[path][1]} and place in: " + deforum_models_path) \ No newline at end of file diff --git a/spaces/jbilcke-hf/MusicGen/CONTRIBUTING.md b/spaces/jbilcke-hf/MusicGen/CONTRIBUTING.md deleted file mode 100644 index 55b99140204d785d572ada9761dd77f302ae31c6..0000000000000000000000000000000000000000 --- a/spaces/jbilcke-hf/MusicGen/CONTRIBUTING.md +++ /dev/null @@ -1,35 +0,0 @@ -# Contributing to Audiocraft - -We want to make contributing to this project as easy and transparent as -possible. - -## Pull Requests - -Audiocraft is the implementation of a research paper. -Therefore, we do not plan on accepting many pull requests for new features. -We certainly welcome them for bug fixes. - -1. Fork the repo and create your branch from `main`. -2. If you've added code that should be tested, add tests. -3. If you've changed APIs, update the documentation. -4. Ensure the test suite passes. -5. Make sure your code lints. -6. If you haven't already, complete the Contributor License Agreement ("CLA"). - -## Contributor License Agreement ("CLA") -In order to accept your pull request, we need you to submit a CLA. You only need -to do this once to work on any of Meta's open source projects. - -Complete your CLA here: - -## Issues -We use GitHub issues to track public bugs. Please ensure your description is -clear and has sufficient instructions to be able to reproduce the issue. - -Meta has a [bounty program](https://www.facebook.com/whitehat/) for the safe -disclosure of security bugs. In those cases, please go through the process -outlined on that page and do not file a public issue. - -## License -By contributing to encodec, you agree that your contributions will be licensed -under the LICENSE file in the root directory of this source tree. diff --git a/spaces/jbilcke-hf/Panoremix/src/app/engine/censorship.ts b/spaces/jbilcke-hf/Panoremix/src/app/engine/censorship.ts deleted file mode 100644 index ae4cc0b98b1cc09b9dda0aed35767bb7faee3b6e..0000000000000000000000000000000000000000 --- a/spaces/jbilcke-hf/Panoremix/src/app/engine/censorship.ts +++ /dev/null @@ -1,184 +0,0 @@ - -// I don't want to be banned by Replicate because bad actors are asking -// for some naked anime stuff or whatever -// I also want to avoid a PR scandal due to some bad user generated content - -import { computeSecretFingerprint } from "@/lib/computeSecretFingerprint" - -// those keywords have been generated by looking at the logs of the panorama and the AI Comic Factory -// those are real requests some users tried to attempt.. :| - -const chickens = [ - "fcb4dacbd99b21368c50f29c1d47071c87cf2225ab9192282c785460391cd365", - "68840b60ac27eacaa7afe17e898d3c4a2dc71acff8c74d6782c1bcaafd14963d", - "67f745224fd6e1a7a3a244514d5807fcc994cbb62ca4ec8fa44cd14244a515ae", - "681fea565117808c6dbe002520d2cfeeb3e5c67e68630afb4a453449a9da587b", - "2f3d913b3db9e15a930aac43eb2d6fe8817db8e4bcf37794bf0227b06b718d1b", - "922a700b807e4994df82eba2b48a6ac131fe8d8d1035d06b3592d622fb232161", - "cb69ee6774eafcc720adb1f689d28acbb9f47998cbea0299ec66a58dedf91c37" -] - -const ducks = [ - "1c52cb20c0cbc76349fa63232b982bd394cf0850ebc17240dcf33c19fb15a26d", - "e1d4de9b8d464d7da07c276b63a42c1c9922224f0a6cab6b0826427ce4a7461a", - "0be3174bfb1a48a65875c2f035b1ae14fbc8f232f55785018de0cfe2132fa952", - "0f174769641b2e5d2c79b5a83e8ef91e004f6f3e62531cd70cfdff02159268cb", - "e9fb8ae8ff720acd91025229478a21e43e8e976e30119a76c293201adf572736", - "f65a0dc0e07b5d084ff24c69dcdb953f7b57101d2ebb716d4dfb5963076ef807", - "2bf38af1646489c2c086f811d082054cd29e23fa7bb5c525396bec01b3ab688e" -] - -const cats = [ - "fcffc3e997d952007d1b902a9cf40b750ba4a410ac65bfd95475996bf51359e4", - "3172a5fa159754d703489dfba5af520b8ace107cdf170f4c4cb38a6797aa163f", - "500012dbff4498a9c4513369d6b9b373fab9330ffd2cb1e622294043cc21b610", - "84e3a8d34ee7d0c8e7a2926dd1acad46a0b66b9d27725b3a7e5053550f490301" -] - -const roasted = [ - "a2bfbce0046c9a52a0eabf98f73e0f8e09959970431fc892ebdb4e1c97031b50", - "6eca1adf06851f99e9cdfbb496c27d46ff81106903d11f3346a146e96082b016", - "49a124c9ed6fbbad4105b3657dc25de369bcafb9d6787f610c08f584cd607d0f", - "c3afb59420c812cbc7c8f57ad3e8d79407f10106a99f829aa65316c99d0b29c4", - "2b808858836a5c205080f5b93201ef92e098cff931d8de6d9f20dc722997d077", - "07bef89d1a7d63c9c5ed64ba0f73d6cff689811847c2e20c8b3fbfb060e1d64e", - "baeb994922d5473f534aa54322d83effe74c6c4dac807e6b523a677d7acdc17b", - "ea4735a879edd5cc94ca7db26edd5a970df69a41f0009d3444486647e44175af", - "f2412249030454cd13ac6f7965871d924c16daacda0123de81892adb19ce49ac", - "9958c56e12bab8549cf752bcd8bec4ac36cf79c404b1faf5611f057bb71bc0e1", - "76cdade0b3d4caf0888f60318a5cbca00f830a3b0bf37735fc64fdaeb67c34d3", - "1bf53c97869e1ea89bda19da64a9173d48fe4ec823e949e2c898f8abb3fbf457", - "1bf53c97869e1ea89bda19da64a9173d48fe4ec823e949e2c898f8abb3fbf457", - "3d7f973fab8f4a19c0a3e59efe970ed7bd55a1cb795752d9cbe3c19e8a7d81ec" -] - -const banned = [ - "8a05d4869d9d6ce388c6cd2db13ca12b88097b90f9be027d5ffaaa467c7a6e5e", - "0c475212a608138244c5fc150b1563e5ef79c516234fd78dcd5993f726c359a0", - "df17388805f99f2ff3e5ae97a0f55e5c927eb47f17ca65822bf8c88f02bac3dd", - "86c3355d1bd581cdf7306729d8dd0ee9b7a317b9cfd6d7a6f5fad9c0dafe2167", - "23a2484cd420c9ffbfcc2c0075a9b330664450ced1fc64ab6a65e278086b8c6e", - "fb4cabe709b62eea1b4cc0030c76f5e4a43ee677ce19124e8e7bafa86c78ab66", - "d99c26daee85f7dc81c46c061a5874cff7179ed72d884d2316d664d36ffe7ab5", - "b93c38af5aa221d76c60ee3eb762efee0cdb0daf29ceb235b7dda6d46c06490d", - "8cf6c8765dc757319461dd9a785e77c201b8e5a604d36b817cd987c6a5e62500", - "f4a1cb290745717f86c3cee30fc324c0d80a9945fcbc7bbeb010579f58792f1e", - "7c87c47c42fc983119551342be9ddd5b32e530c0504ccdbbaa1e12b1d9f1bbcb", - "d04fad4f21d030da7a1301afbf480ef6246eb7bbf0f26e31865b2e015a25f747", - "d685ff22fb9da01ee949db212770729603989850864ef7a7085e1f086cfa7deb", - "533b90588d9ccf7967da54691f575e9fd4926c6e0b5fd94a47b932bcea270bee", - "9c2d61f28f5bb7f3f1dc9122be64cda8a428b46ce68b70120da4c41dba96ba4c", - "5d4b1a3eebe64dfa631d0e3b084bd96ee9364c3669269f838ca17a4900276264", - "d56f56413b9679fc0820a2c0237224ded8554c61fab8959c174123c8b68ba029", - "323a9ab60739726070d615ff3a05d7ff6bb6e3c4dd9ff16ce24f253ecd7b8851", - "975c6739de7d4999db15972f707f5f4e95649275f1c0c48e895b8c537e8638ec", - "67ee26eb9e1c1c7124797321b02bca90a19c18171782917cd4a487b722484dce", - "6df5aa7b72a4e6e3fb726489ff1437daa5752047507f4da912680b1d6647c7d6", - "b0864805364359e8c5810c233b1bf2c74dedce9055ae5f7680ba05b4e39db8e2", - "a8f841472ecffdd6266151148320c8e36847a24ead9d3338e0313b075c16649d", - "f9b127cd90e85b0ff68dd220361671663f0154b2b827f1f7ea797b020ca0018c", - "d5c20e9a1ecf01c82da24c514d867498b3e5f522adc1523ce29404a6563641d5", - "241022b49d7c0aba24a61eea1137a804f36e4bcb47af42950275baac9b4e7aac", - "fc99a70e17b6c86ef1b537654b0f50353567a7b59912c3ba955f3fca4d1ea696", - "255306e968009003d295cb2a7256f27bfcdb5d1743bf4d9f2aa4b8adf1a7734d", - "048c7b709763dd9c43794d241c369f0abcb079d546ddcbbba9968a1ed1da7ed7", - "520cbfeef3e4c405d79478eedccb97a4d476be585626dd2b1c53292797491bc7", - "f9f28a7ae7e8b1719b350a04dc087a4b8e33478d109ceeef6ba892b32d1105c9", - "d177f1bfe603647ef4c1c0e6f1a7172081fb9bbc2ea859705949f2c5aa5d4f22", - "302feef2c09247fbd23789581f7f5e2219f88ae0a937880954938573c2a52a84", - "99edd6f57b864873835f16f19c805dd94bed9da8967b84e3a62782f106d9ebcc", - "e75e5f01dcd8351c9553e89558085bd68e6feb295dee5d8da0c9b43ee303ce36", - "135e52a026aea9d2e12de358a85e05cf21121a18269269b7c62678c3bc846f5b", - "28e5b2d3eb5f1ef4cc7b570878b03acf303a6ca4ca95893591e0fb943b0beab0", - "a26b26340f8d0363633490556d20bcc250726d10e1431eb8c22d6b1ff3f2b14a", - "27e4ddde96ec6a1dbe1cf12d79448b3e72f144944c15b299629542d1b65fbabf", - "efd9c0a391ee93251046a58326d1b21b33fe21d71a3fb1855b9048ade53df77c", - "6d505fcce416c26a606878aab4d249a034ba2a9846cb1f883e0f9e3fb76ba6da", - "3a37b8a1b72f9bca51233536d50f9c8d33a787434684787871e0049c82347cda", - "16f9b451184a7c3148344c7d0315f5312ca20553d2271912ecaad91810d977e6", - "7406537eb74d1885bd05e191228de313b13702a64d90ae1736c6377b25ab579a", - "7e4d1395ae18980015cab16c85ffa20b4cb90a2db594126e893d0f7ac6eecaa8", - "ba813ee6c25698f0f68a07121d38bb47c9aa404c1ab0a6e767595cb75e1747b8", - "6586c93f3ece83e01ecc1eb84a7711e7975826a388d478a009468ea0ed9dc03e", - "8960174c74d86e03ae88fb6774580170e49952f2286d960be08c556bbd0dda95", - "4d611454369aa1a4e2b7eed1734fac5d480f08fb86b87a162967e416370f2a8e", - "59d48440f85eabf565fe8d3bc6b973ba64c70df3b36b0511e0e67ceca91762b3", - "cd926926e2af74e43d1a6a420a7e1933b78662320477a3c018b2711d8765e339", - "80e90057df6a59823f51aafac36ed5bc4e5ac26d675d9c1467501590c82f12d4", - "a9cf28b869b70e258adde5639a048f866ec86f8f3f3d53bfc960b86aa6da9239", - "cc2adbf8ac0cddeefa304d7b20f14a7e047a4b2299cc5e8f898f5c59660bd964", - "92a150a46146e9d3f84899cf15e12514af684e7ee18d7add782ddd4f4a15ef18", - "d9b2e84ef6dc0ce449357d52c9095f69b173a1b848ea2921199d33b0ec10024a", - "a9329a7e4d367a0135c1ca86c6ce5ecabcc26529235229d71b6bf991f7689e21", - "8f160c6fd8ccc3fb2a371a4b52748f0bd030766627c4322e2911fe82f6b10497", - "620e96eae4f3e88cbe0770292b33724c5df3866d83f39df6380441f7271c80e2", - "cafa3481fa3c45ed1e55cd0129c12b477eeab5aa3d6da20cae6d6292f19b0e6d", - "be07994e9a83aa3689e79b6e96123676ccc4fa29f523c28c750c6d60505531ee", - "f6498069768cd3aa79b2b0c91879694f05a259c8ee4a6bb343f0435f74eb1b53", - "c9b6b26cb3a694eb78fcac0a14ad18d46d50907186a9add41022d31d191b2b65" -] - -const young = [ - "ffdf66787b4a33b78b18c18822e334cfe2c8406caf442851deef451bd43140a1", - "858f22219afc4b32a7ba9a27a213d7f495e77c3cceed8147eae5282bf3e23d39", - "8c3c46df84ace3d58d4ce0fbc513017986b33c6002ae369d9f7dd1f892a898cb", - "66caa22b9483fdf026ce67de61067d81535a7c9b3169cbc5c2a455ac8dcc7bec", - "76893047b1eff9fadc7be07b13adb5aaed9c73bcdeea46ee07098605e2c7ff76", - "526cb848754e2baaa17376a5693d90ba3f69f71fd2a866f22876ac8a075849a7", - "f59c38e31d0f64dc1bfcdf34451723bc1a65570e209e5496c8d1d7f6d3d649db", - "e013a67e275c62c1402ccbbb11ad14afb8b8a82318a44c07d67599ed5ac874de", - "3bef34219fb07f867ecbff4d6748f598d6cc0761e17dd0d431ee1f4ec3281374", - "8211bf5f613fac06cd5d074d34c16dfacc9367c8afaa6ad3aff99d145e5221be" -] - -const getFingerprint = (word: string) => { - return computeSecretFingerprint( - word.toLocaleLowerCase().replaceAll(/[^a-zA-Z0-9]/gi, "") - ) -} - -const encode = (list: string[]) => { - console.log(JSON.stringify( - list.sort((a, b) => (b.length - a.length)) - .map(item => getFingerprint(item)), null, 2)) -} - -// encode([ "badword" ]) - -export const filterOutBadWords = (sentence: string) => { - if (process.env.ENABLE_CENSORSHIP !== "true") { return sentence } - - let requireCensorship = false - - const words = sentence.replaceAll(/[^a-zA-Z0-9]/gi, " ").replaceAll(/\s+/gi, " ").trim().split(" ") - - const sanitized = words.map(word => { - const fingerprint = getFingerprint(word) - - let result: string = word - // some users want to play it smart and bypass our system so let's play too - if (chickens.includes(fingerprint)) { - result = "large chicken" - } else if (ducks.includes(fingerprint)) { - result = "big duck" - } else if (cats.includes(fingerprint)) { - result = "cat" - } else if (roasted.includes(fingerprint)) { - result = "roasted chicken" - } else if (young.includes(fingerprint)) { - result = "adult" - } else if (banned.includes(fingerprint)) { - result = "_BANNED_" - } - - if (result !== word) { - requireCensorship = true - } - return result - }).filter(item => item !== "_BANNED_").join(" ") - - // if the user didn't try to use a bad word, we leave it untouched - // he words array has been degraded by the replace operation, but it removes commas etc which isn't great - // so if the request was genuine and SFW, it's best to return the original prompt - return requireCensorship ? sanitized : sentence -} \ No newline at end of file diff --git a/spaces/jbilcke-hf/VideoChain-UI/scripts/test.js b/spaces/jbilcke-hf/VideoChain-UI/scripts/test.js deleted file mode 100644 index 67a07d8e5fdac589d574c227500bf8a08b23c92b..0000000000000000000000000000000000000000 --- a/spaces/jbilcke-hf/VideoChain-UI/scripts/test.js +++ /dev/null @@ -1,23 +0,0 @@ -const { promises: fs } = require("node:fs") - -const main = async () => { - console.log('generating shot..') - const response = await fetch("http://localhost:3000/api/shot", { - method: "POST", - headers: { - "Accept": "application/json", - "Content-Type": "application/json" - }, - body: JSON.stringify({ - token: process.env.VC_SECRET_ACCESS_TOKEN, - shotPrompt: "video of a dancing cat" - }) - }); - - console.log('response:', response) - const buffer = await response.buffer() - - fs.writeFile(`./test-juju.mp4`, buffer) -} - -main() \ No newline at end of file diff --git a/spaces/jbilcke-hf/webapp-factory-llama-node/public/index.html b/spaces/jbilcke-hf/webapp-factory-llama-node/public/index.html deleted file mode 100644 index e29dc98d00f7b7ca3f5384c5ff34b4a14a78c198..0000000000000000000000000000000000000000 --- a/spaces/jbilcke-hf/webapp-factory-llama-node/public/index.html +++ /dev/null @@ -1,137 +0,0 @@ - - - Webapp Factory 🏭 - - - -
      -
      -
      -
      -

      Webapp Factory 🏭

      -
      -

      A Hugging Face space to generate web applications using a local LLM (Airoboros-13B).

      -

      No 3rd party service or token needed: feel free to duplicate and create interesting forks of this space 🔧

      -
      - - - Waiting for the stream to begin (might take a few minutes).. - - Streamed so far
      (hang on, this may take 5-15 minutes ☕)
      -
      -
      -
      -
      - -
      -
      - - - - - diff --git a/spaces/jgurzoni/image_background_swapper/saicinpainting/evaluation/data.py b/spaces/jgurzoni/image_background_swapper/saicinpainting/evaluation/data.py deleted file mode 100644 index 89a4ea4c9577e6131731444f149eec76978ec260..0000000000000000000000000000000000000000 --- a/spaces/jgurzoni/image_background_swapper/saicinpainting/evaluation/data.py +++ /dev/null @@ -1,168 +0,0 @@ -import glob -import os - -import cv2 -import PIL.Image as Image -import numpy as np - -from torch.utils.data import Dataset -import torch.nn.functional as F - - -def load_image(fname, mode='RGB', return_orig=False): - img = np.array(Image.open(fname).convert(mode)) - if img.ndim == 3: - img = np.transpose(img, (2, 0, 1)) - out_img = img.astype('float32') / 255 - if return_orig: - return out_img, img - else: - return out_img - - -def ceil_modulo(x, mod): - if x % mod == 0: - return x - return (x // mod + 1) * mod - - -def pad_img_to_modulo(img, mod): - channels, height, width = img.shape - out_height = ceil_modulo(height, mod) - out_width = ceil_modulo(width, mod) - return np.pad(img, ((0, 0), (0, out_height - height), (0, out_width - width)), mode='symmetric') - - -def pad_tensor_to_modulo(img, mod): - batch_size, channels, height, width = img.shape - out_height = ceil_modulo(height, mod) - out_width = ceil_modulo(width, mod) - return F.pad(img, pad=(0, out_width - width, 0, out_height - height), mode='reflect') - - -def scale_image(img, factor, interpolation=cv2.INTER_AREA): - if img.shape[0] == 1: - img = img[0] - else: - img = np.transpose(img, (1, 2, 0)) - - img = cv2.resize(img, dsize=None, fx=factor, fy=factor, interpolation=interpolation) - - if img.ndim == 2: - img = img[None, ...] - else: - img = np.transpose(img, (2, 0, 1)) - return img - - -class InpaintingDataset(Dataset): - def __init__(self, datadir, img_suffix='.jpg', pad_out_to_modulo=None, scale_factor=None): - self.datadir = datadir - self.mask_filenames = sorted(list(glob.glob(os.path.join(self.datadir, '**', '*mask*.png'), recursive=True))) - self.img_filenames = [fname.rsplit('_mask', 1)[0] + img_suffix for fname in self.mask_filenames] - self.pad_out_to_modulo = pad_out_to_modulo - self.scale_factor = scale_factor - - def __len__(self): - return len(self.mask_filenames) - - def __getitem__(self, i): - image = load_image(self.img_filenames[i], mode='RGB') - mask = load_image(self.mask_filenames[i], mode='L') - result = dict(image=image, mask=mask[None, ...]) - - if self.scale_factor is not None: - result['image'] = scale_image(result['image'], self.scale_factor) - result['mask'] = scale_image(result['mask'], self.scale_factor, interpolation=cv2.INTER_NEAREST) - - if self.pad_out_to_modulo is not None and self.pad_out_to_modulo > 1: - result['unpad_to_size'] = result['image'].shape[1:] - result['image'] = pad_img_to_modulo(result['image'], self.pad_out_to_modulo) - result['mask'] = pad_img_to_modulo(result['mask'], self.pad_out_to_modulo) - - return result - -class OurInpaintingDataset(Dataset): - def __init__(self, datadir, img_suffix='.jpg', pad_out_to_modulo=None, scale_factor=None): - self.datadir = datadir - self.mask_filenames = sorted(list(glob.glob(os.path.join(self.datadir, 'mask', '**', '*mask*.png'), recursive=True))) - self.img_filenames = [os.path.join(self.datadir, 'img', os.path.basename(fname.rsplit('-', 1)[0].rsplit('_', 1)[0]) + '.png') for fname in self.mask_filenames] - self.pad_out_to_modulo = pad_out_to_modulo - self.scale_factor = scale_factor - - def __len__(self): - return len(self.mask_filenames) - - def __getitem__(self, i): - result = dict(image=load_image(self.img_filenames[i], mode='RGB'), - mask=load_image(self.mask_filenames[i], mode='L')[None, ...]) - - if self.scale_factor is not None: - result['image'] = scale_image(result['image'], self.scale_factor) - result['mask'] = scale_image(result['mask'], self.scale_factor) - - if self.pad_out_to_modulo is not None and self.pad_out_to_modulo > 1: - result['image'] = pad_img_to_modulo(result['image'], self.pad_out_to_modulo) - result['mask'] = pad_img_to_modulo(result['mask'], self.pad_out_to_modulo) - - return result - -class PrecomputedInpaintingResultsDataset(InpaintingDataset): - def __init__(self, datadir, predictdir, inpainted_suffix='_inpainted.jpg', **kwargs): - super().__init__(datadir, **kwargs) - if not datadir.endswith('/'): - datadir += '/' - self.predictdir = predictdir - self.pred_filenames = [os.path.join(predictdir, os.path.splitext(fname[len(datadir):])[0] + inpainted_suffix) - for fname in self.mask_filenames] - - def __getitem__(self, i): - result = super().__getitem__(i) - result['inpainted'] = load_image(self.pred_filenames[i]) - if self.pad_out_to_modulo is not None and self.pad_out_to_modulo > 1: - result['inpainted'] = pad_img_to_modulo(result['inpainted'], self.pad_out_to_modulo) - return result - -class OurPrecomputedInpaintingResultsDataset(OurInpaintingDataset): - def __init__(self, datadir, predictdir, inpainted_suffix="png", **kwargs): - super().__init__(datadir, **kwargs) - if not datadir.endswith('/'): - datadir += '/' - self.predictdir = predictdir - self.pred_filenames = [os.path.join(predictdir, os.path.basename(os.path.splitext(fname)[0]) + f'_inpainted.{inpainted_suffix}') - for fname in self.mask_filenames] - # self.pred_filenames = [os.path.join(predictdir, os.path.splitext(fname[len(datadir):])[0] + inpainted_suffix) - # for fname in self.mask_filenames] - - def __getitem__(self, i): - result = super().__getitem__(i) - result['inpainted'] = self.file_loader(self.pred_filenames[i]) - - if self.pad_out_to_modulo is not None and self.pad_out_to_modulo > 1: - result['inpainted'] = pad_img_to_modulo(result['inpainted'], self.pad_out_to_modulo) - return result - -class InpaintingEvalOnlineDataset(Dataset): - def __init__(self, indir, mask_generator, img_suffix='.jpg', pad_out_to_modulo=None, scale_factor=None, **kwargs): - self.indir = indir - self.mask_generator = mask_generator - self.img_filenames = sorted(list(glob.glob(os.path.join(self.indir, '**', f'*{img_suffix}' ), recursive=True))) - self.pad_out_to_modulo = pad_out_to_modulo - self.scale_factor = scale_factor - - def __len__(self): - return len(self.img_filenames) - - def __getitem__(self, i): - img, raw_image = load_image(self.img_filenames[i], mode='RGB', return_orig=True) - mask = self.mask_generator(img, raw_image=raw_image) - result = dict(image=img, mask=mask) - - if self.scale_factor is not None: - result['image'] = scale_image(result['image'], self.scale_factor) - result['mask'] = scale_image(result['mask'], self.scale_factor, interpolation=cv2.INTER_NEAREST) - - if self.pad_out_to_modulo is not None and self.pad_out_to_modulo > 1: - result['image'] = pad_img_to_modulo(result['image'], self.pad_out_to_modulo) - result['mask'] = pad_img_to_modulo(result['mask'], self.pad_out_to_modulo) - return result \ No newline at end of file diff --git a/spaces/jie1/succ1/ProteinMPNN-main/helper_scripts/make_tied_positions_dict.py b/spaces/jie1/succ1/ProteinMPNN-main/helper_scripts/make_tied_positions_dict.py deleted file mode 100644 index 0ffe65cd37e24c38523c78bd476e214b759c20a2..0000000000000000000000000000000000000000 --- a/spaces/jie1/succ1/ProteinMPNN-main/helper_scripts/make_tied_positions_dict.py +++ /dev/null @@ -1,61 +0,0 @@ -import argparse - -def m_t_p_d(input_path, output_path, chain_list, position_list, homooligomer): - - import glob - import random - import numpy as np - import json - import itertools - - with open(input_path.name, 'r') as json_file: - json_list = list(json_file) - - homooligomeric_state = int(homooligomer) - - if homooligomeric_state == 0: - tied_list = [[int(item) for item in one.split()] for one in position_list.split(",")] - global_designed_chain_list = [str(item) for item in chain_list.split()] - my_dict = {} - for json_str in json_list: - result = json.loads(json_str) - all_chain_list = sorted([item[-1:] for item in list(result) if item[:9]=='seq_chain']) #A, B, C, ... - tied_positions_list = [] - for i, pos in enumerate(tied_list[0]): - temp_dict = {} - for j, chain in enumerate(global_designed_chain_list): - temp_dict[chain] = [tied_list[j][i]] #needs to be a list - tied_positions_list.append(temp_dict) - my_dict[result['name']] = tied_positions_list - else: - my_dict = {} - for json_str in json_list: - result = json.loads(json_str) - all_chain_list = sorted([item[-1:] for item in list(result) if item[:9]=='seq_chain']) #A, B, C, ... - tied_positions_list = [] - chain_length = len(result[f"seq_chain_{all_chain_list[0]}"]) - for i in range(1,chain_length+1): - temp_dict = {} - for j, chain in enumerate(all_chain_list): - temp_dict[chain] = [i] #needs to be a list - tied_positions_list.append(temp_dict) - my_dict[result['name']] = tied_positions_list - - with open(output_path, 'w') as f: - f.write(json.dumps(my_dict) + '\n') - return output_path -# if __name__ == "__main__": -# argparser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter) -# argparser.add_argument("--input_path", type=str, help="Path to the parsed PDBs") -# argparser.add_argument("--output_path", type=str, help="Path to the output dictionary") -# argparser.add_argument("--chain_list", type=str, default='', help="List of the chains that need to be fixed") -# argparser.add_argument("--position_list", type=str, default='', help="Position lists, e.g. 11 12 14 18, 1 2 3 4 for first chain and the second chain") -# argparser.add_argument("--homooligomer", type=int, default=0, help="If 0 do not use, if 1 then design homooligomer") -# -# args = argparser.parse_args() -# main(args) - - -#e.g. output -#{"5TTA": [], "3LIS": [{"A": [1], "B": [1]}, {"A": [2], "B": [2]}, {"A": [3], "B": [3]}, {"A": [4], "B": [4]}, {"A": [5], "B": [5]}, {"A": [6], "B": [6]}, {"A": [7], "B": [7]}, {"A": [8], "B": [8]}, {"A": [9], "B": [9]}, {"A": [10], "B": [10]}, {"A": [11], "B": [11]}, {"A": [12], "B": [12]}, {"A": [13], "B": [13]}, {"A": [14], "B": [14]}, {"A": [15], "B": [15]}, {"A": [16], "B": [16]}, {"A": [17], "B": [17]}, {"A": [18], "B": [18]}, {"A": [19], "B": [19]}, {"A": [20], "B": [20]}, {"A": [21], "B": [21]}, {"A": [22], "B": [22]}, {"A": [23], "B": [23]}, {"A": [24], "B": [24]}, {"A": [25], "B": [25]}, {"A": [26], "B": [26]}, {"A": [27], "B": [27]}, {"A": [28], "B": [28]}, {"A": [29], "B": [29]}, {"A": [30], "B": [30]}, {"A": [31], "B": [31]}, {"A": [32], "B": [32]}, {"A": [33], "B": [33]}, {"A": [34], "B": [34]}, {"A": [35], "B": [35]}, {"A": [36], "B": [36]}, {"A": [37], "B": [37]}, {"A": [38], "B": [38]}, {"A": [39], "B": [39]}, {"A": [40], "B": [40]}, {"A": [41], "B": [41]}, {"A": [42], "B": [42]}, {"A": [43], "B": [43]}, {"A": [44], "B": [44]}, {"A": [45], "B": [45]}, {"A": [46], "B": [46]}, {"A": [47], "B": [47]}, {"A": [48], "B": [48]}, {"A": [49], "B": [49]}, {"A": [50], "B": [50]}, {"A": [51], "B": [51]}, {"A": [52], "B": [52]}, {"A": [53], "B": [53]}, {"A": [54], "B": [54]}, {"A": [55], "B": [55]}, {"A": [56], "B": [56]}, {"A": [57], "B": [57]}, {"A": [58], "B": [58]}, {"A": [59], "B": [59]}, {"A": [60], "B": [60]}, {"A": [61], "B": [61]}, {"A": [62], "B": [62]}, {"A": [63], "B": [63]}, {"A": [64], "B": [64]}, {"A": [65], "B": [65]}, {"A": [66], "B": [66]}, {"A": [67], "B": [67]}, {"A": [68], "B": [68]}, {"A": [69], "B": [69]}, {"A": [70], "B": [70]}, {"A": [71], "B": [71]}, {"A": [72], "B": [72]}, {"A": [73], "B": [73]}, {"A": [74], "B": [74]}, {"A": [75], "B": [75]}, {"A": [76], "B": [76]}, {"A": [77], "B": [77]}, {"A": [78], "B": [78]}, {"A": [79], "B": [79]}, {"A": [80], "B": [80]}, {"A": [81], "B": [81]}, {"A": [82], "B": [82]}, {"A": [83], "B": [83]}, {"A": [84], "B": [84]}, {"A": [85], "B": [85]}, {"A": [86], "B": [86]}, {"A": [87], "B": [87]}, {"A": [88], "B": [88]}, {"A": [89], "B": [89]}, {"A": [90], "B": [90]}, {"A": [91], "B": [91]}, {"A": [92], "B": [92]}, {"A": [93], "B": [93]}, {"A": [94], "B": [94]}, {"A": [95], "B": [95]}, {"A": [96], "B": [96]}]} - diff --git a/spaces/jimr1603/galactica-base-api/README.md b/spaces/jimr1603/galactica-base-api/README.md deleted file mode 100644 index d5ca100e02de69a4581b79e5c9f5fd59c9819752..0000000000000000000000000000000000000000 --- a/spaces/jimr1603/galactica-base-api/README.md +++ /dev/null @@ -1,14 +0,0 @@ ---- -title: Galactica Base - Inference API -emoji: 📝 -colorFrom: yellow -colorTo: blue -sdk: gradio -sdk_version: 3.9.1 -app_file: app.py -pinned: false -license: apache-2.0 -duplicated_from: morenolq/galactica-base-api ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/joaogante/contrastive_search_generation/app.py b/spaces/joaogante/contrastive_search_generation/app.py deleted file mode 100644 index 05b6f2223e8b1e2ff2f50c3e95d15432fbda80f0..0000000000000000000000000000000000000000 --- a/spaces/joaogante/contrastive_search_generation/app.py +++ /dev/null @@ -1,204 +0,0 @@ -import time -from functools import lru_cache - -import torch -import gradio as gr -from transformers import AutoConfig, AutoTokenizer, AutoModelForCausalLM, AutoModelForSeq2SeqLM - - -@lru_cache(maxsize=1) # only cache the latest model -def get_model_and_tokenizer(model_id): - config = AutoConfig.from_pretrained(model_id) - if config.is_encoder_decoder: - model = AutoModelForSeq2SeqLM.from_pretrained(model_id) - else: - model = AutoModelForCausalLM.from_pretrained(model_id) - - tokenizer = AutoTokenizer.from_pretrained(model_id) - return model, tokenizer - - -@lru_cache(maxsize=32768) # cache up to 32k examples -def run_generation( - text, - model_id, - max_new_tokens, - alpha=0.0, - top_k=0, - num_beams=1, - do_sample=False, - top_p=0.0, - seed=0 -): - model, tokenizer = get_model_and_tokenizer(model_id) - - inputs = tokenizer(text, return_tensors='pt') - if seed: - torch.manual_seed(seed) - - start = time.time_ns() - contrastive_ids = model.generate( - # from the tokenizer - **inputs, - # fixed arguments - num_return_sequences=1, - early_stopping=True, - # variable arguments - max_new_tokens=max_new_tokens, - do_sample=do_sample, - num_beams=num_beams, - penalty_alpha=alpha or None, - top_k=top_k or None, - top_p=top_p or None, - ) - end = time.time_ns() - - contrastive_time = (end - start) / 1e6 - contrastive_text = tokenizer.decode(contrastive_ids[0], skip_special_tokens=True) - return contrastive_text, contrastive_time - - -def generate_beam_search(text, model_id, max_new_tokens, alpha, k, num_beams): - contrastive_text, contrastive_time = run_generation(text, model_id, max_new_tokens, alpha=alpha, top_k=k) - beam_search_text, beam_search_time = run_generation(text, model_id, max_new_tokens, num_beams=num_beams) - return contrastive_text, contrastive_time, beam_search_text, beam_search_time - - -def generate_top_k(text, model_id, max_new_tokens, alpha, k, top_k, seed): - contrastive_text, contrastive_time = run_generation(text, model_id, max_new_tokens, alpha=alpha, top_k=k) - top_k_text, top_k_time = run_generation( - text, model_id, max_new_tokens, top_k=top_k, seed=seed, do_sample=True - ) - return contrastive_text, contrastive_time, top_k_text, top_k_time - - -def generate_top_p(text, model_id, max_new_tokens, alpha, k, top_p, seed): - contrastive_text, contrastive_time = run_generation(text, model_id, max_new_tokens, alpha=alpha, top_k=k) - top_p_text, top_p_time = run_generation( - text, model_id, max_new_tokens, top_p=top_p, seed=seed, do_sample=True - ) - return contrastive_text, contrastive_time, top_p_text, top_p_time - - -demo = gr.Blocks() - -with demo: - gr.Markdown( - """ - # Contrastive Search Generation comparison - - Credits to the contrastive search generation [paper](https://arxiv.org/abs/2202.06417) authors, including - @[pangpang666](https://huggingface.co/pangpang666) and @[GMFTBY](https://huggingface.co/GMFTBY). Check out the - follow-up [work](https://arxiv.org/abs/2210.14140), which demonstrates the usefulness of the technique with - off-the-shelf LLMs, as well as their [HF guest blog post](https://huggingface.co/blog/introducing-csearch). - - From the paper: - "At each decoding step, the key ideas of contrastive search are (i) the generated output should be selected - from the set of most probable candidates predicted by the model; and (ii) the generated output should be - discriminative enough with respect to the previous context. In this way, the generated text can (i) better - maintain the semantic coherence with respect to the prefix while (ii) avoiding model degeneration." - - 🚨 Warnings: 🚨 - - Avoid using large models (> 1GB) in this demo. It will take a long time to load the model and generate text. - - Too slow/long queue? Check our - [colab](https://colab.research.google.com/github/huggingface/blog/blob/main/notebooks/115_introducing_contrastive_search.ipynb) - instead. - """ - ) - with gr.Tabs(): - with gr.TabItem("vs. Beam Search"): - with gr.Row(): - with gr.Column(): - gr.Markdown("## Inputs ✍️") - gr.Markdown("General options:") - model_id = gr.Text(value="facebook/opt-125m", label="Model Repository") - input_text = gr.Textbox(value="DeepMind Company is", lines=5, label="Input Text") - max_new_tokens = gr.Slider(value=50, minimum=1, maximum=256, label="New tokens to generate") - gr.Markdown("Contrastive Search options:") - alpha = gr.Slider(value=0.6, minimum=0.01, maximum=1.0, step=0.01, label="Alpha") - k = gr.Slider(value=6, minimum=1, maximum=20, step=1, label="K") - gr.Markdown("Beam Search options:") - num_beams = gr.Slider(value=4, minimum=1, maximum=16, step=1, label="Number of beams") - generate_button = gr.Button(value="Generate", label="Generate") - - with gr.Column(): - gr.Markdown("## Outputs 🤖") - gr.Markdown("Contrastive Search generation:") - text_contrastive = gr.Textbox(value="", label="") - time_contrastive = gr.Number(value=0.0, precision=1, label="Generation time (ms)") - gr.Markdown("Beam Search generation:") - text_beam_search = gr.Textbox(value="", label="") - time_beam_search = gr.Number(value=0.0, precision=1, label="Generation time (ms)") - - # actions - generate_button.click( - fn=generate_beam_search, - inputs=[input_text, model_id, max_new_tokens, alpha, k, num_beams], - outputs=[text_contrastive, time_contrastive, text_beam_search, time_beam_search] - ) - - with gr.TabItem("vs. Top K Sampling"): - with gr.Row(): - with gr.Column(): - gr.Markdown("## Inputs ✍️") - gr.Markdown("General options:") - model_id = gr.Text(value="facebook/opt-125m", label="Model Repository") - input_text = gr.Textbox(value="DeepMind Company is", lines=5, label="Input Text") - max_new_tokens = gr.Slider(value=50, minimum=1, maximum=256, label="New tokens to generate") - gr.Markdown("Contrastive Search options:") - alpha = gr.Slider(value=0.6, minimum=0.01, maximum=1.0, step=0.01, label="Alpha") - k = gr.Slider(value=6, minimum=1, maximum=20, step=1, label="K") - gr.Markdown("Sampling options:") - top_k = gr.Slider(value=50, minimum=1, maximum=100, step=1, label="Top K") - seed = gr.Number(value=42, precision=0, label="Seed") - generate_button = gr.Button(value="Generate", label="Generate") - - with gr.Column(): - gr.Markdown("## Outputs 🤖") - gr.Markdown("Contrastive Search generation:") - text_contrastive = gr.Textbox(value="", label="") - time_contrastive = gr.Number(value=0.0, precision=1, label="Generation time (ms)") - gr.Markdown("Top K Sampling generation:") - text_top_k = gr.Textbox(value="", label="") - time_top_k = gr.Number(value=0.0, precision=1, label="Generation time (ms)") - - # actions - generate_button.click( - fn=generate_top_k, - inputs=[input_text, model_id, max_new_tokens, alpha, k, top_k, seed], - outputs=[text_contrastive, time_contrastive, text_top_k, time_top_k] - ) - - with gr.TabItem("vs. Nucleus Sampling"): - with gr.Row(): - with gr.Column(): - gr.Markdown("## Inputs ✍️") - gr.Markdown("General options:") - model_id = gr.Text(value="facebook/opt-125m", label="Model Repository") - input_text = gr.Textbox(value="DeepMind Company is", lines=5, label="Input Text") - max_new_tokens = gr.Slider(value=50, minimum=1, maximum=256, label="New tokens to generate") - gr.Markdown("Contrastive Search options:") - alpha = gr.Slider(value=0.6, minimum=0.01, maximum=1.0, step=0.01, label="Alpha") - k = gr.Slider(value=6, minimum=1, maximum=20, step=1, label="K") - gr.Markdown("Sampling options:") - top_p = gr.Slider(value=0.95, minimum=0.01, maximum=1.0, step=0.01, label="Top P") - seed = gr.Number(value=42, precision=0, label="Seed") - generate_button = gr.Button(value="Generate", label="Generate") - - with gr.Column(): - gr.Markdown("## Outputs 🤖") - gr.Markdown("Contrastive Search generation:") - text_contrastive = gr.Textbox(value="", label="") - time_contrastive = gr.Number(value=0.0, precision=1, label="Generation time (ms)") - gr.Markdown("Nucleus Sampling generation:") - text_top_p = gr.Textbox(value="", label="") - time_top_p = gr.Number(value=0.0, precision=1, label="Generation time (ms)") - - # actions - generate_button.click( - fn=generate_top_p, - inputs=[input_text, model_id, max_new_tokens, alpha, k, top_p, seed], - outputs=[text_contrastive, time_contrastive, text_top_p, time_top_p] - ) - -demo.launch() diff --git a/spaces/joaogante/transformers_streaming/README.md b/spaces/joaogante/transformers_streaming/README.md deleted file mode 100644 index 2ca007fc69b10a9fb73ef6fddd70a7ff65017b71..0000000000000000000000000000000000000000 --- a/spaces/joaogante/transformers_streaming/README.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: Chatbot Transformers Streaming -emoji: 👀 -colorFrom: gray -colorTo: blue -sdk: gradio -sdk_version: 3.23.0 -app_file: app.py -pinned: false ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/joaopereirajp/livvieChatBot/venv/lib/python3.9/site-packages/Crypto/Hash/cSHAKE256.py b/spaces/joaopereirajp/livvieChatBot/venv/lib/python3.9/site-packages/Crypto/Hash/cSHAKE256.py deleted file mode 100644 index b3b31d6de1bbf9170a672c81eeb2cf24310642a7..0000000000000000000000000000000000000000 --- a/spaces/joaopereirajp/livvieChatBot/venv/lib/python3.9/site-packages/Crypto/Hash/cSHAKE256.py +++ /dev/null @@ -1,56 +0,0 @@ -# =================================================================== -# -# Copyright (c) 2021, Legrandin -# All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions -# are met: -# -# 1. Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# 2. Redistributions in binary form must reproduce the above copyright -# notice, this list of conditions and the following disclaimer in -# the documentation and/or other materials provided with the -# distribution. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS -# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE -# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, -# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, -# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN -# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -# POSSIBILITY OF SUCH DAMAGE. -# =================================================================== - -from Crypto.Util._raw_api import c_size_t -from Crypto.Hash.cSHAKE128 import cSHAKE_XOF - - -def _new(data, custom, function): - # Use Keccak[512] - return cSHAKE_XOF(data, custom, 512, function) - - -def new(data=None, custom=None): - """Return a fresh instance of a cSHAKE256 object. - - Args: - data (bytes/bytearray/memoryview): - The very first chunk of the message to hash. - It is equivalent to an early call to :meth:`update`. - Optional. - custom (bytes): - Optional. - A customization bytestring (``S`` in SP 800-185). - - :Return: A :class:`cSHAKE_XOF` object - """ - - # Use Keccak[512] - return cSHAKE_XOF(data, custom, 512, b'') diff --git a/spaces/joaopereirajp/livvieChatBot/venv/lib/python3.9/site-packages/fontTools/varLib/instancer/__init__.py b/spaces/joaopereirajp/livvieChatBot/venv/lib/python3.9/site-packages/fontTools/varLib/instancer/__init__.py deleted file mode 100644 index a8663ec42247a7967675755090b34cec2e9e2cd8..0000000000000000000000000000000000000000 --- a/spaces/joaopereirajp/livvieChatBot/venv/lib/python3.9/site-packages/fontTools/varLib/instancer/__init__.py +++ /dev/null @@ -1,1508 +0,0 @@ -""" Partially instantiate a variable font. - -The module exports an `instantiateVariableFont` function and CLI that allow to -create full instances (i.e. static fonts) from variable fonts, as well as "partial" -variable fonts that only contain a subset of the original variation space. - -For example, if you wish to pin the width axis to a given location while also -restricting the weight axis to 400..700 range, you can do:: - - $ fonttools varLib.instancer ./NotoSans-VF.ttf wdth=85 wght=400:700 - -See `fonttools varLib.instancer --help` for more info on the CLI options. - -The module's entry point is the `instantiateVariableFont` function, which takes -a TTFont object and a dict specifying either axis coodinates or (min, max) ranges, -and returns a new TTFont representing either a partial VF, or full instance if all -the VF axes were given an explicit coordinate. - -E.g. here's how to pin the wght axis at a given location in a wght+wdth variable -font, keeping only the deltas associated with the wdth axis:: - -| >>> from fontTools import ttLib -| >>> from fontTools.varLib import instancer -| >>> varfont = ttLib.TTFont("path/to/MyVariableFont.ttf") -| >>> [a.axisTag for a in varfont["fvar"].axes] # the varfont's current axes -| ['wght', 'wdth'] -| >>> partial = instancer.instantiateVariableFont(varfont, {"wght": 300}) -| >>> [a.axisTag for a in partial["fvar"].axes] # axes left after pinning 'wght' -| ['wdth'] - -If the input location specifies all the axes, the resulting instance is no longer -'variable' (same as using fontools varLib.mutator): - -| >>> instance = instancer.instantiateVariableFont( -| ... varfont, {"wght": 700, "wdth": 67.5} -| ... ) -| >>> "fvar" not in instance -| True - -If one just want to drop an axis at the default location, without knowing in -advance what the default value for that axis is, one can pass a `None` value: - -| >>> instance = instancer.instantiateVariableFont(varfont, {"wght": None}) -| >>> len(varfont["fvar"].axes) -| 1 - -From the console script, this is equivalent to passing `wght=drop` as input. - -This module is similar to fontTools.varLib.mutator, which it's intended to supersede. -Note that, unlike varLib.mutator, when an axis is not mentioned in the input -location, the varLib.instancer will keep the axis and the corresponding deltas, -whereas mutator implicitly drops the axis at its default coordinate. - -The module supports all the following "levels" of instancing, which can of -course be combined: - -L1 - dropping one or more axes while leaving the default tables unmodified; - - | >>> font = instancer.instantiateVariableFont(varfont, {"wght": None}) - -L2 - dropping one or more axes while pinning them at non-default locations; - - | >>> font = instancer.instantiateVariableFont(varfont, {"wght": 700}) - -L3 - restricting the range of variation of one or more axes, by setting either - a new minimum or maximum, potentially -- though not necessarily -- dropping - entire regions of variations that fall completely outside this new range. - - | >>> font = instancer.instantiateVariableFont(varfont, {"wght": (100, 300)}) - -L4 - moving the default location of an axis, by specifying (min,defalt,max) values: - - | >>> font = instancer.instantiateVariableFont(varfont, {"wght": (100, 300, 700)}) - -Currently only TrueType-flavored variable fonts (i.e. containing 'glyf' table) -are supported, but support for CFF2 variable fonts will be added soon. - -The discussion and implementation of these features are tracked at -https://github.com/fonttools/fonttools/issues/1537 -""" -from fontTools.misc.fixedTools import ( - floatToFixedToFloat, - strToFixedToFloat, - otRound, -) -from fontTools.varLib.models import supportScalar, normalizeValue, piecewiseLinearMap -from fontTools.ttLib import TTFont -from fontTools.ttLib.tables.TupleVariation import TupleVariation -from fontTools.ttLib.tables import _g_l_y_f -from fontTools import varLib - -# we import the `subset` module because we use the `prune_lookups` method on the GSUB -# table class, and that method is only defined dynamically upon importing `subset` -from fontTools import subset # noqa: F401 -from fontTools.varLib import builder -from fontTools.varLib.mvar import MVAR_ENTRIES -from fontTools.varLib.merger import MutatorMerger -from fontTools.varLib.instancer import names -from .featureVars import instantiateFeatureVariations -from fontTools.misc.cliTools import makeOutputFileName -from fontTools.varLib.instancer import solver -import collections -import dataclasses -from copy import deepcopy -from enum import IntEnum -import logging -import os -import re -from typing import Dict, Iterable, Mapping, Optional, Sequence, Tuple, Union -import warnings - - -log = logging.getLogger("fontTools.varLib.instancer") - - -def AxisRange(minimum, maximum): - warnings.warn( - "AxisRange is deprecated; use AxisTriple instead", - DeprecationWarning, - stacklevel=2, - ) - return AxisTriple(minimum, None, maximum) - - -def NormalizedAxisRange(minimum, maximum): - warnings.warn( - "NormalizedAxisRange is deprecated; use AxisTriple instead", - DeprecationWarning, - stacklevel=2, - ) - return NormalizedAxisTriple(minimum, None, maximum) - - -@dataclasses.dataclass(frozen=True, order=True, repr=False) -class AxisTriple(Sequence): - """A triple of (min, default, max) axis values. - - The default value can be None, in which case the limitRangeAndPopulateDefault() - method can be used to fill in the missing default value based on the fvar axis - default. - """ - - minimum: float - default: Optional[float] # if None, filled with by limitRangeAndPopulateDefault - maximum: float - - def __post_init__(self): - if self.default is None and self.minimum == self.maximum: - object.__setattr__(self, "default", self.minimum) - if not ( - (self.minimum <= self.default <= self.maximum) - if self.default is not None - else (self.minimum <= self.maximum) - ): - raise ValueError( - f"{type(self).__name__} minimum ({self.minimum}) must be <= default " - f"({self.default}) which must be <= maximum ({self.maximum})" - ) - - def __getitem__(self, i): - fields = dataclasses.fields(self) - return getattr(self, fields[i].name) - - def __len__(self): - return len(dataclasses.fields(self)) - - def _replace(self, **kwargs): - return dataclasses.replace(self, **kwargs) - - def __repr__(self): - return ( - f"({', '.join(format(v, 'g') if v is not None else 'None' for v in self)})" - ) - - @classmethod - def expand( - cls, - v: Union[ - "AxisTriple", - float, # pin axis at single value, same as min==default==max - Tuple[float, float], # (min, max), restrict axis and keep default - Tuple[float, float, float], # (min, default, max) - ], - ) -> "AxisTriple": - """Convert a single value or a tuple into an AxisTriple. - - If the input is a single value, it is interpreted as a pin at that value. - If the input is a tuple, it is interpreted as (min, max) or (min, default, max). - """ - if isinstance(v, cls): - return v - if isinstance(v, (int, float)): - return cls(v, v, v) - try: - n = len(v) - except TypeError as e: - raise ValueError( - f"expected float, 2- or 3-tuple of floats; got {type(v)}: {v!r}" - ) from e - default = None - if n == 2: - minimum, maximum = v - elif n >= 3: - return cls(*v) - else: - raise ValueError(f"expected sequence of 2 or 3; got {n}: {v!r}") - return cls(minimum, default, maximum) - - def limitRangeAndPopulateDefault(self, fvarTriple) -> "AxisTriple": - """Return a new AxisTriple with the default value filled in. - - Set default to fvar axis default if the latter is within the min/max range, - otherwise set default to the min or max value, whichever is closer to the - fvar axis default. - If the default value is already set, return self. - """ - minimum = self.minimum - maximum = self.maximum - default = self.default - if default is None: - default = fvarTriple[1] - - minimum = max(self.minimum, fvarTriple[0]) - maximum = max(self.maximum, fvarTriple[0]) - minimum = min(minimum, fvarTriple[2]) - maximum = min(maximum, fvarTriple[2]) - default = max(minimum, min(maximum, default)) - - return AxisTriple(minimum, default, maximum) - - -@dataclasses.dataclass(frozen=True, order=True, repr=False) -class NormalizedAxisTriple(AxisTriple): - """A triple of (min, default, max) normalized axis values.""" - - minimum: float - default: float - maximum: float - - def __post_init__(self): - if self.default is None: - object.__setattr__(self, "default", max(self.minimum, min(self.maximum, 0))) - if not (-1.0 <= self.minimum <= self.default <= self.maximum <= 1.0): - raise ValueError( - "Normalized axis values not in -1..+1 range; got " - f"minimum={self.minimum:g}, default={self.default:g}, maximum={self.maximum:g})" - ) - - -@dataclasses.dataclass(frozen=True, order=True, repr=False) -class NormalizedAxisTripleAndDistances(AxisTriple): - """A triple of (min, default, max) normalized axis values, - with distances between min and default, and default and max, - in the *pre-normalized* space.""" - - minimum: float - default: float - maximum: float - distanceNegative: Optional[float] = 1 - distancePositive: Optional[float] = 1 - - def __post_init__(self): - if self.default is None: - object.__setattr__(self, "default", max(self.minimum, min(self.maximum, 0))) - if not (-1.0 <= self.minimum <= self.default <= self.maximum <= 1.0): - raise ValueError( - "Normalized axis values not in -1..+1 range; got " - f"minimum={self.minimum:g}, default={self.default:g}, maximum={self.maximum:g})" - ) - - def reverse_negate(self): - v = self - return self.__class__(-v[2], -v[1], -v[0], v[4], v[3]) - - def renormalizeValue(self, v, extrapolate=True): - """Renormalizes a normalized value v to the range of this axis, - considering the pre-normalized distances as well as the new - axis limits.""" - - lower, default, upper, distanceNegative, distancePositive = self - assert lower <= default <= upper - - if not extrapolate: - v = max(lower, min(upper, v)) - - if v == default: - return 0 - - if default < 0: - return -self.reverse_negate().renormalizeValue(-v, extrapolate=extrapolate) - - # default >= 0 and v != default - - if v > default: - return (v - default) / (upper - default) - - # v < default - - if lower >= 0: - return (v - default) / (default - lower) - - # lower < 0 and v < default - - totalDistance = distanceNegative * -lower + distancePositive * default - - if v >= 0: - vDistance = (default - v) * distancePositive - else: - vDistance = -v * distanceNegative + distancePositive * default - - return -vDistance / totalDistance - - -class _BaseAxisLimits(Mapping[str, AxisTriple]): - def __getitem__(self, key: str) -> AxisTriple: - return self._data[key] - - def __iter__(self) -> Iterable[str]: - return iter(self._data) - - def __len__(self) -> int: - return len(self._data) - - def __repr__(self) -> str: - return f"{type(self).__name__}({self._data!r})" - - def __str__(self) -> str: - return str(self._data) - - def defaultLocation(self) -> Dict[str, float]: - """Return a dict of default axis values.""" - return {k: v.default for k, v in self.items()} - - def pinnedLocation(self) -> Dict[str, float]: - """Return a location dict with only the pinned axes.""" - return {k: v.default for k, v in self.items() if v.minimum == v.maximum} - - -class AxisLimits(_BaseAxisLimits): - """Maps axis tags (str) to AxisTriple values.""" - - def __init__(self, *args, **kwargs): - self._data = data = {} - for k, v in dict(*args, **kwargs).items(): - if v is None: - # will be filled in by limitAxesAndPopulateDefaults - data[k] = v - else: - try: - triple = AxisTriple.expand(v) - except ValueError as e: - raise ValueError(f"Invalid axis limits for {k!r}: {v!r}") from e - data[k] = triple - - def limitAxesAndPopulateDefaults(self, varfont) -> "AxisLimits": - """Return a new AxisLimits with defaults filled in from fvar table. - - If all axis limits already have defaults, return self. - """ - fvar = varfont["fvar"] - fvarTriples = { - a.axisTag: (a.minValue, a.defaultValue, a.maxValue) for a in fvar.axes - } - newLimits = {} - for axisTag, triple in self.items(): - fvarTriple = fvarTriples[axisTag] - default = fvarTriple[1] - if triple is None: - newLimits[axisTag] = AxisTriple(default, default, default) - else: - newLimits[axisTag] = triple.limitRangeAndPopulateDefault(fvarTriple) - return type(self)(newLimits) - - def normalize(self, varfont, usingAvar=True) -> "NormalizedAxisLimits": - """Return a new NormalizedAxisLimits with normalized -1..0..+1 values. - - If usingAvar is True, the avar table is used to warp the default normalization. - """ - fvar = varfont["fvar"] - badLimits = set(self.keys()).difference(a.axisTag for a in fvar.axes) - if badLimits: - raise ValueError("Cannot limit: {} not present in fvar".format(badLimits)) - - axes = { - a.axisTag: (a.minValue, a.defaultValue, a.maxValue) - for a in fvar.axes - if a.axisTag in self - } - - avarSegments = {} - if usingAvar and "avar" in varfont: - avarSegments = varfont["avar"].segments - - normalizedLimits = {} - - for axis_tag, triple in axes.items(): - distanceNegative = triple[1] - triple[0] - distancePositive = triple[2] - triple[1] - - if self[axis_tag] is None: - normalizedLimits[axis_tag] = NormalizedAxisTripleAndDistances( - 0, 0, 0, distanceNegative, distancePositive - ) - continue - - minV, defaultV, maxV = self[axis_tag] - - if defaultV is None: - defaultV = triple[1] - - avarMapping = avarSegments.get(axis_tag, None) - normalizedLimits[axis_tag] = NormalizedAxisTripleAndDistances( - *(normalize(v, triple, avarMapping) for v in (minV, defaultV, maxV)), - distanceNegative, - distancePositive, - ) - - return NormalizedAxisLimits(normalizedLimits) - - -class NormalizedAxisLimits(_BaseAxisLimits): - """Maps axis tags (str) to NormalizedAxisTriple values.""" - - def __init__(self, *args, **kwargs): - self._data = data = {} - for k, v in dict(*args, **kwargs).items(): - try: - triple = NormalizedAxisTripleAndDistances.expand(v) - except ValueError as e: - raise ValueError(f"Invalid axis limits for {k!r}: {v!r}") from e - data[k] = triple - - -class OverlapMode(IntEnum): - KEEP_AND_DONT_SET_FLAGS = 0 - KEEP_AND_SET_FLAGS = 1 - REMOVE = 2 - REMOVE_AND_IGNORE_ERRORS = 3 - - -def instantiateTupleVariationStore( - variations, axisLimits, origCoords=None, endPts=None -): - """Instantiate TupleVariation list at the given location, or limit axes' min/max. - - The 'variations' list of TupleVariation objects is modified in-place. - The 'axisLimits' (dict) maps axis tags (str) to NormalizedAxisTriple namedtuples - specifying (minimum, default, maximum) in the -1,0,+1 normalized space. Pinned axes - have minimum == default == maximum. - - A 'full' instance (i.e. static font) is produced when all the axes are pinned to - single coordinates; a 'partial' instance (i.e. a less variable font) is produced - when some of the axes are omitted, or restricted with a new range. - - Tuples that do not participate are kept as they are. Those that have 0 influence - at the given location are removed from the variation store. - Those that are fully instantiated (i.e. all their axes are being pinned) are also - removed from the variation store, their scaled deltas accummulated and returned, so - that they can be added by the caller to the default instance's coordinates. - Tuples that are only partially instantiated (i.e. not all the axes that they - participate in are being pinned) are kept in the store, and their deltas multiplied - by the scalar support of the axes to be pinned at the desired location. - - Args: - variations: List[TupleVariation] from either 'gvar' or 'cvar'. - axisLimits: NormalizedAxisLimits: map from axis tags to (min, default, max) - normalized coordinates for the full or partial instance. - origCoords: GlyphCoordinates: default instance's coordinates for computing 'gvar' - inferred points (cf. table__g_l_y_f._getCoordinatesAndControls). - endPts: List[int]: indices of contour end points, for inferring 'gvar' deltas. - - Returns: - List[float]: the overall delta adjustment after applicable deltas were summed. - """ - - newVariations = changeTupleVariationsAxisLimits(variations, axisLimits) - - mergedVariations = collections.OrderedDict() - for var in newVariations: - # compute inferred deltas only for gvar ('origCoords' is None for cvar) - if origCoords is not None: - var.calcInferredDeltas(origCoords, endPts) - - # merge TupleVariations with overlapping "tents" - axes = frozenset(var.axes.items()) - if axes in mergedVariations: - mergedVariations[axes] += var - else: - mergedVariations[axes] = var - - # drop TupleVariation if all axes have been pinned (var.axes.items() is empty); - # its deltas will be added to the default instance's coordinates - defaultVar = mergedVariations.pop(frozenset(), None) - - for var in mergedVariations.values(): - var.roundDeltas() - variations[:] = list(mergedVariations.values()) - - return defaultVar.coordinates if defaultVar is not None else [] - - -def changeTupleVariationsAxisLimits(variations, axisLimits): - for axisTag, axisLimit in sorted(axisLimits.items()): - newVariations = [] - for var in variations: - newVariations.extend(changeTupleVariationAxisLimit(var, axisTag, axisLimit)) - variations = newVariations - return variations - - -def changeTupleVariationAxisLimit(var, axisTag, axisLimit): - assert isinstance(axisLimit, NormalizedAxisTripleAndDistances) - - # Skip when current axis is missing (i.e. doesn't participate), - lower, peak, upper = var.axes.get(axisTag, (-1, 0, 1)) - if peak == 0: - return [var] - # Drop if the var 'tent' isn't well-formed - if not (lower <= peak <= upper) or (lower < 0 and upper > 0): - return [] - - if axisTag not in var.axes: - return [var] - - tent = var.axes[axisTag] - - solutions = solver.rebaseTent(tent, axisLimit) - - out = [] - for scalar, tent in solutions: - newVar = ( - TupleVariation(var.axes, var.coordinates) if len(solutions) > 1 else var - ) - if tent is None: - newVar.axes.pop(axisTag) - else: - assert tent[1] != 0, tent - newVar.axes[axisTag] = tent - newVar *= scalar - out.append(newVar) - - return out - - -def _instantiateGvarGlyph( - glyphname, glyf, gvar, hMetrics, vMetrics, axisLimits, optimize=True -): - coordinates, ctrl = glyf._getCoordinatesAndControls(glyphname, hMetrics, vMetrics) - endPts = ctrl.endPts - - # Not every glyph may have variations - tupleVarStore = gvar.variations.get(glyphname) - - if tupleVarStore: - defaultDeltas = instantiateTupleVariationStore( - tupleVarStore, axisLimits, coordinates, endPts - ) - - if defaultDeltas: - coordinates += _g_l_y_f.GlyphCoordinates(defaultDeltas) - - glyph = glyf[glyphname] - if glyph.isVarComposite(): - for component in glyph.components: - newLocation = {} - for tag, loc in component.location.items(): - if tag not in axisLimits: - newLocation[tag] = loc - continue - if component.flags & _g_l_y_f.VarComponentFlags.AXES_HAVE_VARIATION: - raise NotImplementedError( - "Instancing accross VarComposite axes with variation is not supported." - ) - limits = axisLimits[tag] - loc = limits.renormalizeValue(loc, extrapolate=False) - newLocation[tag] = loc - component.location = newLocation - - # _setCoordinates also sets the hmtx/vmtx advance widths and sidebearings from - # the four phantom points and glyph bounding boxes. - # We call it unconditionally even if a glyph has no variations or no deltas are - # applied at this location, in case the glyph's xMin and in turn its sidebearing - # have changed. E.g. a composite glyph has no deltas for the component's (x, y) - # offset nor for the 4 phantom points (e.g. it's monospaced). Thus its entry in - # gvar table is empty; however, the composite's base glyph may have deltas - # applied, hence the composite's bbox and left/top sidebearings may need updating - # in the instanced font. - glyf._setCoordinates(glyphname, coordinates, hMetrics, vMetrics) - - if not tupleVarStore: - if glyphname in gvar.variations: - del gvar.variations[glyphname] - return - - if optimize: - isComposite = glyf[glyphname].isComposite() - for var in tupleVarStore: - var.optimize(coordinates, endPts, isComposite) - - -def instantiateGvarGlyph(varfont, glyphname, axisLimits, optimize=True): - """Remove? - https://github.com/fonttools/fonttools/pull/2266""" - gvar = varfont["gvar"] - glyf = varfont["glyf"] - hMetrics = varfont["hmtx"].metrics - vMetrics = getattr(varfont.get("vmtx"), "metrics", None) - _instantiateGvarGlyph( - glyphname, glyf, gvar, hMetrics, vMetrics, axisLimits, optimize=optimize - ) - - -def instantiateGvar(varfont, axisLimits, optimize=True): - log.info("Instantiating glyf/gvar tables") - - gvar = varfont["gvar"] - glyf = varfont["glyf"] - hMetrics = varfont["hmtx"].metrics - vMetrics = getattr(varfont.get("vmtx"), "metrics", None) - # Get list of glyph names sorted by component depth. - # If a composite glyph is processed before its base glyph, the bounds may - # be calculated incorrectly because deltas haven't been applied to the - # base glyph yet. - glyphnames = sorted( - glyf.glyphOrder, - key=lambda name: ( - glyf[name].getCompositeMaxpValues(glyf).maxComponentDepth - if glyf[name].isComposite() or glyf[name].isVarComposite() - else 0, - name, - ), - ) - for glyphname in glyphnames: - _instantiateGvarGlyph( - glyphname, glyf, gvar, hMetrics, vMetrics, axisLimits, optimize=optimize - ) - - if not gvar.variations: - del varfont["gvar"] - - -def setCvarDeltas(cvt, deltas): - for i, delta in enumerate(deltas): - if delta: - cvt[i] += otRound(delta) - - -def instantiateCvar(varfont, axisLimits): - log.info("Instantiating cvt/cvar tables") - - cvar = varfont["cvar"] - - defaultDeltas = instantiateTupleVariationStore(cvar.variations, axisLimits) - - if defaultDeltas: - setCvarDeltas(varfont["cvt "], defaultDeltas) - - if not cvar.variations: - del varfont["cvar"] - - -def setMvarDeltas(varfont, deltas): - mvar = varfont["MVAR"].table - records = mvar.ValueRecord - for rec in records: - mvarTag = rec.ValueTag - if mvarTag not in MVAR_ENTRIES: - continue - tableTag, itemName = MVAR_ENTRIES[mvarTag] - delta = deltas[rec.VarIdx] - if delta != 0: - setattr( - varfont[tableTag], - itemName, - getattr(varfont[tableTag], itemName) + otRound(delta), - ) - - -def instantiateMVAR(varfont, axisLimits): - log.info("Instantiating MVAR table") - - mvar = varfont["MVAR"].table - fvarAxes = varfont["fvar"].axes - varStore = mvar.VarStore - defaultDeltas = instantiateItemVariationStore(varStore, fvarAxes, axisLimits) - setMvarDeltas(varfont, defaultDeltas) - - if varStore.VarRegionList.Region: - varIndexMapping = varStore.optimize() - for rec in mvar.ValueRecord: - rec.VarIdx = varIndexMapping[rec.VarIdx] - else: - del varfont["MVAR"] - - -def _remapVarIdxMap(table, attrName, varIndexMapping, glyphOrder): - oldMapping = getattr(table, attrName).mapping - newMapping = [varIndexMapping[oldMapping[glyphName]] for glyphName in glyphOrder] - setattr(table, attrName, builder.buildVarIdxMap(newMapping, glyphOrder)) - - -# TODO(anthrotype) Add support for HVAR/VVAR in CFF2 -def _instantiateVHVAR(varfont, axisLimits, tableFields): - location = axisLimits.pinnedLocation() - tableTag = tableFields.tableTag - fvarAxes = varfont["fvar"].axes - # Deltas from gvar table have already been applied to the hmtx/vmtx. For full - # instances (i.e. all axes pinned), we can simply drop HVAR/VVAR and return - if set(location).issuperset(axis.axisTag for axis in fvarAxes): - log.info("Dropping %s table", tableTag) - del varfont[tableTag] - return - - log.info("Instantiating %s table", tableTag) - vhvar = varfont[tableTag].table - varStore = vhvar.VarStore - # since deltas were already applied, the return value here is ignored - instantiateItemVariationStore(varStore, fvarAxes, axisLimits) - - if varStore.VarRegionList.Region: - # Only re-optimize VarStore if the HVAR/VVAR already uses indirect AdvWidthMap - # or AdvHeightMap. If a direct, implicit glyphID->VariationIndex mapping is - # used for advances, skip re-optimizing and maintain original VariationIndex. - if getattr(vhvar, tableFields.advMapping): - varIndexMapping = varStore.optimize(use_NO_VARIATION_INDEX=False) - glyphOrder = varfont.getGlyphOrder() - _remapVarIdxMap(vhvar, tableFields.advMapping, varIndexMapping, glyphOrder) - if getattr(vhvar, tableFields.sb1): # left or top sidebearings - _remapVarIdxMap(vhvar, tableFields.sb1, varIndexMapping, glyphOrder) - if getattr(vhvar, tableFields.sb2): # right or bottom sidebearings - _remapVarIdxMap(vhvar, tableFields.sb2, varIndexMapping, glyphOrder) - if tableTag == "VVAR" and getattr(vhvar, tableFields.vOrigMapping): - _remapVarIdxMap( - vhvar, tableFields.vOrigMapping, varIndexMapping, glyphOrder - ) - - -def instantiateHVAR(varfont, axisLimits): - return _instantiateVHVAR(varfont, axisLimits, varLib.HVAR_FIELDS) - - -def instantiateVVAR(varfont, axisLimits): - return _instantiateVHVAR(varfont, axisLimits, varLib.VVAR_FIELDS) - - -class _TupleVarStoreAdapter(object): - def __init__(self, regions, axisOrder, tupleVarData, itemCounts): - self.regions = regions - self.axisOrder = axisOrder - self.tupleVarData = tupleVarData - self.itemCounts = itemCounts - - @classmethod - def fromItemVarStore(cls, itemVarStore, fvarAxes): - axisOrder = [axis.axisTag for axis in fvarAxes] - regions = [ - region.get_support(fvarAxes) for region in itemVarStore.VarRegionList.Region - ] - tupleVarData = [] - itemCounts = [] - for varData in itemVarStore.VarData: - variations = [] - varDataRegions = (regions[i] for i in varData.VarRegionIndex) - for axes, coordinates in zip(varDataRegions, zip(*varData.Item)): - variations.append(TupleVariation(axes, list(coordinates))) - tupleVarData.append(variations) - itemCounts.append(varData.ItemCount) - return cls(regions, axisOrder, tupleVarData, itemCounts) - - def rebuildRegions(self): - # Collect the set of all unique region axes from the current TupleVariations. - # We use an OrderedDict to de-duplicate regions while keeping the order. - uniqueRegions = collections.OrderedDict.fromkeys( - ( - frozenset(var.axes.items()) - for variations in self.tupleVarData - for var in variations - ) - ) - # Maintain the original order for the regions that pre-existed, appending - # the new regions at the end of the region list. - newRegions = [] - for region in self.regions: - regionAxes = frozenset(region.items()) - if regionAxes in uniqueRegions: - newRegions.append(region) - del uniqueRegions[regionAxes] - if uniqueRegions: - newRegions.extend(dict(region) for region in uniqueRegions) - self.regions = newRegions - - def instantiate(self, axisLimits): - defaultDeltaArray = [] - for variations, itemCount in zip(self.tupleVarData, self.itemCounts): - defaultDeltas = instantiateTupleVariationStore(variations, axisLimits) - if not defaultDeltas: - defaultDeltas = [0] * itemCount - defaultDeltaArray.append(defaultDeltas) - - # rebuild regions whose axes were dropped or limited - self.rebuildRegions() - - pinnedAxes = set(axisLimits.pinnedLocation()) - self.axisOrder = [ - axisTag for axisTag in self.axisOrder if axisTag not in pinnedAxes - ] - - return defaultDeltaArray - - def asItemVarStore(self): - regionOrder = [frozenset(axes.items()) for axes in self.regions] - varDatas = [] - for variations, itemCount in zip(self.tupleVarData, self.itemCounts): - if variations: - assert len(variations[0].coordinates) == itemCount - varRegionIndices = [ - regionOrder.index(frozenset(var.axes.items())) for var in variations - ] - varDataItems = list(zip(*(var.coordinates for var in variations))) - varDatas.append( - builder.buildVarData(varRegionIndices, varDataItems, optimize=False) - ) - else: - varDatas.append( - builder.buildVarData([], [[] for _ in range(itemCount)]) - ) - regionList = builder.buildVarRegionList(self.regions, self.axisOrder) - itemVarStore = builder.buildVarStore(regionList, varDatas) - # remove unused regions from VarRegionList - itemVarStore.prune_regions() - return itemVarStore - - -def instantiateItemVariationStore(itemVarStore, fvarAxes, axisLimits): - """Compute deltas at partial location, and update varStore in-place. - - Remove regions in which all axes were instanced, or fall outside the new axis - limits. Scale the deltas of the remaining regions where only some of the axes - were instanced. - - The number of VarData subtables, and the number of items within each, are - not modified, in order to keep the existing VariationIndex valid. - One may call VarStore.optimize() method after this to further optimize those. - - Args: - varStore: An otTables.VarStore object (Item Variation Store) - fvarAxes: list of fvar's Axis objects - axisLimits: NormalizedAxisLimits: mapping axis tags to normalized - min/default/max axis coordinates. May not specify coordinates/ranges for - all the fvar axes. - - Returns: - defaultDeltas: to be added to the default instance, of type dict of floats - keyed by VariationIndex compound values: i.e. (outer << 16) + inner. - """ - tupleVarStore = _TupleVarStoreAdapter.fromItemVarStore(itemVarStore, fvarAxes) - defaultDeltaArray = tupleVarStore.instantiate(axisLimits) - newItemVarStore = tupleVarStore.asItemVarStore() - - itemVarStore.VarRegionList = newItemVarStore.VarRegionList - assert itemVarStore.VarDataCount == newItemVarStore.VarDataCount - itemVarStore.VarData = newItemVarStore.VarData - - defaultDeltas = { - ((major << 16) + minor): delta - for major, deltas in enumerate(defaultDeltaArray) - for minor, delta in enumerate(deltas) - } - defaultDeltas[itemVarStore.NO_VARIATION_INDEX] = 0 - return defaultDeltas - - -def instantiateOTL(varfont, axisLimits): - # TODO(anthrotype) Support partial instancing of JSTF and BASE tables - - if ( - "GDEF" not in varfont - or varfont["GDEF"].table.Version < 0x00010003 - or not varfont["GDEF"].table.VarStore - ): - return - - if "GPOS" in varfont: - msg = "Instantiating GDEF and GPOS tables" - else: - msg = "Instantiating GDEF table" - log.info(msg) - - gdef = varfont["GDEF"].table - varStore = gdef.VarStore - fvarAxes = varfont["fvar"].axes - - defaultDeltas = instantiateItemVariationStore(varStore, fvarAxes, axisLimits) - - # When VF are built, big lookups may overflow and be broken into multiple - # subtables. MutatorMerger (which inherits from AligningMerger) reattaches - # them upon instancing, in case they can now fit a single subtable (if not, - # they will be split again upon compilation). - # This 'merger' also works as a 'visitor' that traverses the OTL tables and - # calls specific methods when instances of a given type are found. - # Specifically, it adds default deltas to GPOS Anchors/ValueRecords and GDEF - # LigatureCarets, and optionally deletes all VariationIndex tables if the - # VarStore is fully instanced. - merger = MutatorMerger( - varfont, defaultDeltas, deleteVariations=(not varStore.VarRegionList.Region) - ) - merger.mergeTables(varfont, [varfont], ["GDEF", "GPOS"]) - - if varStore.VarRegionList.Region: - varIndexMapping = varStore.optimize() - gdef.remap_device_varidxes(varIndexMapping) - if "GPOS" in varfont: - varfont["GPOS"].table.remap_device_varidxes(varIndexMapping) - else: - # Downgrade GDEF. - del gdef.VarStore - gdef.Version = 0x00010002 - if gdef.MarkGlyphSetsDef is None: - del gdef.MarkGlyphSetsDef - gdef.Version = 0x00010000 - - if not ( - gdef.LigCaretList - or gdef.MarkAttachClassDef - or gdef.GlyphClassDef - or gdef.AttachList - or (gdef.Version >= 0x00010002 and gdef.MarkGlyphSetsDef) - ): - del varfont["GDEF"] - - -def _isValidAvarSegmentMap(axisTag, segmentMap): - if not segmentMap: - return True - if not {(-1.0, -1.0), (0, 0), (1.0, 1.0)}.issubset(segmentMap.items()): - log.warning( - f"Invalid avar SegmentMap record for axis '{axisTag}': does not " - "include all required value maps {-1.0: -1.0, 0: 0, 1.0: 1.0}" - ) - return False - previousValue = None - for fromCoord, toCoord in sorted(segmentMap.items()): - if previousValue is not None and previousValue > toCoord: - log.warning( - f"Invalid avar AxisValueMap({fromCoord}, {toCoord}) record " - f"for axis '{axisTag}': the toCoordinate value must be >= to " - f"the toCoordinate value of the preceding record ({previousValue})." - ) - return False - previousValue = toCoord - return True - - -def instantiateAvar(varfont, axisLimits): - # 'axisLimits' dict must contain user-space (non-normalized) coordinates. - - segments = varfont["avar"].segments - - # drop table if we instantiate all the axes - pinnedAxes = set(axisLimits.pinnedLocation()) - if pinnedAxes.issuperset(segments): - log.info("Dropping avar table") - del varfont["avar"] - return - - log.info("Instantiating avar table") - for axis in pinnedAxes: - if axis in segments: - del segments[axis] - - # First compute the default normalization for axisLimits coordinates: i.e. - # min = -1.0, default = 0, max = +1.0, and in between values interpolated linearly, - # without using the avar table's mappings. - # Then, for each SegmentMap, if we are restricting its axis, compute the new - # mappings by dividing the key/value pairs by the desired new min/max values, - # dropping any mappings that fall outside the restricted range. - # The keys ('fromCoord') are specified in default normalized coordinate space, - # whereas the values ('toCoord') are "mapped forward" using the SegmentMap. - normalizedRanges = axisLimits.normalize(varfont, usingAvar=False) - newSegments = {} - for axisTag, mapping in segments.items(): - if not _isValidAvarSegmentMap(axisTag, mapping): - continue - if mapping and axisTag in normalizedRanges: - axisRange = normalizedRanges[axisTag] - mappedMin = floatToFixedToFloat( - piecewiseLinearMap(axisRange.minimum, mapping), 14 - ) - mappedDef = floatToFixedToFloat( - piecewiseLinearMap(axisRange.default, mapping), 14 - ) - mappedMax = floatToFixedToFloat( - piecewiseLinearMap(axisRange.maximum, mapping), 14 - ) - mappedAxisLimit = NormalizedAxisTripleAndDistances( - mappedMin, - mappedDef, - mappedMax, - axisRange.distanceNegative, - axisRange.distancePositive, - ) - newMapping = {} - for fromCoord, toCoord in mapping.items(): - if fromCoord < axisRange.minimum or fromCoord > axisRange.maximum: - continue - fromCoord = axisRange.renormalizeValue(fromCoord) - - assert mappedMin <= toCoord <= mappedMax - toCoord = mappedAxisLimit.renormalizeValue(toCoord) - - fromCoord = floatToFixedToFloat(fromCoord, 14) - toCoord = floatToFixedToFloat(toCoord, 14) - newMapping[fromCoord] = toCoord - newMapping.update({-1.0: -1.0, 0.0: 0.0, 1.0: 1.0}) - newSegments[axisTag] = newMapping - else: - newSegments[axisTag] = mapping - varfont["avar"].segments = newSegments - - -def isInstanceWithinAxisRanges(location, axisRanges): - for axisTag, coord in location.items(): - if axisTag in axisRanges: - axisRange = axisRanges[axisTag] - if coord < axisRange.minimum or coord > axisRange.maximum: - return False - return True - - -def instantiateFvar(varfont, axisLimits): - # 'axisLimits' dict must contain user-space (non-normalized) coordinates - - location = axisLimits.pinnedLocation() - - fvar = varfont["fvar"] - - # drop table if we instantiate all the axes - if set(location).issuperset(axis.axisTag for axis in fvar.axes): - log.info("Dropping fvar table") - del varfont["fvar"] - return - - log.info("Instantiating fvar table") - - axes = [] - for axis in fvar.axes: - axisTag = axis.axisTag - if axisTag in location: - continue - if axisTag in axisLimits: - triple = axisLimits[axisTag] - if triple.default is None: - triple = (triple.minimum, axis.defaultValue, triple.maximum) - axis.minValue, axis.defaultValue, axis.maxValue = triple - axes.append(axis) - fvar.axes = axes - - # only keep NamedInstances whose coordinates == pinned axis location - instances = [] - for instance in fvar.instances: - if any(instance.coordinates[axis] != value for axis, value in location.items()): - continue - for axisTag in location: - del instance.coordinates[axisTag] - if not isInstanceWithinAxisRanges(instance.coordinates, axisLimits): - continue - instances.append(instance) - fvar.instances = instances - - -def instantiateSTAT(varfont, axisLimits): - # 'axisLimits' dict must contain user-space (non-normalized) coordinates - - stat = varfont["STAT"].table - if not stat.DesignAxisRecord or not ( - stat.AxisValueArray and stat.AxisValueArray.AxisValue - ): - return # STAT table empty, nothing to do - - log.info("Instantiating STAT table") - newAxisValueTables = axisValuesFromAxisLimits(stat, axisLimits) - stat.AxisValueCount = len(newAxisValueTables) - if stat.AxisValueCount: - stat.AxisValueArray.AxisValue = newAxisValueTables - else: - stat.AxisValueArray = None - - -def axisValuesFromAxisLimits(stat, axisLimits): - def isAxisValueOutsideLimits(axisTag, axisValue): - if axisTag in axisLimits: - triple = axisLimits[axisTag] - if axisValue < triple.minimum or axisValue > triple.maximum: - return True - return False - - # only keep AxisValues whose axis is not pinned nor restricted, or is pinned at the - # exact (nominal) value, or is restricted but the value is within the new range - designAxes = stat.DesignAxisRecord.Axis - newAxisValueTables = [] - for axisValueTable in stat.AxisValueArray.AxisValue: - axisValueFormat = axisValueTable.Format - if axisValueFormat in (1, 2, 3): - axisTag = designAxes[axisValueTable.AxisIndex].AxisTag - if axisValueFormat == 2: - axisValue = axisValueTable.NominalValue - else: - axisValue = axisValueTable.Value - if isAxisValueOutsideLimits(axisTag, axisValue): - continue - elif axisValueFormat == 4: - # drop 'non-analytic' AxisValue if _any_ AxisValueRecord doesn't match - # the pinned location or is outside range - dropAxisValueTable = False - for rec in axisValueTable.AxisValueRecord: - axisTag = designAxes[rec.AxisIndex].AxisTag - axisValue = rec.Value - if isAxisValueOutsideLimits(axisTag, axisValue): - dropAxisValueTable = True - break - if dropAxisValueTable: - continue - else: - log.warning("Unknown AxisValue table format (%s); ignored", axisValueFormat) - newAxisValueTables.append(axisValueTable) - return newAxisValueTables - - -def setMacOverlapFlags(glyfTable): - flagOverlapCompound = _g_l_y_f.OVERLAP_COMPOUND - flagOverlapSimple = _g_l_y_f.flagOverlapSimple - for glyphName in glyfTable.keys(): - glyph = glyfTable[glyphName] - # Set OVERLAP_COMPOUND bit for compound glyphs - if glyph.isComposite(): - glyph.components[0].flags |= flagOverlapCompound - # Set OVERLAP_SIMPLE bit for simple glyphs - elif glyph.numberOfContours > 0: - glyph.flags[0] |= flagOverlapSimple - - -def normalize(value, triple, avarMapping): - value = normalizeValue(value, triple) - if avarMapping: - value = piecewiseLinearMap(value, avarMapping) - # Quantize to F2Dot14, to avoid surprise interpolations. - return floatToFixedToFloat(value, 14) - - -def sanityCheckVariableTables(varfont): - if "fvar" not in varfont: - raise ValueError("Missing required table fvar") - if "gvar" in varfont: - if "glyf" not in varfont: - raise ValueError("Can't have gvar without glyf") - # TODO(anthrotype) Remove once we do support partial instancing CFF2 - if "CFF2" in varfont: - raise NotImplementedError("Instancing CFF2 variable fonts is not supported yet") - - -def instantiateVariableFont( - varfont, - axisLimits, - inplace=False, - optimize=True, - overlap=OverlapMode.KEEP_AND_SET_FLAGS, - updateFontNames=False, -): - """Instantiate variable font, either fully or partially. - - Depending on whether the `axisLimits` dictionary references all or some of the - input varfont's axes, the output font will either be a full instance (static - font) or a variable font with possibly less variation data. - - Args: - varfont: a TTFont instance, which must contain at least an 'fvar' table. - Note that variable fonts with 'CFF2' table are not supported yet. - axisLimits: a dict keyed by axis tags (str) containing the coordinates (float) - along one or more axes where the desired instance will be located. - If the value is `None`, the default coordinate as per 'fvar' table for - that axis is used. - The limit values can also be (min, max) tuples for restricting an - axis's variation range. The default axis value must be included in - the new range. - inplace (bool): whether to modify input TTFont object in-place instead of - returning a distinct object. - optimize (bool): if False, do not perform IUP-delta optimization on the - remaining 'gvar' table's deltas. Possibly faster, and might work around - rendering issues in some buggy environments, at the cost of a slightly - larger file size. - overlap (OverlapMode): variable fonts usually contain overlapping contours, and - some font rendering engines on Apple platforms require that the - `OVERLAP_SIMPLE` and `OVERLAP_COMPOUND` flags in the 'glyf' table be set to - force rendering using a non-zero fill rule. Thus we always set these flags - on all glyphs to maximise cross-compatibility of the generated instance. - You can disable this by passing OverlapMode.KEEP_AND_DONT_SET_FLAGS. - If you want to remove the overlaps altogether and merge overlapping - contours and components, you can pass OverlapMode.REMOVE (or - REMOVE_AND_IGNORE_ERRORS to not hard-fail on tricky glyphs). Note that this - requires the skia-pathops package (available to pip install). - The overlap parameter only has effect when generating full static instances. - updateFontNames (bool): if True, update the instantiated font's name table using - the Axis Value Tables from the STAT table. The name table and the style bits - in the head and OS/2 table will be updated so they conform to the R/I/B/BI - model. If the STAT table is missing or an Axis Value table is missing for - a given axis coordinate, a ValueError will be raised. - """ - # 'overlap' used to be bool and is now enum; for backward compat keep accepting bool - overlap = OverlapMode(int(overlap)) - - sanityCheckVariableTables(varfont) - - axisLimits = AxisLimits(axisLimits).limitAxesAndPopulateDefaults(varfont) - - log.info("Restricted limits: %s", axisLimits) - - normalizedLimits = axisLimits.normalize(varfont) - - log.info("Normalized limits: %s", normalizedLimits) - - if not inplace: - varfont = deepcopy(varfont) - - if "DSIG" in varfont: - del varfont["DSIG"] - - if updateFontNames: - log.info("Updating name table") - names.updateNameTable(varfont, axisLimits) - - if "gvar" in varfont: - instantiateGvar(varfont, normalizedLimits, optimize=optimize) - - if "cvar" in varfont: - instantiateCvar(varfont, normalizedLimits) - - if "MVAR" in varfont: - instantiateMVAR(varfont, normalizedLimits) - - if "HVAR" in varfont: - instantiateHVAR(varfont, normalizedLimits) - - if "VVAR" in varfont: - instantiateVVAR(varfont, normalizedLimits) - - instantiateOTL(varfont, normalizedLimits) - - instantiateFeatureVariations(varfont, normalizedLimits) - - if "avar" in varfont: - instantiateAvar(varfont, axisLimits) - - with names.pruningUnusedNames(varfont): - if "STAT" in varfont: - instantiateSTAT(varfont, axisLimits) - - instantiateFvar(varfont, axisLimits) - - if "fvar" not in varfont: - if "glyf" in varfont: - if overlap == OverlapMode.KEEP_AND_SET_FLAGS: - setMacOverlapFlags(varfont["glyf"]) - elif overlap in (OverlapMode.REMOVE, OverlapMode.REMOVE_AND_IGNORE_ERRORS): - from fontTools.ttLib.removeOverlaps import removeOverlaps - - log.info("Removing overlaps from glyf table") - removeOverlaps( - varfont, - ignoreErrors=(overlap == OverlapMode.REMOVE_AND_IGNORE_ERRORS), - ) - - varLib.set_default_weight_width_slant( - varfont, location=axisLimits.defaultLocation() - ) - - if updateFontNames: - # Set Regular/Italic/Bold/Bold Italic bits as appropriate, after the - # name table has been updated. - setRibbiBits(varfont) - - return varfont - - -def setRibbiBits(font): - """Set the `head.macStyle` and `OS/2.fsSelection` style bits - appropriately.""" - - english_ribbi_style = font["name"].getName(names.NameID.SUBFAMILY_NAME, 3, 1, 0x409) - if english_ribbi_style is None: - return - - styleMapStyleName = english_ribbi_style.toStr().lower() - if styleMapStyleName not in {"regular", "bold", "italic", "bold italic"}: - return - - if styleMapStyleName == "bold": - font["head"].macStyle = 0b01 - elif styleMapStyleName == "bold italic": - font["head"].macStyle = 0b11 - elif styleMapStyleName == "italic": - font["head"].macStyle = 0b10 - - selection = font["OS/2"].fsSelection - # First clear... - selection &= ~(1 << 0) - selection &= ~(1 << 5) - selection &= ~(1 << 6) - # ...then re-set the bits. - if styleMapStyleName == "regular": - selection |= 1 << 6 - elif styleMapStyleName == "bold": - selection |= 1 << 5 - elif styleMapStyleName == "italic": - selection |= 1 << 0 - elif styleMapStyleName == "bold italic": - selection |= 1 << 0 - selection |= 1 << 5 - font["OS/2"].fsSelection = selection - - -def parseLimits(limits: Iterable[str]) -> Dict[str, Optional[AxisTriple]]: - result = {} - for limitString in limits: - match = re.match( - r"^(\w{1,4})=(?:(drop)|(?:([^:]+)(?:[:]([^:]+))?(?:[:]([^:]+))?))$", - limitString, - ) - if not match: - raise ValueError("invalid location format: %r" % limitString) - tag = match.group(1).ljust(4) - if match.group(2): # 'drop' - lbound = None - else: - lbound = strToFixedToFloat(match.group(3), precisionBits=16) - ubound = default = lbound - if match.group(4): - ubound = default = strToFixedToFloat(match.group(4), precisionBits=16) - default = None - if match.group(5): - default = ubound - ubound = strToFixedToFloat(match.group(5), precisionBits=16) - - if all(v is None for v in (lbound, default, ubound)): - result[tag] = None - continue - - result[tag] = AxisTriple(lbound, default, ubound) - - return result - - -def parseArgs(args): - """Parse argv. - - Returns: - 3-tuple (infile, axisLimits, options) - axisLimits is either a Dict[str, Optional[float]], for pinning variation axes - to specific coordinates along those axes (with `None` as a placeholder for an - axis' default value); or a Dict[str, Tuple(float, float)], meaning limit this - axis to min/max range. - Axes locations are in user-space coordinates, as defined in the "fvar" table. - """ - from fontTools import configLogger - import argparse - - parser = argparse.ArgumentParser( - "fonttools varLib.instancer", - description="Partially instantiate a variable font", - ) - parser.add_argument("input", metavar="INPUT.ttf", help="Input variable TTF file.") - parser.add_argument( - "locargs", - metavar="AXIS=LOC", - nargs="*", - help="List of space separated locations. A location consists of " - "the tag of a variation axis, followed by '=' and one of number, " - "number:number or the literal string 'drop'. " - "E.g.: wdth=100 or wght=75.0:125.0 or wght=drop", - ) - parser.add_argument( - "-o", - "--output", - metavar="OUTPUT.ttf", - default=None, - help="Output instance TTF file (default: INPUT-instance.ttf).", - ) - parser.add_argument( - "--no-optimize", - dest="optimize", - action="store_false", - help="Don't perform IUP optimization on the remaining gvar TupleVariations", - ) - parser.add_argument( - "--no-overlap-flag", - dest="overlap", - action="store_false", - help="Don't set OVERLAP_SIMPLE/OVERLAP_COMPOUND glyf flags (only applicable " - "when generating a full instance)", - ) - parser.add_argument( - "--remove-overlaps", - dest="remove_overlaps", - action="store_true", - help="Merge overlapping contours and components (only applicable " - "when generating a full instance). Requires skia-pathops", - ) - parser.add_argument( - "--ignore-overlap-errors", - dest="ignore_overlap_errors", - action="store_true", - help="Don't crash if the remove-overlaps operation fails for some glyphs.", - ) - parser.add_argument( - "--update-name-table", - action="store_true", - help="Update the instantiated font's `name` table. Input font must have " - "a STAT table with Axis Value Tables", - ) - parser.add_argument( - "--no-recalc-timestamp", - dest="recalc_timestamp", - action="store_false", - help="Don't set the output font's timestamp to the current time.", - ) - parser.add_argument( - "--no-recalc-bounds", - dest="recalc_bounds", - action="store_false", - help="Don't recalculate font bounding boxes", - ) - loggingGroup = parser.add_mutually_exclusive_group(required=False) - loggingGroup.add_argument( - "-v", "--verbose", action="store_true", help="Run more verbosely." - ) - loggingGroup.add_argument( - "-q", "--quiet", action="store_true", help="Turn verbosity off." - ) - options = parser.parse_args(args) - - if options.remove_overlaps: - if options.ignore_overlap_errors: - options.overlap = OverlapMode.REMOVE_AND_IGNORE_ERRORS - else: - options.overlap = OverlapMode.REMOVE - else: - options.overlap = OverlapMode(int(options.overlap)) - - infile = options.input - if not os.path.isfile(infile): - parser.error("No such file '{}'".format(infile)) - - configLogger( - level=("DEBUG" if options.verbose else "ERROR" if options.quiet else "INFO") - ) - - try: - axisLimits = parseLimits(options.locargs) - except ValueError as e: - parser.error(str(e)) - - if len(axisLimits) != len(options.locargs): - parser.error("Specified multiple limits for the same axis") - - return (infile, axisLimits, options) - - -def main(args=None): - """Partially instantiate a variable font""" - infile, axisLimits, options = parseArgs(args) - log.info("Restricting axes: %s", axisLimits) - - log.info("Loading variable font") - varfont = TTFont( - infile, - recalcTimestamp=options.recalc_timestamp, - recalcBBoxes=options.recalc_bounds, - ) - - isFullInstance = { - axisTag for axisTag, limit in axisLimits.items() if not isinstance(limit, tuple) - }.issuperset(axis.axisTag for axis in varfont["fvar"].axes) - - instantiateVariableFont( - varfont, - axisLimits, - inplace=True, - optimize=options.optimize, - overlap=options.overlap, - updateFontNames=options.update_name_table, - ) - - suffix = "-instance" if isFullInstance else "-partial" - outfile = ( - makeOutputFileName(infile, overWrite=True, suffix=suffix) - if not options.output - else options.output - ) - - log.info( - "Saving %s font %s", - "instance" if isFullInstance else "partial variable", - outfile, - ) - varfont.save(outfile) diff --git a/spaces/johnslegers/ImageProcessService/start.py b/spaces/johnslegers/ImageProcessService/start.py deleted file mode 100644 index 7e8dee855ac1295bb98943d96d5044cce3d3de29..0000000000000000000000000000000000000000 --- a/spaces/johnslegers/ImageProcessService/start.py +++ /dev/null @@ -1,74 +0,0 @@ -import os -import logging -import sys - -from gunicorn.app.base import BaseApplication -from gunicorn.glogging import Logger -from loguru import logger - -from modules.server import routes - -#LOG_LEVEL = logging.getLevelName(os.environ.get("LOG_LEVEL", "DEBUG")) -LOG_LEVEL = "DEBUG" -JSON_LOGS = True if os.environ.get("JSON_LOGS", "0") == "1" else False -WORKERS = int(os.environ.get("GUNICORN_WORKERS", "5")) - - -class InterceptHandler(logging.Handler): - def emit(self, record): - # Get corresponding Loguru level if it exists - try: - level = logger.level(record.levelname).name - except ValueError: - level = record.levelno - - # Find caller from where originated the logged message - frame, depth = logging.currentframe(), 2 - while frame.f_code.co_filename == logging.__file__: - frame = frame.f_back - depth += 1 - - logger.opt(depth=depth, exception=record.exc_info).log(level, record.getMessage()) - - -class GunicornLogger(Logger): - def setup(self, cfg) -> None: - handler = InterceptHandler() - - # Add log handler to logger and set log level - self.error_log.addHandler(handler) - self.error_log.setLevel(LOG_LEVEL) - self.access_log.addHandler(handler) - self.access_log.setLevel(LOG_LEVEL) - - # Configure logger before gunicorn starts logging - logger.configure(handlers=[{"sink": sys.stdout, "level": LOG_LEVEL}]) - - -class StandaloneApplication(BaseApplication): - """Our Gunicorn application.""" - - def __init__(self, app, options=None): - self.options = options or {} - self.application = app - super().__init__() - - def load_config(self): - config = { - key: value for key, value in self.options.items() - if key in self.cfg.settings and value is not None - } - for key, value in config.items(): - self.cfg.set(key.lower(), value) - - def load(self): - return self.application - - -if __name__ == '__main__': - StandaloneApplication(routes, { - "bind": "0.0.0.0:7860", - "workers": WORKERS, - "worker_class": "uvicorn.workers.UvicornWorker", - "logger_class": GunicornLogger - }).run() diff --git a/spaces/johnslegers/stable-diffusion-gui-test/ldmlib/models/diffusion/plms.py b/spaces/johnslegers/stable-diffusion-gui-test/ldmlib/models/diffusion/plms.py deleted file mode 100644 index 1f7297a1e71e5dffb3008b0ff1cca57569777ada..0000000000000000000000000000000000000000 --- a/spaces/johnslegers/stable-diffusion-gui-test/ldmlib/models/diffusion/plms.py +++ /dev/null @@ -1,236 +0,0 @@ -"""SAMPLING ONLY.""" - -import torch -import numpy as np -from tqdm import tqdm -from functools import partial - -from ldmlib.modules.diffusionmodules.util import make_ddim_sampling_parameters, make_ddim_timesteps, noise_like - - -class PLMSSampler(object): - def __init__(self, model, schedule="linear", **kwargs): - super().__init__() - self.model = model - self.ddpm_num_timesteps = model.num_timesteps - self.schedule = schedule - - def register_buffer(self, name, attr): - if type(attr) == torch.Tensor: - if attr.device != torch.device("cuda"): - attr = attr.to(torch.device("cuda")) - setattr(self, name, attr) - - def make_schedule(self, ddim_num_steps, ddim_discretize="uniform", ddim_eta=0., verbose=True): - if ddim_eta != 0: - raise ValueError('ddim_eta must be 0 for PLMS') - self.ddim_timesteps = make_ddim_timesteps(ddim_discr_method=ddim_discretize, num_ddim_timesteps=ddim_num_steps, - num_ddpm_timesteps=self.ddpm_num_timesteps,verbose=verbose) - alphas_cumprod = self.model.alphas_cumprod - assert alphas_cumprod.shape[0] == self.ddpm_num_timesteps, 'alphas have to be defined for each timestep' - to_torch = lambda x: x.clone().detach().to(torch.float32).to(self.model.device) - - self.register_buffer('betas', to_torch(self.model.betas)) - self.register_buffer('alphas_cumprod', to_torch(alphas_cumprod)) - self.register_buffer('alphas_cumprod_prev', to_torch(self.model.alphas_cumprod_prev)) - - # calculations for diffusion q(x_t | x_{t-1}) and others - self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod.cpu()))) - self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod.cpu()))) - self.register_buffer('log_one_minus_alphas_cumprod', to_torch(np.log(1. - alphas_cumprod.cpu()))) - self.register_buffer('sqrt_recip_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod.cpu()))) - self.register_buffer('sqrt_recipm1_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod.cpu() - 1))) - - # ddim sampling parameters - ddim_sigmas, ddim_alphas, ddim_alphas_prev = make_ddim_sampling_parameters(alphacums=alphas_cumprod.cpu(), - ddim_timesteps=self.ddim_timesteps, - eta=ddim_eta,verbose=verbose) - self.register_buffer('ddim_sigmas', ddim_sigmas) - self.register_buffer('ddim_alphas', ddim_alphas) - self.register_buffer('ddim_alphas_prev', ddim_alphas_prev) - self.register_buffer('ddim_sqrt_one_minus_alphas', np.sqrt(1. - ddim_alphas)) - sigmas_for_original_sampling_steps = ddim_eta * torch.sqrt( - (1 - self.alphas_cumprod_prev) / (1 - self.alphas_cumprod) * ( - 1 - self.alphas_cumprod / self.alphas_cumprod_prev)) - self.register_buffer('ddim_sigmas_for_original_num_steps', sigmas_for_original_sampling_steps) - - @torch.no_grad() - def sample(self, - S, - batch_size, - shape, - conditioning=None, - callback=None, - normals_sequence=None, - img_callback=None, - quantize_x0=False, - eta=0., - mask=None, - x0=None, - temperature=1., - noise_dropout=0., - score_corrector=None, - corrector_kwargs=None, - verbose=True, - x_T=None, - log_every_t=100, - unconditional_guidance_scale=1., - unconditional_conditioning=None, - # this has to come in the same format as the conditioning, # e.g. as encoded tokens, ... - **kwargs - ): - if conditioning is not None: - if isinstance(conditioning, dict): - cbs = conditioning[list(conditioning.keys())[0]].shape[0] - if cbs != batch_size: - print(f"Warning: Got {cbs} conditionings but batch-size is {batch_size}") - else: - if conditioning.shape[0] != batch_size: - print(f"Warning: Got {conditioning.shape[0]} conditionings but batch-size is {batch_size}") - - self.make_schedule(ddim_num_steps=S, ddim_eta=eta, verbose=verbose) - # sampling - C, H, W = shape - size = (batch_size, C, H, W) - print(f'Data shape for PLMS sampling is {size}') - - samples, intermediates = self.plms_sampling(conditioning, size, - callback=callback, - img_callback=img_callback, - quantize_denoised=quantize_x0, - mask=mask, x0=x0, - ddim_use_original_steps=False, - noise_dropout=noise_dropout, - temperature=temperature, - score_corrector=score_corrector, - corrector_kwargs=corrector_kwargs, - x_T=x_T, - log_every_t=log_every_t, - unconditional_guidance_scale=unconditional_guidance_scale, - unconditional_conditioning=unconditional_conditioning, - ) - return samples, intermediates - - @torch.no_grad() - def plms_sampling(self, cond, shape, - x_T=None, ddim_use_original_steps=False, - callback=None, timesteps=None, quantize_denoised=False, - mask=None, x0=None, img_callback=None, log_every_t=100, - temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None, - unconditional_guidance_scale=1., unconditional_conditioning=None,): - device = self.model.betas.device - b = shape[0] - if x_T is None: - img = torch.randn(shape, device=device) - else: - img = x_T - - if timesteps is None: - timesteps = self.ddpm_num_timesteps if ddim_use_original_steps else self.ddim_timesteps - elif timesteps is not None and not ddim_use_original_steps: - subset_end = int(min(timesteps / self.ddim_timesteps.shape[0], 1) * self.ddim_timesteps.shape[0]) - 1 - timesteps = self.ddim_timesteps[:subset_end] - - intermediates = {'x_inter': [img], 'pred_x0': [img]} - time_range = list(reversed(range(0,timesteps))) if ddim_use_original_steps else np.flip(timesteps) - total_steps = timesteps if ddim_use_original_steps else timesteps.shape[0] - print(f"Running PLMS Sampling with {total_steps} timesteps") - - iterator = tqdm(time_range, desc='PLMS Sampler', total=total_steps) - old_eps = [] - - for i, step in enumerate(iterator): - index = total_steps - i - 1 - ts = torch.full((b,), step, device=device, dtype=torch.long) - ts_next = torch.full((b,), time_range[min(i + 1, len(time_range) - 1)], device=device, dtype=torch.long) - - if mask is not None: - assert x0 is not None - img_orig = self.model.q_sample(x0, ts) # TODO: deterministic forward pass? - img = img_orig * mask + (1. - mask) * img - - outs = self.p_sample_plms(img, cond, ts, index=index, use_original_steps=ddim_use_original_steps, - quantize_denoised=quantize_denoised, temperature=temperature, - noise_dropout=noise_dropout, score_corrector=score_corrector, - corrector_kwargs=corrector_kwargs, - unconditional_guidance_scale=unconditional_guidance_scale, - unconditional_conditioning=unconditional_conditioning, - old_eps=old_eps, t_next=ts_next) - img, pred_x0, e_t = outs - old_eps.append(e_t) - if len(old_eps) >= 4: - old_eps.pop(0) - if callback: callback(i) - if img_callback: img_callback(pred_x0, i) - - if index % log_every_t == 0 or index == total_steps - 1: - intermediates['x_inter'].append(img) - intermediates['pred_x0'].append(pred_x0) - - return img, intermediates - - @torch.no_grad() - def p_sample_plms(self, x, c, t, index, repeat_noise=False, use_original_steps=False, quantize_denoised=False, - temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None, - unconditional_guidance_scale=1., unconditional_conditioning=None, old_eps=None, t_next=None): - b, *_, device = *x.shape, x.device - - def get_model_output(x, t): - if unconditional_conditioning is None or unconditional_guidance_scale == 1.: - e_t = self.model.apply_model(x, t, c) - else: - x_in = torch.cat([x] * 2) - t_in = torch.cat([t] * 2) - c_in = torch.cat([unconditional_conditioning, c]) - e_t_uncond, e_t = self.model.apply_model(x_in, t_in, c_in).chunk(2) - e_t = e_t_uncond + unconditional_guidance_scale * (e_t - e_t_uncond) - - if score_corrector is not None: - assert self.model.parameterization == "eps" - e_t = score_corrector.modify_score(self.model, e_t, x, t, c, **corrector_kwargs) - - return e_t - - alphas = self.model.alphas_cumprod if use_original_steps else self.ddim_alphas - alphas_prev = self.model.alphas_cumprod_prev if use_original_steps else self.ddim_alphas_prev - sqrt_one_minus_alphas = self.model.sqrt_one_minus_alphas_cumprod if use_original_steps else self.ddim_sqrt_one_minus_alphas - sigmas = self.model.ddim_sigmas_for_original_num_steps if use_original_steps else self.ddim_sigmas - - def get_x_prev_and_pred_x0(e_t, index): - # select parameters corresponding to the currently considered timestep - a_t = torch.full((b, 1, 1, 1), alphas[index], device=device) - a_prev = torch.full((b, 1, 1, 1), alphas_prev[index], device=device) - sigma_t = torch.full((b, 1, 1, 1), sigmas[index], device=device) - sqrt_one_minus_at = torch.full((b, 1, 1, 1), sqrt_one_minus_alphas[index],device=device) - - # current prediction for x_0 - pred_x0 = (x - sqrt_one_minus_at * e_t) / a_t.sqrt() - if quantize_denoised: - pred_x0, _, *_ = self.model.first_stage_model.quantize(pred_x0) - # direction pointing to x_t - dir_xt = (1. - a_prev - sigma_t**2).sqrt() * e_t - noise = sigma_t * noise_like(x.shape, device, repeat_noise) * temperature - if noise_dropout > 0.: - noise = torch.nn.functional.dropout(noise, p=noise_dropout) - x_prev = a_prev.sqrt() * pred_x0 + dir_xt + noise - return x_prev, pred_x0 - - e_t = get_model_output(x, t) - if len(old_eps) == 0: - # Pseudo Improved Euler (2nd order) - x_prev, pred_x0 = get_x_prev_and_pred_x0(e_t, index) - e_t_next = get_model_output(x_prev, t_next) - e_t_prime = (e_t + e_t_next) / 2 - elif len(old_eps) == 1: - # 2nd order Pseudo Linear Multistep (Adams-Bashforth) - e_t_prime = (3 * e_t - old_eps[-1]) / 2 - elif len(old_eps) == 2: - # 3nd order Pseudo Linear Multistep (Adams-Bashforth) - e_t_prime = (23 * e_t - 16 * old_eps[-1] + 5 * old_eps[-2]) / 12 - elif len(old_eps) >= 3: - # 4nd order Pseudo Linear Multistep (Adams-Bashforth) - e_t_prime = (55 * e_t - 59 * old_eps[-1] + 37 * old_eps[-2] - 9 * old_eps[-3]) / 24 - - x_prev, pred_x0 = get_x_prev_and_pred_x0(e_t_prime, index) - - return x_prev, pred_x0, e_t diff --git a/spaces/jone/GFPGAN/PaperModel.md b/spaces/jone/GFPGAN/PaperModel.md deleted file mode 100644 index aec81d31de56df74c19ae840d44ad2b2a1f06d28..0000000000000000000000000000000000000000 --- a/spaces/jone/GFPGAN/PaperModel.md +++ /dev/null @@ -1,76 +0,0 @@ -# Installation - -We now provide a *clean* version of GFPGAN, which does not require customized CUDA extensions. See [here](README.md#installation) for this easier installation.
      -If you want want to use the original model in our paper, please follow the instructions below. - -1. Clone repo - - ```bash - git clone https://github.com/xinntao/GFPGAN.git - cd GFPGAN - ``` - -1. Install dependent packages - - As StyleGAN2 uses customized PyTorch C++ extensions, you need to **compile them during installation** or **load them just-in-time(JIT)**. - You can refer to [BasicSR-INSTALL.md](https://github.com/xinntao/BasicSR/blob/master/INSTALL.md) for more details. - - **Option 1: Load extensions just-in-time(JIT)** (For those just want to do simple inferences, may have less issues) - - ```bash - # Install basicsr - https://github.com/xinntao/BasicSR - # We use BasicSR for both training and inference - pip install basicsr - - # Install facexlib - https://github.com/xinntao/facexlib - # We use face detection and face restoration helper in the facexlib package - pip install facexlib - - pip install -r requirements.txt - python setup.py develop - - # remember to set BASICSR_JIT=True before your running commands - ``` - - **Option 2: Compile extensions during installation** (For those need to train/inference for many times) - - ```bash - # Install basicsr - https://github.com/xinntao/BasicSR - # We use BasicSR for both training and inference - # Set BASICSR_EXT=True to compile the cuda extensions in the BasicSR - It may take several minutes to compile, please be patient - # Add -vvv for detailed log prints - BASICSR_EXT=True pip install basicsr -vvv - - # Install facexlib - https://github.com/xinntao/facexlib - # We use face detection and face restoration helper in the facexlib package - pip install facexlib - - pip install -r requirements.txt - python setup.py develop - ``` - -## :zap: Quick Inference - -Download pre-trained models: [GFPGANv1.pth](https://github.com/TencentARC/GFPGAN/releases/download/v0.1.0/GFPGANv1.pth) - -```bash -wget https://github.com/TencentARC/GFPGAN/releases/download/v0.1.0/GFPGANv1.pth -P experiments/pretrained_models -``` - -- Option 1: Load extensions just-in-time(JIT) - - ```bash - BASICSR_JIT=True python inference_gfpgan.py --model_path experiments/pretrained_models/GFPGANv1.pth --test_path inputs/whole_imgs --save_root results --arch original --channel 1 - - # for aligned images - BASICSR_JIT=True python inference_gfpgan.py --model_path experiments/pretrained_models/GFPGANv1.pth --test_path inputs/cropped_faces --save_root results --arch original --channel 1 --aligned - ``` - -- Option 2: Have successfully compiled extensions during installation - - ```bash - python inference_gfpgan.py --model_path experiments/pretrained_models/GFPGANv1.pth --test_path inputs/whole_imgs --save_root results --arch original --channel 1 - - # for aligned images - python inference_gfpgan.py --model_path experiments/pretrained_models/GFPGANv1.pth --test_path inputs/cropped_faces --save_root results --arch original --channel 1 --aligned - ``` diff --git a/spaces/jpfearnworks/ai_agents/modules/base/llm_chain_config.py b/spaces/jpfearnworks/ai_agents/modules/base/llm_chain_config.py deleted file mode 100644 index 1d3b1f3ff995305f5ae85a88c69ff6971db527ea..0000000000000000000000000000000000000000 --- a/spaces/jpfearnworks/ai_agents/modules/base/llm_chain_config.py +++ /dev/null @@ -1,19 +0,0 @@ -from pydantic import BaseModel -from langchain.llms.base import BaseLLM -from langchain.llms import OpenAI -from typing import Type - -class LLMChainConfig(BaseModel): - """ - A configuration class for the chain strategy. - - Attributes: - temperature (float): The temperature parameter for the language model. - max_tokens (int): The maximum number of tokens to generate. - llm_class (Type[BaseLLM]): The language model class to use for reasoning. - usage (str): String describing when it is appropriate to use this chain strategy. - """ - temperature: float = 0.7 - max_tokens: int = 1500 - llm_class: Type[BaseLLM] = OpenAI # Overrideable default - usage: str \ No newline at end of file diff --git a/spaces/julien-c/streamlit-cheatsheet/app.py b/spaces/julien-c/streamlit-cheatsheet/app.py deleted file mode 100644 index 78ca9c7edb36b1c88f280dcba94b3cd4c448aa82..0000000000000000000000000000000000000000 --- a/spaces/julien-c/streamlit-cheatsheet/app.py +++ /dev/null @@ -1,304 +0,0 @@ -""" -Streamlit Cheat Sheet - -App to summarise streamlit docs v1.0.0 - -There is also an accompanying png and pdf version - -https://github.com/daniellewisDL/streamlit-cheat-sheet - -v1.0.0 October 2021 - -Author: - @daniellewisDL : https://github.com/daniellewisDL - -Contributors: - arnaudmiribel : https://github.com/arnaudmiribel - akrolsmir : https://github.com/akrolsmir - nathancarter : https://github.com/nathancarter - epogrebnyak : https://github.com/epogrebnyak - -""" - -import streamlit as st -from pathlib import Path -import base64 - -# Initial page config - -st.set_page_config( - page_title='Streamlit cheat sheet', - layout="wide", - initial_sidebar_state="expanded", -) - -def main(): - cs_sidebar() - cs_body() - - return None - -# Thanks to streamlitopedia for the following code snippet - -def img_to_bytes(img_path): - img_bytes = Path(img_path).read_bytes() - encoded = base64.b64encode(img_bytes).decode() - return encoded - -# sidebar - -def cs_sidebar(): - - st.sidebar.markdown('''[](https://streamlit.io/)'''.format(img_to_bytes("logomark_website.png")), unsafe_allow_html=True) - st.sidebar.header('Streamlit cheat sheet') - - st.sidebar.markdown(''' -Summary of the [docs](https://docs.streamlit.io/en/stable/api.html), as of [Streamlit v1.0.0](https://www.streamlit.io/). - ''', unsafe_allow_html=True) - - st.sidebar.markdown('__How to install and import__') - - st.sidebar.code('$ pip install streamlit') - - st.sidebar.markdown('Import convention') - st.sidebar.code('>>> import streamlit as st') - - st.sidebar.markdown('__Add widgets to sidebar__') - st.sidebar.code(''' -st.sidebar. ->>> a = st.sidebar.radio(\'R:\',[1,2]) - ''') - - st.sidebar.markdown('__Command line__') - st.sidebar.code(''' -$ streamlit --help -$ streamlit run your_script.py -$ streamlit hello -$ streamlit config show -$ streamlit cache clear -$ streamlit docs -$ streamlit --version - ''') - - st.sidebar.markdown('__Pre-release features__') - st.sidebar.markdown('[Beta and experimental features](https://docs.streamlit.io/en/stable/api.html#beta-and-experimental-features)') - st.sidebar.code(''' -pip uninstall streamlit -pip install streamlit-nightly --upgrade - ''') - - st.sidebar.markdown('''[st.cheat_sheet v1.0.0](https://github.com/daniellewisDL/streamlit-cheat-sheet) | Oct 2021''', unsafe_allow_html=True) - - return None - -########################## -# Main body of cheat sheet -########################## - -def cs_body(): - # Magic commands - - col1, col2, col3 = st.columns(3) - - col1.subheader('Magic commands') - col1.code('''# Magic commands implicitly `st.write()` -\'\'\' _This_ is some __Markdown__ \'\'\' -a=3 -'dataframe:', data - ''') - - # Display text - - col1.subheader('Display text') - col1.code(''' -st.text('Fixed width text') -st.markdown('_Markdown_') # see * -st.caption('Balloons. Hundreds of them...') -st.latex(r\'\'\' e^{i\pi} + 1 = 0 \'\'\') -st.write('Most objects') # df, err, func, keras! -st.write(['st', 'is <', 3]) # see * -st.title('My title') -st.header('My header') -st.subheader('My sub') -st.code('for i in range(8): foo()') - -* optional kwarg unsafe_allow_html = True - - ''') - - # Display data - - col1.subheader('Display data') - col1.code(''' -st.dataframe(my_dataframe) -st.table(data.iloc[0:10]) -st.json({'foo':'bar','fu':'ba'}) -st.metric(label="Temp", value="273 K", delta="1.2 K") - ''') - - # Display charts - - col1.subheader('Display charts') - col1.code(''' -st.line_chart(data) -st.area_chart(data) -st.bar_chart(data) -st.pyplot(fig) -st.altair_chart(data) -st.vega_lite_chart(data) -st.plotly_chart(data) -st.bokeh_chart(data) -st.pydeck_chart(data) -st.deck_gl_chart(data) -st.graphviz_chart(data) -st.map(data) - ''') - - # Display media - - col1.subheader('Display media') - col1.code(''' -st.image('./header.png') -st.audio(data) -st.video(data) - ''') - - # Display interactive widgets - - col2.subheader('Display interactive widgets') - col2.code(''' -st.button('Hit me') -st.download_button('On the dl', data) -st.checkbox('Check me out') -st.radio('Radio', [1,2,3]) -st.selectbox('Select', [1,2,3]) -st.multiselect('Multiselect', [1,2,3]) -st.slider('Slide me', min_value=0, max_value=10) -st.select_slider('Slide to select', options=[1,'2']) -st.text_input('Enter some text') -st.number_input('Enter a number') -st.text_area('Area for textual entry') -st.date_input('Date input') -st.time_input('Time entry') -st.file_uploader('File uploader') -st.color_picker('Pick a color') - ''') - col2.write('Use widgets\' returned values in variables:') - col2.code(''' ->>> for i in range(int(st.number_input('Num:'))): foo() ->>> if st.sidebar.selectbox('I:',['f']) == 'f': b() ->>> my_slider_val = st.slider('Quinn Mallory', 1, 88) ->>> st.write(slider_val) - ''') - - # Control flow - - col2.subheader('Control flow') - col2.code(''' -st.stop() - ''') - - # Lay out your app - - col2.subheader('Lay out your app') - col2.code(''' -st.form('my_form_identifier') -st.form_submit_button('Submit to me') -st.container() -st.columns(spec) ->>> col1, col2 = st.columns(2) ->>> col1.subheader('Columnisation') -st.expander('Expander') ->>> with st.expander('Expand'): ->>> st.write('Juicy deets') - ''') - - col2.write('Batch widgets together in a form:') - col2.code(''' ->>> with st.form(key='my_form'): ->>> text_input = st.text_input(label='Enter some text') ->>> submit_button = st.form_submit_button(label='Submit') - ''') - - # Display code - - col2.subheader('Display code') - col2.code(''' -st.echo() ->>> with st.echo(): ->>> st.write('Code will be executed and printed') - ''') - - # Display progress and status - - col3.subheader('Display progress and status') - col3.code(''' -st.progress(progress_variable_1_to_100) -st.spinner() ->>> with st.spinner(text='In progress'): ->>> time.sleep(5) ->>> st.success('Done') -st.balloons() -st.error('Error message') -st.warning('Warning message') -st.info('Info message') -st.success('Success message') -st.exception(e) - ''') - - # Placeholders, help, and options - - col3.subheader('Placeholders, help, and options') - col3.code(''' -st.empty() ->>> my_placeholder = st.empty() ->>> my_placeholder.text('Replaced!') -st.help(pandas.DataFrame) -st.get_option(key) -st.set_option(key, value) -st.set_page_config(layout='wide') - ''') - - # Mutate data - - col3.subheader('Mutate data') - col3.code(''' -DeltaGenerator.add_rows(data) ->>> my_table = st.table(df1) ->>> my_table.add_rows(df2) ->>> my_chart = st.line_chart(df1) ->>> my_chart.add_rows(df2) - ''') - - # Optimize performance - - col3.subheader('Optimize performance') - col3.code(''' -@st.cache ->>> @st.cache -... def fetch_and_clean_data(url): -... # Mutate data at url -... return data ->>> # Executes d1 as first time ->>> d1 = fetch_and_clean_data(ref1) ->>> # Does not execute d1; returns cached value, d1==d2 ->>> d2 = fetch_and_clean_data(ref1) ->>> # Different arg, so function d1 executes ->>> d3 = fetch_and_clean_data(ref2) - - ''') - - col3.subheader('Other key parts of the API') - col3.markdown(''' -[State API](https://docs.streamlit.io/en/stable/session_state_api.html)
      -[Theme option reference](https://docs.streamlit.io/en/stable/theme_options.html)
      -[Components API reference](https://docs.streamlit.io/en/stable/develop_streamlit_components.html)
      -[API cheat sheet](https://share.streamlit.io/daniellewisdl/streamlit-cheat-sheet/app.py)
      -''', unsafe_allow_html=True) - - return None - -# Run main() - -if __name__ == '__main__': - main() \ No newline at end of file diff --git a/spaces/kdrkdrkdr/HinaTTS/text/japanese.py b/spaces/kdrkdrkdr/HinaTTS/text/japanese.py deleted file mode 100644 index 65480534b452efabe87b40033316e2c1577ff3ea..0000000000000000000000000000000000000000 --- a/spaces/kdrkdrkdr/HinaTTS/text/japanese.py +++ /dev/null @@ -1,132 +0,0 @@ -import re -from unidecode import unidecode -import pyopenjtalk - - -# Regular expression matching Japanese without punctuation marks: -_japanese_characters = re.compile( - r'[A-Za-z\d\u3005\u3040-\u30ff\u4e00-\u9fff\uff11-\uff19\uff21-\uff3a\uff41-\uff5a\uff66-\uff9d]') - -# Regular expression matching non-Japanese characters or punctuation marks: -_japanese_marks = re.compile( - r'[^A-Za-z\d\u3005\u3040-\u30ff\u4e00-\u9fff\uff11-\uff19\uff21-\uff3a\uff41-\uff5a\uff66-\uff9d]') - -# List of (symbol, Japanese) pairs for marks: -_symbols_to_japanese = [(re.compile('%s' % x[0]), x[1]) for x in [ - ('%', 'パーセント') -]] - -# List of (romaji, ipa) pairs for marks: -_romaji_to_ipa = [(re.compile('%s' % x[0], re.IGNORECASE), x[1]) for x in [ - ('ts', 'ʦ'), - ('u', 'ɯ'), - ('...', '…'), - ('j', 'ʥ'), - ('y', 'j'), - ('ni', 'n^i'), - ('nj', 'n^'), - ('hi', 'çi'), - ('hj', 'ç'), - ('f', 'ɸ'), - ('I', 'i*'), - ('U', 'ɯ*'), - ('r', 'ɾ') -]] - -# Dictinary of (consonant, sokuon) pairs: -_real_sokuon = { - 'k': 'k#', - 'g': 'k#', - 't': 't#', - 'd': 't#', - 'ʦ': 't#', - 'ʧ': 't#', - 'ʥ': 't#', - 'j': 't#', - 's': 's', - 'ʃ': 's', - 'p': 'p#', - 'b': 'p#' -} - -# Dictinary of (consonant, hatsuon) pairs: -_real_hatsuon = { - 'p': 'm', - 'b': 'm', - 'm': 'm', - 't': 'n', - 'd': 'n', - 'n': 'n', - 'ʧ': 'n^', - 'ʥ': 'n^', - 'k': 'ŋ', - 'g': 'ŋ' -} - - -def symbols_to_japanese(text): - for regex, replacement in _symbols_to_japanese: - text = re.sub(regex, replacement, text) - return text - - -def japanese_to_romaji_with_accent(text): - '''Reference https://r9y9.github.io/ttslearn/latest/notebooks/ch10_Recipe-Tacotron.html''' - text = symbols_to_japanese(text) - sentences = re.split(_japanese_marks, text) - marks = re.findall(_japanese_marks, text) - text = '' - for i, sentence in enumerate(sentences): - if re.match(_japanese_characters, sentence): - if text != '': - text += ' ' - labels = pyopenjtalk.extract_fullcontext(sentence) - for n, label in enumerate(labels): - phoneme = re.search(r'\-([^\+]*)\+', label).group(1) - if phoneme not in ['sil', 'pau']: - text += phoneme.replace('ch', 'ʧ').replace('sh', - 'ʃ').replace('cl', 'Q') - else: - continue - # n_moras = int(re.search(r'/F:(\d+)_', label).group(1)) - a1 = int(re.search(r"/A:(\-?[0-9]+)\+", label).group(1)) - a2 = int(re.search(r"\+(\d+)\+", label).group(1)) - a3 = int(re.search(r"\+(\d+)/", label).group(1)) - if re.search(r'\-([^\+]*)\+', labels[n + 1]).group(1) in ['sil', 'pau']: - a2_next = -1 - else: - a2_next = int( - re.search(r"\+(\d+)\+", labels[n + 1]).group(1)) - # Accent phrase boundary - if a3 == 1 and a2_next == 1: - text += ' ' - # Falling - elif a1 == 0 and a2_next == a2 + 1: - text += '↓' - # Rising - elif a2 == 1 and a2_next == 2: - text += '↑' - if i < len(marks): - text += unidecode(marks[i]).replace(' ', '') - return text - - -def get_real_sokuon(text): - text=re.sub('Q[↑↓]*(.)',lambda x:_real_sokuon[x.group(1)]+x.group(0)[1:] if x.group(1) in _real_sokuon.keys() else x.group(0),text) - return text - - -def get_real_hatsuon(text): - text=re.sub('N[↑↓]*(.)',lambda x:_real_hatsuon[x.group(1)]+x.group(0)[1:] if x.group(1) in _real_hatsuon.keys() else x.group(0),text) - return text - - -def japanese_to_ipa(text): - text=japanese_to_romaji_with_accent(text) - for regex, replacement in _romaji_to_ipa: - text = re.sub(regex, replacement, text) - text = re.sub( - r'([A-Za-zɯ])\1+', lambda x: x.group(0)[0]+'ː'*(len(x.group(0))-1), text) - text = get_real_sokuon(text) - text = get_real_hatsuon(text) - return text diff --git a/spaces/keithhon/Real-Time-Voice-Cloning/synthesizer_preprocess_embeds.py b/spaces/keithhon/Real-Time-Voice-Cloning/synthesizer_preprocess_embeds.py deleted file mode 100644 index 94f864d5d3c36c6177b211f5818e7c920a41cd8c..0000000000000000000000000000000000000000 --- a/spaces/keithhon/Real-Time-Voice-Cloning/synthesizer_preprocess_embeds.py +++ /dev/null @@ -1,25 +0,0 @@ -from synthesizer.preprocess import create_embeddings -from utils.argutils import print_args -from pathlib import Path -import argparse - - -if __name__ == "__main__": - parser = argparse.ArgumentParser( - description="Creates embeddings for the synthesizer from the LibriSpeech utterances.", - formatter_class=argparse.ArgumentDefaultsHelpFormatter - ) - parser.add_argument("synthesizer_root", type=Path, help=\ - "Path to the synthesizer training data that contains the audios and the train.txt file. " - "If you let everything as default, it should be /SV2TTS/synthesizer/.") - parser.add_argument("-e", "--encoder_model_fpath", type=Path, - default="encoder/saved_models/pretrained.pt", help=\ - "Path your trained encoder model.") - parser.add_argument("-n", "--n_processes", type=int, default=4, help= \ - "Number of parallel processes. An encoder is created for each, so you may need to lower " - "this value on GPUs with low memory. Set it to 1 if CUDA is unhappy.") - args = parser.parse_args() - - # Preprocess the dataset - print_args(args, parser) - create_embeddings(**vars(args)) diff --git a/spaces/kepl/gpt/get_working_providers.py b/spaces/kepl/gpt/get_working_providers.py deleted file mode 100644 index 37ac5e5eed144fd14eca6fc425cb01c3678896b2..0000000000000000000000000000000000000000 --- a/spaces/kepl/gpt/get_working_providers.py +++ /dev/null @@ -1,7 +0,0 @@ -from g4f.active_providers import get_active_model_providers - -working_providers = get_active_model_providers() - -print("\nWorking providers by model:") -for model, providers in working_providers.items(): - print(f"{model}: {', '.join(providers)}") diff --git a/spaces/kevinwang676/VITS2-Mandarin/data_utils.py b/spaces/kevinwang676/VITS2-Mandarin/data_utils.py deleted file mode 100644 index 87ce3bbc74c6cf430b9d4aeaa8f8ed3751926789..0000000000000000000000000000000000000000 --- a/spaces/kevinwang676/VITS2-Mandarin/data_utils.py +++ /dev/null @@ -1,434 +0,0 @@ -import time -import os -import random -import numpy as np -import torch -import torch.utils.data - -import commons -from mel_processing import spectrogram_torch, mel_spectrogram_torch, spec_to_mel_torch -from utils import load_wav_to_torch, load_filepaths_and_text -from text import text_to_sequence, cleaned_text_to_sequence - - -class TextAudioLoader(torch.utils.data.Dataset): - """ - 1) loads audio, text pairs - 2) normalizes text and converts them to sequences of integers - 3) computes spectrograms from audio files. - """ - def __init__(self, audiopaths_and_text, hparams): - self.hparams = hparams - self.audiopaths_and_text = load_filepaths_and_text(audiopaths_and_text) - self.text_cleaners = hparams.text_cleaners - self.max_wav_value = hparams.max_wav_value - self.sampling_rate = hparams.sampling_rate - self.filter_length = hparams.filter_length - self.hop_length = hparams.hop_length - self.win_length = hparams.win_length - self.sampling_rate = hparams.sampling_rate - - self.use_mel_spec_posterior = getattr(hparams, "use_mel_posterior_encoder", False) - if self.use_mel_spec_posterior: - self.n_mel_channels = getattr(hparams, "n_mel_channels", 80) - self.cleaned_text = getattr(hparams, "cleaned_text", False) - - self.add_blank = hparams.add_blank - self.min_text_len = getattr(hparams, "min_text_len", 1) - self.max_text_len = getattr(hparams, "max_text_len", 190) - - random.seed(1234) - random.shuffle(self.audiopaths_and_text) - self._filter() - - - def _filter(self): - """ - Filter text & store spec lengths - """ - # Store spectrogram lengths for Bucketing - # wav_length ~= file_size / (wav_channels * Bytes per dim) = file_size / (1 * 2) - # spec_length = wav_length // hop_length - - audiopaths_and_text_new = [] - lengths = [] - for audiopath, text in self.audiopaths_and_text: - if self.min_text_len <= len(text) and len(text) <= self.max_text_len: - audiopaths_and_text_new.append([audiopath, text]) - lengths.append(os.path.getsize(audiopath) // (2 * self.hop_length)) - self.audiopaths_and_text = audiopaths_and_text_new - self.lengths = lengths - - def get_audio_text_pair(self, audiopath_and_text): - # separate filename and text - audiopath, text = audiopath_and_text[0], audiopath_and_text[1] - text = self.get_text(text) - spec, wav = self.get_audio(audiopath) - return (text, spec, wav) - - def get_audio(self, filename): - # TODO : if linear spec exists convert to mel from existing linear spec - audio, sampling_rate = load_wav_to_torch(filename) - if sampling_rate != self.sampling_rate: - raise ValueError("{} {} SR doesn't match target {} SR".format( - sampling_rate, self.sampling_rate)) - audio_norm = audio / self.max_wav_value - audio_norm = audio_norm.unsqueeze(0) - spec_filename = filename.replace(".wav", ".spec.pt") - if self.use_mel_spec_posterior: - spec_filename = spec_filename.replace(".spec.pt", ".mel.pt") - if os.path.exists(spec_filename): - spec = torch.load(spec_filename) - else: - if self.use_mel_spec_posterior: - ''' TODO : (need verification) - if linear spec exists convert to - mel from existing linear spec (uncomment below lines) ''' - # if os.path.exists(filename.replace(".wav", ".spec.pt")): - # # spec, n_fft, num_mels, sampling_rate, fmin, fmax - # spec = spec_to_mel_torch( - # torch.load(filename.replace(".wav", ".spec.pt")), - # self.filter_length, self.n_mel_channels, self.sampling_rate, - # self.hparams.mel_fmin, self.hparams.mel_fmax) - spec = mel_spectrogram_torch(audio_norm, self.filter_length, - self.n_mel_channels, self.sampling_rate, self.hop_length, - self.win_length, self.hparams.mel_fmin, self.hparams.mel_fmax, center=False) - else: - spec = spectrogram_torch(audio_norm, self.filter_length, - self.sampling_rate, self.hop_length, self.win_length, - center=False) - spec = torch.squeeze(spec, 0) - torch.save(spec, spec_filename) - return spec, audio_norm - - def get_text(self, text): - if self.cleaned_text: - text_norm = cleaned_text_to_sequence(text) - else: - text_norm = text_to_sequence(text, self.text_cleaners) - if self.add_blank: - text_norm = commons.intersperse(text_norm, 0) - text_norm = torch.LongTensor(text_norm) - return text_norm - - def __getitem__(self, index): - return self.get_audio_text_pair(self.audiopaths_and_text[index]) - - def __len__(self): - return len(self.audiopaths_and_text) - - -class TextAudioCollate(): - """ Zero-pads model inputs and targets - """ - def __init__(self, return_ids=False): - self.return_ids = return_ids - - def __call__(self, batch): - """Collate's training batch from normalized text and aduio - PARAMS - ------ - batch: [text_normalized, spec_normalized, wav_normalized] - """ - # Right zero-pad all one-hot text sequences to max input length - _, ids_sorted_decreasing = torch.sort( - torch.LongTensor([x[1].size(1) for x in batch]), - dim=0, descending=True) - - max_text_len = max([len(x[0]) for x in batch]) - max_spec_len = max([x[1].size(1) for x in batch]) - max_wav_len = max([x[2].size(1) for x in batch]) - - text_lengths = torch.LongTensor(len(batch)) - spec_lengths = torch.LongTensor(len(batch)) - wav_lengths = torch.LongTensor(len(batch)) - - text_padded = torch.LongTensor(len(batch), max_text_len) - spec_padded = torch.FloatTensor(len(batch), batch[0][1].size(0), max_spec_len) - wav_padded = torch.FloatTensor(len(batch), 1, max_wav_len) - text_padded.zero_() - spec_padded.zero_() - wav_padded.zero_() - for i in range(len(ids_sorted_decreasing)): - row = batch[ids_sorted_decreasing[i]] - - text = row[0] - text_padded[i, :text.size(0)] = text - text_lengths[i] = text.size(0) - - spec = row[1] - spec_padded[i, :, :spec.size(1)] = spec - spec_lengths[i] = spec.size(1) - - wav = row[2] - wav_padded[i, :, :wav.size(1)] = wav - wav_lengths[i] = wav.size(1) - - if self.return_ids: - return text_padded, text_lengths, spec_padded, spec_lengths, wav_padded, wav_lengths, ids_sorted_decreasing - return text_padded, text_lengths, spec_padded, spec_lengths, wav_padded, wav_lengths - - -"""Multi speaker version""" -class TextAudioSpeakerLoader(torch.utils.data.Dataset): - """ - 1) loads audio, speaker_id, text pairs - 2) normalizes text and converts them to sequences of integers - 3) computes spectrograms from audio files. - """ - def __init__(self, audiopaths_sid_text, hparams): - self.hparams = hparams - self.audiopaths_sid_text = load_filepaths_and_text(audiopaths_sid_text) - self.text_cleaners = hparams.text_cleaners - self.max_wav_value = hparams.max_wav_value - self.sampling_rate = hparams.sampling_rate - self.filter_length = hparams.filter_length - self.hop_length = hparams.hop_length - self.win_length = hparams.win_length - self.sampling_rate = hparams.sampling_rate - - self.use_mel_spec_posterior = getattr(hparams, "use_mel_posterior_encoder", False) - if self.use_mel_spec_posterior: - self.n_mel_channels = getattr(hparams, "n_mel_channels", 80) - self.cleaned_text = getattr(hparams, "cleaned_text", False) - - self.add_blank = hparams.add_blank - self.min_text_len = getattr(hparams, "min_text_len", 1) - self.max_text_len = getattr(hparams, "max_text_len", 190) - - random.seed(1234) - random.shuffle(self.audiopaths_sid_text) - self._filter() - - def _filter(self): - """ - Filter text & store spec lengths - """ - # Store spectrogram lengths for Bucketing - # wav_length ~= file_size / (wav_channels * Bytes per dim) = file_size / (1 * 2) - # spec_length = wav_length // hop_length - - audiopaths_sid_text_new = [] - lengths = [] - for audiopath, sid, text in self.audiopaths_sid_text: - if self.min_text_len <= len(text) and len(text) <= self.max_text_len: - audiopaths_sid_text_new.append([audiopath, sid, text]) - lengths.append(os.path.getsize(audiopath) // (2 * self.hop_length)) - self.audiopaths_sid_text = audiopaths_sid_text_new - self.lengths = lengths - - def get_audio_text_speaker_pair(self, audiopath_sid_text): - # separate filename, speaker_id and text - audiopath, sid, text = audiopath_sid_text[0], audiopath_sid_text[1], audiopath_sid_text[2] - text = self.get_text(text) - spec, wav = self.get_audio(audiopath) - sid = self.get_sid(sid) - return (text, spec, wav, sid) - - def get_audio(self, filename): - # TODO : if linear spec exists convert to mel from existing linear spec - audio, sampling_rate = load_wav_to_torch(filename) - if sampling_rate != self.sampling_rate: - raise ValueError("{} {} SR doesn't match target {} SR".format( - sampling_rate, self.sampling_rate)) - audio_norm = audio / self.max_wav_value - audio_norm = audio_norm.unsqueeze(0) - spec_filename = filename.replace(".wav", ".spec.pt") - if self.use_mel_spec_posterior: - spec_filename = spec_filename.replace(".spec.pt", ".mel.pt") - if os.path.exists(spec_filename): - spec = torch.load(spec_filename) - else: - if self.use_mel_spec_posterior: - ''' TODO : (need verification) - if linear spec exists convert to - mel from existing linear spec (uncomment below lines) ''' - # if os.path.exists(filename.replace(".wav", ".spec.pt")): - # # spec, n_fft, num_mels, sampling_rate, fmin, fmax - # spec = spec_to_mel_torch( - # torch.load(filename.replace(".wav", ".spec.pt")), - # self.filter_length, self.n_mel_channels, self.sampling_rate, - # self.hparams.mel_fmin, self.hparams.mel_fmax) - spec = mel_spectrogram_torch(audio_norm, self.filter_length, - self.n_mel_channels, self.sampling_rate, self.hop_length, - self.win_length, self.hparams.mel_fmin, self.hparams.mel_fmax, center=False) - else: - spec = spectrogram_torch(audio_norm, self.filter_length, - self.sampling_rate, self.hop_length, self.win_length, - center=False) - spec = torch.squeeze(spec, 0) - torch.save(spec, spec_filename) - return spec, audio_norm - - def get_text(self, text): - if self.cleaned_text: - text_norm = cleaned_text_to_sequence(text) - else: - text_norm = text_to_sequence(text, self.text_cleaners) - if self.add_blank: - text_norm = commons.intersperse(text_norm, 0) - text_norm = torch.LongTensor(text_norm) - return text_norm - - def get_sid(self, sid): - sid = torch.LongTensor([int(sid)]) - return sid - - def __getitem__(self, index): - return self.get_audio_text_speaker_pair(self.audiopaths_sid_text[index]) - - def __len__(self): - return len(self.audiopaths_sid_text) - - -class TextAudioSpeakerCollate(): - """ Zero-pads model inputs and targets - """ - def __init__(self, return_ids=False): - self.return_ids = return_ids - - def __call__(self, batch): - """Collate's training batch from normalized text, audio and speaker identities - PARAMS - ------ - batch: [text_normalized, spec_normalized, wav_normalized, sid] - """ - # Right zero-pad all one-hot text sequences to max input length - _, ids_sorted_decreasing = torch.sort( - torch.LongTensor([x[1].size(1) for x in batch]), - dim=0, descending=True) - - max_text_len = max([len(x[0]) for x in batch]) - max_spec_len = max([x[1].size(1) for x in batch]) - max_wav_len = max([x[2].size(1) for x in batch]) - - text_lengths = torch.LongTensor(len(batch)) - spec_lengths = torch.LongTensor(len(batch)) - wav_lengths = torch.LongTensor(len(batch)) - sid = torch.LongTensor(len(batch)) - - text_padded = torch.LongTensor(len(batch), max_text_len) - spec_padded = torch.FloatTensor(len(batch), batch[0][1].size(0), max_spec_len) - wav_padded = torch.FloatTensor(len(batch), 1, max_wav_len) - text_padded.zero_() - spec_padded.zero_() - wav_padded.zero_() - for i in range(len(ids_sorted_decreasing)): - row = batch[ids_sorted_decreasing[i]] - - text = row[0] - text_padded[i, :text.size(0)] = text - text_lengths[i] = text.size(0) - - spec = row[1] - spec_padded[i, :, :spec.size(1)] = spec - spec_lengths[i] = spec.size(1) - - wav = row[2] - wav_padded[i, :, :wav.size(1)] = wav - wav_lengths[i] = wav.size(1) - - sid[i] = row[3] - - if self.return_ids: - return text_padded, text_lengths, spec_padded, spec_lengths, wav_padded, wav_lengths, sid, ids_sorted_decreasing - return text_padded, text_lengths, spec_padded, spec_lengths, wav_padded, wav_lengths, sid - - -class DistributedBucketSampler(torch.utils.data.distributed.DistributedSampler): - """ - Maintain similar input lengths in a batch. - Length groups are specified by boundaries. - Ex) boundaries = [b1, b2, b3] -> any batch is included either {x | b1 < length(x) <=b2} or {x | b2 < length(x) <= b3}. - - It removes samples which are not included in the boundaries. - Ex) boundaries = [b1, b2, b3] -> any x s.t. length(x) <= b1 or length(x) > b3 are discarded. - """ - def __init__(self, dataset, batch_size, boundaries, num_replicas=None, rank=None, shuffle=True): - super().__init__(dataset, num_replicas=num_replicas, rank=rank, shuffle=shuffle) - self.lengths = dataset.lengths - self.batch_size = batch_size - self.boundaries = boundaries - - self.buckets, self.num_samples_per_bucket = self._create_buckets() - self.total_size = sum(self.num_samples_per_bucket) - self.num_samples = self.total_size // self.num_replicas - - def _create_buckets(self): - buckets = [[] for _ in range(len(self.boundaries) - 1)] - for i in range(len(self.lengths)): - length = self.lengths[i] - idx_bucket = self._bisect(length) - if idx_bucket != -1: - buckets[idx_bucket].append(i) - - for i in range(len(buckets) - 1, 0, -1): - if len(buckets[i]) == 0: - buckets.pop(i) - self.boundaries.pop(i+1) - - num_samples_per_bucket = [] - for i in range(len(buckets)): - len_bucket = len(buckets[i]) - total_batch_size = self.num_replicas * self.batch_size - rem = (total_batch_size - (len_bucket % total_batch_size)) % total_batch_size - num_samples_per_bucket.append(len_bucket + rem) - return buckets, num_samples_per_bucket - - def __iter__(self): - # deterministically shuffle based on epoch - g = torch.Generator() - g.manual_seed(self.epoch) - - indices = [] - if self.shuffle: - for bucket in self.buckets: - indices.append(torch.randperm(len(bucket), generator=g).tolist()) - else: - for bucket in self.buckets: - indices.append(list(range(len(bucket)))) - - batches = [] - for i in range(len(self.buckets)): - bucket = self.buckets[i] - len_bucket = len(bucket) - ids_bucket = indices[i] - num_samples_bucket = self.num_samples_per_bucket[i] - - # add extra samples to make it evenly divisible - rem = num_samples_bucket - len_bucket - ids_bucket = ids_bucket + ids_bucket * (rem // len_bucket) + ids_bucket[:(rem % len_bucket)] - - # subsample - ids_bucket = ids_bucket[self.rank::self.num_replicas] - - # batching - for j in range(len(ids_bucket) // self.batch_size): - batch = [bucket[idx] for idx in ids_bucket[j*self.batch_size:(j+1)*self.batch_size]] - batches.append(batch) - - if self.shuffle: - batch_ids = torch.randperm(len(batches), generator=g).tolist() - batches = [batches[i] for i in batch_ids] - self.batches = batches - - assert len(self.batches) * self.batch_size == self.num_samples - return iter(self.batches) - - def _bisect(self, x, lo=0, hi=None): - if hi is None: - hi = len(self.boundaries) - 1 - - if hi > lo: - mid = (hi + lo) // 2 - if self.boundaries[mid] < x and x <= self.boundaries[mid+1]: - return mid - elif x <= self.boundaries[mid]: - return self._bisect(x, lo, mid) - else: - return self._bisect(x, mid + 1, hi) - else: - return -1 - - def __len__(self): - return self.num_samples // self.batch_size diff --git a/spaces/kevinwang676/VITS2-Mandarin/text/korean.py b/spaces/kevinwang676/VITS2-Mandarin/text/korean.py deleted file mode 100644 index 8d2b549e15e87c5fd84c4ff368ab42e919e3209b..0000000000000000000000000000000000000000 --- a/spaces/kevinwang676/VITS2-Mandarin/text/korean.py +++ /dev/null @@ -1,215 +0,0 @@ -import re -from jamo import h2j, j2hcj -import ko_pron -from g2pk2 import G2p - - -# This is a list of Korean classifiers preceded by pure Korean numerals. -_korean_classifiers = '군데 권 개 그루 닢 대 두 마리 모 모금 뭇 발 발짝 방 번 벌 보루 살 수 술 시 쌈 움큼 정 짝 채 척 첩 축 켤레 톨 통' - -# List of (hangul, hangul divided) pairs: -_hangul_divided = [(re.compile('%s' % x[0]), x[1]) for x in [ - # ('ㄳ', 'ㄱㅅ'), # g2pk2, A Syllable-ending Rule - # ('ㄵ', 'ㄴㅈ'), - # ('ㄶ', 'ㄴㅎ'), - # ('ㄺ', 'ㄹㄱ'), - # ('ㄻ', 'ㄹㅁ'), - # ('ㄼ', 'ㄹㅂ'), - # ('ㄽ', 'ㄹㅅ'), - # ('ㄾ', 'ㄹㅌ'), - # ('ㄿ', 'ㄹㅍ'), - # ('ㅀ', 'ㄹㅎ'), - # ('ㅄ', 'ㅂㅅ'), - ('ㅘ', 'ㅗㅏ'), - ('ㅙ', 'ㅗㅐ'), - ('ㅚ', 'ㅗㅣ'), - ('ㅝ', 'ㅜㅓ'), - ('ㅞ', 'ㅜㅔ'), - ('ㅟ', 'ㅜㅣ'), - ('ㅢ', 'ㅡㅣ'), - ('ㅑ', 'ㅣㅏ'), - ('ㅒ', 'ㅣㅐ'), - ('ㅕ', 'ㅣㅓ'), - ('ㅖ', 'ㅣㅔ'), - ('ㅛ', 'ㅣㅗ'), - ('ㅠ', 'ㅣㅜ') -]] - -# List of (Latin alphabet, hangul) pairs: -_latin_to_hangul = [(re.compile('%s' % x[0], re.IGNORECASE), x[1]) for x in [ - ('a', '에이'), - ('b', '비'), - ('c', '시'), - ('d', '디'), - ('e', '이'), - ('f', '에프'), - ('g', '지'), - ('h', '에이치'), - ('i', '아이'), - ('j', '제이'), - ('k', '케이'), - ('l', '엘'), - ('m', '엠'), - ('n', '엔'), - ('o', '오'), - ('p', '피'), - ('q', '큐'), - ('r', '아르'), - ('s', '에스'), - ('t', '티'), - ('u', '유'), - ('v', '브이'), - ('w', '더블유'), - ('x', '엑스'), - ('y', '와이'), - ('z', '제트') -]] - -# List of (ipa, lazy ipa) pairs: -_ipa_to_lazy_ipa = [(re.compile('%s' % x[0], re.IGNORECASE), x[1]) for x in [ - ('t͡ɕ','ʧ'), - ('d͡ʑ','ʥ'), - ('ɲ','n^'), - ('ɕ','ʃ'), - ('ʷ','w'), - ('ɭ','l`'), - ('ʎ','ɾ'), - ('ɣ','ŋ'), - ('ɰ','ɯ'), - ('ʝ','j'), - ('ʌ','ə'), - ('ɡ','g'), - ('\u031a','#'), - ('\u0348','='), - ('\u031e',''), - ('\u0320',''), - ('\u0339','') -]] - - -def latin_to_hangul(text): - for regex, replacement in _latin_to_hangul: - text = re.sub(regex, replacement, text) - return text - - -def divide_hangul(text): - text = j2hcj(h2j(text)) - for regex, replacement in _hangul_divided: - text = re.sub(regex, replacement, text) - return text - - -def hangul_number(num, sino=True): - '''Reference https://github.com/Kyubyong/g2pK''' - num = re.sub(',', '', num) - - if num == '0': - return '영' - if not sino and num == '20': - return '스무' - - digits = '123456789' - names = '일이삼사오육칠팔구' - digit2name = {d: n for d, n in zip(digits, names)} - - modifiers = '한 두 세 네 다섯 여섯 일곱 여덟 아홉' - decimals = '열 스물 서른 마흔 쉰 예순 일흔 여든 아흔' - digit2mod = {d: mod for d, mod in zip(digits, modifiers.split())} - digit2dec = {d: dec for d, dec in zip(digits, decimals.split())} - - spelledout = [] - for i, digit in enumerate(num): - i = len(num) - i - 1 - if sino: - if i == 0: - name = digit2name.get(digit, '') - elif i == 1: - name = digit2name.get(digit, '') + '십' - name = name.replace('일십', '십') - else: - if i == 0: - name = digit2mod.get(digit, '') - elif i == 1: - name = digit2dec.get(digit, '') - if digit == '0': - if i % 4 == 0: - last_three = spelledout[-min(3, len(spelledout)):] - if ''.join(last_three) == '': - spelledout.append('') - continue - else: - spelledout.append('') - continue - if i == 2: - name = digit2name.get(digit, '') + '백' - name = name.replace('일백', '백') - elif i == 3: - name = digit2name.get(digit, '') + '천' - name = name.replace('일천', '천') - elif i == 4: - name = digit2name.get(digit, '') + '만' - name = name.replace('일만', '만') - elif i == 5: - name = digit2name.get(digit, '') + '십' - name = name.replace('일십', '십') - elif i == 6: - name = digit2name.get(digit, '') + '백' - name = name.replace('일백', '백') - elif i == 7: - name = digit2name.get(digit, '') + '천' - name = name.replace('일천', '천') - elif i == 8: - name = digit2name.get(digit, '') + '억' - elif i == 9: - name = digit2name.get(digit, '') + '십' - elif i == 10: - name = digit2name.get(digit, '') + '백' - elif i == 11: - name = digit2name.get(digit, '') + '천' - elif i == 12: - name = digit2name.get(digit, '') + '조' - elif i == 13: - name = digit2name.get(digit, '') + '십' - elif i == 14: - name = digit2name.get(digit, '') + '백' - elif i == 15: - name = digit2name.get(digit, '') + '천' - spelledout.append(name) - return ''.join(elem for elem in spelledout) - - -def number_to_hangul(text): - '''Reference https://github.com/Kyubyong/g2pK''' - tokens = set(re.findall(r'(\d[\d,]*)([\uac00-\ud71f]+)', text)) - for token in tokens: - num, classifier = token - if classifier[:2] in _korean_classifiers or classifier[0] in _korean_classifiers: - spelledout = hangul_number(num, sino=False) - else: - spelledout = hangul_number(num, sino=True) - text = text.replace(f'{num}{classifier}', f'{spelledout}{classifier}') - # digit by digit for remaining digits - digits = '0123456789' - names = '영일이삼사오육칠팔구' - for d, n in zip(digits, names): - text = text.replace(d, n) - return text - - -def korean_to_lazy_ipa(text): - text = latin_to_hangul(text) - text = number_to_hangul(text) - text=re.sub('[\uac00-\ud7af]+',lambda x:ko_pron.romanise(x.group(0),'ipa').split('] ~ [')[0],text) - for regex, replacement in _ipa_to_lazy_ipa: - text = re.sub(regex, replacement, text) - return text - - -def korean_to_ipa(text): - text = latin_to_hangul(text) - text = number_to_hangul(text) - g2p = G2p() - text = g2p(text) - text = korean_to_lazy_ipa(text) - return text.replace('ʧ','tʃ').replace('ʥ','dʑ') diff --git a/spaces/kevinwang676/VoiceChanger/src/facerender/modules/mapping.py b/spaces/kevinwang676/VoiceChanger/src/facerender/modules/mapping.py deleted file mode 100644 index 0e3a1c2d1770996080c08e9daafb346f05d7bcdd..0000000000000000000000000000000000000000 --- a/spaces/kevinwang676/VoiceChanger/src/facerender/modules/mapping.py +++ /dev/null @@ -1,47 +0,0 @@ -import numpy as np - -import torch -import torch.nn as nn -import torch.nn.functional as F - - -class MappingNet(nn.Module): - def __init__(self, coeff_nc, descriptor_nc, layer, num_kp, num_bins): - super( MappingNet, self).__init__() - - self.layer = layer - nonlinearity = nn.LeakyReLU(0.1) - - self.first = nn.Sequential( - torch.nn.Conv1d(coeff_nc, descriptor_nc, kernel_size=7, padding=0, bias=True)) - - for i in range(layer): - net = nn.Sequential(nonlinearity, - torch.nn.Conv1d(descriptor_nc, descriptor_nc, kernel_size=3, padding=0, dilation=3)) - setattr(self, 'encoder' + str(i), net) - - self.pooling = nn.AdaptiveAvgPool1d(1) - self.output_nc = descriptor_nc - - self.fc_roll = nn.Linear(descriptor_nc, num_bins) - self.fc_pitch = nn.Linear(descriptor_nc, num_bins) - self.fc_yaw = nn.Linear(descriptor_nc, num_bins) - self.fc_t = nn.Linear(descriptor_nc, 3) - self.fc_exp = nn.Linear(descriptor_nc, 3*num_kp) - - def forward(self, input_3dmm): - out = self.first(input_3dmm) - for i in range(self.layer): - model = getattr(self, 'encoder' + str(i)) - out = model(out) + out[:,:,3:-3] - out = self.pooling(out) - out = out.view(out.shape[0], -1) - #print('out:', out.shape) - - yaw = self.fc_yaw(out) - pitch = self.fc_pitch(out) - roll = self.fc_roll(out) - t = self.fc_t(out) - exp = self.fc_exp(out) - - return {'yaw': yaw, 'pitch': pitch, 'roll': roll, 't': t, 'exp': exp} \ No newline at end of file diff --git a/spaces/kira4424/Tacotron-zero-short-voice-clone/web/__init__.py b/spaces/kira4424/Tacotron-zero-short-voice-clone/web/__init__.py deleted file mode 100644 index 0b71aa5ded086d398c53ce60604c368a1f703c4f..0000000000000000000000000000000000000000 --- a/spaces/kira4424/Tacotron-zero-short-voice-clone/web/__init__.py +++ /dev/null @@ -1,135 +0,0 @@ -from web.api import api_blueprint -from pathlib import Path -from gevent import pywsgi as wsgi -from flask import Flask, Response, request, render_template -from synthesizer.inference import Synthesizer -from encoder import inference as encoder -from vocoder.hifigan import inference as gan_vocoder -from vocoder.wavernn import inference as rnn_vocoder -import numpy as np -import re -from scipy.io.wavfile import write -import librosa -import io -import base64 -from flask_cors import CORS -from flask_wtf import CSRFProtect -import webbrowser - -def webApp(): - # Init and load config - app = Flask(__name__, instance_relative_config=True) - app.config.from_object("web.config.default") - app.config['RESTPLUS_MASK_SWAGGER'] = False - app.register_blueprint(api_blueprint) - - # CORS(app) #允许跨域,注释掉此行则禁止跨域请求 - csrf = CSRFProtect(app) - csrf.init_app(app) - - syn_models_dirt = "synthesizer/saved_models" - synthesizers = list(Path(syn_models_dirt).glob("**/*.pt")) - synthesizers_cache = {} - encoder.load_model(Path("encoder/saved_models/pretrained.pt")) - rnn_vocoder.load_model(Path("vocoder/saved_models/pretrained/pretrained.pt")) - gan_vocoder.load_model(Path("vocoder/saved_models/pretrained/g_hifigan.pt")) - - def pcm2float(sig, dtype='float32'): - """Convert PCM signal to floating point with a range from -1 to 1. - Use dtype='float32' for single precision. - Parameters - ---------- - sig : array_like - Input array, must have integral type. - dtype : data type, optional - Desired (floating point) data type. - Returns - ------- - numpy.ndarray - Normalized floating point data. - See Also - -------- - float2pcm, dtype - """ - sig = np.asarray(sig) - if sig.dtype.kind not in 'iu': - raise TypeError("'sig' must be an array of integers") - dtype = np.dtype(dtype) - if dtype.kind != 'f': - raise TypeError("'dtype' must be a floating point type") - - i = np.iinfo(sig.dtype) - abs_max = 2 ** (i.bits - 1) - offset = i.min + abs_max - return (sig.astype(dtype) - offset) / abs_max - - # Cache for synthesizer - @csrf.exempt - @app.route("/api/synthesize", methods=["POST"]) - def synthesize(): - # TODO Implementation with json to support more platform - # Load synthesizer - if "synt_path" in request.form: - synt_path = request.form["synt_path"] - else: - synt_path = synthesizers[0] - print("NO synthsizer is specified, try default first one.") - if synthesizers_cache.get(synt_path) is None: - current_synt = Synthesizer(Path(synt_path)) - synthesizers_cache[synt_path] = current_synt - else: - current_synt = synthesizers_cache[synt_path] - print("using synthesizer model: " + str(synt_path)) - # Load input wav - if "upfile_b64" in request.form: - wav_base64 = request.form["upfile_b64"] - wav = base64.b64decode(bytes(wav_base64, 'utf-8')) - wav = pcm2float(np.frombuffer(wav, dtype=np.int16), dtype=np.float32) - sample_rate = Synthesizer.sample_rate - else: - wav, sample_rate, = librosa.load(request.files['file']) - write("temp.wav", sample_rate, wav) #Make sure we get the correct wav - - encoder_wav = encoder.preprocess_wav(wav, sample_rate) - embed, _, _ = encoder.embed_utterance(encoder_wav, return_partials=True) - - # Load input text - texts = filter(None, request.form["text"].split("\n")) - punctuation = '!,。、,' # punctuate and split/clean text - processed_texts = [] - for text in texts: - for processed_text in re.sub(r'[{}]+'.format(punctuation), '\n', text).split('\n'): - if processed_text: - processed_texts.append(processed_text.strip()) - texts = processed_texts - - # synthesize and vocode - embeds = [embed] * len(texts) - specs = current_synt.synthesize_spectrograms(texts, embeds) - spec = np.concatenate(specs, axis=1) - sample_rate = Synthesizer.sample_rate - if "vocoder" in request.form and request.form["vocoder"] == "WaveRNN": - wav, sample_rate = rnn_vocoder.infer_waveform(spec) - else: - wav, sample_rate = gan_vocoder.infer_waveform(spec) - - # Return cooked wav - out = io.BytesIO() - write(out, sample_rate, wav.astype(np.float32)) - return Response(out, mimetype="audio/wav") - - @app.route('/', methods=['GET']) - def index(): - return render_template("index.html") - - host = app.config.get("HOST") - port = app.config.get("PORT") - web_address = 'http://{}:{}'.format(host, port) - print(f"Web server:" + web_address) - webbrowser.open(web_address) - server = wsgi.WSGIServer((host, port), app) - server.serve_forever() - return app - -if __name__ == "__main__": - webApp() diff --git a/spaces/kirch/Text2Video-Zero/annotator/uniformer/mmcv/ops/points_sampler.py b/spaces/kirch/Text2Video-Zero/annotator/uniformer/mmcv/ops/points_sampler.py deleted file mode 100644 index a802a74fd6c3610d9ae178e6201f47423eca7ad1..0000000000000000000000000000000000000000 --- a/spaces/kirch/Text2Video-Zero/annotator/uniformer/mmcv/ops/points_sampler.py +++ /dev/null @@ -1,177 +0,0 @@ -from typing import List - -import torch -from torch import nn as nn - -from annotator.uniformer.mmcv.runner import force_fp32 -from .furthest_point_sample import (furthest_point_sample, - furthest_point_sample_with_dist) - - -def calc_square_dist(point_feat_a, point_feat_b, norm=True): - """Calculating square distance between a and b. - - Args: - point_feat_a (Tensor): (B, N, C) Feature vector of each point. - point_feat_b (Tensor): (B, M, C) Feature vector of each point. - norm (Bool, optional): Whether to normalize the distance. - Default: True. - - Returns: - Tensor: (B, N, M) Distance between each pair points. - """ - num_channel = point_feat_a.shape[-1] - # [bs, n, 1] - a_square = torch.sum(point_feat_a.unsqueeze(dim=2).pow(2), dim=-1) - # [bs, 1, m] - b_square = torch.sum(point_feat_b.unsqueeze(dim=1).pow(2), dim=-1) - - corr_matrix = torch.matmul(point_feat_a, point_feat_b.transpose(1, 2)) - - dist = a_square + b_square - 2 * corr_matrix - if norm: - dist = torch.sqrt(dist) / num_channel - return dist - - -def get_sampler_cls(sampler_type): - """Get the type and mode of points sampler. - - Args: - sampler_type (str): The type of points sampler. - The valid value are "D-FPS", "F-FPS", or "FS". - - Returns: - class: Points sampler type. - """ - sampler_mappings = { - 'D-FPS': DFPSSampler, - 'F-FPS': FFPSSampler, - 'FS': FSSampler, - } - try: - return sampler_mappings[sampler_type] - except KeyError: - raise KeyError( - f'Supported `sampler_type` are {sampler_mappings.keys()}, but got \ - {sampler_type}') - - -class PointsSampler(nn.Module): - """Points sampling. - - Args: - num_point (list[int]): Number of sample points. - fps_mod_list (list[str], optional): Type of FPS method, valid mod - ['F-FPS', 'D-FPS', 'FS'], Default: ['D-FPS']. - F-FPS: using feature distances for FPS. - D-FPS: using Euclidean distances of points for FPS. - FS: using F-FPS and D-FPS simultaneously. - fps_sample_range_list (list[int], optional): - Range of points to apply FPS. Default: [-1]. - """ - - def __init__(self, - num_point: List[int], - fps_mod_list: List[str] = ['D-FPS'], - fps_sample_range_list: List[int] = [-1]): - super().__init__() - # FPS would be applied to different fps_mod in the list, - # so the length of the num_point should be equal to - # fps_mod_list and fps_sample_range_list. - assert len(num_point) == len(fps_mod_list) == len( - fps_sample_range_list) - self.num_point = num_point - self.fps_sample_range_list = fps_sample_range_list - self.samplers = nn.ModuleList() - for fps_mod in fps_mod_list: - self.samplers.append(get_sampler_cls(fps_mod)()) - self.fp16_enabled = False - - @force_fp32() - def forward(self, points_xyz, features): - """ - Args: - points_xyz (Tensor): (B, N, 3) xyz coordinates of the features. - features (Tensor): (B, C, N) Descriptors of the features. - - Returns: - Tensor: (B, npoint, sample_num) Indices of sampled points. - """ - indices = [] - last_fps_end_index = 0 - - for fps_sample_range, sampler, npoint in zip( - self.fps_sample_range_list, self.samplers, self.num_point): - assert fps_sample_range < points_xyz.shape[1] - - if fps_sample_range == -1: - sample_points_xyz = points_xyz[:, last_fps_end_index:] - if features is not None: - sample_features = features[:, :, last_fps_end_index:] - else: - sample_features = None - else: - sample_points_xyz = \ - points_xyz[:, last_fps_end_index:fps_sample_range] - if features is not None: - sample_features = features[:, :, last_fps_end_index: - fps_sample_range] - else: - sample_features = None - - fps_idx = sampler(sample_points_xyz.contiguous(), sample_features, - npoint) - - indices.append(fps_idx + last_fps_end_index) - last_fps_end_index += fps_sample_range - indices = torch.cat(indices, dim=1) - - return indices - - -class DFPSSampler(nn.Module): - """Using Euclidean distances of points for FPS.""" - - def __init__(self): - super().__init__() - - def forward(self, points, features, npoint): - """Sampling points with D-FPS.""" - fps_idx = furthest_point_sample(points.contiguous(), npoint) - return fps_idx - - -class FFPSSampler(nn.Module): - """Using feature distances for FPS.""" - - def __init__(self): - super().__init__() - - def forward(self, points, features, npoint): - """Sampling points with F-FPS.""" - assert features is not None, \ - 'feature input to FFPS_Sampler should not be None' - features_for_fps = torch.cat([points, features.transpose(1, 2)], dim=2) - features_dist = calc_square_dist( - features_for_fps, features_for_fps, norm=False) - fps_idx = furthest_point_sample_with_dist(features_dist, npoint) - return fps_idx - - -class FSSampler(nn.Module): - """Using F-FPS and D-FPS simultaneously.""" - - def __init__(self): - super().__init__() - - def forward(self, points, features, npoint): - """Sampling points with FS_Sampling.""" - assert features is not None, \ - 'feature input to FS_Sampler should not be None' - ffps_sampler = FFPSSampler() - dfps_sampler = DFPSSampler() - fps_idx_ffps = ffps_sampler(points, features, npoint) - fps_idx_dfps = dfps_sampler(points, features, npoint) - fps_idx = torch.cat([fps_idx_ffps, fps_idx_dfps], dim=1) - return fps_idx diff --git a/spaces/kirch/Text2Video-Zero/annotator/uniformer/mmseg/models/decode_heads/aspp_head.py b/spaces/kirch/Text2Video-Zero/annotator/uniformer/mmseg/models/decode_heads/aspp_head.py deleted file mode 100644 index aa914b5bb25124d1ff199553d96713d6a80484c0..0000000000000000000000000000000000000000 --- a/spaces/kirch/Text2Video-Zero/annotator/uniformer/mmseg/models/decode_heads/aspp_head.py +++ /dev/null @@ -1,107 +0,0 @@ -import torch -import torch.nn as nn -from annotator.uniformer.mmcv.cnn import ConvModule - -from annotator.uniformer.mmseg.ops import resize -from ..builder import HEADS -from .decode_head import BaseDecodeHead - - -class ASPPModule(nn.ModuleList): - """Atrous Spatial Pyramid Pooling (ASPP) Module. - - Args: - dilations (tuple[int]): Dilation rate of each layer. - in_channels (int): Input channels. - channels (int): Channels after modules, before conv_seg. - conv_cfg (dict|None): Config of conv layers. - norm_cfg (dict|None): Config of norm layers. - act_cfg (dict): Config of activation layers. - """ - - def __init__(self, dilations, in_channels, channels, conv_cfg, norm_cfg, - act_cfg): - super(ASPPModule, self).__init__() - self.dilations = dilations - self.in_channels = in_channels - self.channels = channels - self.conv_cfg = conv_cfg - self.norm_cfg = norm_cfg - self.act_cfg = act_cfg - for dilation in dilations: - self.append( - ConvModule( - self.in_channels, - self.channels, - 1 if dilation == 1 else 3, - dilation=dilation, - padding=0 if dilation == 1 else dilation, - conv_cfg=self.conv_cfg, - norm_cfg=self.norm_cfg, - act_cfg=self.act_cfg)) - - def forward(self, x): - """Forward function.""" - aspp_outs = [] - for aspp_module in self: - aspp_outs.append(aspp_module(x)) - - return aspp_outs - - -@HEADS.register_module() -class ASPPHead(BaseDecodeHead): - """Rethinking Atrous Convolution for Semantic Image Segmentation. - - This head is the implementation of `DeepLabV3 - `_. - - Args: - dilations (tuple[int]): Dilation rates for ASPP module. - Default: (1, 6, 12, 18). - """ - - def __init__(self, dilations=(1, 6, 12, 18), **kwargs): - super(ASPPHead, self).__init__(**kwargs) - assert isinstance(dilations, (list, tuple)) - self.dilations = dilations - self.image_pool = nn.Sequential( - nn.AdaptiveAvgPool2d(1), - ConvModule( - self.in_channels, - self.channels, - 1, - conv_cfg=self.conv_cfg, - norm_cfg=self.norm_cfg, - act_cfg=self.act_cfg)) - self.aspp_modules = ASPPModule( - dilations, - self.in_channels, - self.channels, - conv_cfg=self.conv_cfg, - norm_cfg=self.norm_cfg, - act_cfg=self.act_cfg) - self.bottleneck = ConvModule( - (len(dilations) + 1) * self.channels, - self.channels, - 3, - padding=1, - conv_cfg=self.conv_cfg, - norm_cfg=self.norm_cfg, - act_cfg=self.act_cfg) - - def forward(self, inputs): - """Forward function.""" - x = self._transform_inputs(inputs) - aspp_outs = [ - resize( - self.image_pool(x), - size=x.size()[2:], - mode='bilinear', - align_corners=self.align_corners) - ] - aspp_outs.extend(self.aspp_modules(x)) - aspp_outs = torch.cat(aspp_outs, dim=1) - output = self.bottleneck(aspp_outs) - output = self.cls_seg(output) - return output diff --git a/spaces/kirch/Text2Video-Zero/annotator/uniformer/mmseg/models/segmentors/base.py b/spaces/kirch/Text2Video-Zero/annotator/uniformer/mmseg/models/segmentors/base.py deleted file mode 100644 index 172fc63b736c4f13be1cd909433bc260760a1eaa..0000000000000000000000000000000000000000 --- a/spaces/kirch/Text2Video-Zero/annotator/uniformer/mmseg/models/segmentors/base.py +++ /dev/null @@ -1,273 +0,0 @@ -import logging -import warnings -from abc import ABCMeta, abstractmethod -from collections import OrderedDict - -import annotator.uniformer.mmcv as mmcv -import numpy as np -import torch -import torch.distributed as dist -import torch.nn as nn -from annotator.uniformer.mmcv.runner import auto_fp16 - - -class BaseSegmentor(nn.Module): - """Base class for segmentors.""" - - __metaclass__ = ABCMeta - - def __init__(self): - super(BaseSegmentor, self).__init__() - self.fp16_enabled = False - - @property - def with_neck(self): - """bool: whether the segmentor has neck""" - return hasattr(self, 'neck') and self.neck is not None - - @property - def with_auxiliary_head(self): - """bool: whether the segmentor has auxiliary head""" - return hasattr(self, - 'auxiliary_head') and self.auxiliary_head is not None - - @property - def with_decode_head(self): - """bool: whether the segmentor has decode head""" - return hasattr(self, 'decode_head') and self.decode_head is not None - - @abstractmethod - def extract_feat(self, imgs): - """Placeholder for extract features from images.""" - pass - - @abstractmethod - def encode_decode(self, img, img_metas): - """Placeholder for encode images with backbone and decode into a - semantic segmentation map of the same size as input.""" - pass - - @abstractmethod - def forward_train(self, imgs, img_metas, **kwargs): - """Placeholder for Forward function for training.""" - pass - - @abstractmethod - def simple_test(self, img, img_meta, **kwargs): - """Placeholder for single image test.""" - pass - - @abstractmethod - def aug_test(self, imgs, img_metas, **kwargs): - """Placeholder for augmentation test.""" - pass - - def init_weights(self, pretrained=None): - """Initialize the weights in segmentor. - - Args: - pretrained (str, optional): Path to pre-trained weights. - Defaults to None. - """ - if pretrained is not None: - logger = logging.getLogger() - logger.info(f'load model from: {pretrained}') - - def forward_test(self, imgs, img_metas, **kwargs): - """ - Args: - imgs (List[Tensor]): the outer list indicates test-time - augmentations and inner Tensor should have a shape NxCxHxW, - which contains all images in the batch. - img_metas (List[List[dict]]): the outer list indicates test-time - augs (multiscale, flip, etc.) and the inner list indicates - images in a batch. - """ - for var, name in [(imgs, 'imgs'), (img_metas, 'img_metas')]: - if not isinstance(var, list): - raise TypeError(f'{name} must be a list, but got ' - f'{type(var)}') - - num_augs = len(imgs) - if num_augs != len(img_metas): - raise ValueError(f'num of augmentations ({len(imgs)}) != ' - f'num of image meta ({len(img_metas)})') - # all images in the same aug batch all of the same ori_shape and pad - # shape - for img_meta in img_metas: - ori_shapes = [_['ori_shape'] for _ in img_meta] - assert all(shape == ori_shapes[0] for shape in ori_shapes) - img_shapes = [_['img_shape'] for _ in img_meta] - assert all(shape == img_shapes[0] for shape in img_shapes) - pad_shapes = [_['pad_shape'] for _ in img_meta] - assert all(shape == pad_shapes[0] for shape in pad_shapes) - - if num_augs == 1: - return self.simple_test(imgs[0], img_metas[0], **kwargs) - else: - return self.aug_test(imgs, img_metas, **kwargs) - - @auto_fp16(apply_to=('img', )) - def forward(self, img, img_metas, return_loss=True, **kwargs): - """Calls either :func:`forward_train` or :func:`forward_test` depending - on whether ``return_loss`` is ``True``. - - Note this setting will change the expected inputs. When - ``return_loss=True``, img and img_meta are single-nested (i.e. Tensor - and List[dict]), and when ``resturn_loss=False``, img and img_meta - should be double nested (i.e. List[Tensor], List[List[dict]]), with - the outer list indicating test time augmentations. - """ - if return_loss: - return self.forward_train(img, img_metas, **kwargs) - else: - return self.forward_test(img, img_metas, **kwargs) - - def train_step(self, data_batch, optimizer, **kwargs): - """The iteration step during training. - - This method defines an iteration step during training, except for the - back propagation and optimizer updating, which are done in an optimizer - hook. Note that in some complicated cases or models, the whole process - including back propagation and optimizer updating is also defined in - this method, such as GAN. - - Args: - data (dict): The output of dataloader. - optimizer (:obj:`torch.optim.Optimizer` | dict): The optimizer of - runner is passed to ``train_step()``. This argument is unused - and reserved. - - Returns: - dict: It should contain at least 3 keys: ``loss``, ``log_vars``, - ``num_samples``. - ``loss`` is a tensor for back propagation, which can be a - weighted sum of multiple losses. - ``log_vars`` contains all the variables to be sent to the - logger. - ``num_samples`` indicates the batch size (when the model is - DDP, it means the batch size on each GPU), which is used for - averaging the logs. - """ - losses = self(**data_batch) - loss, log_vars = self._parse_losses(losses) - - outputs = dict( - loss=loss, - log_vars=log_vars, - num_samples=len(data_batch['img_metas'])) - - return outputs - - def val_step(self, data_batch, **kwargs): - """The iteration step during validation. - - This method shares the same signature as :func:`train_step`, but used - during val epochs. Note that the evaluation after training epochs is - not implemented with this method, but an evaluation hook. - """ - output = self(**data_batch, **kwargs) - return output - - @staticmethod - def _parse_losses(losses): - """Parse the raw outputs (losses) of the network. - - Args: - losses (dict): Raw output of the network, which usually contain - losses and other necessary information. - - Returns: - tuple[Tensor, dict]: (loss, log_vars), loss is the loss tensor - which may be a weighted sum of all losses, log_vars contains - all the variables to be sent to the logger. - """ - log_vars = OrderedDict() - for loss_name, loss_value in losses.items(): - if isinstance(loss_value, torch.Tensor): - log_vars[loss_name] = loss_value.mean() - elif isinstance(loss_value, list): - log_vars[loss_name] = sum(_loss.mean() for _loss in loss_value) - else: - raise TypeError( - f'{loss_name} is not a tensor or list of tensors') - - loss = sum(_value for _key, _value in log_vars.items() - if 'loss' in _key) - - log_vars['loss'] = loss - for loss_name, loss_value in log_vars.items(): - # reduce loss when distributed training - if dist.is_available() and dist.is_initialized(): - loss_value = loss_value.data.clone() - dist.all_reduce(loss_value.div_(dist.get_world_size())) - log_vars[loss_name] = loss_value.item() - - return loss, log_vars - - def show_result(self, - img, - result, - palette=None, - win_name='', - show=False, - wait_time=0, - out_file=None, - opacity=0.5): - """Draw `result` over `img`. - - Args: - img (str or Tensor): The image to be displayed. - result (Tensor): The semantic segmentation results to draw over - `img`. - palette (list[list[int]]] | np.ndarray | None): The palette of - segmentation map. If None is given, random palette will be - generated. Default: None - win_name (str): The window name. - wait_time (int): Value of waitKey param. - Default: 0. - show (bool): Whether to show the image. - Default: False. - out_file (str or None): The filename to write the image. - Default: None. - opacity(float): Opacity of painted segmentation map. - Default 0.5. - Must be in (0, 1] range. - Returns: - img (Tensor): Only if not `show` or `out_file` - """ - img = mmcv.imread(img) - img = img.copy() - seg = result[0] - if palette is None: - if self.PALETTE is None: - palette = np.random.randint( - 0, 255, size=(len(self.CLASSES), 3)) - else: - palette = self.PALETTE - palette = np.array(palette) - assert palette.shape[0] == len(self.CLASSES) - assert palette.shape[1] == 3 - assert len(palette.shape) == 2 - assert 0 < opacity <= 1.0 - color_seg = np.zeros((seg.shape[0], seg.shape[1], 3), dtype=np.uint8) - for label, color in enumerate(palette): - color_seg[seg == label, :] = color - # convert to BGR - color_seg = color_seg[..., ::-1] - - img = img * (1 - opacity) + color_seg * opacity - img = img.astype(np.uint8) - # if out_file specified, do not show image in window - if out_file is not None: - show = False - - if show: - mmcv.imshow(img, win_name, wait_time) - if out_file is not None: - mmcv.imwrite(img, out_file) - - if not (show or out_file): - warnings.warn('show==False and out_file is not specified, only ' - 'result image will be returned') - return img diff --git a/spaces/koajoel/PolyFormer/fairseq/examples/constrained_decoding/tok.py b/spaces/koajoel/PolyFormer/fairseq/examples/constrained_decoding/tok.py deleted file mode 100644 index b1f888a8c0d1b8ec7174859476cc3222456e0d2c..0000000000000000000000000000000000000000 --- a/spaces/koajoel/PolyFormer/fairseq/examples/constrained_decoding/tok.py +++ /dev/null @@ -1,34 +0,0 @@ -#!/usr/bin/env python3 -# -# Copyright (c) Facebook, Inc. and its affiliates. -# -# This source code is licensed under the MIT license found in the -# LICENSE file in the root directory of this source tree. - -import sys - -import sacremoses - - -def main(args): - """Tokenizes, preserving tabs""" - mt = sacremoses.MosesTokenizer(lang=args.lang) - - def tok(s): - return mt.tokenize(s, return_str=True) - - for line in sys.stdin: - parts = list(map(tok, line.split("\t"))) - print(*parts, sep="\t", flush=True) - - -if __name__ == "__main__": - import argparse - - parser = argparse.ArgumentParser() - parser.add_argument("--lang", "-l", default="en") - parser.add_argument("--penn", "-p", action="store_true") - parser.add_argument("--fields", "-f", help="fields to tokenize") - args = parser.parse_args() - - main(args) diff --git a/spaces/ky2k/Toxicity_Classifier_POC/.venv/lib/python3.9/site-packages/gradio/templates/frontend/assets/index-928645ac.css b/spaces/ky2k/Toxicity_Classifier_POC/.venv/lib/python3.9/site-packages/gradio/templates/frontend/assets/index-928645ac.css deleted file mode 100644 index 4329ebb21b609937b3a2fdd0c3a1ef2edf96b04c..0000000000000000000000000000000000000000 --- a/spaces/ky2k/Toxicity_Classifier_POC/.venv/lib/python3.9/site-packages/gradio/templates/frontend/assets/index-928645ac.css +++ /dev/null @@ -1 +0,0 @@ -.container.svelte-19on2m6.svelte-19on2m6{display:flex;flex-direction:column;gap:var(--spacing-sm);padding:var(--block-padding)}.hl.svelte-19on2m6+.hl.svelte-19on2m6{margin-left:var(--size-1)}.textspan.svelte-19on2m6:last-child>.label.svelte-19on2m6{margin-right:0}.category-legend.svelte-19on2m6.svelte-19on2m6{display:flex;flex-wrap:wrap;gap:var(--spacing-sm);color:#000}.category-label.svelte-19on2m6.svelte-19on2m6{cursor:pointer;border-radius:var(--radius-xs);padding-right:var(--size-2);padding-left:var(--size-2);font-weight:var(--weight-semibold)}.color-legend.svelte-19on2m6.svelte-19on2m6{display:flex;justify-content:space-between;border-radius:var(--radius-xs);background:linear-gradient(to right,var(--color-purple),rgba(255,255,255,0),var(--color-red));padding:var(--size-1) var(--size-2);font-weight:var(--weight-semibold)}.textfield.svelte-19on2m6.svelte-19on2m6{box-sizing:border-box;border-radius:var(--radius-xs);background:var(--background-fill-primary);background-color:transparent;max-width:var(--size-full);line-height:var(--scale-4);word-break:break-all}.textspan.svelte-19on2m6.svelte-19on2m6{transition:.15s;border-radius:var(--radius-xs);padding-top:2.5px;padding-right:var(--size-1);padding-bottom:3.5px;padding-left:var(--size-1);color:#000}.label.svelte-19on2m6.svelte-19on2m6{transition:.15s;margin-top:1px;margin-right:calc(var(--size-1) * -1);border-radius:var(--radius-xs);padding:1px 5px;color:var(--body-text-color);color:#fff;font-weight:var(--weight-bold);font-size:var(--text-sm);text-transform:uppercase}.text.svelte-19on2m6.svelte-19on2m6{color:#000}.score-text.svelte-19on2m6 .text.svelte-19on2m6{color:var(--body-text-color)}.score-text.svelte-19on2m6.svelte-19on2m6{margin-right:var(--size-1);padding:var(--size-1)}.no-cat.svelte-19on2m6.svelte-19on2m6,.no-label.svelte-19on2m6.svelte-19on2m6{color:var(--body-text-color)}.selectable.svelte-19on2m6.svelte-19on2m6{cursor:pointer} diff --git a/spaces/ky2k/Toxicity_Classifier_POC/.venv/lib/python3.9/site-packages/httpcore/backends/sync.py b/spaces/ky2k/Toxicity_Classifier_POC/.venv/lib/python3.9/site-packages/httpcore/backends/sync.py deleted file mode 100644 index a4c85f0449af4e1150b21f36606597ddb00775d9..0000000000000000000000000000000000000000 --- a/spaces/ky2k/Toxicity_Classifier_POC/.venv/lib/python3.9/site-packages/httpcore/backends/sync.py +++ /dev/null @@ -1,133 +0,0 @@ -import socket -import ssl -import sys -import typing - -from .._exceptions import ( - ConnectError, - ConnectTimeout, - ExceptionMapping, - ReadError, - ReadTimeout, - WriteError, - WriteTimeout, - map_exceptions, -) -from .._utils import is_socket_readable -from .base import SOCKET_OPTION, NetworkBackend, NetworkStream - - -class SyncStream(NetworkStream): - def __init__(self, sock: socket.socket) -> None: - self._sock = sock - - def read(self, max_bytes: int, timeout: typing.Optional[float] = None) -> bytes: - exc_map: ExceptionMapping = {socket.timeout: ReadTimeout, OSError: ReadError} - with map_exceptions(exc_map): - self._sock.settimeout(timeout) - return self._sock.recv(max_bytes) - - def write(self, buffer: bytes, timeout: typing.Optional[float] = None) -> None: - if not buffer: - return - - exc_map: ExceptionMapping = {socket.timeout: WriteTimeout, OSError: WriteError} - with map_exceptions(exc_map): - while buffer: - self._sock.settimeout(timeout) - n = self._sock.send(buffer) - buffer = buffer[n:] - - def close(self) -> None: - self._sock.close() - - def start_tls( - self, - ssl_context: ssl.SSLContext, - server_hostname: typing.Optional[str] = None, - timeout: typing.Optional[float] = None, - ) -> NetworkStream: - exc_map: ExceptionMapping = { - socket.timeout: ConnectTimeout, - OSError: ConnectError, - } - with map_exceptions(exc_map): - try: - self._sock.settimeout(timeout) - sock = ssl_context.wrap_socket( - self._sock, server_hostname=server_hostname - ) - except Exception as exc: # pragma: nocover - self.close() - raise exc - return SyncStream(sock) - - def get_extra_info(self, info: str) -> typing.Any: - if info == "ssl_object" and isinstance(self._sock, ssl.SSLSocket): - return self._sock._sslobj # type: ignore - if info == "client_addr": - return self._sock.getsockname() - if info == "server_addr": - return self._sock.getpeername() - if info == "socket": - return self._sock - if info == "is_readable": - return is_socket_readable(self._sock) - return None - - -class SyncBackend(NetworkBackend): - def connect_tcp( - self, - host: str, - port: int, - timeout: typing.Optional[float] = None, - local_address: typing.Optional[str] = None, - socket_options: typing.Optional[typing.Iterable[SOCKET_OPTION]] = None, - ) -> NetworkStream: - # Note that we automatically include `TCP_NODELAY` - # in addition to any other custom socket options. - if socket_options is None: - socket_options = [] # pragma: no cover - address = (host, port) - source_address = None if local_address is None else (local_address, 0) - exc_map: ExceptionMapping = { - socket.timeout: ConnectTimeout, - OSError: ConnectError, - } - - with map_exceptions(exc_map): - sock = socket.create_connection( - address, - timeout, - source_address=source_address, - ) - for option in socket_options: - sock.setsockopt(*option) # pragma: no cover - sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) - return SyncStream(sock) - - def connect_unix_socket( - self, - path: str, - timeout: typing.Optional[float] = None, - socket_options: typing.Optional[typing.Iterable[SOCKET_OPTION]] = None, - ) -> NetworkStream: # pragma: nocover - if sys.platform == "win32": - raise RuntimeError( - "Attempted to connect to a UNIX socket on a Windows system." - ) - if socket_options is None: - socket_options = [] - - exc_map: ExceptionMapping = { - socket.timeout: ConnectTimeout, - OSError: ConnectError, - } - with map_exceptions(exc_map): - sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) - for option in socket_options: - sock.setsockopt(*option) - sock.settimeout(timeout) - sock.connect(path) - return SyncStream(sock) diff --git a/spaces/ky2k/Toxicity_Classifier_POC/.venv/lib/python3.9/site-packages/huggingface_hub/utils/_hf_folder.py b/spaces/ky2k/Toxicity_Classifier_POC/.venv/lib/python3.9/site-packages/huggingface_hub/utils/_hf_folder.py deleted file mode 100644 index 5c9f07c9ba3a3d860e197312023857cb97230361..0000000000000000000000000000000000000000 --- a/spaces/ky2k/Toxicity_Classifier_POC/.venv/lib/python3.9/site-packages/huggingface_hub/utils/_hf_folder.py +++ /dev/null @@ -1,102 +0,0 @@ -# coding=utf-8 -# Copyright 2022-present, the HuggingFace Inc. team. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -"""Contain helper class to retrieve/store token from/to local cache.""" -import os -import warnings -from pathlib import Path -from typing import Optional - -from .. import constants - - -class HfFolder: - path_token = Path(constants.HF_TOKEN_PATH) - # Private attribute. Will be removed in v0.15 - _old_path_token = Path(constants._OLD_HF_TOKEN_PATH) - - @classmethod - def save_token(cls, token: str) -> None: - """ - Save token, creating folder as needed. - - Token is saved in the huggingface home folder. You can configure it by setting - the `HF_HOME` environment variable. - - Args: - token (`str`): - The token to save to the [`HfFolder`] - """ - cls.path_token.parent.mkdir(parents=True, exist_ok=True) - cls.path_token.write_text(token) - - @classmethod - def get_token(cls) -> Optional[str]: - """ - Get token or None if not existent. - - Note that a token can be also provided using the `HUGGING_FACE_HUB_TOKEN` environment variable. - - Token is saved in the huggingface home folder. You can configure it by setting - the `HF_HOME` environment variable. Previous location was `~/.huggingface/token`. - If token is found in old location but not in new location, it is copied there first. - For more details, see https://github.com/huggingface/huggingface_hub/issues/1232. - - Returns: - `str` or `None`: The token, `None` if it doesn't exist. - """ - # 0. Check if token exist in old path but not new location - try: - cls._copy_to_new_path_and_warn() - except Exception: # if not possible (e.g. PermissionError), do not raise - pass - - # 1. Is it set by environment variable ? - token: Optional[str] = os.environ.get("HUGGING_FACE_HUB_TOKEN") - if token is not None: - return token - - # 2. Is it set in token path ? - try: - return cls.path_token.read_text() - except FileNotFoundError: - return None - - @classmethod - def delete_token(cls) -> None: - """ - Deletes the token from storage. Does not fail if token does not exist. - """ - try: - cls.path_token.unlink() - except FileNotFoundError: - pass - - try: - cls._old_path_token.unlink() - except FileNotFoundError: - pass - - @classmethod - def _copy_to_new_path_and_warn(cls): - if cls._old_path_token.exists() and not cls.path_token.exists(): - cls.save_token(cls._old_path_token.read_text()) - warnings.warn( - f"A token has been found in `{cls._old_path_token}`. This is the old" - " path where tokens were stored. The new location is" - f" `{cls.path_token}` which is configurable using `HF_HOME` environment" - " variable. Your token has been copied to this new location. You can" - " now safely delete the old token file manually or use" - " `huggingface-cli logout`." - ) diff --git a/spaces/kyotoyx/medical-diagnosis/README.md b/spaces/kyotoyx/medical-diagnosis/README.md deleted file mode 100644 index 361d203deb5b9ff489de4c3d01ca618e441b248b..0000000000000000000000000000000000000000 --- a/spaces/kyotoyx/medical-diagnosis/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: Medical Diagnosis -emoji: 🦀 -colorFrom: yellow -colorTo: purple -sdk: streamlit -sdk_version: 1.10.0 -app_file: app.py -pinned: false -license: apache-2.0 ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/lewiswu1209/MockingBird/mkgui/base/ui/__init__.py b/spaces/lewiswu1209/MockingBird/mkgui/base/ui/__init__.py deleted file mode 100644 index 593b254ea68dc4c5b3c3f5d4622334133316866f..0000000000000000000000000000000000000000 --- a/spaces/lewiswu1209/MockingBird/mkgui/base/ui/__init__.py +++ /dev/null @@ -1 +0,0 @@ -from .streamlit_ui import render_streamlit_ui diff --git a/spaces/librarian-bots/recommend_similar_papers/README.md b/spaces/librarian-bots/recommend_similar_papers/README.md deleted file mode 100644 index 704cea6e512c3e13e8f09a2949bc6087b2856378..0000000000000000000000000000000000000000 --- a/spaces/librarian-bots/recommend_similar_papers/README.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: Recommend Similar Papers -emoji: 🌖 -colorFrom: yellow -colorTo: green -sdk: gradio -sdk_version: 3.45.1 -app_file: app.py -pinned: false -license: mit ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/spaces/lincquiQcaudo/Top-20-Diffusion/CRACK ADOBE MASTER COLLECTION CC 2015 Espa Ol Serial Crack.md b/spaces/lincquiQcaudo/Top-20-Diffusion/CRACK ADOBE MASTER COLLECTION CC 2015 Espa Ol Serial Crack.md deleted file mode 100644 index c4e80b41f0e75984bf1b9a02ebf555f9e8350934..0000000000000000000000000000000000000000 --- a/spaces/lincquiQcaudo/Top-20-Diffusion/CRACK ADOBE MASTER COLLECTION CC 2015 Espa Ol Serial Crack.md +++ /dev/null @@ -1,62 +0,0 @@ -

      CRACK ADOBE MASTER COLLECTION CC 2015 espa ol serial crack


      Download Ziphttps://bytlly.com/2uGvyI



      - -About this offer. Click the red button to download the Adobe Creative Cloud 2015 Complete Pack for Windows or macOS. This is where you’ll download the offline installer. It’s the best way to get all the new features in Adobe Creative Cloud 2015 and use the latest updates without an internet connection. - -Open the Adobe Creative Cloud 2015 Complete Pack folder, and locate the offline_installer.exe file inside, and double-click it to install Adobe Creative Cloud 2015. - -0 - - - -a - -f - -c - -t - -o - -r - -5 - -8 - -2 - -1 - -7 - -? - -u - -e - -D - -s - -4 - -i - -v - -3 - -6 - -l - -9 - -m - -p 4fefd39f24
      -
      -
      -

      diff --git a/spaces/lincquiQcaudo/Top-20-Diffusion/Chal Bhaag Part 1 In Hindi Dubbed Torrent Download.md b/spaces/lincquiQcaudo/Top-20-Diffusion/Chal Bhaag Part 1 In Hindi Dubbed Torrent Download.md deleted file mode 100644 index e90f1cf960547f3c9dd895d0e59861585ddd7602..0000000000000000000000000000000000000000 --- a/spaces/lincquiQcaudo/Top-20-Diffusion/Chal Bhaag Part 1 In Hindi Dubbed Torrent Download.md +++ /dev/null @@ -1,55 +0,0 @@ -## Chal Bhaag Part 1 In Hindi Dubbed Torrent Download - - - -**Download →→→ [https://urlca.com/2twTml](https://urlca.com/2twTml)** - - - -# Chal Bhaag Part 1 In Hindi Dubbed Torrent Download: A Comedy of Errors - - - -Chal Bhaag is a 2014 Hindi comedy film directed by Prakash Saini and starring Deepak Dobriyal, Taran Bajaj, Keeya Khanna and Varun Mehra. The film revolves around three petty criminals who get arrested on the same day as an MLA is assassinated by three shooters. They are mistaken for the killers and are forced to escape from the police and the real culprits. - - - -If you are looking for a fun and entertaining movie to watch, you can download Chal Bhaag Part 1 in Hindi dubbed torrent from various online sources. However, be careful of the quality and legality of the download links. Some of them may be fake or contain malware that can harm your device. To avoid any risk, you can also watch Chal Bhaag Part 1 in Hindi dubbed online on streaming platforms like FilmyGod or IMDb. - - - -Chal Bhaag Part 1 in Hindi dubbed torrent download is a great option for those who love comedy and action. The film has a lot of hilarious scenes and dialogues that will make you laugh out loud. The film also has some thrilling moments and twists that will keep you hooked till the end. The film has received mixed reviews from critics and audiences, but it is worth a watch for its entertainment value. - - - -So, what are you waiting for? Download Chal Bhaag Part 1 in Hindi dubbed torrent today and enjoy this comedy of errors with your friends and family. - - - -Chal Bhaag Part 1 in Hindi dubbed torrent download is not only a comedy film, but also a social satire. The film exposes the corruption and crime in the Indian society and politics. The film shows how the common people are exploited and manipulated by the powerful and influential. The film also questions the role and responsibility of the media and the judiciary in such situations. - - - -The film has a talented cast of actors who deliver excellent performances. Deepak Dobriyal, who plays Munna Supari, is the highlight of the film. He is known for his comic timing and expressions. Taran Bajaj, who plays Bunty Chor, is also very funny and charming. Keeya Khanna, who plays Kajari, is the female lead of the film. She is a journalist who helps the trio in their escape. Varun Mehra, who plays Daler Singh, is the third member of the gang. He is a singer who dreams of becoming famous. - - - -The film has a catchy soundtrack composed by Sadhu Sushil Tiwari. The songs are upbeat and suit the mood of the film. The film also has some action sequences that are well-choreographed and executed. The film has a good pace and does not drag or bore the viewers. - - - -Chal Bhaag Part 1 in Hindi dubbed torrent download is a film that will make you laugh and think at the same time. It is a film that will entertain you and also make you aware of the realities of the society. It is a film that you should not miss. - - - -Chal Bhaag Part 1 in Hindi dubbed torrent download is a film that has a lot of positive messages and lessons. The film shows how friendship and loyalty can overcome any obstacle and challenge. The film shows how courage and determination can help one achieve their dreams and goals. The film shows how honesty and justice can prevail over dishonesty and injustice. The film shows how love and compassion can heal any wound and pain. - - - -The film is a perfect blend of comedy and drama. The film has a lot of emotions and sentiments that will touch your heart. The film has a lot of surprises and shocks that will keep you on the edge of your seat. The film has a lot of fun and humor that will make you smile and laugh. The film has a lot of charm and appeal that will make you enjoy and appreciate it. - - - -Chal Bhaag Part 1 in Hindi dubbed torrent download is a film that you will love and remember. It is a film that you will recommend and share with others. It is a film that you will watch again and again. - - 1b8d091108 \ No newline at end of file diff --git a/spaces/lincquiQcaudo/Top-20-Diffusion/Hotspot Shield VPN Elite V11.21.0 Setup Crack.md b/spaces/lincquiQcaudo/Top-20-Diffusion/Hotspot Shield VPN Elite V11.21.0 Setup Crack.md deleted file mode 100644 index 4bc1ae32d3d7f93f521d2d32e89c7f93c09e2690..0000000000000000000000000000000000000000 --- a/spaces/lincquiQcaudo/Top-20-Diffusion/Hotspot Shield VPN Elite V11.21.0 Setup Crack.md +++ /dev/null @@ -1,6 +0,0 @@ -

      Hotspot Shield VPN Elite V11.21.0 Setup Crack


      Download Filehttps://bytlly.com/2uGytU



      - -Hotspot Shield VPN Elite 13.26.33 Full + Patch + Crack, Size : 17.2 MB , Magnet, Torrent, , infohash ... Hotspot Shield VPN Elite v11.21.0 Setup + Crack. 4d29de3e1b
      -
      -
      -

      diff --git a/spaces/lincquiQcaudo/Top-20-Diffusion/Igi2indirfullgezginler PATCHED.md b/spaces/lincquiQcaudo/Top-20-Diffusion/Igi2indirfullgezginler PATCHED.md deleted file mode 100644 index 23be365c0de313352603aac3526eb3e042c541d8..0000000000000000000000000000000000000000 --- a/spaces/lincquiQcaudo/Top-20-Diffusion/Igi2indirfullgezginler PATCHED.md +++ /dev/null @@ -1,14 +0,0 @@ -

      igi2indirfullgezginler


      Download ->>->>->> https://bytlly.com/2uGyj7



      - -Düşünceyi Bildirmek için Tüketti Olarak Gezgin Kullanımına Dair Tüm Detaylar... - -. . . - -. - -. . . . . . - -.  4fefd39f24
      -
      -
      -

      diff --git a/spaces/linfanluntan/Grounded-SAM/GroundingDINO/demo/gradio_app.py b/spaces/linfanluntan/Grounded-SAM/GroundingDINO/demo/gradio_app.py deleted file mode 100644 index 15e08323f485291df8b53eefd4691c087d7863f7..0000000000000000000000000000000000000000 --- a/spaces/linfanluntan/Grounded-SAM/GroundingDINO/demo/gradio_app.py +++ /dev/null @@ -1,125 +0,0 @@ -import argparse -from functools import partial -import cv2 -import requests -import os -from io import BytesIO -from PIL import Image -import numpy as np -from pathlib import Path - - -import warnings - -import torch - -# prepare the environment -os.system("python setup.py build develop --user") -os.system("pip install packaging==21.3") -os.system("pip install gradio") - - -warnings.filterwarnings("ignore") - -import gradio as gr - -from groundingdino.models import build_model -from groundingdino.util.slconfig import SLConfig -from groundingdino.util.utils import clean_state_dict -from groundingdino.util.inference import annotate, load_image, predict -import groundingdino.datasets.transforms as T - -from huggingface_hub import hf_hub_download - - - -# Use this command for evaluate the GLIP-T model -config_file = "groundingdino/config/GroundingDINO_SwinT_OGC.py" -ckpt_repo_id = "ShilongLiu/GroundingDINO" -ckpt_filenmae = "groundingdino_swint_ogc.pth" - - -def load_model_hf(model_config_path, repo_id, filename, device='cpu'): - args = SLConfig.fromfile(model_config_path) - model = build_model(args) - args.device = device - - cache_file = hf_hub_download(repo_id=repo_id, filename=filename) - checkpoint = torch.load(cache_file, map_location='cpu') - log = model.load_state_dict(clean_state_dict(checkpoint['model']), strict=False) - print("Model loaded from {} \n => {}".format(cache_file, log)) - _ = model.eval() - return model - -def image_transform_grounding(init_image): - transform = T.Compose([ - T.RandomResize([800], max_size=1333), - T.ToTensor(), - T.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) - ]) - image, _ = transform(init_image, None) # 3, h, w - return init_image, image - -def image_transform_grounding_for_vis(init_image): - transform = T.Compose([ - T.RandomResize([800], max_size=1333), - ]) - image, _ = transform(init_image, None) # 3, h, w - return image - -model = load_model_hf(config_file, ckpt_repo_id, ckpt_filenmae) - -def run_grounding(input_image, grounding_caption, box_threshold, text_threshold): - init_image = input_image.convert("RGB") - original_size = init_image.size - - _, image_tensor = image_transform_grounding(init_image) - image_pil: Image = image_transform_grounding_for_vis(init_image) - - # run grounidng - boxes, logits, phrases = predict(model, image_tensor, grounding_caption, box_threshold, text_threshold, device='cpu') - annotated_frame = annotate(image_source=np.asarray(image_pil), boxes=boxes, logits=logits, phrases=phrases) - image_with_box = Image.fromarray(cv2.cvtColor(annotated_frame, cv2.COLOR_BGR2RGB)) - - - return image_with_box - -if __name__ == "__main__": - - parser = argparse.ArgumentParser("Grounding DINO demo", add_help=True) - parser.add_argument("--debug", action="store_true", help="using debug mode") - parser.add_argument("--share", action="store_true", help="share the app") - args = parser.parse_args() - - block = gr.Blocks().queue() - with block: - gr.Markdown("# [Grounding DINO](https://github.com/IDEA-Research/GroundingDINO)") - gr.Markdown("### Open-World Detection with Grounding DINO") - - with gr.Row(): - with gr.Column(): - input_image = gr.Image(source='upload', type="pil") - grounding_caption = gr.Textbox(label="Detection Prompt") - run_button = gr.Button(label="Run") - with gr.Accordion("Advanced options", open=False): - box_threshold = gr.Slider( - label="Box Threshold", minimum=0.0, maximum=1.0, value=0.25, step=0.001 - ) - text_threshold = gr.Slider( - label="Text Threshold", minimum=0.0, maximum=1.0, value=0.25, step=0.001 - ) - - with gr.Column(): - gallery = gr.outputs.Image( - type="pil", - # label="grounding results" - ).style(full_width=True, full_height=True) - # gallery = gr.Gallery(label="Generated images", show_label=False).style( - # grid=[1], height="auto", container=True, full_width=True, full_height=True) - - run_button.click(fn=run_grounding, inputs=[ - input_image, grounding_caption, box_threshold, text_threshold], outputs=[gallery]) - - - block.launch(server_name='0.0.0.0', server_port=7579, debug=args.debug, share=args.share) - diff --git a/spaces/lithiumice/SadTalker/src/face3d/options/test_options.py b/spaces/lithiumice/SadTalker/src/face3d/options/test_options.py deleted file mode 100644 index 4ff3ad142779850d1d5a1640bc00f70d34d4a862..0000000000000000000000000000000000000000 --- a/spaces/lithiumice/SadTalker/src/face3d/options/test_options.py +++ /dev/null @@ -1,21 +0,0 @@ -"""This script contains the test options for Deep3DFaceRecon_pytorch -""" - -from .base_options import BaseOptions - - -class TestOptions(BaseOptions): - """This class includes test options. - - It also includes shared options defined in BaseOptions. - """ - - def initialize(self, parser): - parser = BaseOptions.initialize(self, parser) # define shared options - parser.add_argument('--phase', type=str, default='test', help='train, val, test, etc') - parser.add_argument('--dataset_mode', type=str, default=None, help='chooses how datasets are loaded. [None | flist]') - parser.add_argument('--img_folder', type=str, default='examples', help='folder for test images.') - - # Dropout and Batchnorm has different behavior during training and test. - self.isTrain = False - return parser diff --git a/spaces/liuyuan-pal/SyncDreamer/ldm/models/diffusion/sync_dreamer_network.py b/spaces/liuyuan-pal/SyncDreamer/ldm/models/diffusion/sync_dreamer_network.py deleted file mode 100644 index c03b3ddfba02781beb0a196f55472567e55ac627..0000000000000000000000000000000000000000 --- a/spaces/liuyuan-pal/SyncDreamer/ldm/models/diffusion/sync_dreamer_network.py +++ /dev/null @@ -1,186 +0,0 @@ -import torch -import torch.nn as nn - -class Image2DResBlockWithTV(nn.Module): - def __init__(self, dim, tdim, vdim): - super().__init__() - norm = lambda c: nn.GroupNorm(8, c) - self.time_embed = nn.Conv2d(tdim, dim, 1, 1) - self.view_embed = nn.Conv2d(vdim, dim, 1, 1) - self.conv = nn.Sequential( - norm(dim), - nn.SiLU(True), - nn.Conv2d(dim, dim, 3, 1, 1), - norm(dim), - nn.SiLU(True), - nn.Conv2d(dim, dim, 3, 1, 1), - ) - - def forward(self, x, t, v): - return x+self.conv(x+self.time_embed(t)+self.view_embed(v)) - - -class NoisyTargetViewEncoder(nn.Module): - def __init__(self, time_embed_dim, viewpoint_dim, run_dim=16, output_dim=8): - super().__init__() - - self.init_conv = nn.Conv2d(4, run_dim, 3, 1, 1) - self.out_conv0 = Image2DResBlockWithTV(run_dim, time_embed_dim, viewpoint_dim) - self.out_conv1 = Image2DResBlockWithTV(run_dim, time_embed_dim, viewpoint_dim) - self.out_conv2 = Image2DResBlockWithTV(run_dim, time_embed_dim, viewpoint_dim) - self.final_out = nn.Sequential( - nn.GroupNorm(8, run_dim), - nn.SiLU(True), - nn.Conv2d(run_dim, output_dim, 3, 1, 1) - ) - - def forward(self, x, t, v): - B, DT = t.shape - t = t.view(B, DT, 1, 1) - B, DV = v.shape - v = v.view(B, DV, 1, 1) - - x = self.init_conv(x) - x = self.out_conv0(x, t, v) - x = self.out_conv1(x, t, v) - x = self.out_conv2(x, t, v) - x = self.final_out(x) - return x - -class SpatialUpTimeBlock(nn.Module): - def __init__(self, x_in_dim, t_in_dim, out_dim): - super().__init__() - norm_act = lambda c: nn.GroupNorm(8, c) - self.t_conv = nn.Conv3d(t_in_dim, x_in_dim, 1, 1) # 16 - self.norm = norm_act(x_in_dim) - self.silu = nn.SiLU(True) - self.conv = nn.ConvTranspose3d(x_in_dim, out_dim, kernel_size=3, padding=1, output_padding=1, stride=2) - - def forward(self, x, t): - x = x + self.t_conv(t) - return self.conv(self.silu(self.norm(x))) - -class SpatialTimeBlock(nn.Module): - def __init__(self, x_in_dim, t_in_dim, out_dim, stride): - super().__init__() - norm_act = lambda c: nn.GroupNorm(8, c) - self.t_conv = nn.Conv3d(t_in_dim, x_in_dim, 1, 1) # 16 - self.bn = norm_act(x_in_dim) - self.silu = nn.SiLU(True) - self.conv = nn.Conv3d(x_in_dim, out_dim, 3, stride=stride, padding=1) - - def forward(self, x, t): - x = x + self.t_conv(t) - return self.conv(self.silu(self.bn(x))) - -class SpatialTime3DNet(nn.Module): - def __init__(self, time_dim=256, input_dim=128, dims=(32, 64, 128, 256)): - super().__init__() - d0, d1, d2, d3 = dims - dt = time_dim - - self.init_conv = nn.Conv3d(input_dim, d0, 3, 1, 1) # 32 - self.conv0 = SpatialTimeBlock(d0, dt, d0, stride=1) - - self.conv1 = SpatialTimeBlock(d0, dt, d1, stride=2) - self.conv2_0 = SpatialTimeBlock(d1, dt, d1, stride=1) - self.conv2_1 = SpatialTimeBlock(d1, dt, d1, stride=1) - - self.conv3 = SpatialTimeBlock(d1, dt, d2, stride=2) - self.conv4_0 = SpatialTimeBlock(d2, dt, d2, stride=1) - self.conv4_1 = SpatialTimeBlock(d2, dt, d2, stride=1) - - self.conv5 = SpatialTimeBlock(d2, dt, d3, stride=2) - self.conv6_0 = SpatialTimeBlock(d3, dt, d3, stride=1) - self.conv6_1 = SpatialTimeBlock(d3, dt, d3, stride=1) - - self.conv7 = SpatialUpTimeBlock(d3, dt, d2) - self.conv8 = SpatialUpTimeBlock(d2, dt, d1) - self.conv9 = SpatialUpTimeBlock(d1, dt, d0) - - def forward(self, x, t): - B, C = t.shape - t = t.view(B, C, 1, 1, 1) - - x = self.init_conv(x) - conv0 = self.conv0(x, t) - - x = self.conv1(conv0, t) - x = self.conv2_0(x, t) - conv2 = self.conv2_1(x, t) - - x = self.conv3(conv2, t) - x = self.conv4_0(x, t) - conv4 = self.conv4_1(x, t) - - x = self.conv5(conv4, t) - x = self.conv6_0(x, t) - x = self.conv6_1(x, t) - - x = conv4 + self.conv7(x, t) - x = conv2 + self.conv8(x, t) - x = conv0 + self.conv9(x, t) - return x - -class FrustumTVBlock(nn.Module): - def __init__(self, x_dim, t_dim, v_dim, out_dim, stride): - super().__init__() - norm_act = lambda c: nn.GroupNorm(8, c) - self.t_conv = nn.Conv3d(t_dim, x_dim, 1, 1) # 16 - self.v_conv = nn.Conv3d(v_dim, x_dim, 1, 1) # 16 - self.bn = norm_act(x_dim) - self.silu = nn.SiLU(True) - self.conv = nn.Conv3d(x_dim, out_dim, 3, stride=stride, padding=1) - - def forward(self, x, t, v): - x = x + self.t_conv(t) + self.v_conv(v) - return self.conv(self.silu(self.bn(x))) - -class FrustumTVUpBlock(nn.Module): - def __init__(self, x_dim, t_dim, v_dim, out_dim): - super().__init__() - norm_act = lambda c: nn.GroupNorm(8, c) - self.t_conv = nn.Conv3d(t_dim, x_dim, 1, 1) # 16 - self.v_conv = nn.Conv3d(v_dim, x_dim, 1, 1) # 16 - self.norm = norm_act(x_dim) - self.silu = nn.SiLU(True) - self.conv = nn.ConvTranspose3d(x_dim, out_dim, kernel_size=3, padding=1, output_padding=1, stride=2) - - def forward(self, x, t, v): - x = x + self.t_conv(t) + self.v_conv(v) - return self.conv(self.silu(self.norm(x))) - -class FrustumTV3DNet(nn.Module): - def __init__(self, in_dim, t_dim, v_dim, dims=(32, 64, 128, 256)): - super().__init__() - self.conv0 = nn.Conv3d(in_dim, dims[0], 3, 1, 1) # 32 - - self.conv1 = FrustumTVBlock(dims[0], t_dim, v_dim, dims[1], 2) - self.conv2 = FrustumTVBlock(dims[1], t_dim, v_dim, dims[1], 1) - - self.conv3 = FrustumTVBlock(dims[1], t_dim, v_dim, dims[2], 2) - self.conv4 = FrustumTVBlock(dims[2], t_dim, v_dim, dims[2], 1) - - self.conv5 = FrustumTVBlock(dims[2], t_dim, v_dim, dims[3], 2) - self.conv6 = FrustumTVBlock(dims[3], t_dim, v_dim, dims[3], 1) - - self.up0 = FrustumTVUpBlock(dims[3], t_dim, v_dim, dims[2]) - self.up1 = FrustumTVUpBlock(dims[2], t_dim, v_dim, dims[1]) - self.up2 = FrustumTVUpBlock(dims[1], t_dim, v_dim, dims[0]) - - def forward(self, x, t, v): - B,DT = t.shape - t = t.view(B,DT,1,1,1) - B,DV = v.shape - v = v.view(B,DV,1,1,1) - - b, _, d, h, w = x.shape - x0 = self.conv0(x) - x1 = self.conv2(self.conv1(x0, t, v), t, v) - x2 = self.conv4(self.conv3(x1, t, v), t, v) - x3 = self.conv6(self.conv5(x2, t, v), t, v) - - x2 = self.up0(x3, t, v) + x2 - x1 = self.up1(x2, t, v) + x1 - x0 = self.up2(x1, t, v) + x0 - return {w: x0, w//2: x1, w//4: x2, w//8: x3} diff --git a/spaces/lixq/bingo61/src/app/loading.css b/spaces/lixq/bingo61/src/app/loading.css deleted file mode 100644 index eaaab6a86a228334c4eca3c5368ae6f0f593d405..0000000000000000000000000000000000000000 --- a/spaces/lixq/bingo61/src/app/loading.css +++ /dev/null @@ -1,68 +0,0 @@ -::-webkit-scrollbar { - width: 10px; - height: 10px; - display: none; -} - -::-webkit-scrollbar-button:start:decrement, -::-webkit-scrollbar-button:end:increment { - height: 30px; - background-color: transparent; -} - -::-webkit-scrollbar-track-piece { - background-color: #3b3b3b; - -webkit-border-radius: 16px; -} - -::-webkit-scrollbar-thumb:vertical { - height: 50px; - background-color: #666; - border: 1px solid #eee; - -webkit-border-radius: 6px; -} - -/* loading start */ -.loading-spinner { - display: flex; - justify-content: center; - align-items: center; - height: 100vh; - opacity: 1; - transition: opacity .8s ease-out; -} - -.loading-spinner.hidden { - opacity: 0; -} - -.loading-spinner>div { - width: 30px; - height: 30px; - background: linear-gradient(90deg, #2870EA 10.79%, #1B4AEF 87.08%); - - border-radius: 100%; - display: inline-block; - animation: sk-bouncedelay 1.4s infinite ease-in-out both; -} - -.loading-spinner .bounce1 { - animation-delay: -0.32s; -} - -.loading-spinner .bounce2 { - animation-delay: -0.16s; -} - -@keyframes sk-bouncedelay { - - 0%, - 80%, - 100% { - transform: scale(0); - } - - 40% { - transform: scale(1.0); - } -} diff --git a/spaces/lixq/bingo61/src/components/ui/button.tsx b/spaces/lixq/bingo61/src/components/ui/button.tsx deleted file mode 100644 index 281da005124fa94c89a9a9db7605748a92b60865..0000000000000000000000000000000000000000 --- a/spaces/lixq/bingo61/src/components/ui/button.tsx +++ /dev/null @@ -1,57 +0,0 @@ -import * as React from 'react' -import { Slot } from '@radix-ui/react-slot' -import { cva, type VariantProps } from 'class-variance-authority' - -import { cn } from '@/lib/utils' - -const buttonVariants = cva( - 'inline-flex items-center justify-center rounded-md text-sm font-medium shadow ring-offset-background transition-colors outline-none disabled:pointer-events-none disabled:opacity-50', - { - variants: { - variant: { - default: - 'bg-primary text-primary-foreground shadow-md hover:bg-primary/90', - destructive: - 'bg-destructive text-destructive-foreground hover:bg-destructive/90', - outline: - 'border border-input hover:bg-accent hover:text-accent-foreground', - secondary: - 'bg-secondary text-secondary-foreground hover:bg-secondary/80', - ghost: 'shadow-none hover:bg-accent hover:text-accent-foreground', - link: 'text-primary underline-offset-4 shadow-none hover:underline' - }, - size: { - default: 'h-8 px-4 py-2', - sm: 'h-8 rounded-md px-3', - lg: 'h-11 rounded-md px-8', - icon: 'h-8 w-8 p-0' - } - }, - defaultVariants: { - variant: 'default', - size: 'default' - } - } -) - -export interface ButtonProps - extends React.ButtonHTMLAttributes, - VariantProps { - asChild?: boolean -} - -const Button = React.forwardRef( - ({ className, variant, size, asChild = false, ...props }, ref) => { - const Comp = asChild ? Slot : 'button' - return ( - - ) - } -) -Button.displayName = 'Button' - -export { Button, buttonVariants } diff --git a/spaces/lizhen30/LangChainGo/llms_asyncio.py b/spaces/lizhen30/LangChainGo/llms_asyncio.py deleted file mode 100644 index 31983918a1a0927c3385d2e176014c6a4797e42a..0000000000000000000000000000000000000000 --- a/spaces/lizhen30/LangChainGo/llms_asyncio.py +++ /dev/null @@ -1,35 +0,0 @@ -import time -import asyncio - -from langchain.llms import OpenAI - - -def generate_serially(): - llm = OpenAI(temperature=0.9) - for _ in range(10): - resp = llm.generate(["Hello, how are you?"]) - print(resp.generations[0][0].text) - - -async def async_generate(llm): - resp = await llm.agenerate(["Hello, how are you?"]) - print(resp.generations[0][0].text) - - -async def generate_concurrently(): - llm = OpenAI(temperature=0.9) - tasks = [async_generate(llm) for _ in range(10)] - await asyncio.gather(*tasks) - - -s = time.perf_counter() -# If running this outside of Jupyter, use asyncio.run(generate_concurrently()) -generate_concurrently() -elapsed = time.perf_counter() - s -print('\033[1m' + - f"Concurrent executed in {elapsed:0.2f} seconds." + '\033[0m') - -s = time.perf_counter() -generate_serially() -elapsed = time.perf_counter() - s -print('\033[1m' + f"Serial executed in {elapsed:0.2f} seconds." + '\033[0m') diff --git a/spaces/luca-martial/neural-style-transfer/app.py b/spaces/luca-martial/neural-style-transfer/app.py deleted file mode 100644 index c9918bfa3e0d06db59a3b389816a223a61d4daaf..0000000000000000000000000000000000000000 --- a/spaces/luca-martial/neural-style-transfer/app.py +++ /dev/null @@ -1,49 +0,0 @@ -import gradio as gr -import tensorflow as tf -import tensorflow_hub as hub -import matplotlib.pyplot as plt -import numpy as np -import PIL.Image - -# Load model from TF-Hub -hub_model = hub.load('https://tfhub.dev/google/magenta/arbitrary-image-stylization-v1-256/2') - -# Function to convert tensor to image -def tensor_to_image(tensor): - tensor = tensor*255 - tensor = np.array(tensor, dtype=np.uint8) - if np.ndim(tensor)>3: - assert tensor.shape[0] == 1 - tensor = tensor[0] - return PIL.Image.fromarray(tensor) - -# Stylize function -def stylize(content_image, style_image): - # Convert to float32 numpy array, add batch dimension, and normalize to range [0, 1]. Example using numpy: - content_image = content_image.astype(np.float32)[np.newaxis, ...] / 255. - style_image = style_image.astype(np.float32)[np.newaxis, ...] / 255. - # Stylize image - stylized_image = hub_model(tf.constant(content_image), tf.constant(style_image))[0] - return tensor_to_image(stylized_image) - -# Add image examples for users -joker = ["example_joker.jpeg", "example_polasticot1.jpeg"] -paris = ["example_paris.jpeg", "example_vangogh.jpeg"] -einstein = ["example_einstein.jpeg", "example_polasticot2.jpeg"] - -# Customize interface -title = "Fast Neural Style Transfer using TF-Hub" -description = "Demo for neural style transfer using the pretrained Arbitrary Image Stylization model from TensorFlow Hub." -article = "

      Exploring the structure of a real-time, arbitrary neural artistic stylization network

      " -content_input = gr.inputs.Image(label="Content Image", source="upload") -style_input = gr.inputs.Image(label="Style Image", source="upload") - -# Build and launch -iface = gr.Interface(fn=stylize, - inputs=[content_input, style_input], - outputs="image", - title=title, - description=description, - article=article, - examples=[joker, paris, einstein]) -iface.launch() \ No newline at end of file diff --git a/spaces/mantisnlp/SearchMesh/preprocess.py b/spaces/mantisnlp/SearchMesh/preprocess.py deleted file mode 100644 index feed523f37e2fc61a33019c7813fe086cf040e3b..0000000000000000000000000000000000000000 --- a/spaces/mantisnlp/SearchMesh/preprocess.py +++ /dev/null @@ -1,23 +0,0 @@ -import json - -from tqdm import tqdm -import typer - - -def preprocess(data_path, processed_data_path): - with open(data_path) as f: - data = json.loads(f.read()) - - with open(processed_data_path, "w") as f: - for grant in tqdm(data["grants"]): - if any( - [ - org["name"] == "The Wellcome Trust" - for org in grant["fundingOrganization"] - ] - ): - f.write(json.dumps(grant) + "\n") - - -if __name__ == "__main__": - typer.run(preprocess) diff --git a/spaces/marvingabler/codellama-34b-chat/model.py b/spaces/marvingabler/codellama-34b-chat/model.py deleted file mode 100644 index 6285cafdc17a0be33a32244d3552c4e59bbfde75..0000000000000000000000000000000000000000 --- a/spaces/marvingabler/codellama-34b-chat/model.py +++ /dev/null @@ -1,75 +0,0 @@ -from threading import Thread -from typing import Iterator - -import torch -from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer - -model_id = 'codellama/CodeLlama-34b-Instruct-hf' - -if torch.cuda.is_available(): - config = AutoConfig.from_pretrained(model_id) - config.pretraining_tp = 1 - model = AutoModelForCausalLM.from_pretrained( - model_id, - config=config, - torch_dtype=torch.float16, - load_in_4bit=True, - device_map='auto', - use_safetensors=False, - ) -else: - model = None -tokenizer = AutoTokenizer.from_pretrained(model_id) - - -def get_prompt(message: str, chat_history: list[tuple[str, str]], - system_prompt: str) -> str: - texts = [f'[INST] <>\n{system_prompt}\n<>\n\n'] - # The first user input is _not_ stripped - do_strip = False - for user_input, response in chat_history: - user_input = user_input.strip() if do_strip else user_input - do_strip = True - texts.append(f'{user_input} [/INST] {response.strip()} [INST] ') - message = message.strip() if do_strip else message - texts.append(f'{message} [/INST]') - return ''.join(texts) - - -def get_input_token_length(message: str, chat_history: list[tuple[str, str]], system_prompt: str) -> int: - prompt = get_prompt(message, chat_history, system_prompt) - input_ids = tokenizer([prompt], return_tensors='np', add_special_tokens=False)['input_ids'] - return input_ids.shape[-1] - - -def run(message: str, - chat_history: list[tuple[str, str]], - system_prompt: str, - max_new_tokens: int = 1024, - temperature: float = 0.1, - top_p: float = 0.9, - top_k: int = 50) -> Iterator[str]: - prompt = get_prompt(message, chat_history, system_prompt) - inputs = tokenizer([prompt], return_tensors='pt', add_special_tokens=False).to('cuda') - - streamer = TextIteratorStreamer(tokenizer, - timeout=10., - skip_prompt=True, - skip_special_tokens=True) - generate_kwargs = dict( - inputs, - streamer=streamer, - max_new_tokens=max_new_tokens, - do_sample=True, - top_p=top_p, - top_k=top_k, - temperature=temperature, - num_beams=1, - ) - t = Thread(target=model.generate, kwargs=generate_kwargs) - t.start() - - outputs = [] - for text in streamer: - outputs.append(text) - yield ''.join(outputs) diff --git a/spaces/matthoffner/chatbot-mini/next-env.d.ts b/spaces/matthoffner/chatbot-mini/next-env.d.ts deleted file mode 100644 index 4f11a03dc6cc37f2b5105c08f2e7b24c603ab2f4..0000000000000000000000000000000000000000 --- a/spaces/matthoffner/chatbot-mini/next-env.d.ts +++ /dev/null @@ -1,5 +0,0 @@ -/// -/// - -// NOTE: This file should not be edited -// see https://nextjs.org/docs/basic-features/typescript for more information. diff --git a/spaces/matthoffner/open-codetree/esbuild/plugins/unpkg-path-plugin.ts b/spaces/matthoffner/open-codetree/esbuild/plugins/unpkg-path-plugin.ts deleted file mode 100644 index 84b62b8e9846956f2cbd8050aebdb88d2b01f14d..0000000000000000000000000000000000000000 --- a/spaces/matthoffner/open-codetree/esbuild/plugins/unpkg-path-plugin.ts +++ /dev/null @@ -1,31 +0,0 @@ -import * as esbuild from "esbuild-wasm"; - -export const unpkgPathPlugin = (): esbuild.Plugin => { - return { - name: "unpkg-path-plugin", - setup(build: esbuild.PluginBuild) { - // - build.onResolve({ filter: /.*/ }, (args) => { - if (args.kind === "entry-point") { - return { path: args.path, namespace: "a" }; - } - }); - - //match relative path in a module "./" or "../" - build.onResolve({ filter: /^\.+\// }, (args: esbuild.OnResolveArgs) => { - return { - namespace: "a", - path: new URL(args.path, `https://unpkg.com${args.resolveDir}/`).href, - }; - }); - - //match main file in a module - build.onResolve({ filter: /.*/ }, async (args: esbuild.OnResolveArgs) => { - return { - namespace: "a", - path: `https://unpkg.com/${args.path}`, - }; - }); - }, - }; -}; diff --git a/spaces/merve/anonymization/public/anonymization/annotations.js b/spaces/merve/anonymization/public/anonymization/annotations.js deleted file mode 100644 index ed45db46369d1bb2a709b20bd97c29451d4284c0..0000000000000000000000000000000000000000 --- a/spaces/merve/anonymization/public/anonymization/annotations.js +++ /dev/null @@ -1,38 +0,0 @@ -var annotations = - -[ -] - - - - -function addSwoop(c){ - var swoopy = d3.swoopyDrag() - .x(d => c.x(d.x)) - .y(d => c.y(d.y)) - .draggable(0) - .annotations(annotations) - - var swoopySel = c.svg.append('g.annotations').call(swoopy) - - c.svg.append('marker#arrow') - .attr('viewBox', '-10 -10 20 20') - .attr('markerWidth', 20) - .attr('markerHeight', 20) - .attr('orient', 'auto') - .append('path').at({d: 'M-6.75,-6.75 L 0,0 L -6.75,6.75'}) - - - swoopySel.selectAll('path').attr('marker-end', 'url(#arrow)') - window.annotationSel = swoopySel.selectAll('g') - .st({fontSize: 12, opacity: d => d.slide == 0 ? 1 : 0}) - - swoopySel.selectAll('text') - .each(function(d){ - d3.select(this) - .text('') //clear existing text - .tspans(d3.wordwrap(d.text, d.width || 20), 12) //wrap after 20 char - }) -} - - diff --git a/spaces/merve/anonymization/source/uncertainty-calibration/init.js b/spaces/merve/anonymization/source/uncertainty-calibration/init.js deleted file mode 100644 index d23a4fecea1bfa4fae6557043d8053dc3acc29ce..0000000000000000000000000000000000000000 --- a/spaces/merve/anonymization/source/uncertainty-calibration/init.js +++ /dev/null @@ -1,36 +0,0 @@ -window.thresholds = [0, 0.2, 0.4, 0.6, 0.8, 1]; -window.emojis = ['☀️','🌧️']; -window.constant_score = 0.5; - -window.ttSel = d3.select('body').selectAppend('div.tooltip.tooltip-hidden') - - -window.init = function(){ - - var graphSel = d3.select('#graph') - var width = height = graphSel.node().offsetWidth - if (innerWidth <= 925){ - width = innerWidth - height = innerHeight*.65 - window.isMobile = true - } - fig_height = height/2 - fig_width = width - - - window.util = window.initUtil() - window.weatherGraph = window.drawWeatherGraph(graphSel, fig_height, fig_width); - window.calibrationCurve = window.drawCalibrationCurve(graphSel, fig_height, fig_width); - // window.calibrationSlider = window.drawCalibrationSlider(weatherGraph, calibrationCurve, fig_width/2) - // window.modelRemapper = window.drawModelRemapping(fig_width/2); - - - window.slides = window.drawSlides() - weatherGraph.renderThresholds() - -} - -window.init() - - - diff --git a/spaces/merve/fill-in-the-blank/source/hidden-bias/script.js b/spaces/merve/fill-in-the-blank/source/hidden-bias/script.js deleted file mode 100644 index 526901a0178a3ef069380410dd33fdc0334f2bae..0000000000000000000000000000000000000000 --- a/spaces/merve/fill-in-the-blank/source/hidden-bias/script.js +++ /dev/null @@ -1,467 +0,0 @@ -/* Copyright 2020 Google LLC. All Rights Reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -==============================================================================*/ - - -var ttSel = d3.select('body').selectAppend('div.tooltip.tooltip-hidden') - -var colors = { - m: '#7DDAD3', - f: '#9B86EF', - h: '#F0BD80', - l: '#FF777B', - grey: '#ccc', -} - - -var totalWidth = width = d3.select('#graph').node().offsetWidth -var r = 40 - -var sel = d3.select('#graph').html('') - .append('div') - -var extraWidth = d3.clamp(500, innerHeight - 150, innerWidth - 500) -var scale = extraWidth/500 -scale = 1 -sel.st({transform: `scale(${scale})`, transformOrigin: '0% 0%'}) - -var c = d3.conventions({ - sel, - totalWidth, - totalHeight: totalWidth, - margin: {left: 25, right: 7}, - layers: 'sd', -}) -var divSel = c.layers[1] - -c.x.domain([1, 4]).clamp(true).interpolate(d3.interpolateRound) -c.y.domain([1, 4]).clamp(true).interpolate(d3.interpolateRound) - -c.xAxis.ticks(3).tickFormat(d3.format('.1f')) -c.yAxis.ticks(3).tickFormat(d3.format('.1f')) -d3.drawAxis(c) - -var axis2Sel= c.svg.append('g.axis').append('line') - .translate(Math.round(c.y(2)) + .5, 1) - .at({x2: c.width, stroke: '#000', opacity: 0}) - -var meanGPADiff = .6 - -var seed = new Math.seedrandom('hii') -var students = d3.range(150).map((d, index) => { - var collegeGPA = d3.randomUniform.source(seed)(1, 4)() - - // if (index == 93) collegeGPA = 2.05 - // if (index == 87) collegeGPA = 2.15 - // if (index == 32) collegeGPA = 2.25 - if (index == 131) collegeGPA = 3.9 - - // var hsGPA = collegeGPA*d3.randomNormal(1, .4)() - var hsGPA = collegeGPA + d3.randomNormal.source(seed)(meanGPADiff, .8)() - var hsGPAadjusted = hsGPA - meanGPADiff - - var rand = d3.randomUniform.source(seed)(0, 1) - - var isMale = rand() < .5 - var name = names[isMale ? 'm' : 'f'][Math.floor(d/2)] - var lastName = names.last[d] - var maleOffset = rand()*(isMale ? 1 : -1)*.6 - - // if (index == 47) name = 'Mia' - // if (index == 82) name = 'Mason' - - - var compGPA0 = lerp(hsGPAadjusted, collegeGPA, rand()*.7) + maleOffset - var compGPA1 = lerp(compGPA0, collegeGPA + maleOffset, rand()*1.1) - var compGPA2 = compGPA1 + rand()/4 - 1/4/2 - // var compGPA0 = collegeGPA + d3.randomNormal.source(seed)(0, .5)() - // var compGPA1 = collegeGPA + d3.randomNormal.source(seed)(0, .3)() - - if (index == 69){ - compGPA1 = 2.0 - } - if (index == 37){ - compGPA1 = 2.0 - } - - - var isLowIncome = rand() < .5 - - var inteviewGPA = collegeGPA + d3.randomNormal.source(seed)(0, .15)() - var inteviewGPAbias = inteviewGPA + rand()*(isLowIncome ? -1 : 1)*.5 - - // if (index == 115) name = 'Mason' - // if (index == 32) name = 'Mia' - - if (name == 'Camila') name = 'Mia' - - - return {name, index, lastName, collegeGPA, hsGPA, hsGPAadjusted, compGPA0, compGPA1, compGPA2, isMale, isLowIncome, inteviewGPA, inteviewGPAbias} -}) - -students = _.sortBy(students, d => d.collegeGPA) - -students = students.filter(d => { - return d3.entries(d).every(({key, value}) => { - if (!key.includes('GPA')) return true - - return 1 < value && value < 4.0 - }) -}) - - -c.svg.append('path') - .at({ - d: ['M', 0, c.height, 'L', c.width, 0].join(' '), - stroke: '#ccc', - strokeWidth: 2, - strokeDasharray: '4 2' - }) - -!(function(){ - // return window.annotationSel = d3.select(null) - var isDrag = 0 - if (!isDrag) annotations.forEach(d => d.text = d.html ? '' : d.text) - if (isDrag){ - d3.select('#sections').st({pointerEvents: 'none'}) - } - - // copy('window.annotations = ' + JSON.stringify(annotations, null, 2)) - var swoopy = d3.swoopyDrag() - .x(d => c.x(d.x)) - .y(d => c.y(d.y)) - .draggable(isDrag) - .annotations(annotations) - .on('drag', d => { - - }) - - - var htmlAnnoSel = divSel.appendMany('div.annotation', annotations.filter(d => d.html)) - .translate(d => [c.x(d.x), c.y(d.y)]).st({position: 'absolute', opacity: 0}) - .append('div') - .translate(d => d.textOffset) - .html(d => d.html) - .st({width: 150}) - - - - var swoopySel = c.svg.append('g.annotations').call(swoopy) - - c.svg.append('marker') - .attr('id', 'arrow') - .attr('viewBox', '-10 -10 20 20') - .attr('markerWidth', 20) - .attr('markerHeight', 20) - .attr('orient', 'auto') - .append('path') - .attr('d', 'M-6.75,-6.75 L 0,0 L -6.75,6.75') - - swoopySel.selectAll('path') - .attr('marker-end', 'url(#arrow)') - .st({'opacity': d => d.path == 'M 0 0' ? 0 : 1}) - window.annotationSel = swoopySel.selectAll('g') - .st({fontSize: 12, opacity: d => d.slide == 0 ? 1 : 0}) - - window.annotationSel = d3.selectAll('g.annotations g, div.annotation') - - swoopySel.selectAll('text') - .each(function(d){ - d3.select(this) - .text('') //clear existing text - .tspans(d3.wordwrap(d.text, d.width || 20), 13) //wrap after 20 char - }) - })() - - - -students = _.sortBy(students, d => d.collegeGPA) -var lineSel = c.svg.appendMany('path', students) - .translate(d => [c.x(d.hsGPA), c.y(d.collegeGPA)]) - .at({ - // fill: d => d.hsGPA > d.collegeGPA ? 'blue' : 'orange', - fill: '#eee', - stroke: '#aaa', - strokeWidth: .5, - opacity: 0, - // strokeWidth: 1/scale, - }) - - -var circleSel = c.svg.appendMany('g', students) - .translate(d => [c.x(d.collegeGPA), c.y(d.hsGPA)]) - .call(d3.attachTooltip) - .on('mouseover', d => { - var html = '' - html += `
      ${d.name} ${d.lastName}
      ` - - if (curSlide.circleFill == 'gender'){ - html += `${d.isMale ? 'Male' : 'Female'}` - } - - if (curSlide.circleFill == 'income'){ - html += `${d.isLowIncome ? 'Low Income' : 'High Income'}` - } - html += ` -
      ${d3.format('.2f')(d[curSlide.yKey]).slice(0, 4)} ${curSlide.index ? 'Predicted' : 'High School'} GPA
      -
      ${d3.format('.2f')(d.collegeGPA).slice(0, 4)} College GPA
      ` - - ttSel.html(html) - }) - - -var innerCircleSel = circleSel.append('circle') - .at({ - r: 5, - fill: '#eee', - stroke: '#aaa' - }) - -// var textSel = circleSel.append('text').text(d => d.isMale ? 'M' : 'F') -// .at({textAnchor: 'middle', dy: '.33em', fontSize: 8, fill: '#eee'}) -// var textSel2 = circleSel.append('text').text(d => d.isLowIncome ? 'L' : 'H') -// .at({textAnchor: 'middle', dy: '.33em', fontSize: 8, opacity: 0}) - - -c.svg.select('.y').selectAll('line').filter(d => d == 4) - .remove() -c.svg.select('.y').selectAll('text').filter(d => d == 4) - .select(function() { - return this.parentNode.insertBefore(this.cloneNode(1), this.nextSibling); - }) - .text('Actual College GPA') - .at({x: c.width/2, y: c.height + 35, textAnchor: 'middle', fontWeight: 800}) - -var yLabelSel = divSel.st({pointerEvents: 'none'}).append('div.axis') - .html('High School GPA') - .translate([0, -9]) - .st({textAlign: 'left', maxWidth: 260}) - -// c.svg.append('text').text('Actual College GPA').st({fontWeight: 800}) - -var longLabel = 'high school GPA, essay, clubs, zip code, teacher recommendations, sports, AP scores, demonstrated interest, gender, SAT scores, interviews, portfolio, race, work experience' - -var slides = [ - { - yKey: 'hsGPA', - isLineVisible: 0, - yLabel: 'High School GPA', - circleFill: 'grey', - circleFillDelay: d => 0, - }, - - { - yKey: 'hsGPA', - isLineVisible: true, - yLabel: 'High School GPA' - }, - - { - yKey: 'hsGPAadjusted', - yLabel: 'high school GPA' - }, - - { - yKey: 'compGPA0', - yLabel: 'high school GPA, essay, clubs, zip code'.replace('essay', 'essay') + '' - }, - - { - yKey: 'compGPA1', - yLabel: longLabel.replace('teacher', 'teacher') + '', - circleFill: 'grey', - circleFillDelay: d => 0, - textFill: '#eee', - }, - - { - yKey: 'compGPA1', - yLabel: longLabel, - circleFill: 'gender', - circleFillDelay: (d, i) => i*20 + (d.isMale ? 0 : 2000), - textFill: '#000', - }, - - { - name: 'proxyHighlight', - yKey: 'compGPA2', - yLabel: longLabel, - circleFill: 'gender', - circleFillDelay: d => 0, - textFill: '#000', - }, - - { - textFill: '#eee', - yLabel: 'Alumni interview', - yKey: 'inteviewGPAbias', - circleFill: 'grey', - text2Opacity: 0, - }, - - { - textFill: '#eee', - yLabel: 'Alumni interview', - yKey: 'inteviewGPAbias', - circleFill: 'income', - circleFillDelay: (d, i) => i*20 + (!d.isLowIncome ? 2000 : 0), - text2Opacity: 1, - }, - - { - textFill: '#eee', - yLabel: 'Alumni interview, household income'.replace('household', 'household') + '', - yKey: 'inteviewGPA', - text2Opacity: 1, - }, -] - -slides.forEach(d => { - if (d.name == 'proxyHighlight'){ - var proxies = 'clubs, interviews, portfolio, sports'.split(', ') - d.yLabel = d.yLabel - .split(', ') - .map(d => { - if (d == 'gender') return `gender` - if (!proxies.includes(d)) return d - - return `${d}` - }) - .join(', ') - } - - - if (d.yLabel[0] != '<') d.yLabel = 'Predicted College GPA using ' + d.yLabel.replace('School', 'school') -}) - -var keys = [] -slides.forEach(d => keys = keys.concat(d3.keys(d))) -_.uniq(keys).forEach(str => { - var prev = null - slides.forEach(d => { - if (typeof(d[str]) === 'undefined'){ - d[str] = prev - } - prev = d[str] - }) -}) - -slides.forEach((d, i) => { - d.circleFillFn = { - grey: d => '#eee', - gender: d => d.isMale ? colors.m : colors.f, - income: d => d.isLowIncome ? colors.l : colors.h, - }[d.circleFill] - - d.index = i -}) - - - - -var gs = d3.graphScroll() - .container(d3.select('.container-1')) - .graph(d3.selectAll('container-1 #graph')) - .eventId('uniqueId1') - .sections(d3.selectAll('.container-1 #sections > div')) - .offset(innerWidth < 900 ? 300 : 520) - .on('active', updateSlide) - - -var prevSlide = -1 -function updateSlide(i){ - var slide = slides[i] - if (!slide) return - curSlide = slide - var {yKey} = slide - - lineSel.transition('yKey').duration(500) - .at({ - d: d => [ - 'M 5 0', - 'C 0 0', - 0, c.y(d['collegeGPA']) - c.y(d[yKey]), - 0, c.y(d['collegeGPA']) - c.y(d[yKey]), - 'S 0 0 -5.5 0' - ].join(' ') - }) - .translate(d => [c.x(d.collegeGPA), c.y(d[yKey])]) - - - circleSel.transition('yKey').duration(500) - .translate(d => [c.x(d.collegeGPA), c.y(d[yKey])]) - - innerCircleSel.transition('colorFill').duration(30) - .delay(slide.circleFillDelay) - .at({ - fill: slide.circleFillFn, - stroke: d => d3.color(slide.circleFillFn(d)).darker(1.5) - }) - - axis2Sel.transition() - .st({opacity: i == 5 ? 1 : 0}) - - lineSel.transition('opacity').duration(500) - .st({ - opacity: slide.isLineVisible ? 1 : 0 - }) - - if (slide.yLabel) yLabelSel.html(slide.yLabel) - - - annotationSel.transition() - .st({opacity: d => i == d.slide ? 1 : 0}) - - - - prevSlide = i -} - -slide = slides[0] - - - - -d3.selectAll('.circle').each(function(){ - var d = d3.select(this).attr('class').split(' ')[0] - - d3.select(this) - .st({ - backgroundColor: d3.color(colors[d]), - borderColor: d3.color(colors[d]).darker(1.5), - }) - - -}) - - - - -function lerp(a, b, t){ return a + t*(b - a) } - - - -c.svg.selectAll('g.annotations').raise() - - - -d3.selectAll('#sections img').attr('aria-hidden', true) - - - - - - - - diff --git a/spaces/merve/hidden-bias/public/third_party/topojson-client.js b/spaces/merve/hidden-bias/public/third_party/topojson-client.js deleted file mode 100644 index 728070f185d11aa72b3f78ab88037275614fe89b..0000000000000000000000000000000000000000 --- a/spaces/merve/hidden-bias/public/third_party/topojson-client.js +++ /dev/null @@ -1,2 +0,0 @@ -// https://github.com/topojson/topojson-client v3.0.1 Copyright 2019 Mike Bostock -!function(e,r){"object"==typeof exports&&"undefined"!=typeof module?r(exports):"function"==typeof define&&define.amd?define(["exports"],r):r((e=e||self).topojson=e.topojson||{})}(this,function(e){"use strict";function r(e){return e}function t(e){if(null==e)return r;var t,n,o=e.scale[0],a=e.scale[1],i=e.translate[0],c=e.translate[1];return function(e,r){r||(t=n=0);var u=2,f=e.length,s=new Array(f);for(s[0]=(t+=e[0])*o+i,s[1]=(n+=e[1])*a+c;ui&&(i=e[0]),e[1]c&&(c=e[1])}function f(e){switch(e.type){case"GeometryCollection":e.geometries.forEach(f);break;case"Point":u(e.coordinates);break;case"MultiPoint":e.coordinates.forEach(u)}}for(r in e.arcs.forEach(function(e){for(var r,t=-1,u=e.length;++ti&&(i=r[0]),r[1]c&&(c=r[1])}),e.objects)f(e.objects[r]);return[o,a,i,c]}function o(e,r){var t=r.id,n=r.bbox,o=null==r.properties?{}:r.properties,i=a(e,r);return null==t&&null==n?{type:"Feature",properties:o,geometry:i}:null==n?{type:"Feature",id:t,properties:o,geometry:i}:{type:"Feature",id:t,bbox:n,properties:o,geometry:i}}function a(e,r){var n=t(e.transform),o=e.arcs;function a(e,r){r.length&&r.pop();for(var t=o[e<0?~e:e],a=0,i=t.length;a1)n=function(e,r,t){var n,o=[],a=[];function i(e){var r=e<0?~e:e;(a[r]||(a[r]=[])).push({i:e,g:n})}function c(e){e.forEach(i)}function u(e){e.forEach(c)}return function e(r){switch(n=r,r.type){case"GeometryCollection":r.geometries.forEach(e);break;case"LineString":c(r.arcs);break;case"MultiLineString":case"Polygon":u(r.arcs);break;case"MultiPolygon":!function(e){e.forEach(u)}(r.arcs)}}(r),a.forEach(null==t?function(e){o.push(e[0].i)}:function(e){t(e[0].g,e[e.length-1].g)&&o.push(e[0].i)}),o}(0,r,t);else for(o=0,n=new Array(a=e.arcs.length);o1)for(var a,c,f=1,s=u(o[0]);fs&&(c=o[0],o[0]=o[f],o[f]=c,s=a);return o}).filter(function(e){return e.length>0})}}function f(e,r){for(var t=0,n=e.length;t>>1;e[o]=2))throw new Error("n must be ≥2");var t,o=(u=e.bbox||n(e))[0],a=u[1],i=u[2],c=u[3];r={scale:[i-o?(i-o)/(t-1):1,c-a?(c-a)/(t-1):1],translate:[o,a]}}var u,f,l=s(r),h=e.objects,p={};function g(e){return l(e)}function y(e){var r;switch(e.type){case"GeometryCollection":r={type:"GeometryCollection",geometries:e.geometries.map(y)};break;case"Point":r={type:"Point",coordinates:g(e.coordinates)};break;case"MultiPoint":r={type:"MultiPoint",coordinates:e.coordinates.map(g)};break;default:return e}return null!=e.id&&(r.id=e.id),null!=e.bbox&&(r.bbox=e.bbox),null!=e.properties&&(r.properties=e.properties),r}for(f in h)p[f]=y(h[f]);return{type:"Topology",bbox:u,transform:r,objects:p,arcs:e.arcs.map(function(e){var r,t=0,n=1,o=e.length,a=new Array(o);for(a[0]=l(e[0],0);++t0&&i[i.length-1])&&(6===a[0]||2===a[0])){o=0;continue}if(3===a[0]&&(!i||a[1]>i[0]&&a[1]0;)r=Math.random()*e|0,n=t[--e],t[e]=t[r],t[r]=n}function c(t,e,n){return Math.max(t,Math.min(e,n))}function p(t){return t%2==0?t:t+1}function h(t){for(var e=0,n=0;n=n?i():setTimeout(o,s)}};o()})}function E(t,e){for(var n=1,r=-1,i=0;i=0)n*=t[i];else if(-1===t[i]){if(-1!==r)throw Error("Shapes can only have 1 implicit size. Found -1 at dim "+r+" and dim "+i);r=i}else if(t[i]<0)throw Error("Shapes can not be < 0. Found "+t[i]+" at dim "+i);if(-1===r){if(e>0&&e!==n)throw Error("Size("+e+") must match the product of shape "+t);return t}if(0===n)throw Error("Cannot infer the missing size in ["+t+"] when there are 0 elements");if(e%n!=0)throw Error("The implicit shape can't be a fractional number. Got "+e+" / "+n);var a=t.slice();return a[r]=e/n,a}function S(t,e){var n=e.length;return f((t=null==t?e.map(function(t,e){return e}):[].concat(t)).every(function(t){return t>=-n&&ts)&&1===t[s]&&(n.push(t[s]),r.push(s)),a[o]<=s&&o++}1!==t[s]&&(n.push(t[s]),r.push(s))}return{newShape:n,keptDims:r}}function I(t,e){var n=null;if(null==t||"float32"===t)n=new Float32Array(e);else if("int32"===t)n=new Int32Array(e);else{if("bool"!==t)throw new Error("Unknown data type "+t);n=new Uint8Array(e)}return n}function A(t,e){var n=null;if(null==t||"float32"===t)n=new Float32Array(e);else if("int32"===t)n=new Int32Array(e);else if("bool"===t)n=new Uint8Array(e);else{if("string"!==t)throw new Error("Unknown data type "+t);n=new Array(e)}return n}function R(t,e){for(var n=0;n=0;--r)n[r]=n[r+1]*t[r+1];return n}function U(t,e,n){if("string"===e)throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(t)&&(t=g(t)),n&&R(t,e),function(t,e){return t instanceof Float32Array&&"float32"===e||t instanceof Int32Array&&"int32"===e||t instanceof Uint8Array&&"bool"===e}(t,e))return t;if(null==e||"float32"===e||"complex64"===e)return new Float32Array(t);if("int32"===e)return new Int32Array(t);if("bool"===e){for(var r=new Uint8Array(t.length),i=0;i=0,function(){return"Tensor must have a shape comprised of positive integers but got shape ["+t+"]."})})}function $(e,n){return void 0===n&&(n="utf-8"),n=n||"utf-8",t.ENV.platform.encode(e,n)}function X(e,n){return void 0===n&&(n="utf-8"),n=n||"utf-8",t.ENV.platform.decode(e,n)}var Y=Object.freeze({shuffle:l,clamp:c,nearestLargerEven:p,sum:h,randUniform:function(t,e){var n=Math.random();return e*n+(1-n)*t},distSquared:function(t,e){for(var n=0,r=0;r0?f:"")+" "}console.log("%c"+s+"\t%c"+o+"\t%c"+u+"D "+c+"\t%c"+l+"\t%c"+p+"\t%c"+a,"font-weight:bold","color:red","color:blue","color: orange","color: green","color: steelblue")},t}(),Q=20,tt=3,et=7;function nt(t,e,n){return N(Array.isArray(t)?parseFloat(t[0].toFixed(et))+" + "+parseFloat(t[1].toFixed(et))+"j":M(t)?"'"+t+"'":"bool"===n?rt(t):parseFloat(t.toFixed(et)).toString(),e)}function rt(t){return 0===t?"false":"true"}function it(t){for(var e=[],n=0;n=this.shape[n]){var o="Requested out of range element at "+t+". Buffer shape="+this.shape;throw new Error(o)}n++}for(var s=t[t.length-1],u=0;u1)for(var l=0;lQ){var c=tt*s,p=Array.from(e.slice(0,c)),h=Array.from(e.slice(u-tt*s,u));return"complex64"===r&&(p=it(p),h=it(h)),["["+p.map(function(t,e){return nt(t,a[e],r)}).join(", ")+", ..., "+h.map(function(t,e){return nt(t,a[u-tt+e],r)}).join(", ")+"]"]}return["["+("complex64"===r?it(e):Array.from(e)).map(function(t,e){return nt(t,a[e],r)}).join(", ")+"]"]}var f=n.slice(1),d=i.slice(1),m=i[0]*s,g=[];if(u>Q){for(var v=0;v0&&(t.unreliable=!0,null==t.reasons&&(t.reasons=[]),t.reasons.push("Memory usage by string tensors is approximate (2 bytes per character)")),t},t.prototype.profile=function(t){return r(this,void 0,void 0,function(){var e,n;return i(this,function(r){return this.state.profiling=!0,e=this.state.numBytes,n=this.state.numTensors,this.state.activeProfile.kernels=[],this.state.activeProfile.result=t(),this.state.profiling=!1,this.state.activeProfile.peakBytes=Math.max.apply(Math,this.state.activeProfile.kernels.map(function(t){return t.totalBytesSnapshot})),this.state.activeProfile.newBytes=this.state.numBytes-e,this.state.activeProfile.newTensors=this.state.numTensors-n,[2,this.state.activeProfile]})})},t.prototype.isTapeOn=function(){return this.state.gradientDepth>0&&0===this.state.kernelDepth},t.prototype.addTapeNode=function(t,e,n){var r={};t.forEach(function(t,e){r[e]=t});var i={id:this.state.nextTapeNodeId++,name:this.state.activeScope.name,inputs:r,outputs:[e],gradient:function(t){var e={};return n(t).forEach(function(t,n){e[n]=function(){return t}}),e}};this.state.activeTape.push(i)},t.prototype.keep=function(t){return t.kept=!0,t},t.prototype.startTape=function(){0===this.state.gradientDepth&&(this.state.activeTape=[]),this.state.gradientDepth++},t.prototype.endTape=function(){this.state.gradientDepth--},t.prototype.startScope=function(t){var e={track:[],name:"unnamed scope",id:this.state.nextScopeId++};t&&(e.name=t),this.state.scopeStack.push(e),this.state.activeScope=e},t.prototype.endScope=function(t){for(var e=this,n=wt(t),r=new Set(n.map(function(t){return t.id})),i=0;i0,function(){return"gradients() received an empty list of xs."}),null!=n&&"float32"!==n.dtype)throw new Error("dy must have 'float32' dtype, but has '"+n.dtype+"'");var a=this.scopedRun(function(){return i.startTape()},function(){return i.endTape()},function(){return i.tidy("forward",t)});f(a instanceof lt,function(){return"The result y returned by f() must be a tensor."});var o=function(t,e,n){for(var r={},i={},a=0;a=0;a--)for(o=(d=t[a]).inputs,c=0;c0)throw new Error("Cannot compute gradient of y=f(x) with respect to x. Make sure that the f you passed encloses all operations that lead from x to y.");return this.tidy("backward",function(){var t,r,s={};s[a.id]=null==n?(r=G(v(t=a.shape),"float32"),lt.make(t,{values:r})):n,function(t,e,n){for(var r=function(r){var i=e[r],a=[];if(i.outputs.forEach(function(e){var n=t[e.id];if(null!=n)a.push(n);else{var r=lt.make(e.shape,{values:H(e.size,e.dtype)},e.dtype);a.push(r)}}),null==i.gradient)throw new Error("Cannot compute gradient: gradient function not found for "+i.name+".");var o=i.gradient(1===i.outputs.length?a[0]:a),s=function(e){if(!(e in o))throw new Error("Cannot backprop through input "+e+". Available gradients found: "+Object.keys(o)+".");var r=n(function(){return o[e]()});if("float32"!==r.dtype)throw new Error("Error in gradient for op "+i.name+". The gradient of input "+e+" must have 'float32' dtype, but has '"+r.dtype+"'");var a=i.inputs[e];if(!y(r.shape,a.shape))throw new Error("Error in gradient for op "+i.name+". The gradient of input '"+e+"' has shape '"+r.shape+"', which does not match the shape of the input '"+a.shape+"'");if(null==t[a.id])t[a.id]=r;else{var s=t[a.id];t[a.id]=s.add(r),s.dispose()}};for(var u in i.inputs)s(u)},i=e.length-1;i>=0;i--)r(i)}(s,o,function(t){return i.tidy(t)});var u=e.map(function(t){return s[t.id]});return 0===i.state.gradientDepth&&(i.state.activeTape.forEach(function(t){for(var e in t.saved)t.saved[e].dispose()}),i.state.activeTape=null),{value:a,grads:u}})},t.prototype.customGrad=function(t){var e=this;return f(B(t),function(){return"The f passed in customGrad(f) must be a function."}),function(){for(var n,r=[],i=0;ir||n>r)throw i="["+e+"x"+n+"]",new Error("Requested texture size "+i+" greater than WebGL maximum on this browser / GPU ["+r+"x"+r+"].")}function re(t,e){return fe(t,e,function(){return t.createFramebuffer()},"Unable to create WebGLFramebuffer.")}function ie(t,e,n,r,i,a,o,s){var u=t.getAttribLocation(n,r);return-1!==u&&(Bt(t,e,function(){return t.bindBuffer(t.ARRAY_BUFFER,i)}),Bt(t,e,function(){return t.vertexAttribPointer(u,a,t.FLOAT,!1,o,s)}),Bt(t,e,function(){return t.enableVertexAttribArray(u)}),!0)}function ae(t,e,n,r){de(t,r),Bt(t,e,function(){return t.activeTexture(t.TEXTURE0+r)}),Bt(t,e,function(){return t.bindTexture(t.TEXTURE_2D,n)})}function oe(t,e,n,r){return fe(t,e,function(){return t.getUniformLocation(n,r)},'uniform "'+r+'" not present in program.')}function se(t,e,n){return t.getUniformLocation(e,n)}function ue(t,e,n,r,i,a){Bt(t,e,function(){return ae(t,e,r,a)}),Bt(t,e,function(){return t.uniform1i(i,a)})}function le(t,e,n,r){Bt(t,e,function(){return t.bindFramebuffer(t.FRAMEBUFFER,r)}),Bt(t,e,function(){return t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,n,0)})}function ce(t,e,n){Bt(t,e,function(){return t.bindFramebuffer(t.FRAMEBUFFER,n)}),Bt(t,e,function(){return t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,null,0)})}function pe(t){var e=t.checkFramebufferStatus(t.FRAMEBUFFER);if(e!==t.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+he(t,e))}function he(t,e){switch(e){case t.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case t.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case t.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:return"FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case t.FRAMEBUFFER_UNSUPPORTED:return"FRAMEBUFFER_UNSUPPORTED";default:return"unknown error "+e}}function fe(t,e,n,r){var i=Bt(t,e,function(){return n()});if(null==i)throw new Error(r);return i}function de(t,e){var n=t.MAX_COMBINED_TEXTURE_IMAGE_UNITS-1,r=e+t.TEXTURE0;if(rn)throw new Error("textureUnit must be in [gl.TEXTURE0, gl.TEXTURE"+n+"].")}function me(t,e){return void 0===e&&(e=2),v(t.slice(0,t.length-e))}function ge(t){if(0===t.length)throw Error("Cannot get rows and columns of an empty shape array.");return[t.length>1?t[t.length-2]:1,t[t.length-1]]}function ve(t){var e=[1,1,1];return 0===t.length||1===t.length&&1===t[0]||(e=[me(t)].concat(ge(t))),e}function ye(e,n){var r;void 0===n&&(n=!1);var i=t.ENV.getNumber("WEBGL_MAX_TEXTURE_SIZE");if(n&&(i*=2,1===(e=e.map(function(t,n){return n>=e.length-2?p(e[n]):e[n]})).length&&(e=[2,e[0]])),2!==e.length){var a=k(e);e=a.newShape}var o=v(e);if(e.length<=1&&o<=i)return[1,o];if(2===e.length&&e[0]<=i&&e[1]<=i)return e;if(3===e.length&&e[0]*e[1]<=i&&e[2]<=i)return[e[0]*e[1],e[2]];if(3===e.length&&e[0]<=i&&e[1]*e[2]<=i)return[e[0],e[1]*e[2]];if(4===e.length&&e[0]*e[1]*e[2]<=i&&e[3]<=i)return[e[0]*e[1]*e[2],e[3]];if(4===e.length&&e[0]<=i&&e[1]*e[2]*e[3]<=i)return[e[0],e[1]*e[2]*e[3]];if(n){var s=me(e),u=2,l=2;return e.length&&(u=(r=ge(e))[0],l=r[1]),w(o=s*(u/2)*(l/2)).map(function(t){return 2*t})}return w(o)}function be(t){return t%2==0}function xe(t,e){if(y(t=t.slice(-2),e=e.slice(-2)))return!0;if(!t.length||!e.length)return!0;if(0===t[0]||0===t[1]||0===e[0]||0===e[1])return!0;if(t.length!==e.length){var n=t.slice(-1)[0],r=e.slice(-1)[0];if(n===r)return!0;if(be(n)&&be(r)&&(1===t[0]||1===e[0]))return!0}return t[1]===e[1]&&be(t[0])&&be(e[0])}function we(t){if(null==Kt){var e=_t(t);Kt=e.getParameter(e.MAX_TEXTURE_SIZE)}return Kt}function Ne(t){if(null==$t){var e=_t(t);$t=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS)}return Math.min(16,$t)}function Ce(t){if(0===t)return 0;var e=_t(t);return Ee(e,"EXT_disjoint_timer_query_webgl2")&&2===t?2:Ee(e,"EXT_disjoint_timer_query")?1:0}function Ee(t,e){return null!=t.getExtension(e)}function Se(t){try{if(null!=_t(t))return!0}catch(t){return!1}return!1}function ke(t){if(0===t)return!1;var e=_t(t);if(1===t){if(!Ee(e,"OES_texture_float"))return!1}else if(!Ee(e,"EXT_color_buffer_float"))return!1;return Ae(e)}function Ie(t){if(0===t)return!1;var e=_t(t);return 1!==t?Ee(e,"EXT_color_buffer_float")?Ae(e):!!Ee(e,"EXT_color_buffer_half_float")&&function(t,e){var n=Pt(t,e),r=t.createTexture();t.bindTexture(t.TEXTURE_2D,r),t.texImage2D(t.TEXTURE_2D,0,n.internalFormatHalfFloat,1,1,0,n.textureFormatFloat,n.textureTypeHalfFloat,null);var i=t.createFramebuffer();t.bindFramebuffer(t.FRAMEBUFFER,i),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,r,0);var a=t.checkFramebufferStatus(t.FRAMEBUFFER)===t.FRAMEBUFFER_COMPLETE;return t.bindTexture(t.TEXTURE_2D,null),t.bindFramebuffer(t.FRAMEBUFFER,null),t.deleteTexture(r),t.deleteFramebuffer(i),a}(e,e.getExtension("EXT_color_buffer_half_float")):!!Ee(e,"OES_texture_float")&&!!Ee(e,"WEBGL_color_buffer_float")&&Ae(e)}function Ae(t){var e=Pt(t),n=t.createTexture();t.bindTexture(t.TEXTURE_2D,n),t.texImage2D(t.TEXTURE_2D,0,e.internalFormatFloat,1,1,0,e.textureFormatFloat,e.textureTypeFloat,null);var r=t.createFramebuffer();t.bindFramebuffer(t.FRAMEBUFFER,r),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,n,0);var i=t.checkFramebufferStatus(t.FRAMEBUFFER)===t.FRAMEBUFFER_COMPLETE;return t.bindTexture(t.TEXTURE_2D,null),t.bindFramebuffer(t.FRAMEBUFFER,null),t.deleteTexture(n),t.deleteFramebuffer(r),i}function Re(t){return 2===t&&null!=_t(t).fenceSync}var Te=Object.freeze({callAndCheck:Bt,canBeRepresented:Ut,getWebGLErrorMessage:jt,getExtensionOrThrow:Gt,createVertexShader:Ht,createFragmentShader:qt,createProgram:Yt,linkProgram:Jt,validateProgram:Zt,createStaticVertexBuffer:Qt,createStaticIndexBuffer:te,getNumChannels:function(){return 2===t.ENV.getNumber("WEBGL_VERSION")?1:4},createTexture:ee,validateTextureSize:ne,createFramebuffer:re,bindVertexBufferToProgramAttribute:ie,bindTextureUnit:ae,unbindTextureUnit:function(t,e,n){de(t,n),Bt(t,e,function(){return t.activeTexture(t.TEXTURE0+n)}),Bt(t,e,function(){return t.bindTexture(t.TEXTURE_2D,null)})},getProgramUniformLocationOrThrow:oe,getProgramUniformLocation:se,bindTextureToProgramUniformSampler:ue,bindCanvasToFramebuffer:function(t,e){Bt(t,e,function(){return t.bindFramebuffer(t.FRAMEBUFFER,null)}),Bt(t,e,function(){return t.viewport(0,0,t.canvas.width,t.canvas.height)}),Bt(t,e,function(){return t.scissor(0,0,t.canvas.width,t.canvas.height)})},bindColorTextureToFramebuffer:le,unbindColorTextureFromFramebuffer:ce,validateFramebuffer:pe,getFramebufferErrorMessage:he,getBatchDim:me,getRowsCols:ge,getShapeAs3D:ve,getTextureShapeFromLogicalShape:ye,isReshapeFree:xe,getWebGLMaxTextureSize:we,resetMaxTextureSize:function(){Kt=null},resetMaxTexturesInShader:function(){$t=null},getMaxTexturesInShader:Ne,getWebGLDisjointQueryTimerVersion:Ce,hasExtension:Ee,isWebGLVersionEnabled:Se,isCapableOfRenderingToFloatTexture:ke,isDownloadFloatTextureEnabled:Ie,isWebGLFenceEnabled:Re});function De(e){t.ENV.getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(e+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")}function Oe(){return kt.memory()}function _e(t,e){return kt.tidy(t,e)}function Fe(t){wt(t).forEach(function(t){return t.dispose()})}function Me(t){return kt.keep(t)}function ze(){return kt.backend}function Le(){for(var e=[],n=0;n0,function(){return"Element arr["+r.join("][")+"] should be a primitive, but is an array of "+e.length+" elements"}),f(e.length===n[0],function(){return"Element arr["+r.join("][")+"] should have "+n[0]+" elements, but has "+e.length+" elements"});for(var i=n.slice(1),a=0;a=0&&(a=i),Be(i,a,n,r),null==e||!O(e)&&!Array.isArray(e)&&"number"!=typeof e&&"boolean"!=typeof e&&"string"!=typeof e){var o=null==e?"null":e.constructor.name;throw new Error("Argument '"+n+"' passed to '"+r+"' must be a Tensor or TensorLike, but got '"+o+"'")}var s=Pe(e,a);O(e)||Array.isArray(e)||(e=[e]);var u="string"!==a?U(e,a,t.ENV.getBool("DEBUG")):g(e,[],!0);return lt.make(s,{values:u},a)}function We(t,e,n,r){if(void 0===r&&(r="numeric"),!Array.isArray(t))throw new Error("Argument "+e+" passed to "+n+" must be a `Tensor[]` or `TensorLike[]`");return t.map(function(t,r){return Ve(t,e+"["+r+"]",n)},r)}function Ue(t,e){for(var n=0;n=0&&e0}),t.ENV.registerFlag("WEBGL_VERSION",function(){return Se(2)?2:Se(1)?1:0}),t.ENV.registerFlag("WEBGL_BUFFER_SUPPORTED",function(){return 2===t.ENV.get("WEBGL_VERSION")}),t.ENV.registerFlag("WEBGL_CPU_FORWARD",function(){return!0}),t.ENV.registerFlag("WEBGL_FORCE_F16_TEXTURES",function(){return!1}),t.ENV.registerFlag("WEBGL_PACK",function(){return t.ENV.getBool("HAS_WEBGL")}),t.ENV.registerFlag("WEBGL_PACK_NORMALIZATION",function(){return t.ENV.getBool("WEBGL_PACK")}),t.ENV.registerFlag("WEBGL_PACK_CLIP",function(){return t.ENV.getBool("WEBGL_PACK")}),t.ENV.registerFlag("WEBGL_PACK_DEPTHWISECONV",function(){return!1}),t.ENV.registerFlag("WEBGL_PACK_BINARY_OPERATIONS",function(){return t.ENV.getBool("WEBGL_PACK")}),t.ENV.registerFlag("WEBGL_PACK_UNARY_OPERATIONS",function(){return t.ENV.getBool("WEBGL_PACK")}),t.ENV.registerFlag("WEBGL_PACK_ARRAY_OPERATIONS",function(){return t.ENV.getBool("WEBGL_PACK")}),t.ENV.registerFlag("WEBGL_PACK_IMAGE_OPERATIONS",function(){return t.ENV.getBool("WEBGL_PACK")}),t.ENV.registerFlag("WEBGL_PACK_REDUCE",function(){return t.ENV.getBool("WEBGL_PACK")}),t.ENV.registerFlag("WEBGL_LAZILY_UNPACK",function(){return t.ENV.getBool("WEBGL_PACK")}),t.ENV.registerFlag("WEBGL_CONV_IM2COL",function(){return t.ENV.getBool("WEBGL_PACK")}),t.ENV.registerFlag("WEBGL_MAX_TEXTURE_SIZE",function(){return we(t.ENV.getNumber("WEBGL_VERSION"))}),t.ENV.registerFlag("WEBGL_MAX_TEXTURES_IN_SHADER",function(){return Ne(t.ENV.getNumber("WEBGL_VERSION"))}),t.ENV.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION",function(){var e=t.ENV.getNumber("WEBGL_VERSION");return 0===e?0:Ce(e)}),t.ENV.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE",function(){return t.ENV.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0&&(e=navigator.userAgent||navigator.vendor||window.opera,!(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(e)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(e.substr(0,4))));var e}),t.ENV.registerFlag("WEBGL_RENDER_FLOAT32_CAPABLE",function(){return ke(t.ENV.getNumber("WEBGL_VERSION"))}),t.ENV.registerFlag("WEBGL_RENDER_FLOAT32_ENABLED",function(){return!t.ENV.getBool("WEBGL_FORCE_F16_TEXTURES")&&t.ENV.getBool("WEBGL_RENDER_FLOAT32_CAPABLE")}),t.ENV.registerFlag("WEBGL_DOWNLOAD_FLOAT_ENABLED",function(){return Ie(t.ENV.getNumber("WEBGL_VERSION"))}),t.ENV.registerFlag("WEBGL_FENCE_API_ENABLED",function(){return Re(t.ENV.getNumber("WEBGL_VERSION"))}),t.ENV.registerFlag("WEBGL_SIZE_UPLOAD_UNIFORM",function(){return t.ENV.getBool("WEBGL_RENDER_FLOAT32_ENABLED")?4:0}),ut=De;var Qe=Ze({complex_:function(t,e){var n=Ve(t,"real","complex"),r=Ve(e,"imag","complex");return d(n.shape,r.shape,"real and imag shapes, "+n.shape+" and "+r.shape+", must match in call to tf.complex()."),kt.runKernel(function(t){return t.complex(n,r)},{$real:n,$imag:r})}}),tn=Ze({real_:function(t){var e=Ve(t,"input","real");return kt.runKernel(function(t){return t.real(e)},{$input:e})}}),en=Ze({imag_:function(t){var e=Ve(t,"input","imag");return kt.runKernel(function(t){return t.imag(e)},{$input:e})}});function nn(t,e,n){return rn(t,e,Pe(t,n),n)}function rn(e,n,r,i){if(null==i&&(i=P(e)),"complex64"===i)throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if(!O(e)&&!Array.isArray(e)&&"number"!=typeof e&&"boolean"!=typeof e&&"string"!=typeof e)throw new Error("values passed to tensor(values) must be a number/boolean/string or an array of numbers/booleans/strings, or a TypedArray");if(null!=n){K(n);var a=v(n),o=v(r);f(a===o,function(){return"Based on the provided shape, ["+n+"], the tensor should have "+a+" values but has "+o});for(var s=0;s1)return fn([0],r);var i=H(Math.abs(Math.ceil((e-t)/n)),r);e=1,function(){return"Pass at least one tensor to concat"});var n=We(t,"tensors","concat");"complex64"===n[0].dtype&&n.forEach(function(t){if("complex64"!==t.dtype)throw new Error("Cannot concatenate complex64 tensors with a tensor\n with dtype "+t.dtype+". ")}),e=S(e,n[0].shape)[0];var r=Je(n.map(function(t){return t.shape}),e);if(0===v(r))return nn([],r);if(1===(n=n.filter(function(t){return t.size>0})).length)return n[0];var i=n.map(function(t){return t.shape});Ye(i,e);var a=n;return kt.runKernel(function(t){return t.concat(n,e)},a,function(t){var n=i.map(function(t){return t[e]});return En(t,n,e).map(function(t){return function(){return t}})})}}),xn=Ze({concat1d_:function(t){return bn(t,0)}}),wn=Ze({concat2d_:function(t,e){return bn(t,e)}}),Nn=Ze({concat3d_:function(t,e){return bn(t,e)}}),Cn=Ze({concat4d_:function(t,e){return bn(t,e)}}),En=Ze({split_:function(t,e,n){void 0===n&&(n=0);var r,i=Ve(t,"x","split");return n=S(n,i.shape)[0],"number"==typeof e?(f(i.shape[n]%e==0,function(){return"Number of splits must evenly divide the axis."}),r=new Array(e).fill(i.shape[n]/e)):(f(i.shape[n]===e.reduce(function(t,e){return t+e}),function(){return"The sum of sizes must match the size of the axis dimension."}),r=e),kt.runKernel(function(t){return t.split(i,r,n)},{$x:i},function(t){return{$x:function(){return bn(t,n)}}})}});function Sn(t,e){return t(e={exports:{}},e.exports),e.exports}var kn=Sn(function(t){!function(t,e,n){function r(t,e){return e.c=t.c,e.s0=t.s0,e.s1=t.s1,e.s2=t.s2,e}function i(t,e){var n=new function(t){var e,n=this,r=(e=4022871197,function(t){t=t.toString();for(var n=0;n>>0,e=(r*=e)>>>0,e+=4294967296*(r-=e)}return 2.3283064365386963e-10*(e>>>0)});n.next=function(){var t=2091639*n.s0+2.3283064365386963e-10*n.c;return n.s0=n.s1,n.s1=n.s2,n.s2=t-(n.c=0|t)},n.c=1,n.s0=r(" "),n.s1=r(" "),n.s2=r(" "),n.s0-=r(t),n.s0<0&&(n.s0+=1),n.s1-=r(t),n.s1<0&&(n.s1+=1),n.s2-=r(t),n.s2<0&&(n.s2+=1),r=null}(t),i=e&&e.state,a=n.next;return a.int32=function(){return 4294967296*n.next()|0},a.double=function(){return a()+1.1102230246251565e-16*(2097152*a()|0)},a.quick=a,i&&("object"==typeof i&&r(i,n),a.state=function(){return r(n,{})}),a}e&&e.exports?e.exports=i:this.alea=i}(0,t)}),In=Sn(function(t){!function(t,e,n){function r(t,e){return e.x=t.x,e.y=t.y,e.z=t.z,e.w=t.w,e}function i(t,e){var n=new function(t){var e=this,n="";e.x=0,e.y=0,e.z=0,e.w=0,e.next=function(){var t=e.x^e.x<<11;return e.x=e.y,e.y=e.z,e.z=e.w,e.w^=e.w>>>19^t^t>>>8},t===(0|t)?e.x=t:n+=t;for(var r=0;r>>0)/4294967296};return a.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},a.int32=n.next,a.quick=a,i&&("object"==typeof i&&r(i,n),a.state=function(){return r(n,{})}),a}e&&e.exports?e.exports=i:this.xor128=i}(0,t)}),An=Sn(function(t){!function(t,e,n){function r(t,e){return e.x=t.x,e.y=t.y,e.z=t.z,e.w=t.w,e.v=t.v,e.d=t.d,e}function i(t,e){var n=new function(t){var e=this,n="";e.next=function(){var t=e.x^e.x>>>2;return e.x=e.y,e.y=e.z,e.z=e.w,e.w=e.v,(e.d=e.d+362437|0)+(e.v=e.v^e.v<<4^t^t<<1)|0},e.x=0,e.y=0,e.z=0,e.w=0,e.v=0,t===(0|t)?e.x=t:n+=t;for(var r=0;r>>4),e.next()}(t),i=e&&e.state,a=function(){return(n.next()>>>0)/4294967296};return a.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},a.int32=n.next,a.quick=a,i&&("object"==typeof i&&r(i,n),a.state=function(){return r(n,{})}),a}e&&e.exports?e.exports=i:this.xorwow=i}(0,t)}),Rn=Sn(function(t){!function(t,e,n){function r(t,e){return e.x=t.x.slice(),e.i=t.i,e}function i(t,e){null==t&&(t=+new Date);var n=new function(t){var e=this;e.next=function(){var t,n,r=e.x,i=e.i;return t=r[i],n=(t^=t>>>7)^t<<24,n^=(t=r[i+1&7])^t>>>10,n^=(t=r[i+3&7])^t>>>3,n^=(t=r[i+4&7])^t<<7,t=r[i+7&7],n^=(t^=t<<13)^t<<9,r[i]=n,e.i=i+1&7,n},function(t,e){var n,r=[];if(e===(0|e))r[0]=e;else for(e=""+e,n=0;n0;--n)t.next()}(e,t)}(t),i=e&&e.state,a=function(){return(n.next()>>>0)/4294967296};return a.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},a.int32=n.next,a.quick=a,i&&(i.x&&r(i,n),a.state=function(){return r(n,{})}),a}e&&e.exports?e.exports=i:this.xorshift7=i}(0,t)}),Tn=Sn(function(t){!function(t,e,n){function r(t,e){return e.i=t.i,e.w=t.w,e.X=t.X.slice(),e}function i(t,e){null==t&&(t=+new Date);var n=new function(t){var e=this;e.next=function(){var t,n,r=e.w,i=e.X,a=e.i;return e.w=r=r+1640531527|0,n=i[a+34&127],t=i[a=a+1&127],n^=n<<13,t^=t<<17,n^=n>>>15,t^=t>>>12,n=i[a]=n^t,e.i=a,n+(r^r>>>16)|0},function(t,e){var n,r,i,a,o,s=[],u=128;for(e===(0|e)?(r=e,e=null):(e+="\0",r=0,u=Math.max(u,e.length)),i=0,a=-32;a>>15,r^=r<<4,r^=r>>>13,a>=0&&(o=o+1640531527|0,i=0==(n=s[127&a]^=r+o)?i+1:0);for(i>=128&&(s[127&(e&&e.length||0)]=-1),i=127,a=512;a>0;--a)r=s[i+34&127],n=s[i=i+1&127],r^=r<<13,n^=n<<17,r^=r>>>15,n^=n>>>12,s[i]=r^n;t.w=o,t.X=s,t.i=i}(e,t)}(t),i=e&&e.state,a=function(){return(n.next()>>>0)/4294967296};return a.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},a.int32=n.next,a.quick=a,i&&(i.X&&r(i,n),a.state=function(){return r(n,{})}),a}e&&e.exports?e.exports=i:this.xor4096=i}(0,t)}),Dn=Sn(function(t){!function(t,e,n){function r(t,e){return e.a=t.a,e.b=t.b,e.c=t.c,e.d=t.d,e}function i(t,e){var n=new function(t){var e=this,n="";e.next=function(){var t=e.b,n=e.c,r=e.d,i=e.a;return t=t<<25^t>>>7^n,n=n-r|0,r=r<<24^r>>>8^i,i=i-t|0,e.b=t=t<<20^t>>>12^n,e.c=n=n-r|0,e.d=r<<16^n>>>16^i,e.a=i-t|0},e.a=0,e.b=0,e.c=-1640531527,e.d=1367130551,t===Math.floor(t)?(e.a=t/4294967296|0,e.b=0|t):n+=t;for(var r=0;r>>0)/4294967296};return a.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},a.int32=n.next,a.quick=a,i&&("object"==typeof i&&r(i,n),a.state=function(){return r(n,{})}),a}e&&e.exports?e.exports=i:this.tychei=i}(0,t)}),On=Sn(function(t){!function(e,n){var r,i=this,a=256,o=6,s="random",u=n.pow(a,o),l=n.pow(2,52),c=2*l,p=a-1;function h(t,p,h){var v=[],y=m(function t(e,n){var r,i=[],a=typeof e;if(n&&"object"==a)for(r in e)try{i.push(t(e[r],n-1))}catch(t){}return i.length?i:"string"==a?e:e+"\0"}((p=1==p?{entropy:!0}:p||{}).entropy?[t,g(e)]:null==t?function(){try{var t;return r&&(t=r.randomBytes)?t=t(a):(t=new Uint8Array(a),(i.crypto||i.msCrypto).getRandomValues(t)),g(t)}catch(t){var n=i.navigator,o=n&&n.plugins;return[+new Date,i,o,i.screen,g(e)]}}():t,3),v),b=new f(v),x=function(){for(var t=b.g(o),e=u,n=0;t=c;)t/=2,e/=2,n>>>=1;return(t+n)/e};return x.int32=function(){return 0|b.g(4)},x.quick=function(){return b.g(4)/4294967296},x.double=x,m(g(b.S),e),(p.pass||h||function(t,e,r,i){return i&&(i.S&&d(i,b),t.state=function(){return d(b,{})}),r?(n[s]=t,e):t})(x,y,"global"in p?p.global:this==n,p.state)}function f(t){var e,n=t.length,r=this,i=0,o=r.i=r.j=0,s=r.S=[];for(n||(t=[n++]);i=1||0===o);var s=Math.sqrt(-2*Math.log(o)/o);e=this.mean+this.stdDev*i*s,n=this.mean+this.stdDev*a*s,this.truncated&&!this.isValidTruncated(e)||(r=!0)}return this.truncated&&!this.isValidTruncated(n)||(this.nextVal=this.convertValue(n)),this.convertValue(e)},t.prototype.convertValue=function(t){return null==this.dtype||"float32"===this.dtype?t:Math.round(t)},t.prototype.isValidTruncated=function(t){return t<=this.upper&&t>=this.lower},t}(),Mn=function(){function t(t,e,n,r){this.alpha=t,this.beta=1/e,this.dtype=n;var i=r||Math.random();this.randu=_n(i.toString()),this.randn=new Fn(0,1,n,!1,this.randu()),this.d=t<1?t+2/3:t-1/3,this.c=1/Math.sqrt(9*this.d)}return t.prototype.nextValue=function(){for(var t,e,n,r,i,a;;){do{r=this.randn.nextValue(),a=1+this.c*r}while(a<=0);if(a*=a*a,e=1-.331*(t=r*r)*t,n=.5*t+this.d*(1-a+Math.log(a)),(i=this.randu())=1+e.length,function(){return"input rank is "+r.rank+" but should be > than blockShape.length "+e.length}),f(n.length===e.length,function(){return"crops.length is "+n.length+" but should be equal to blockShape.length "+e.length}),f(r.shape[0]%i==0,function(){return"input tensor batch is "+r.shape[0]+" but is not divisible by the product of the elements of blockShape "+e.join(" * ")+" === "+i}),kt.runKernel(function(t){return t.batchToSpaceND(r,e,n)},{$x:r},function(t){return{$x:function(){return t.spaceToBatchND(e,n)}}})}}),Vn=Ze({cast_:function(t,e){var n=Ve(t,"x","cast");if(!T(e))throw new Error("Failed to cast to unknown dtype "+e);if("string"===e&&"string"!==n.dtype||"string"!==e&&"string"===n.dtype)throw new Error("Only strings can be casted to strings");return kt.runKernel(function(t){return t.cast(n,e)},{$x:n},function(t){return{$x:function(){return t.clone()}}})}}),Wn=Ze({clone_:function(t){var e=Ve(t,"x","clone",null);return kt.runKernel(function(t){return lt.make(e.shape,{dataId:e.dataId},e.dtype)},{$x:e},function(t){return{$x:function(){return t.toFloat()}}})}}),Un=Ze({cumsum_:function(t,e,n,r){void 0===e&&(e=0),void 0===n&&(n=!1),void 0===r&&(r=!1);var i=Ve(t,"x","cumsum"),a=Ke([e|=0],i.rank),o=i;null!=a&&(o=i.transpose(a));var s=Xe(1,i.rank)[0],u=kt.runKernel(function(t){return t.cumsum(o,s,n,r)},{permutedX:o},function(t){return{permutedX:function(){return t.cumsum(e,n,!r)}}});return null!=a&&(u=u.transpose(a)),u}}),jn=Ze({depthToSpace_:function(t,e,n){void 0===n&&(n="NHWC");var r=Ve(t,"x","depthToSpace"),i="NHWC"===n?r.shape[1]:r.shape[2],a="NHWC"===n?r.shape[2]:r.shape[3],o="NHWC"===n?r.shape[3]:r.shape[1];return f(i*e>=0,function(){return"Negative dimension size caused by overflow when multiplying\n "+i+" and "+e+" for depthToSpace with input shape\n "+r.shape}),f(a*e>=0,function(){return"Negative dimension size caused by overflow when multiplying\n "+a+" and "+e+" for depthToSpace with input shape\n "+r.shape}),f(o%(e*e)==0,function(){return"Dimension size must be evenly divisible by "+e*e+" but is "+o+" for depthToSpace with input shape "+r.shape}),kt.runKernel(function(t){return t.depthToSpace(r,e,n)},{$x:r})}}),Gn=Ze({expandDims_:function(t,e){void 0===e&&(e=0);var n=Ve(t,"x","expandDims",null);f(e<=n.rank,function(){return"Axis must be <= rank of the tensor"});var r=n.shape.slice();return e<0&&(f(-(n.rank+1)<=e,function(){return"Axis must be in the interval ["+-(n.rank+1)+", "+n.rank+"]"}),e=n.rank+e+1),r.splice(e,0,1),rr(n,r)}}),Hn=Ze({eye_:function(t,e,n,r){void 0===r&&(r="float32"),null==e&&(e=t);for(var i=Ln([t,e],r),a=t<=e?t:e,o=0;o2)throw new Error("Rank of probabilities must be 1 or 2, but is "+o);n=n||Math.random();var s=1===o?i.as2D(1,-1):i,u=kt.runKernel(function(t){return t.multinomial(s,r,e,n)},{logits2D:s});return 1===o?u.as1D():u}}),Kn=Ze({oneHot_:function(t,e,n,r){if(void 0===n&&(n=1),void 0===r&&(r=0),e<2)throw new Error("Error in oneHot: depth must be >=2, but it is "+e);var i=Ve(t,"indices","oneHot","int32"),a=i.shape.concat([e]);return i=i.flatten(),kt.runKernel(function(t){return t.oneHot(i,e,n,r)},{$indices:i},function(t){return{$indices:function(){return fn(i.shape,"float32")}}}).reshape(a)}}),$n=Ze({pad_:function(t,e,n){void 0===n&&(n=0);var r=Ve(t,"x","pad");if(0===r.rank)throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");var i=e.map(function(t){return t[0]});return kt.runKernel(function(t){return t.pad(r,e,n)},{$x:r},function(t){return{$x:function(){return t.slice(i,r.shape)}}})}}),Xn=Ze({pad1d_:function(t,e,n){return void 0===n&&(n=0),f(2===e.length,function(){return"Invalid number of paddings. Must be length of 2."}),$n(t,[e],n)}}),Yn=Ze({pad2d_:function(t,e,n){return void 0===n&&(n=0),f(2===e.length&&2===e[0].length&&2===e[1].length,function(){return"Invalid number of paddings. Must be length of 2 each."}),$n(t,e,n)}}),Jn=Ze({pad3d_:function(t,e,n){return void 0===n&&(n=0),f(3===e.length&&2===e[0].length&&2===e[1].length&&2===e[2].length,function(){return"Invalid number of paddings. Must be length of 2 each."}),$n(t,e,n)}}),Zn=Ze({pad4d_:function(t,e,n){return void 0===n&&(n=0),f(4===e.length&&2===e[0].length&&2===e[1].length&&2===e[2].length&&2===e[3].length,function(){return"Invalid number of paddings. Must be length of 2 each."}),$n(t,e,n)}}),Qn=Ze({rand_:function(t,e,n){var r=v(t),i=null;if(null==n||"float32"===n)i=new Float32Array(r);else if("int32"===n)i=new Int32Array(r);else{if("bool"!==n)throw new Error("Unknown data type "+n);i=new Uint8Array(r)}for(var a=0;a=1+e.length,function(){return"input rank "+r.rank+" should be > than [blockShape] "+e.length}),f(n.length===e.length,function(){return"paddings.shape[0] "+n.length+" must be equal to [blockShape] "+e.length}),f(r.shape.reduce(function(t,r,i){return i>0&&i<=e.length?t&&(r+n[i-1][0]+n[i-1][1])%e[i-1]==0:t},!0),function(){return"input spatial dimensions "+r.shape.slice(1)+" with paddings "+n.toString()+" must be divisible by blockShapes "+e.toString()}),kt.runKernel(function(t){return t.spaceToBatchND(r,e,n)},{$x:r},function(t){return{$x:function(){return t.batchToSpaceND(e,n)}}})}}),ar=Ze({squeeze_:function(t,e){var n=Ve(t,"x","squeeze");return rr(n,k(n.shape,e).newShape)}}),or=Ze({stack_:function(t,e){void 0===e&&(e=0);var n=We(t,"tensors","stack");if(f(n.length>=1,function(){return"Pass at least one tensor to tf.stack"}),1===n.length)return n[0].expandDims(e);var r=n[0].rank,i=n[0].shape,a=n[0].dtype;f(e<=r,function(){return"Axis must be <= rank of the tensor"}),n.forEach(function(t){d(i,t.shape,"All tensors passed to stack must have matching shapes")}),n.forEach(function(t){f(a===t.dtype,function(){return"All tensors passed to stack must have matching dtypes"})});var o=n.map(function(t){return t.expandDims(e)});return bn(o,e)}}),sr=Ze({tile_:function(t,e){var n=Ve(t,"x","tile",null);return f(n.rank===e.length,function(){return"Error in transpose: rank of input "+n.rank+" must match length of reps "+e+"."}),kt.runKernel(function(t,r){var i=t.tile(n,e);return r([n]),i},{$x:n},function(t,n){var r=n[0];return{$x:function(){var n=yn(r);if(1===r.rank)for(var i=0;i=-n.shape.length&&e=2*e+1||i%2==1?o.push(i):a.push(i);r.push.apply(r,a),r.push(0),r.push.apply(r,o)}return r}function fr(t,e,n,r){void 0===r&&(r=!0);var i=[];r?i.push(t[0]/n):i.push(t[0]*n);for(var a=1;at.rank)throw new Error("index innermost dimension length must be <= tensor rank; saw: "+e.shape[e.rank-1]+" vs. "+t.rank);if(0===t.size)throw new Error("Requested more than 0 entries, but input is empty. Input shape: "+t.shape+".");for(var n=e.shape,r=n[n.length-1],i=1,a=0;a1?e.shape[e.rank-1]:1,i=n.length,a=1,o=r;o0;)1&t&&e.push(n),t/=2,n++;return e}function wr(t,e,n){for(var r=[],i=0;i0?Number.MIN_SAFE_INTEGER:Number.MAX_SAFE_INTEGER);var s=r[i];return a<0&&(a+=s),c(0,a,s-1)}function Cr(t,e,n,r,i){var a=e[i],o=n[i]||1;(t&1<0?Number.MAX_SAFE_INTEGER:Number.MIN_SAFE_INTEGER);var s=r[i];return a<0&&(a+=s),o>0?c(0,a,s):c(-1,a,s-1)}function Er(t,e,n){for(var r=n.length,i=0;i1){r=i;break}for(i=r+1;i0||n[i]!==t[i])return!1;return!0}function Sr(t,e){for(var n=t.length>0?t[t.length-1]:1,r=0;r0,function(){return"variableGrads() expects at least one of the input variables to be trainable, but none of the "+a+" variables is trainable."});var o=kt.gradients(t,e,null,!0),s=o.value,u=o.grads;f(u.some(function(t){return null!=t}),function(){return"Cannot find a connection between any variable and the result of the loss function y=f(x). Please make sure the operations that use variables are inside the function f passed to minimize()."}),f(0===s.rank,function(){return"The f passed in variableGrads(f) must return a scalar, but it returned a rank-"+s.rank+" tensor"});var l={};return e.forEach(function(t,e){null!=u[e]&&(l[t.name]=u[e])}),null!=i&&i.forEach(function(t){return l[t.name]=null}),{value:s,grads:l}}function Ir(t){return kt.customGrad(t)}function Ar(t){if(t.filter(function(t){return null==t}).length>0)throw new Error("Cannot compute gradient of y=f(x) with respect to x. Make sure that\n the f you passed encloses all operations that lead from x to y.")}var Rr=Ze({softmax_:function(t,e){void 0===e&&(e=-1);var n=Ve(t,"logits","softmax");if(-1===e&&(e=n.rank-1),e!==n.rank-1)throw Error("Softmax along a non-last dimension is not yet supported. Logits was rank "+n.rank+" and dim was "+e);return Ir(function(t,n){var r=t.logSumExp([e],!0),i=t.toFloat().sub(r).exp();return n([i]),{value:i,gradFunc:function(t,n){var r=n[0],i=t.mul(r);return i.sub(i.sum([e],!0).mul(r))}}})(n)}}),Tr=Ze({logSoftmax_:function(t,e){void 0===e&&(e=-1);var n=Ve(t,"logits","logSoftmax");if(-1===e&&(e=n.rank-1),e!==n.rank-1)throw Error("Log Softmax along a non-last dimension is not yet supported. Logits was rank "+n.rank+" and axis was "+e);return Ir(function(t,n){var r=t.max(e,!0),i=t.sub(r),a=i.toFloat().sub(i.exp().sum(e,!0).log());return n([a]),{value:a,gradFunc:function(t,n){var r=n[0].exp();return t.sub(t.sum(e,!0).mul(r))}}})(n)}}),Dr=function(){function t(t,e){this.backend=t,this.dataMover=e,this.data=new WeakMap}return t.prototype.get=function(t){return this.data.has(t)||this.dataMover.moveData(this.backend,t),this.data.get(t)},t.prototype.set=function(t,e){this.data.set(t,e)},t.prototype.has=function(t){return this.data.has(t)},t.prototype.delete=function(t){return this.data.delete(t)},t}(),Or=function(){function t(){}return t.prototype.time=function(t){throw new Error("Not yet implemented.")},t.prototype.read=function(t){throw new Error("Not yet implemented.")},t.prototype.readSync=function(t){throw new Error("Not yet implemented.")},t.prototype.disposeData=function(t){throw new Error("Not yet implemented.")},t.prototype.write=function(t,e){throw new Error("Not yet implemented.")},t.prototype.fromPixels=function(t,e){throw new Error("Not yet implemented.")},t.prototype.register=function(t,e,n){throw new Error("Not yet implemented.")},t.prototype.memory=function(){throw new Error("Not yet implemented.")},t.prototype.floatPrecision=function(){throw new Error("Not yet implemented")},t.prototype.epsilon=function(){return 32===this.floatPrecision()?1e-7:1e-4},t.prototype.batchMatMul=function(t,e,n,r){throw new Error("Not yet implemented")},t.prototype.fusedBatchMatMul=function(t){throw t.a,t.b,t.transposeA,t.transposeB,t.bias,t.activation,t.preluActivationWeights,new Error("Not yet implemented")},t.prototype.slice=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.stridedSlice=function(t,e,n,r){throw new Error("Not yet implemented")},t.prototype.unstack=function(t,e){throw new Error("Not yet implemented")},t.prototype.reverse=function(t,e){throw new Error("Not yet implemented")},t.prototype.concat=function(t,e){throw new Error("Not yet implemented")},t.prototype.neg=function(t){throw new Error("Not yet implemented")},t.prototype.add=function(t,e){throw new Error("Not yet implemented")},t.prototype.addN=function(t){throw new Error("Not yet implemented")},t.prototype.subtract=function(t,e){throw new Error("Not yet implemented")},t.prototype.multiply=function(t,e){throw new Error("Not yet implemented")},t.prototype.realDivide=function(t,e){throw new Error("Not yet implemented")},t.prototype.floorDiv=function(t,e){throw new Error("Not yet implemented")},t.prototype.sum=function(t,e){throw new Error("Not yet implemented")},t.prototype.prod=function(t,e){throw new Error("Not yet implemented")},t.prototype.unsortedSegmentSum=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.argMin=function(t,e){throw new Error("Not yet implemented")},t.prototype.argMax=function(t,e){throw new Error("Not yet implemented")},t.prototype.equal=function(t,e){throw new Error("Not yet implemented")},t.prototype.notEqual=function(t,e){throw new Error("Not yet implemented")},t.prototype.less=function(t,e){throw new Error("Not yet implemented")},t.prototype.lessEqual=function(t,e){throw new Error("Not yet implemented")},t.prototype.greater=function(t,e){throw new Error("Not yet implemented")},t.prototype.greaterEqual=function(t,e){throw new Error("Not yet implemented")},t.prototype.logicalNot=function(t){throw new Error("Not yet implemented")},t.prototype.logicalAnd=function(t,e){throw new Error("Not yet implemented")},t.prototype.logicalOr=function(t,e){throw new Error("Not yet implemented")},t.prototype.where=function(t){throw new Error("Not yet implemented")},t.prototype.select=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.topk=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.min=function(t,e){throw new Error("Not yet implemented")},t.prototype.minimum=function(t,e){throw new Error("Not yet implemented")},t.prototype.mod=function(t,e){throw new Error("Not yet implemented")},t.prototype.max=function(t,e){throw new Error("Not yet implemented")},t.prototype.maximum=function(t,e){throw new Error("Not yet implemented")},t.prototype.all=function(t,e){throw new Error("Not yet implemented")},t.prototype.any=function(t,e){throw new Error("Not yet implemented")},t.prototype.squaredDifference=function(t,e){throw new Error("Not yet implemented")},t.prototype.ceil=function(t){throw new Error("Not yet implemented")},t.prototype.floor=function(t){throw new Error("Not yet implemented")},t.prototype.round=function(t){throw new Error("Not yet implemented")},t.prototype.sign=function(t){throw new Error("Not yet implemented")},t.prototype.isNaN=function(t){throw new Error("Not yet implemented")},t.prototype.isInf=function(t){throw new Error("Not yet implemented")},t.prototype.isFinite=function(t){throw new Error("Not yet implemented")},t.prototype.pow=function(t,e){throw new Error("Not yet implemented")},t.prototype.exp=function(t){throw new Error("Not yet implemented")},t.prototype.expm1=function(t){throw new Error("Not yet implemented")},t.prototype.log=function(t){throw new Error("Not yet implemented")},t.prototype.log1p=function(t){throw new Error("Not yet implemented")},t.prototype.sqrt=function(t){throw new Error("Not yet implemented")},t.prototype.rsqrt=function(t){throw new Error("Not yet implemented")},t.prototype.square=function(t){throw new Error("Not yet implemented")},t.prototype.reciprocal=function(t){throw new Error("Not yet implemented")},t.prototype.relu=function(t){throw new Error("Not yet implemented")},t.prototype.prelu=function(t,e){throw new Error("Not yet implemented")},t.prototype.elu=function(t){throw new Error("Not yet implemented")},t.prototype.eluDer=function(t,e){throw new Error("Not yet implemented")},t.prototype.selu=function(t){throw new Error("Not yet implemented")},t.prototype.int=function(t){throw new Error("Not yet implemented")},t.prototype.clip=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.abs=function(t){throw new Error("Not yet implemented")},t.prototype.complexAbs=function(t){throw new Error("Not yet implemented")},t.prototype.sigmoid=function(t){throw new Error("Not yet implemented")},t.prototype.softplus=function(t){throw new Error("Not yet implemented")},t.prototype.sin=function(t){throw new Error("Not yet implemented")},t.prototype.cos=function(t){throw new Error("Not yet implemented")},t.prototype.tan=function(t){throw new Error("Not yet implemented")},t.prototype.asin=function(t){throw new Error("Not yet implemented")},t.prototype.acos=function(t){throw new Error("Not yet implemented")},t.prototype.atan=function(t){throw new Error("Not yet implemented")},t.prototype.atan2=function(t,e){throw new Error("Not yet implemented")},t.prototype.sinh=function(t){throw new Error("Not yet implemented")},t.prototype.cosh=function(t){throw new Error("Not yet implemented")},t.prototype.tanh=function(t){throw new Error("Not yet implemented")},t.prototype.asinh=function(t){throw new Error("Not yet implemented")},t.prototype.acosh=function(t){throw new Error("Not yet implemented")},t.prototype.atanh=function(t){throw new Error("Not yet implemented")},t.prototype.erf=function(t){throw new Error("Not yet implemented")},t.prototype.step=function(t,e){throw new Error("Not yet implemented")},t.prototype.fusedConv2d=function(t,e,n,r,i,a){throw new Error("Not yet implemented")},t.prototype.conv2d=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.conv2dDerInput=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.conv2dDerFilter=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.depthwiseConv2D=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.depthwiseConv2DDerInput=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.depthwiseConv2DDerFilter=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.conv3d=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.conv3dDerInput=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.conv3dDerFilter=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.maxPool=function(t,e){throw new Error("Not yet implemented")},t.prototype.maxPoolBackprop=function(t,e,n,r){throw new Error("Not yet implemented")},t.prototype.avgPool=function(t,e){throw new Error("Not yet implemented")},t.prototype.avgPoolBackprop=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.avgPool3d=function(t,e){throw new Error("Not yet implemented")},t.prototype.avgPool3dBackprop=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.maxPool3d=function(t,e){throw new Error("Not yet implemented")},t.prototype.maxPool3dBackprop=function(t,e,n,r){throw new Error("Not yet implemented")},t.prototype.reshape=function(t,e){throw new Error("Not yet implemented")},t.prototype.cast=function(t,e){throw new Error("Not yet implemented")},t.prototype.tile=function(t,e){throw new Error("Not yet implemented")},t.prototype.pad=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.transpose=function(t,e){throw new Error("Not yet implemented")},t.prototype.gather=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.gatherND=function(t,e){throw new Error("Not yet implemented")},t.prototype.scatterND=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.batchToSpaceND=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.spaceToBatchND=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.resizeBilinear=function(t,e,n,r){throw new Error("Not yet implemented")},t.prototype.resizeBilinearBackprop=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.resizeNearestNeighbor=function(t,e,n,r){throw new Error("Not yet implemented")},t.prototype.resizeNearestNeighborBackprop=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.batchNormalization=function(t,e,n,r,i,a){throw new Error("Not yet implemented")},t.prototype.localResponseNormalization4D=function(t,e,n,r,i){throw new Error("Not yet implemented")},t.prototype.LRNGrad=function(t,e,n,r,i,a,o){throw new Error("Not yet implemented")},t.prototype.multinomial=function(t,e,n,r){throw new Error("Not yet implemented")},t.prototype.oneHot=function(t,e,n,r){throw new Error("Not yet implemented")},t.prototype.cumsum=function(t,e,n,r){throw new Error("Not yet implemented")},t.prototype.nonMaxSuppression=function(t,e,n,r,i){throw new Error("Not yet implemented")},t.prototype.fft=function(t){throw new Error("Not yet implemented")},t.prototype.ifft=function(t){throw new Error("Not yet implemented")},t.prototype.complex=function(t,e){throw new Error("Not yet implemented")},t.prototype.real=function(t){throw new Error("Not yet implemented")},t.prototype.imag=function(t){throw new Error("Not yet implemented")},t.prototype.cropAndResize=function(t,e,n,r,i,a){throw new Error("Not yet implemented")},t.prototype.depthToSpace=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.split=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.sparseToDense=function(t,e,n,r){throw new Error("Not yet implemented")},t.prototype.diag=function(t){throw new Error("Not yet implemented")},t.prototype.fill=function(t,e,n){throw new Error("Not yet implemented.")},t.prototype.onesLike=function(t){throw new Error("Not yet implemented")},t.prototype.zerosLike=function(t){throw new Error("Not yet implemented")},t.prototype.linspace=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.dispose=function(){throw new Error("Not yet implemented")},t}();function _r(t,e){for(var n=t.length,r=[],i=0;i1&&1===o&&r.unshift(a)}return r}function Fr(t,e){for(var n=[],r=0;r1)&&n.unshift(a)}return n}function Mr(t,e){for(var n=[],r=Math.max(t.length,e.length),i=0;ii}).sort(function(t,e){return e.score-t.score}),o=[],s=0;s=0;--h)if(ri(t,c,o[h])>=r){p=!0;break}if(!p&&(o.push(c),o.length>=n))break}return on(o,"int32")}function ri(t,e,n){var r=t.subarray(4*e,4*e+4),i=t.subarray(4*n,4*n+4),a=Math.min(r[0],r[2]),o=Math.min(r[1],r[3]),s=Math.max(r[0],r[2]),u=Math.max(r[1],r[3]),l=Math.min(i[0],i[2]),c=Math.min(i[1],i[3]),p=Math.max(i[0],i[2]),h=Math.max(i[1],i[3]),f=(s-a)*(u-o),d=(p-l)*(h-c);if(f<=0||d<=0)return 0;var m=Math.max(a,l),g=Math.max(o,c),v=Math.min(s,p),y=Math.min(u,h),b=Math.max(v-m,0)*Math.max(y-g,0);return b/(f+d-b)}function ii(t,e,n){var r=new Array(t.rank).fill(0),i=t.shape.slice();return e.map(function(e){i[n]=e;var a=t.slice(r,i);return r[n]+=e,a})}function ai(t,e){for(var n=new Array(t.rank),r=0;r":"<",u=n?"inOffset + i;":"round(getBestIndicesA(batch, inOffset + i));";this.userCode="\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n int outIdx = coords[1];\n int inOffset = outIdx * "+r+";\n\n int bestIndex = inOffset;\n float bestValue = getA(batch, bestIndex);\n\n for (int i = 0; i < "+r+"; i++) {\n int inIdx = "+u+";\n float candidate = getA(batch, inIdx);\n if (candidate "+s+" bestValue) {\n bestValue = candidate;\n bestIndex = inIdx;\n }\n }\n setOutput(float(bestIndex));\n }\n "};function pi(t,e){return["x","y","z","w","u","v"].slice(0,e).map(function(e){return t+"."+e})}function hi(t,e){return 1===e?[t]:pi(t,e)}function fi(){var e,n,r,i,a,o,s,u,l,c;return 2===t.ENV.getNumber("WEBGL_VERSION")?(e="#version 300 es",n="in",r="out",i="in",a="texture",o="outputColor",s="out vec4 outputColor;",u="\n bool isnan_custom(float val) {\n return (val > 0. || val < 0. || val == 0.) ? false : true;\n }\n ",l="",c="\n #define round(value) newRound(value)\n int newRound(float value) {\n return int(floor(value + 0.5));\n }\n\n ivec4 newRound(vec4 value) {\n return ivec4(floor(value + vec4(0.5)));\n }\n "):(e="",n="attribute",r="varying",i="varying",a="texture2D",o="gl_FragColor",s="",u="\n bool isnan_custom(float val) {\n return (val > 0. || val < 1. || val == 0.) ? false : true;\n }\n ",l="\n uniform float INFINITY;\n\n bool isinf(float val) {\n return abs(val) == INFINITY;\n }\n bvec4 isinf(vec4 val) {\n return equal(abs(val), vec4(INFINITY));\n }\n ",c="\n int round(float value) {\n return int(floor(value + 0.5));\n }\n\n ivec4 round(vec4 value) {\n return ivec4(floor(value + vec4(0.5)));\n }\n "),{version:e,attribute:n,varyingVs:r,varyingFs:i,texture2D:a,output:o,defineOutput:s,defineSpecialNaN:u,defineSpecialInf:l,defineRound:c}}function di(t,e,n){void 0===n&&(n="index");var r=W(e);return r.map(function(e,i){return"int "+t[i]+" = "+n+" / "+e+"; "+(i===r.length-1?"int "+t[i+1]+" = "+n+" - "+t[i]+" * "+e:"index -= "+t[i]+" * "+e)+";"}).join("")}function mi(t){var e=W(t).map(function(t){return t.toString()});return"\n int getFlatIndex(ivec3 coords) {\n return coords.x * "+e[0]+" + coords.y * "+e[1]+" + coords.z;\n }\n"}var gi="\n const float FLOAT_MAX = 1.70141184e38;\n const float FLOAT_MIN = 1.17549435e-38;\n\n lowp vec4 encode_float(highp float v) {\n if (isnan(v)) {\n return vec4(255, 255, 255, 255);\n }\n\n highp float av = abs(v);\n\n if(av < FLOAT_MIN) {\n return vec4(0.0, 0.0, 0.0, 0.0);\n } else if(v > FLOAT_MAX) {\n return vec4(0.0, 0.0, 128.0, 127.0) / 255.0;\n } else if(v < -FLOAT_MAX) {\n return vec4(0.0, 0.0, 128.0, 255.0) / 255.0;\n }\n\n highp vec4 c = vec4(0,0,0,0);\n\n highp float e = floor(log2(av));\n highp float m = exp2(fract(log2(av))) - 1.0;\n\n c[2] = floor(128.0 * m);\n m -= c[2] / 128.0;\n c[1] = floor(32768.0 * m);\n m -= c[1] / 32768.0;\n c[0] = floor(8388608.0 * m);\n\n highp float ebias = e + 127.0;\n c[3] = floor(ebias / 2.0);\n ebias -= c[3] * 2.0;\n c[2] += floor(ebias) * 128.0;\n\n c[3] += 128.0 * step(0.0, -v);\n\n return c / 255.0;\n }\n";function vi(t,e,n,r){var i=[];t.forEach(function(t){var e=v(t.shapeInfo.logicalShape);t.shapeInfo.isUniform?i.push("uniform float "+t.name+(e>1?"["+e+"]":"")+";"):(i.push("uniform sampler2D "+t.name+";"),i.push("uniform int offset"+t.name+";"))});var a,o,s=i.join("\n"),u=t.map(function(t){return function(t,e,n){void 0===n&&(n=!1);var r="";r+=n?function t(e){var n,r,i;switch(e.shapeInfo.logicalShape.length){case 0:return n=e.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),i=fi(),"\n vec4 "+r+"() {\n return "+i.texture2D+"("+n+", halfCR);\n }\n ";case 1:return function(t){var e=t.name,n="get"+e.charAt(0).toUpperCase()+e.slice(1),r=t.shapeInfo.texShape,i=[Math.ceil(r[0]/2),Math.ceil(r[1]/2)],a=fi();return"\n vec4 "+n+"(int index) {\n vec2 uv = packedUVfrom1D(\n "+i[0]+", "+i[1]+", index);\n return "+a.texture2D+"("+e+", uv);\n }\n "}(e);case 2:return function(t){var e=t.shapeInfo.logicalShape,n=t.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),i=t.shapeInfo.texShape,a=i[0],o=i[1],s=fi();if(null!=i&&y(e,i))return"\n vec4 "+r+"(int row, int col) {\n vec2 uv = (vec2(col, row) + halfCR) / vec2("+o+".0, "+a+".0);\n\n return "+s.texture2D+"("+n+", uv);\n }\n ";var u=[Math.ceil(i[0]/2),Math.ceil(i[1]/2)],l=Math.ceil(e[1]/2);return"\n vec4 "+r+"(int row, int col) {\n vec2 uv = packedUVfrom2D("+l+", "+u[0]+", "+u[1]+", row, col);\n return "+s.texture2D+"("+n+", uv);\n }\n "}(e);case 3:return function(e){var n=e.shapeInfo.logicalShape,r=e.name,i="get"+r.charAt(0).toUpperCase()+r.slice(1),a=e.shapeInfo.texShape,o=[Math.ceil(a[0]/2),Math.ceil(a[1]/2)];if(1===n[0]){var s=n.slice(1),u=Si(e,s);return"\n "+t(u)+"\n vec4 "+i+"(int b, int row, int col) {\n return "+i+"("+ki(["b","row","col"],[1,2])+");\n }\n "}var l=o[0],c=o[1],p=Math.ceil(n[2]/2),h=p*Math.ceil(n[1]/2),f=fi();return"\n vec4 "+i+"(int b, int row, int col) {\n vec2 uv = packedUVfrom3D(\n "+l+", "+c+", "+h+", "+p+", b, row, col);\n return "+f.texture2D+"("+r+", uv);\n }\n "}(e);default:return function(t){for(var e=t.shapeInfo.logicalShape,n=e.length,r=t.name,i="get"+r.charAt(0).toUpperCase()+r.slice(1),a=t.shapeInfo.texShape,o=[Math.ceil(a[0]/2),Math.ceil(a[1]/2)],s=o[0],u=o[1],l=Math.ceil(e[n-1]/2),c=l*Math.ceil(e[n-2]/2),p="int b, int row, int col",h="b * "+c+" + (row / 2) * "+l+" + (col / 2)",f=2;f=1?"coords = 0;":u.map(function(t){return"coords."+p[t+c]+" = 0;"}).join("\n");var h;h=s<2&&o>0?"coords":t.shapeInfo.logicalShape.map(function(t,e){return"coords."+p[e+c]}).join(", ");var f="return outputValue;",d=1===v(t.shapeInfo.logicalShape),m=1===v(e.logicalShape);if(1!==o||d||m){if(d&&!m)f=1===s?"\n return vec4(outputValue.x, outputValue.x, 0., 0.);\n ":"\n return vec4(outputValue.x);\n ";else if(u.length){var g=o-2,y=o-1;u.indexOf(g)>-1&&u.indexOf(y)>-1?f="return vec4(outputValue.x);":u.indexOf(g)>-1?f="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":u.indexOf(y)>-1&&(f="return vec4(outputValue.xx, outputValue.zz);")}}else f="\n return vec4(outputValue.xy, outputValue.xy);\n ";return"\n vec4 "+a+"() {\n "+l+" coords = getOutputCoords();\n "+n+"\n vec4 outputValue = get"+i+"("+h+");\n "+f+"\n }\n "}(t,e):function(t,e){var n=t.name,r=n.charAt(0).toUpperCase()+n.slice(1),i="get"+r+"AtOutCoords",a=e.texShape,o=t.shapeInfo.texShape,s=t.shapeInfo.logicalShape.length,u=e.logicalShape.length;if(!t.shapeInfo.isUniform&&s===u&&null==t.shapeInfo.flatOffset&&y(o,a))return"\n float "+i+"() {\n return sampleTexture("+n+", resultUV);\n }\n ";var l=Ei(u),c=_r(t.shapeInfo.logicalShape,e.logicalShape),p=u-s,h=["x","y","z","w","u","v"];return"\n float "+i+"() {\n "+l+" coords = getOutputCoords();\n "+(0===s?"":u<2&&c.length>=1?"coords = 0;":c.map(function(t){return"coords."+h[t+p]+" = 0;"}).join("\n"))+"\n return get"+r+"("+(u<2&&s>0?"coords":t.shapeInfo.logicalShape.map(function(t,e){return"coords."+h[e+p]}).join(", "))+");\n }\n "}(t,e)),r}(t,e,r)}).join("\n"),l=e.texShape,c=fi(),p="\n float sampleTexture(sampler2D textureSampler, vec2 uv) {\n return "+c.texture2D+"(textureSampler, uv).r;\n }\n ",h=function(t){return t.version+"\n precision highp float;\n precision highp int;\n precision highp sampler2D;\n "+t.varyingFs+" vec2 resultUV;\n "+t.defineOutput+"\n const vec2 halfCR = vec2(0.5, 0.5);\n\n struct ivec5\n {\n int x;\n int y;\n int z;\n int w;\n int u;\n };\n\n struct ivec6\n {\n int x;\n int y;\n int z;\n int w;\n int u;\n int v;\n };\n\n uniform float NAN;\n #define isnan(value) isnan_custom(value)\n "+t.defineSpecialNaN+"\n bvec4 isnan_custom(vec4 val) {\n return bvec4(isnan(val.x), isnan(val.y), isnan(val.z), isnan(val.w));\n }\n\n "+t.defineSpecialInf+"\n "+t.defineRound+"\n\n int imod(int x, int y) {\n return x - y * (x / y);\n }\n\n int idiv(int a, int b, float sign) {\n int res = a / b;\n int mod = imod(a, b);\n if (sign < 0. && mod != 0) {\n res -= 1;\n }\n return res;\n }\n\n //Based on the work of Dave Hoskins\n //https://www.shadertoy.com/view/4djSRW\n #define HASHSCALE1 443.8975\n float random(float seed){\n vec2 p = resultUV * seed;\n vec3 p3 = fract(vec3(p.xyx) * HASHSCALE1);\n p3 += dot(p3, p3.yzx + 19.19);\n return fract((p3.x + p3.y) * p3.z);\n }\n\n "+yi+"\n "+bi+"\n "+xi+"\n "}(c);return e.isPacked?(a=function(t,e){switch(t.length){case 0:return"\n int getOutputCoords() {\n return 0;\n }\n ";case 1:return function(t,e){var n=[Math.ceil(e[0]/2),Math.ceil(e[1]/2)];return 1===n[0]?"\n int getOutputCoords() {\n return 2 * int(resultUV.x * "+n[1]+".0);\n }\n ":1===n[1]?"\n int getOutputCoords() {\n return 2 * int(resultUV.y * "+n[0]+".0);\n }\n ":"\n int getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+n[0]+", "+n[1]+"));\n return 2 * (resTexRC.x * "+n[1]+" + resTexRC.y);\n }\n "}(0,e);case 2:return function(t,e){var n=[Math.ceil(e[0]/2),Math.ceil(e[1]/2)];if(y(t,e))return"\n ivec2 getOutputCoords() {\n return 2 * ivec2(resultUV.yx * vec2("+n[0]+", "+n[1]+"));\n }\n ";var r=Math.ceil(t[1]/2);return"\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+n[0]+", "+n[1]+"));\n\n int index = resTexRC.x * "+n[1]+" + resTexRC.y;\n int r = 2 * (index / "+r+");\n int c = imod(index, "+r+") * 2;\n\n return ivec2(r, c);\n }\n "}(t,e);case 3:return n=t,r=e,i=[Math.ceil(r[0]/2),Math.ceil(r[1]/2)],o=(a=Math.ceil(n[2]/2))*Math.ceil(n[1]/2),"\n ivec3 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+i[0]+", "+i[1]+"));\n int index = resTexRC.x * "+i[1]+" + resTexRC.y;\n\n int b = index / "+o+";\n index -= b * "+o+";\n\n int r = 2 * (index / "+a+");\n int c = imod(index, "+a+") * 2;\n\n return ivec3(b, r, c);\n }\n ";default:return function(t,e){for(var n=[Math.ceil(e[0]/2),Math.ceil(e[1]/2)],r=Math.ceil(t[t.length-1]/2),i=r*Math.ceil(t[t.length-2]/2),a=i,o="",s="b, r, c",u=2;u2,function(){return"Packed arg"+(n.charAt(0).toUpperCase()+n.slice(1))+" supports only inputs with rank above 2."});var i=t[t.length-1],a=Math.ceil(i/e);this.outputShape=t.slice(0,-1),a>1&&this.outputShape.push(a),r||this.variableNames.push("bestIndicesA");var o,s,u=this.outputShape,l=u.length,c=Ei(l),p=hi("coords",l);if(1===a){var h=Ei(s=l+1);o="\n "+h+" sourceLocR = "+h+"("+p.join()+", 0);\n ++"+p[l-1]+";\n "+h+" sourceLocG = "+h+"("+p.join()+", 0);\n ++"+p[l-2]+";\n "+h+" sourceLocA = "+h+"("+p.join()+", 0);\n --"+p[l-1]+";\n "+h+" sourceLocB = "+h+"("+p.join()+", 0);\n --"+p[l-2]+";"}else s=l,o="\n "+c+" sourceLocR = coords;\n ++"+p[l-1]+";\n "+c+" sourceLocG = coords;\n ++"+p[l-2]+";\n "+c+" sourceLocA = coords;\n --"+p[l-1]+";\n "+c+" sourceLocB = coords;\n --"+p[l-2]+";";var d=["x","y","z","w","u","v"].slice(0,s),m="."+d[s-1],g=d.map(function(t){return"int "+t}),v=hi("sourceLocR",s-1).concat("inIdx.r"),y=hi("sourceLocG",s-1).concat("inIdx.g"),b=hi("sourceLocB",s-1).concat("inIdx.b"),x=hi("sourceLocA",s-1).concat("inIdx.a"),w="max"===n?"greaterThan":"lessThan",N=r?"":"\n inIdx = round(vec4(getBestIndicesAChannel("+v.join()+"),\n getBestIndicesAChannel("+y.join()+"),\n getBestIndicesAChannel("+b.join()+"),\n getBestIndicesAChannel("+x.join()+")));",C="vec4(\n getAChannel("+v.join()+"),\n hasNextCol ? getAChannel("+y.join()+") : 0.,\n hasNextRow ? getAChannel("+b.join()+") : 0.,\n hasNextRow && hasNextCol ? getAChannel("+x.join()+") : 0.)",E=r?"":"\n float getBestIndicesAChannel("+g.join()+") {\n return getChannel(getBestIndicesA("+d.join()+"),\n vec2("+d.slice(-2).join()+"));\n }";this.userCode="\n float getAChannel("+g.join()+") {\n return getChannel(getA("+d.join()+"),\n vec2("+d.slice(-2).join()+"));\n }\n "+E+"\n void main() {\n "+c+" coords = getOutputCoords();\n bool hasNextCol = "+p[l-1]+" < "+(u[l-1]-1)+";\n bool hasNextRow = "+p[l-2]+" < "+(u[l-2]-1)+";\n "+o+"\n ivec4 srcIdx = ivec4(sourceLocR"+m+", sourceLocG"+m+",\n sourceLocB"+m+", sourceLocA"+m+") * "+e+";\n ivec4 inIdx = srcIdx;\n vec4 bestIndex = vec4(inIdx);\n vec4 bestValue = "+C+";\n\n for (int i = 0; i < "+e+"; i++) {\n inIdx = srcIdx;\n "+N+"\n vec4 candidate = "+C+";\n bvec4 nan = isnan(candidate);\n bvec4 replace = bvec4(\n vec4("+w+"(candidate, bestValue)) * (vec4(1.0) - vec4(nan)));\n\n bestValue = vec4(replace.x ? candidate.x : bestValue.x,\n replace.y ? candidate.y : bestValue.y,\n replace.z ? candidate.z : bestValue.z,\n replace.w ? candidate.w : bestValue.w);\n bestIndex = mix(bestIndex, vec4(inIdx), vec4(replace));\n srcIdx++;\n }\n setOutput(bestIndex);\n }\n "},Ai=function(t){this.variableNames=["dy"],this.outputShape=t.inShape;var e=t.filterHeight,n=t.filterWidth,r=t.strideHeight,i=t.strideWidth,a=t.dilationHeight,o=t.dilationWidth,s=t.effectiveFilterHeight,u=t.effectiveFilterWidth,l=s-1-t.padInfo.top,c=u-1-t.padInfo.left,p=1/(e*n);this.userCode="\n const ivec2 pads = ivec2("+l+", "+c+");\n const float avgMultiplier = float("+p+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n\n ivec2 dyRCCorner = coords.yz - pads;\n int dyRCorner = dyRCCorner.x;\n int dyCCorner = dyRCCorner.y;\n\n // Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < "+s+";\n wR += "+a+") {\n float dyR = float(dyRCorner + wR) / "+r+".0;\n\n if (dyR < 0.0 || dyR >= "+t.outHeight+".0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n for (int wC = 0; wC < "+u+";\n wC+= "+o+") {\n float dyC = float(dyCCorner + wC) / "+i+".0;\n\n if (dyC < 0.0 || dyC >= "+t.outWidth+".0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n float dyValue = getDy(b, idyR, idyC, d);\n\n dotProd += dyValue * avgMultiplier;\n }\n }\n setOutput(dotProd);\n }\n "},Ri=function(t){this.variableNames=["dy"],this.outputShape=t.inShape;var e=t.filterDepth,n=t.filterHeight,r=t.filterWidth,i=t.strideDepth,a=t.strideHeight,o=t.strideWidth,s=t.dilationDepth,u=t.dilationHeight,l=t.dilationWidth,c=t.effectiveFilterDepth,p=t.effectiveFilterHeight,h=t.effectiveFilterWidth,f=c-1-t.padInfo.front,d=p-1-t.padInfo.top,m=h-1-t.padInfo.left,g=1/(e*n*r);this.userCode="\n const ivec3 pads = ivec3("+f+", "+d+", "+m+");\n const float avgMultiplier = float("+g+");\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int ch = coords.u;\n\n ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;\n int dyDCorner = dyCorner.x;\n int dyRCorner = dyCorner.y;\n int dyCCorner = dyCorner.z;\n\n // Convolve dy(?, ?, ?, d) with pos mask(:, :, :, ch) to get\n // dx(xD, xR, xC, ch).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n\n for (int wD = 0; wD < "+c+";\n wD += "+s+") {\n float dyD = float(dyDCorner + wD) / "+i+".0;\n\n if (dyD < 0.0 || dyD >= "+t.outDepth+".0 || fract(dyD) > 0.0) {\n continue;\n }\n int idyD = int(dyD);\n\n for (int wR = 0; wR < "+p+";\n wR += "+u+") {\n float dyR = float(dyRCorner + wR) / "+a+".0;\n\n if (dyR < 0.0 || dyR >= "+t.outHeight+".0 ||\n fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n for (int wC = 0; wC < "+h+";\n wC += "+l+") {\n float dyC = float(dyCCorner + wC) / "+o+".0;\n\n if (dyC < 0.0 || dyC >= "+t.outWidth+".0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n float dyValue = getDy(batch, idyD, idyR, idyC, ch);\n\n dotProd += dyValue * avgMultiplier;\n }\n }\n }\n setOutput(dotProd);\n }\n "},Ti=function(t,e,n,r,i,a){this.outputShape=[],this.variableNames=["x","mean","variance"],Mr(t,e),Mr(t,n);var o="0.0";null!=r&&(Mr(t,r),this.variableNames.push("offset"),o="getOffsetAtOutCoords()");var s="1.0";null!=i&&(Mr(t,i),this.variableNames.push("scale"),s="getScaleAtOutCoords()"),this.outputShape=t,this.userCode="\n void main() {\n float x = getXAtOutCoords();\n float mean = getMeanAtOutCoords();\n float variance = getVarianceAtOutCoords();\n float offset = "+o+";\n float scale = "+s+";\n float inv = scale * inversesqrt(variance + float("+a+"));\n setOutput(dot(vec3(x, -mean, offset), vec3(inv, inv, 1)));\n }\n "},Di=function(t,e,n,r,i,a){this.usesPackedTextures=!0,this.variableNames=["x","mean","variance"],Mr(t,e),Mr(t,n);var o="vec4(0.0)";null!=r&&(Mr(t,r),this.variableNames.push("offset"),o="getOffsetAtOutCoords()");var s="vec4(1.0)";null!=i&&(Mr(t,i),this.variableNames.push("scale"),s="getScaleAtOutCoords()"),this.outputShape=t,this.userCode="\n void main() {\n vec4 offset = "+o+";\n vec4 scale = "+s+";\n\n vec4 x = getXAtOutCoords();\n vec4 mean = getMeanAtOutCoords();\n vec4 variance = getVarianceAtOutCoords();\n\n vec4 inv = scale * inversesqrt(variance + vec4("+a+"));\n\n setOutput((x - mean) * inv + offset);\n }\n "},Oi=function(t,e,n){this.variableNames=["AReal","AImag","BReal","BImag"],this.outputShape=Mr(e,n),this.userCode="\n float binaryOpComplex(\n float areal, float aimag, float breal, float bimag) {\n "+t+"\n }\n\n void main() {\n float areal = getARealAtOutCoords();\n float aimag = getAImagAtOutCoords();\n float breal = getBRealAtOutCoords();\n float bimag = getBImagAtOutCoords();\n setOutput(binaryOpComplex(areal, aimag, breal, bimag));\n }\n "},_i="return a + b;",Fi="return a - b;",Mi="return a * b;",zi="return (a < 0.) ? b * a : a;",Li=function(t,e,n){this.variableNames=["A","B"],this.outputShape=Mr(e,n),this.userCode="\n float binaryOperation(float a, float b) {\n "+t+"\n }\n\n void main() {\n float a = getAAtOutCoords();\n float b = getBAtOutCoords();\n setOutput(binaryOperation(a, b));\n }\n "},Pi="\n vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));\n return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);\n",Bi=function(t,e,n,r){void 0===r&&(r=!1),this.variableNames=["A","B"],this.supportsBroadcasting=!0,this.usesPackedTextures=!0,this.outputShape=Mr(e,n);var i=this.outputShape.length,a="";if(r)if(0===i||1===v(this.outputShape))a="\n result.y = 0.;\n result.z = 0.;\n result.w = 0.;\n ";else if(a="\n "+Ei(i)+" coords = getOutputCoords();\n ",1===i)a+="\n result.y = (coords + 1) >= "+this.outputShape[0]+" ? 0. : result.y;\n result.z = 0.;\n result.w = 0.;\n ";else{var o=hi("coords",i);a+="\n bool nextRowOutOfBounds =\n ("+o[i-2]+" + 1) >= "+this.outputShape[i-2]+";\n bool nextColOutOfBounds =\n ("+o[i-1]+" + 1) >= "+this.outputShape[i-1]+";\n result.y = nextColOutOfBounds ? 0. : result.y;\n result.z = nextRowOutOfBounds ? 0. : result.z;\n result.w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result.w;\n "}this.userCode="\n vec4 binaryOperation(vec4 a, vec4 b) {\n "+t+"\n }\n\n void main() {\n vec4 a = getAAtOutCoords();\n vec4 b = getBAtOutCoords();\n\n vec4 result = binaryOperation(a, b);\n "+a+"\n\n setOutput(result);\n }\n "},Vi=function(){function t(t){this.variableNames=["A"],this.outputShape=t,this.userCode="\n uniform float minVal;\n uniform float maxVal;\n\n void main() {\n float value = getAAtOutCoords();\n if (isnan(value)) {\n setOutput(value);\n return;\n }\n\n setOutput(clamp(value, minVal, maxVal));\n }\n "}return t.prototype.getCustomSetupFunc=function(t,e){var n=this;return function(r,i){null==n.minLoc&&(n.minLoc=r.getUniformLocationNoThrow(i,"minVal"),n.maxLoc=r.getUniformLocationNoThrow(i,"maxVal")),r.gl.uniform1f(n.minLoc,t),r.gl.uniform1f(n.maxLoc,e)}},t}(),Wi=function(){function t(t){this.variableNames=["A"],this.usesPackedTextures=!0,this.outputShape=t,this.userCode="\n uniform float minVal;\n uniform float maxVal;\n\n void main() {\n vec4 value = getAAtOutCoords();\n\n if (any(isnan(value))) {\n setOutput(value);\n return;\n }\n\n setOutput(clamp(value, vec4(minVal), vec4(maxVal)));\n }\n "}return t.prototype.getCustomSetupFunc=function(t,e){var n=this;return function(r,i){null==n.minLoc&&(n.minLoc=r.getUniformLocationNoThrow(i,"minVal"),n.maxLoc=r.getUniformLocationNoThrow(i,"maxVal")),r.gl.uniform1f(n.minLoc,t),r.gl.uniform1f(n.maxLoc,e)}},t}(),Ui=function(t){this.variableNames=["real","imag"],this.outputShape=t,this.userCode="\n void main() {\n float re = abs(getRealAtOutCoords());\n float im = abs(getImagAtOutCoords());\n float mx = max(re, im);\n\n // sadly the length function in glsl is not underflow-safe\n // (at least not on Intel GPUs). So the safe solution is\n // to ensure underflow-safety in all cases.\n setOutput(\n mx == 0.0 ? 0.0 : mx * length(vec2(1, min(re, im)/mx))\n );\n }\n "},ji=function(t){this.outputShape=[],this.outputShape=Je(t,1),this.variableNames=t.map(function(t,e){return"T"+e});var e=new Array(t.length-1);e[0]=t[0][1];for(var n=1;n= "+t.inHeight+") {\n continue;\n }\n\n for (int yC = 0; yC < "+t.outWidth+"; yC++) {\n int xC = wC + yC * "+n+" - "+i+";\n\n if (xC < 0 || xC >= "+t.inWidth+") {\n continue;\n }\n\n if ("+a+") {\n float dyValue = getDy(b, yR, yC, d2);\n float xValue = getX(b, xR, xC, d1);\n dotProd += (xValue * dyValue);\n } else {\n float dyValue = getDy(b, d2, yR, yC);\n float xValue = getX(b, d1, xR, xC);\n dotProd += (xValue * dyValue);\n }\n\n }\n }\n }\n setOutput(dotProd);\n }\n "},qi=function(t){this.variableNames=["dy","W"],this.outputShape=t.inShape;var e=t.filterHeight,n=t.filterWidth,r=t.strideHeight,i=t.strideWidth,a="channelsLast"===t.dataFormat,o=e-1-t.padInfo.top,s=n-1-t.padInfo.left,u=a?1:2,l=a?2:3,c=a?3:1;this.userCode="\n const ivec2 pads = ivec2("+o+", "+s+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d1 = coords["+c+"];\n\n ivec2 dyCorner = ivec2(coords["+u+"], coords["+l+"]) - pads;\n int dyRCorner = dyCorner.x;\n int dyCCorner = dyCorner.y;\n\n // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < "+e+"; wR++) {\n float dyR = float(dyRCorner + wR) / "+r+".0;\n\n if (dyR < 0.0 || dyR >= "+t.outHeight+".0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n int wRPerm = "+e+" - 1 - wR;\n\n for (int wC = 0; wC < "+n+"; wC++) {\n float dyC = float(dyCCorner + wC) / "+i+".0;\n\n if (dyC < 0.0 || dyC >= "+t.outWidth+".0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n int wCPerm = "+n+" - 1 - wC;\n\n for (int d2 = 0; d2 < "+t.outChannels+"; d2++) {\n\n if ("+a+") {\n float xValue = getDy(batch, idyR, idyC, d2);\n float wValue = getW(wRPerm, wCPerm, d1, d2);\n dotProd += xValue * wValue;\n } else {\n float xValue = getDy(batch, d2, idyR, idyC);\n float wValue = getW(wRPerm, wCPerm, d1, d2);\n dotProd += xValue * wValue;\n }\n\n }\n }\n }\n setOutput(dotProd);\n }\n "},Ki=function(t){this.variableNames=["x","dy"],this.outputShape=t.filterShape;var e=t.strideDepth,n=t.strideHeight,r=t.strideWidth,i=t.padInfo.front,a=t.padInfo.top,o=t.padInfo.left;this.userCode="\n void main() {\n ivec5 coords = getOutputCoords();\n int wF = coords.x;\n int wR = coords.y;\n int wC = coords.z;\n int d1 = coords.w;\n int d2 = coords.u;\n\n float dotProd = 0.0;\n\n for (int b = 0; b < "+t.batchSize+"; b++) {\n for (int yF = 0; yF < "+t.outDepth+"; yF++) {\n int xF = wF + yF * "+e+" - "+i+";\n\n if (xF < 0 || xF >= "+t.inDepth+") {\n continue;\n }\n\n for (int yR = 0; yR < "+t.outHeight+"; yR++) {\n int xR = wR + yR * "+n+" - "+a+";\n\n if (xR < 0 || xR >= "+t.inHeight+") {\n continue;\n }\n\n for (int yC = 0; yC < "+t.outWidth+"; yC++) {\n int xC = wC + yC * "+r+" - "+o+";\n\n if (xC < 0 || xC >= "+t.inWidth+") {\n continue;\n }\n\n float dyValue = getDy(b, yF, yR, yC, d2);\n float xValue = getX(b, xF, xR, xC, d1);\n dotProd += (xValue * dyValue);\n }\n }\n }\n }\n setOutput(dotProd);\n }\n "},$i=function(t){this.variableNames=["dy","W"],this.outputShape=t.inShape;var e=t.filterDepth,n=t.filterHeight,r=t.filterWidth,i=t.strideDepth,a=t.strideHeight,o=t.strideWidth,s=e-1-t.padInfo.front,u=n-1-t.padInfo.top,l=r-1-t.padInfo.left;this.userCode="\n const ivec3 pads = ivec3("+s+", "+u+", "+l+");\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int d1 = coords.u;\n\n\n ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;\n int dyFCorner = dyCorner.x;\n int dyRCorner = dyCorner.y;\n int dyCCorner = dyCorner.z;\n\n float dotProd = 0.0;\n for (int wF = 0; wF < "+e+"; wF++) {\n float dyF = float(dyFCorner + wF) / "+i+".0;\n\n if (dyF < 0.0 || dyF >= "+t.outDepth+".0 || fract(dyF) > 0.0) {\n continue;\n }\n int idyF = int(dyF);\n\n int wFPerm = "+e+" - 1 - wF;\n\n for (int wR = 0; wR < "+n+"; wR++) {\n float dyR = float(dyRCorner + wR) / "+a+".0;\n\n if (dyR < 0.0 || dyR >= "+t.outHeight+".0 ||\n fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n int wRPerm = "+n+" - 1 - wR;\n\n for (int wC = 0; wC < "+r+"; wC++) {\n float dyC = float(dyCCorner + wC) / "+o+".0;\n\n if (dyC < 0.0 || dyC >= "+t.outWidth+".0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n int wCPerm = "+r+" - 1 - wC;\n\n for (int d2 = 0; d2 < "+t.outChannels+"; d2++) {\n float xValue = getDy(batch, idyF, idyR, idyC, d2);\n float wValue = getW(wFPerm, wRPerm, wCPerm, d1, d2);\n dotProd += xValue * wValue;\n }\n }\n }\n }\n setOutput(dotProd);\n }\n "},Xi=function(t){this.variableNames=["x","dy"],this.outputShape=t.filterShape;var e=t.strideHeight,n=t.strideWidth,r=t.padInfo.top,i=t.padInfo.left,a=t.outChannels/t.inChannels;this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int wR = coords.x;\n int wC = coords.y;\n int d1 = coords.z;\n int dm = coords.w;\n int d2 = d1 * "+a+" + dm;\n\n float dotProd = 0.0;\n\n // TO DO: Vec4 over the batch size\n for (int b = 0; b < "+t.batchSize+"; b++) {\n for (int yR = 0; yR < "+t.outHeight+"; yR++) {\n int xR = wR + yR * "+e+" - "+r+";\n\n if (xR < 0 || xR >= "+t.inHeight+") {\n continue;\n }\n\n for (int yC = 0; yC < "+t.outWidth+"; yC++) {\n int xC = wC + yC * "+n+" - "+i+";\n\n if (xC < 0 || xC >= "+t.inWidth+") {\n continue;\n }\n\n float dyValue = getDy(b, yR, yC, d2);\n float xValue = getX(b, xR, xC, d1);\n dotProd += (xValue * dyValue);\n }\n }\n }\n setOutput(dotProd);\n }\n "},Yi=function(t){this.variableNames=["dy","W"],this.outputShape=t.inShape;var e=t.filterHeight,n=t.filterWidth,r=t.strideHeight,i=t.strideWidth,a=e-1-t.padInfo.top,o=n-1-t.padInfo.left,s=t.outChannels/t.inChannels;this.userCode="\n const ivec2 pads = ivec2("+a+", "+o+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d1 = coords[3];\n ivec2 dyCorner = coords.yz - pads;\n int dyRCorner = dyCorner.x;\n int dyCCorner = dyCorner.y;\n\n float dotProd = 0.0;\n\n for (int wR = 0; wR < "+e+"; wR++) {\n float dyR = float(dyRCorner + wR) / "+r+".0;\n\n if (dyR < 0.0 || dyR >= "+t.outHeight+".0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n int wRPerm = "+e+" - 1 - wR;\n\n for (int wC = 0; wC < "+n+"; wC++) {\n float dyC = float(dyCCorner + wC) / "+i+".0;\n\n if (dyC < 0.0 || dyC >= "+t.outWidth+".0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n int wCPerm = "+n+" - 1 - wC;\n\n // TO DO: Vec4 over the channelMul\n for (int dm = 0; dm < "+s+"; dm++) {\n int d2 = d1 * "+s+" + dm;\n float xValue = getDy(batch, idyR, idyC, d2);\n float wValue = getW(wRPerm, wCPerm, d1, dm);\n dotProd += xValue * wValue;\n }\n }\n }\n setOutput(dotProd);\n }\n "},Ji=function(t,e,n,r){void 0===e&&(e=!1),void 0===n&&(n=null),void 0===r&&(r=!1),this.variableNames=["x","W"],this.outputShape=t.outShape;var i=t.padInfo.top,a=t.padInfo.left,o=t.strideHeight,s=t.strideWidth,u=t.dilationHeight,l=t.dilationWidth,c=t.filterHeight,p=t.filterWidth,h=4*Math.floor(t.inChannels/4),f=t.inChannels%4,d="channelsLast"===t.dataFormat,m=d?1:2,g=d?2:3,v=d?3:1,y="",b="";n&&(y=r?"float activation(float a) {\n float b = getPreluActivationWeightsAtOutCoords();\n "+n+"\n }":"\n float activation(float x) {\n "+n+"\n }\n ",b="result = activation(result);");var x=e?"result += getBiasAtOutCoords();":"";e&&this.variableNames.push("bias"),r&&this.variableNames.push("preluActivationWeights"),this.userCode="\n "+y+"\n\n const ivec2 strides = ivec2("+o+", "+s+");\n const ivec2 pads = ivec2("+i+", "+a+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d2 = coords["+v+"];\n\n ivec2 xRCCorner =\n ivec2(coords["+m+"], coords["+g+"]) * strides - pads;\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n // Convolve x(?, ?, d1) with w(:, :, d1, d2) to get y(yR, yC, d2).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < "+c+"; wR++) {\n int xR = xRCorner + wR * "+u+";\n\n if (xR < 0 || xR >= "+t.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+p+"; wC++) {\n int xC = xCCorner + wC * "+l+";\n\n if (xC < 0 || xC >= "+t.inWidth+") {\n continue;\n }\n\n for (int d1 = 0; d1 < "+h+"; d1 += 4) {\n vec4 wValues = vec4(\n getW(wR, wC, d1, d2),\n getW(wR, wC, d1 + 1, d2),\n getW(wR, wC, d1 + 2, d2),\n getW(wR, wC, d1 + 3, d2)\n );\n\n if ("+d+") {\n vec4 xValues = vec4(\n getX(batch, xR, xC, d1),\n getX(batch, xR, xC, d1 + 1),\n getX(batch, xR, xC, d1 + 2),\n getX(batch, xR, xC, d1 + 3)\n );\n dotProd += dot(xValues, wValues);\n } else {\n vec4 xValues = vec4(\n getX(batch, d1, xR, xC),\n getX(batch, d1 + 1, xR, xC),\n getX(batch, d1 + 2, xR, xC),\n getX(batch, d1 + 3, xR, xC)\n );\n dotProd += dot(xValues, wValues);\n }\n }\n\n if ("+(1===f)+") {\n\n if ("+d+") {\n dotProd +=\n getX(batch, xR, xC, "+h+") *\n getW(wR, wC, "+h+", d2);\n } else {\n dotProd +=\n getX(batch, "+h+", xR, xC) *\n getW(wR, wC, "+h+", d2);\n }\n\n } else if ("+(2===f)+") {\n vec2 wValues = vec2(\n getW(wR, wC, "+h+", d2),\n getW(wR, wC, "+h+" + 1, d2)\n );\n\n if ("+d+") {\n vec2 xValues = vec2(\n getX(batch, xR, xC, "+h+"),\n getX(batch, xR, xC, "+h+" + 1)\n );\n dotProd += dot(xValues, wValues);\n } else {\n vec2 xValues = vec2(\n getX(batch, "+h+", xR, xC),\n getX(batch, "+h+" + 1, xR, xC)\n );\n dotProd += dot(xValues, wValues);\n }\n\n } else if ("+(3===f)+") {\n vec3 wValues = vec3(\n getW(wR, wC, "+h+", d2),\n getW(wR, wC, "+h+" + 1, d2),\n getW(wR, wC, "+h+" + 2, d2)\n );\n\n if ("+d+") {\n vec3 xValues = vec3(\n getX(batch, xR, xC, "+h+"),\n getX(batch, xR, xC, "+h+" + 1),\n getX(batch, xR, xC, "+h+" + 2)\n );\n dotProd += dot(xValues, wValues);\n } else {\n vec3 xValues = vec3(\n getX(batch, "+h+", xR, xC),\n getX(batch, "+h+" + 1, xR, xC),\n getX(batch, "+h+" + 2, xR, xC)\n );\n dotProd += dot(xValues, wValues);\n }\n\n }\n }\n }\n\n float result = dotProd;\n "+x+"\n "+b+"\n setOutput(result);\n }\n "},Zi=function(t){this.variableNames=["x","W"],this.outputShape=t.outShape;var e=t.padInfo.front,n=t.padInfo.top,r=t.padInfo.left,i=t.strideDepth,a=t.strideHeight,o=t.strideWidth,s=t.dilationDepth,u=t.dilationHeight,l=t.dilationWidth,c=t.filterDepth,p=t.filterHeight,h=t.filterWidth,f=4*Math.floor(t.inChannels/4),d=t.inChannels%4;this.userCode="\n const ivec3 strides = ivec3("+i+", "+a+", "+o+");\n const ivec3 pads = ivec3("+e+", "+n+", "+r+");\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int d2 = coords.u;\n\n ivec3 xFRCCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;\n int xFCorner = xFRCCorner.x;\n int xRCorner = xFRCCorner.y;\n int xCCorner = xFRCCorner.z;\n\n // Convolve x(?, ?, ?, d1) with w(:, :, :, d1, d2) to get\n // y(yF, yR, yC, d2). ? = to be determined. : = across all\n // values in that axis.\n float dotProd = 0.0;\n for (int wF = 0; wF < "+c+"; wF++) {\n int xF = xFCorner + wF * "+s+";\n\n if (xF < 0 || xF >= "+t.inDepth+") {\n continue;\n }\n\n for (int wR = 0; wR < "+p+"; wR++) {\n int xR = xRCorner + wR * "+u+";\n\n if (xR < 0 || xR >= "+t.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+h+"; wC++) {\n int xC = xCCorner + wC * "+l+";\n\n if (xC < 0 || xC >= "+t.inWidth+") {\n continue;\n }\n\n for (int d1 = 0; d1 < "+f+"; d1 += 4) {\n vec4 xValues = vec4(\n getX(batch, xF, xR, xC, d1),\n getX(batch, xF, xR, xC, d1 + 1),\n getX(batch, xF, xR, xC, d1 + 2),\n getX(batch, xF, xR, xC, d1 + 3)\n );\n vec4 wValues = vec4(\n getW(wF, wR, wC, d1, d2),\n getW(wF, wR, wC, d1 + 1, d2),\n getW(wF, wR, wC, d1 + 2, d2),\n getW(wF, wR, wC, d1 + 3, d2)\n );\n\n dotProd += dot(xValues, wValues);\n }\n\n if ("+(1===d)+") {\n dotProd +=\n getX(batch, xF, xR, xC, "+f+") *\n getW(wF, wR, wC, "+f+", d2);\n } else if ("+(2===d)+") {\n vec2 xValues = vec2(\n getX(batch, xF, xR, xC, "+f+"),\n getX(batch, xF, xR, xC, "+f+" + 1)\n );\n vec2 wValues = vec2(\n getW(wF, wR, wC, "+f+", d2),\n getW(wF, wR, wC, "+f+" + 1, d2)\n );\n dotProd += dot(xValues, wValues);\n } else if ("+(3===d)+") {\n vec3 xValues = vec3(\n getX(batch, xF, xR, xC, "+f+"),\n getX(batch, xF, xR, xC, "+f+" + 1),\n getX(batch, xF, xR, xC, "+f+" + 2)\n );\n vec3 wValues = vec3(\n getW(wF, wR, wC, "+f+", d2),\n getW(wF, wR, wC, "+f+" + 1, d2),\n getW(wF, wR, wC, "+f+" + 2, d2)\n );\n dotProd += dot(xValues, wValues);\n }\n }\n }\n }\n setOutput(dotProd);\n }\n "},Qi=function(t){this.variableNames=["x","W"],this.outputShape=t.outShape;var e=t.inHeight,n=t.inWidth,r=t.padInfo.top,i=t.padInfo.left,a=t.strideHeight,o=t.strideWidth,s=t.dilationHeight,u=t.dilationWidth,l=t.filterHeight,c=t.filterWidth,p=t.outChannels/t.inChannels;this.userCode="\n const ivec2 strides = ivec2("+a+", "+o+");\n const ivec2 pads = ivec2("+r+", "+i+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords.x;\n ivec2 xRCCorner = coords.yz * strides - pads;\n int d2 = coords.w;\n int d1 = d2 / "+p+";\n int q = d2 - d1 * "+p+";\n\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n // Convolve x(?, ?, d1) with w(:, :, d1, q) to get y(yR, yC, d2).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n // TO DO(dsmilkov): Flatten the two for loops and vec4 the operations.\n for (int wR = 0; wR < "+l+"; wR++) {\n int xR = xRCorner + wR * "+s+";\n\n if (xR < 0 || xR >= "+e+") {\n continue;\n }\n\n for (int wC = 0; wC < "+c+"; wC++) {\n int xC = xCCorner + wC * "+u+";\n\n if (xC < 0 || xC >= "+n+") {\n continue;\n }\n\n float xVal = getX(batch, xR, xC, d1);\n float wVal = getW(wR, wC, d1, q);\n dotProd += xVal * wVal;\n }\n }\n setOutput(dotProd);\n }\n "},ta=function(t){this.variableNames=["x","W"],this.usesPackedTextures=!0,this.outputShape=t.outShape;for(var e=t.inHeight,n=t.inWidth,r=t.padInfo.top,i=t.padInfo.left,a=t.strideHeight,o=t.strideWidth,s=t.dilationHeight,u=t.dilationWidth,l=t.filterHeight,c=t.filterWidth,h=c,f="int xR; int xC; int xCOffset;",d=0;d= 0 && xR < "+e+" && xCOffset >= 0 && xCOffset < "+n+") {\n xTexelR"+d+"C"+m+" = getX(batch, xR, xCOffset, d1);\n } else {\n xTexelR"+d+"C"+m+" = vec4(0.);\n }\n\n xCOffset = xC + 1 - 2;\n if(xR >= 0 && xR < "+e+" && xCOffset >= 0 && xCOffset < "+n+") {\n vec4 previous = getX(batch, xR, xCOffset, d1);\n xR"+d+"C"+m+" = vec4(previous.zw, xTexelR"+d+"C"+m+".xy);\n } else {\n xR"+d+"C"+m+" = vec4(0, 0, xTexelR"+d+"C"+m+".xy);\n }\n ":"\n if(xR >= 0 && xR < "+e+" && xC >= 0 && xC < "+n+") {\n xTexelR"+d+"C"+m+" = getX(batch, xR, xC, d1);\n } else {\n xTexelR"+d+"C"+m+" = vec4(0.);\n }\n\n xR"+d+"C"+m+" = xTexelR"+d+"C"+m+";\n ",m+1= 0 && xR < "+e+" &&\n xCOffset >= 0 && xCOffset < "+n+") {\n xTexelR"+d+"C"+(m+2)+" = getX(batch, xR, xCOffset, d1);\n }\n ",u>1&&(f+="\n xCOffset -= 2;\n if(xR >= 0 && xR < "+e+" &&\n xCOffset >= 0 && xCOffset < "+n+") {\n xTexelR"+d+"C"+m+" = getX(batch, xR, xCOffset, d1);\n } else {\n xTexelR"+d+"C"+m+" = vec4(0.);\n }\n "),f+="\n xR"+d+"C"+(m+1)+" = vec4(\n xTexelR"+d+"C"+m+".zw, xTexelR"+d+"C"+(m+2)+".xy);\n "):f+="\n xCOffset = xC + "+v+";\n\n if(xR >= 0 && xR < "+e+" &&\n xCOffset >= 0 && xCOffset < "+n+") {\n xTexelR"+d+"C"+(m+2)+" = getX(batch, xR, xCOffset, d1);\n }\n\n xR"+d+"C"+(m+1)+" = xTexelR"+d+"C"+(m+2)+";\n "}}else m= 0 && xR < "+e+") {\n ",i%2==1?(f+="\n xCOffset = xC + 1 - "+o+";\n if(xCOffset >= 0 && xCOffset < "+n+") {\n xTexelR"+d+"C"+m+" = getX(batch, xR, xCOffset, d1);\n } else {\n xTexelR"+d+"C"+m+" = vec4(0.);\n }\n\n if(xC + 1 >= 0 && xC + 1 < "+n+") {\n xTexelR"+d+"C"+(m+2)+" = getX(batch, xR, xC + 1, d1);\n } else {\n xTexelR"+d+"C"+(m+2)+" = vec4(0.);\n }\n\n xR"+d+"C"+m+" = vec4(\n xTexelR"+d+"C"+m+".zw, xTexelR"+d+"C"+(m+2)+".zw);\n ",m+1= 0 && xCOffset < "+n+") {\n final = getX(batch, xR, xCOffset, d1);\n }\n xR"+d+"C"+(m+1)+" = vec4(xTexelR"+d+"C"+(m+2)+".xy, final.xy);\n ")):(f+="\n if(xC >= 0 && xC < "+n+") {\n xTexelR"+d+"C"+m+" = getX(batch, xR, xC, d1);\n } else {\n xTexelR"+d+"C"+m+" = vec4(0.);\n }\n\n xCOffset = xC + "+o+";\n if(xCOffset >= 0 && xCOffset < "+n+") {\n xTexelR"+d+"C"+(m+2)+" = getX(batch, xR, xCOffset, d1);\n } else {\n xTexelR"+d+"C"+(m+2)+" = vec4(0.);\n }\n\n xR"+d+"C"+m+" = vec4(\n xTexelR"+d+"C"+m+".xy, xTexelR"+d+"C"+(m+2)+".xy);\n ",m+11?[""+(o-1)/(c-1),"(y2-y1) * height_ratio","y1*"+d+" + float(y)*(height_scale)"]:["0.0","0.0","0.5 * (y1+y2) * "+d],v=g[0],y=g[1],b=g[2],x=p>1?[""+(s-1)/(p-1),"(x2-x1) * width_ratio","x1*"+m+" + float(x)*(width_scale)"]:["0.0","0.0","0.5 * (x1+x2) * "+m],w=x[0],N=x[1],C=x[2];this.userCode="\n const float height_ratio = float("+v+");\n const float width_ratio = float("+w+");\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int y = coords[1];\n int x = coords[2];\n int d = coords[3];\n\n // get box vals\n float y1 = getBoxes(b,0);\n float x1 = getBoxes(b,1);\n float y2 = getBoxes(b,2);\n float x2 = getBoxes(b,3);\n\n // get image in batch index\n int bInd = round(getBoxInd(b));\n if(bInd < 0 || bInd >= "+a+") {\n return;\n }\n\n float height_scale = "+y+";\n float width_scale = "+N+";\n\n float in_y = "+b+";\n if( in_y < 0.0 || in_y > "+d+" ) {\n setOutput(float("+i+"));\n return;\n }\n float in_x = "+C+";\n if( in_x < 0.0 || in_x > "+m+" ) {\n setOutput(float("+i+"));\n return;\n }\n\n vec2 sourceFracIndexCR = vec2(in_x,in_y);\n if("+h+" == 1) {\n // Compute the four integer indices.\n ivec2 sourceFloorCR = ivec2(sourceFracIndexCR);\n ivec2 sourceCeilCR = ivec2(ceil(sourceFracIndexCR));\n\n float topLeft = getImage(b, sourceFloorCR.y, sourceFloorCR.x, d);\n float bottomLeft = getImage(b, sourceCeilCR.y, sourceFloorCR.x, d);\n float topRight = getImage(b, sourceFloorCR.y, sourceCeilCR.x, d);\n float bottomRight = getImage(b, sourceCeilCR.y, sourceCeilCR.x, d);\n\n vec2 fracCR = sourceFracIndexCR - vec2(sourceFloorCR);\n\n float top = topLeft + (topRight - topLeft) * fracCR.x;\n float bottom = bottomLeft + (bottomRight - bottomLeft) * fracCR.x;\n float newValue = top + (bottom - top) * fracCR.y;\n setOutput(newValue);\n } else {\n // Compute the coordinators of nearest neighbor point.\n ivec2 sourceNearestCR = ivec2(floor(\n sourceFracIndexCR + vec2(0.5,0.5)));\n float newValue = getImage(b, sourceNearestCR.y, sourceNearestCR.x, d);\n setOutput(newValue);\n }\n }\n "},na=function(t,e,n){this.variableNames=["x"],this.outputShape=t;var r=t.length,i=t[t.length-1],a=n?"<":">";this.userCode="\n int getIndex(int i) {\n "+(n?"return "+i+" -i - 1;":"return i;")+"\n }\n\n void main() {\n "+Ei(r)+" coords = getOutputCoords();\n int end = "+ra(r,"coords")+";\n float val = 0.0;\n for (int i = "+i+" - 1; i >= 0; i -= 1) {\n int idx = getIndex(i);\n if (idx "+a+" end) {\n continue;\n }\n if (idx == end && "+e+") {\n continue;\n }\n "+ra(r,"coords")+" = idx;\n val += getX("+function(t,e){if(1===t)return""+e;if(2===t)return e+".x, "+e+".y";if(3===t)return e+".x, "+e+".y, "+e+".z";if(4===t)return e+".x, "+e+".y, "+e+".z, "+e+".w";throw Error("Cumulative sum for rank "+t+" is not yet supported")}(r,"coords")+");\n }\n setOutput(val);\n }\n "};function ra(t,e){if(1===t)return""+e;if(2===t)return e+".y";if(3===t)return e+".z";if(4===t)return e+".w";throw Error("Cumulative sum for rank "+t+" is not yet supported")}var ia=function(t,e){this.variableNames=["A"];var n=fi();this.outputShape=t,this.userCode="\n ivec3 outCoordsFromFlatIndex(int index) {\n "+di(["r","c","d"],t)+"\n return ivec3(r, c, d);\n }\n\n void main() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+e[0]+", "+e[1]+"));\n int index = 4 * (resTexRC.x * "+e[1]+" + resTexRC.y);\n\n vec4 result = vec4(0.);\n\n for (int i=0; i<4; i++) {\n int flatIndex = index + i;\n ivec3 rc = outCoordsFromFlatIndex(flatIndex);\n result[i] = getA(rc.x, rc.y, rc.z);\n }\n\n "+n.output+" = result;\n }\n "},aa=function(t,e){this.variableNames=["A"],this.usesPackedTextures=!0;var n=fi();this.outputShape=t,this.userCode="\n ivec3 outCoordsFromFlatIndex(int index) {\n "+di(["r","c","d"],t)+"\n return ivec3(r, c, d);\n }\n\n void main() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+e[0]+", "+e[1]+"));\n int index = 4 * (resTexRC.x * "+e[1]+" + resTexRC.y);\n\n vec4 result = vec4(0.);\n\n for (int i=0; i<4; i++) {\n int flatIndex = index + i;\n ivec3 rc = outCoordsFromFlatIndex(flatIndex);\n result[i] = getChannel(getA(rc.x, rc.y, rc.z), vec2(rc.y, rc.z));\n }\n\n "+n.output+" = result;\n }\n "},oa=function(){function t(t,e,n){this.variableNames=["x"],this.outputShape=[],this.outputShape=t,this.blockSize=e,this.dataFormat=n,this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int h = "+this.getHeightCoordString()+";\n int w = "+this.getWidthCoordString()+";\n int d = "+this.getDepthCoordString()+";\n\n int in_h = h / "+e+";\n int offset_h = imod(h, "+e+");\n int in_w = w / "+e+";\n int offset_w = imod(w, "+e+");\n int offset_d = (offset_h * "+e+" + offset_w) *\n "+this.getOutputDepthSize()+";\n int in_d = d + offset_d;\n\n float result = "+this.getInputSamplingString()+";\n setOutput(result);\n }\n "}return t.prototype.getHeightCoordString=function(){return"NHWC"===this.dataFormat?"coords[1]":"coords[2]"},t.prototype.getWidthCoordString=function(){return"NHWC"===this.dataFormat?"coords[2]":"coords[3]"},t.prototype.getDepthCoordString=function(){return"NHWC"===this.dataFormat?"coords[3]":"coords[1]"},t.prototype.getOutputDepthSize=function(){return"NHWC"===this.dataFormat?this.outputShape[3]:this.outputShape[1]},t.prototype.getInputSamplingString=function(){return"NHWC"===this.dataFormat?"getX(b, in_h, in_w, in_d)":"getX(b, in_d, in_h, in_w)"},t}(),sa=function(t){this.variableNames=["X"],this.outputShape=[t,t],this.userCode="\n void main() {\n ivec2 coords = getOutputCoords();\n float val = coords[0] == coords[1] ? getX(coords[0]) : 0.0;\n setOutput(val);\n }\n "},ua=function(t){this.variableNames=["A"];var e=fi();this.outputShape=t,this.userCode="\n "+gi+"\n\n void main() {\n float x = getAAtOutCoords();\n "+e.output+" = encode_float(x);\n }\n "},la=function(t){this.variableNames=["A"],this.usesPackedTextures=!0;var e=fi();this.outputShape=t,this.userCode="\n "+gi+"\n\n void main() {\n ivec3 coords = getOutputCoords();\n float x = getChannel(getAAtOutCoords(), vec2(coords.y, coords.z));\n "+e.output+" = encode_float(x);\n }\n "},ca=function(t,e,n){void 0===n&&(n=!1),this.variableNames=["A"];var r=fi(),i=e[0],a=e[1];this.outputShape=t;var o="result";n&&(o="floor(result * 255. + 0.5)"),this.userCode="\n "+mi(t)+"\n\n void main() {\n ivec3 coords = getOutputCoords();\n\n int flatIndex = getFlatIndex(coords);\n int offset = imod(flatIndex, 4);\n\n flatIndex = idiv(flatIndex, 4, 1.);\n \n int r = flatIndex / "+a+";\n int c = imod(flatIndex, "+a+");\n vec2 uv = (vec2(c, r) + halfCR) / vec2("+a+".0, "+i+".0);\n vec4 values = "+r.texture2D+"(A, uv);\n\n float result;\n\n if(offset == 0) {\n result = values[0];\n } else if(offset == 1) {\n result = values[1];\n } else if(offset == 2) {\n result = values[2];\n } else {\n result = values[3];\n }\n\n "+r.output+" = vec4("+o+", 0., 0., 0.);\n }\n "},pa=function(t,e,n){void 0===n&&(n=!1),this.variableNames=["A"];var r=fi(),i=e[0],a=e[1];this.outputShape=t;var o="",s="result";n&&(s="floor(result * 255. + 0.5)");for(var u=0;u<=1;u++)for(var l=0;l<=1;l++){var c=2*u+l;o+="\n localCoords = coords;\n if(localCoords[2] + "+l+" < "+t[2]+") {\n localCoords[2] += "+l+";\n if(localCoords[1] + "+u+" < "+t[1]+") {\n localCoords[1] += "+u+";\n\n flatIndex = getFlatIndex(localCoords);\n offset = imod(flatIndex, 4);\n \n flatIndex = idiv(flatIndex, 4, 1.);\n\n r = flatIndex / "+a+";\n c = imod(flatIndex, "+a+");\n uv = (vec2(c, r) + halfCR) / vec2("+a+".0, "+i+".0);\n values = "+r.texture2D+"(A, uv);\n\n if(offset == 0) {\n result["+c+"] = values[0];\n } else if(offset == 1) {\n result["+c+"] = values[1];\n } else if(offset == 2) {\n result["+c+"] = values[2];\n } else {\n result["+c+"] = values[3];\n }\n }\n }\n "}this.userCode="\n "+mi(t)+"\n\n void main() {\n ivec3 coords = getOutputCoords();\n\n vec4 result = vec4(0.);\n int flatIndex, r, c, offset;\n ivec3 localCoords;\n vec2 uv;\n vec4 values;\n \n "+o+"\n\n "+r.output+" = "+s+";\n }\n "},ha=function(t,e,n){this.variableNames=["real","imag"];var r=e[1];this.outputShape=e;var i=n?"2.0 * "+Math.PI:"-2.0 * "+Math.PI,a=n?r+".0":"1.0";this.userCode="\n const float exponentMultiplier = "+i+";\n\n float unaryOpComplex(float real, float expR, float imag, float expI) {\n "+t+"\n }\n\n float mulMatDFT(int batch, int index) {\n float indexRatio = float(index) / float("+r+");\n float exponentMultiplierTimesIndexRatio =\n exponentMultiplier * indexRatio;\n\n float result = 0.0;\n\n for (int i = 0; i < "+r+"; i++) {\n // x = (-2|2 * PI / N) * index * i;\n float x = exponentMultiplierTimesIndexRatio * float(i);\n float expR = cos(x);\n float expI = sin(x);\n float real = getReal(batch, i);\n float imag = getImag(batch, i);\n\n result +=\n unaryOpComplex(real, expR, imag, expI) / "+a+";\n }\n\n return result;\n }\n\n void main() {\n ivec2 coords = getOutputCoords();\n setOutput(mulMatDFT(coords[0], coords[1]));\n }\n "},fa=function(){function t(t,e){this.outputShape=[],this.variableNames=["x"],this.outputShape=t,this.userCode="\n uniform float value;\n void main() {\n // Input can be obtained from uniform value.\n setOutput(value);\n }\n "}return t.prototype.getCustomSetupFunc=function(t){var e=this;return function(n,r){null==e.valueLoc&&(e.valueLoc=n.getUniformLocationNoThrow(r,"value")),n.gl.uniform1f(e.valueLoc,t)}},t}(),da=function(t){this.variableNames=["A"];var e=fi(),n=t[0],r=t[1];this.outputShape=t,this.userCode="\n void main() {\n ivec3 coords = getOutputCoords();\n int texR = coords[0];\n int texC = coords[1];\n int depth = coords[2];\n vec2 uv = (vec2(texC, texR) + halfCR) / vec2("+r+".0, "+n+".0);\n\n vec4 values = "+e.texture2D+"(A, uv);\n float value;\n if (depth == 0) {\n value = values.r;\n } else if (depth == 1) {\n value = values.g;\n } else if (depth == 2) {\n value = values.b;\n } else if (depth == 3) {\n value = values.a;\n }\n\n setOutput(floor(value * 255.0 + 0.5));\n }\n "},ma=function(t){this.variableNames=["A"];var e=fi(),n=t[0],r=t[1];this.outputShape=t,this.userCode="\n void main() {\n ivec3 coords = getOutputCoords();\n int texR = coords[0];\n int texC = coords[1];\n int depth = coords[2];\n\n vec4 result = vec4(0.);\n\n for(int row=0; row<=1; row++) {\n for(int col=0; col<=1; col++) {\n texC = coords[1] + row;\n depth = coords[2] + col;\n\n vec2 uv = (vec2(texC, texR) + halfCR) / vec2("+r+".0, "+n+".0);\n vec4 values = "+e.texture2D+"(A, uv);\n float value;\n if (depth == 0) {\n value = values.r;\n } else if (depth == 1) {\n value = values.g;\n } else if (depth == 2) {\n value = values.b;\n } else if (depth == 3) {\n value = values.a;\n }\n\n result[row * 2 + col] = floor(value * 255.0 + 0.5);\n }\n }\n\n "+e.output+" = result;\n }\n "},ga=function(t,e,n){this.variableNames=["A","indices"];var r=t.slice();r[n]=e,this.outputShape=r,this.rank=r.length;var i=Ei(this.rank),a=function(t,e){var n=t.length;if(n>4)throw Error("Gather for rank "+n+" is not yet supported");if(1===n)return"int(getIndices(resRC))";for(var r=["resRC.x","resRC.y","resRC.z","resRC.w"],i=[],a=0;a1?"strides[j]":"strides";this.userCode="\n "+r+" strides = "+r+"("+this.strides+");\n void main() {\n "+i+" coords = getOutputCoords();\n int flattenIndex = 0;\n for (int j = 0; j < "+this.sliceDim+"; j++) {\n int index = round(getIndices(coords[0], j));\n flattenIndex += index * "+a+";\n }\n setOutput(getX(flattenIndex, coords[1]));\n }\n "};function ya(t,e){var n=fi();return Ht(t,e,n.version+"\n precision highp float;\n "+n.attribute+" vec3 clipSpacePos;\n "+n.attribute+" vec2 uv;\n "+n.varyingVs+" vec2 resultUV;\n\n void main() {\n gl_Position = vec4(clipSpacePos, 1);\n resultUV = uv;\n }")}function ba(t,e){return Qt(t,e,new Float32Array([-1,1,0,0,1,-1,-1,0,0,0,1,1,0,1,1,1,-1,0,1,0]))}function xa(t,e){return te(t,e,new Uint16Array([0,1,2,2,1,3]))}function wa(t,e,n,r,i,a,o){ne(n,r);var s=ee(t,e),u=t.TEXTURE_2D;return Bt(t,e,function(){return t.bindTexture(u,s)}),Bt(t,e,function(){return t.texParameteri(u,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE)}),Bt(t,e,function(){return t.texParameteri(u,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE)}),Bt(t,e,function(){return t.texParameteri(u,t.TEXTURE_MIN_FILTER,t.NEAREST)}),Bt(t,e,function(){return t.texParameteri(u,t.TEXTURE_MAG_FILTER,t.NEAREST)}),Bt(t,e,function(){return t.texImage2D(u,0,i,n,r,0,a,o,null)}),Bt(t,e,function(){return t.bindTexture(t.TEXTURE_2D,null)}),s}function Na(t,e,n,r,i){var a=Mt(n,r);return wa(t,e,a[0],a[1],i.internalFormatFloat,i.textureFormatFloat,t.FLOAT)}function Ca(t,e,n,r,i){var a=Mt(n,r);return wa(t,e,a[0],a[1],i.internalFormatHalfFloat,i.textureFormatFloat,i.textureTypeHalfFloat)}function Ea(t,e,n,r,i){var a=Mt(n,r);return wa(t,e,a[0],a[1],t.RGBA,t.RGBA,t.UNSIGNED_BYTE)}function Sa(t,e,n,r,i){var a=Lt(n,r);return wa(t,e,a[0],a[1],i.internalFormatPackedFloat,t.RGBA,t.FLOAT)}function ka(t,e,n,r,i){var a=Lt(n,r);return wa(t,e,a[0],a[1],i.internalFormatPackedHalfFloat,t.RGBA,i.textureTypeHalfFloat)}function Ia(t,e,n,r){return Bt(t,e,function(){return t.bindBuffer(t.ARRAY_BUFFER,r)}),ie(t,e,n,"clipSpacePos",r,3,20,0)&&ie(t,e,n,"uv",r,2,20,12)}function Aa(t,e,n,r,i,a,o){var s,u,l;Bt(t,e,function(){return t.bindTexture(t.TEXTURE_2D,n)}),a instanceof Uint8Array?(s=new Uint8Array(r*i*4),u=t.UNSIGNED_BYTE,l=t.RGBA):(s=new Float32Array(r*i*4),u=t.FLOAT,l=o.internalFormatPackedFloat),s.set(a),Bt(t,e,function(){return t.texImage2D(t.TEXTURE_2D,0,l,r,i,0,t.RGBA,u,s)}),Bt(t,e,function(){return t.bindTexture(t.TEXTURE_2D,null)})}function Ra(t,e,n,r){Bt(t,e,function(){return t.bindTexture(t.TEXTURE_2D,n)}),r.data instanceof Uint8Array?Bt(t,e,function(){return t.texImage2D(t.TEXTURE_2D,0,t.RGBA,r.width,r.height,0,t.RGBA,t.UNSIGNED_BYTE,r.data)}):Bt(t,e,function(){return t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,r)}),Bt(t,e,function(){return t.bindTexture(t.TEXTURE_2D,null)})}function Ta(t,e,n,r,i){var a=t.createBuffer();Bt(t,e,function(){return t.bindBuffer(t.PIXEL_PACK_BUFFER,a)});var o=16*n*r;return Bt(t,e,function(){return t.bufferData(t.PIXEL_PACK_BUFFER,o,t.STREAM_READ)}),Bt(t,e,function(){return t.readPixels(0,0,r,n,t.RGBA,t.FLOAT,0)}),Bt(t,e,function(){return t.bindBuffer(t.PIXEL_PACK_BUFFER,null)}),a}function Da(t,e,n){var r=t,i=new Float32Array(n);return r.bindBuffer(r.PIXEL_PACK_BUFFER,e),r.getBufferSubData(r.PIXEL_PACK_BUFFER,0,i),r.bindBuffer(r.PIXEL_PACK_BUFFER,null),i}function Oa(t,e,n,r,i){var a=Mt(n,r),o=a[0],s=a[1],u=new Uint8Array(n*r*4);return Bt(t,e,function(){return t.readPixels(0,0,o,s,i.downloadTextureFormat,t.UNSIGNED_BYTE,u)}),new Float32Array(u.buffer)}function _a(t,e,n,r,i,a,o,s){var u=t,l=new Float32Array(function(t,e){var n=Lt(a,o);return n[0]*n[1]*4}());return u.bindBuffer(u.PIXEL_PACK_BUFFER,e),u.getBufferSubData(u.PIXEL_PACK_BUFFER,0,l),u.bindBuffer(u.PIXEL_PACK_BUFFER,null),l}function Fa(t,e,n,r){var i=new Float32Array(n*r*4);return Bt(t,e,function(){return t.readPixels(0,0,r,n,t.RGBA,t.FLOAT,i)}),i}var Ma=Object.freeze({createVertexShader:ya,createVertexBuffer:ba,createIndexBuffer:xa,createFloat32MatrixTexture:Na,createFloat16MatrixTexture:Ca,createUnsignedBytesMatrixTexture:Ea,createPackedMatrixTexture:Sa,createFloat16PackedMatrixTexture:ka,bindVertexProgramAttributeStreams:Ia,uploadDenseMatrixToTexture:Aa,uploadPixelDataToTexture:Ra,createBufferFromOutputTexture:Ta,downloadFloat32MatrixFromBuffer:Da,downloadByteEncodedFloatMatrixFromOutputTexture:Oa,downloadPackedMatrixFromBuffer:_a,downloadMatrixFromPackedOutputTexture:Fa}),za=function(){function e(e){this.outputTexture=null,this.program=null,this.disposed=!1,this.vertexAttrsAreBound=!1,this.itemsToPoll=[];var n=t.ENV.getNumber("WEBGL_VERSION");if(null!=e?(this.gl=e,Ot(n,e)):this.gl=_t(n),1===t.ENV.getNumber("WEBGL_VERSION"))this.textureFloatExtension=Gt(this.gl,this.debug,"OES_texture_float"),this.colorBufferFloatExtension=this.gl.getExtension("WEBGL_color_buffer_float"),this.textureHalfFloatExtension=Gt(this.gl,this.debug,"OES_texture_half_float"),this.colorBufferHalfFloatExtension=this.gl.getExtension("EXT_color_buffer_half_float");else if(Ee(this.gl,"EXT_color_buffer_float"))this.colorBufferFloatExtension=this.gl.getExtension("EXT_color_buffer_float");else{if(!Ee(this.gl,"EXT_color_buffer_half_float"))throw new Error("GL context does not support color renderable floats");this.colorBufferHalfFloatExtension=this.gl.getExtension("EXT_color_buffer_half_float")}this.vertexBuffer=ba(this.gl,this.debug),this.indexBuffer=xa(this.gl,this.debug),this.framebuffer=re(this.gl,this.debug),this.textureConfig=Pt(this.gl,this.textureHalfFloatExtension)}return Object.defineProperty(e.prototype,"debug",{get:function(){return t.ENV.getBool("DEBUG")},enumerable:!0,configurable:!0}),e.prototype.dispose=function(){var t=this;if(!this.disposed){null!=this.program&&console.warn("Disposing a GPGPUContext that still has a bound WebGLProgram. This is probably a resource leak, delete the program with GPGPUContext.deleteProgram before disposing."),null!=this.outputTexture&&console.warn("Disposing a GPGPUContext that still has a bound output matrix texture. This is probably a resource leak, delete the output matrix texture with GPGPUContext.deleteMatrixTexture before disposing.");var e=this.gl;Bt(e,this.debug,function(){return e.finish()}),Bt(e,this.debug,function(){return e.bindFramebuffer(e.FRAMEBUFFER,null)}),Bt(e,this.debug,function(){return e.deleteFramebuffer(t.framebuffer)}),Bt(e,this.debug,function(){return e.bindBuffer(e.ARRAY_BUFFER,null)}),Bt(e,this.debug,function(){return e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null)}),Bt(e,this.debug,function(){return e.deleteBuffer(t.indexBuffer)}),this.disposed=!0}},e.prototype.createFloat32MatrixTexture=function(t,e){return this.throwIfDisposed(),Na(this.gl,this.debug,t,e,this.textureConfig)},e.prototype.createFloat16MatrixTexture=function(t,e){return this.throwIfDisposed(),Ca(this.gl,this.debug,t,e,this.textureConfig)},e.prototype.createUnsignedBytesMatrixTexture=function(t,e){return this.throwIfDisposed(),Ea(this.gl,this.debug,t,e,this.textureConfig)},e.prototype.uploadPixelDataToTexture=function(t,e){this.throwIfDisposed(),Ra(this.gl,this.debug,t,e)},e.prototype.uploadDenseMatrixToTexture=function(t,e,n,r){this.throwIfDisposed(),Aa(this.gl,this.debug,t,e,n,r,this.textureConfig)},e.prototype.createFloat16PackedMatrixTexture=function(t,e){return this.throwIfDisposed(),ka(this.gl,this.debug,t,e,this.textureConfig)},e.prototype.createPackedMatrixTexture=function(t,e){return this.throwIfDisposed(),Sa(this.gl,this.debug,t,e,this.textureConfig)},e.prototype.deleteMatrixTexture=function(t){var e=this;this.throwIfDisposed(),this.outputTexture===t&&(ce(this.gl,this.debug,this.framebuffer),this.outputTexture=null),Bt(this.gl,this.debug,function(){return e.gl.deleteTexture(t)})},e.prototype.downloadByteEncodedFloatMatrixFromOutputTexture=function(t,e,n){var r=this;return this.downloadMatrixDriver(t,function(){return Oa(r.gl,r.debug,e,n,r.textureConfig)})},e.prototype.downloadPackedMatrixFromBuffer=function(t,e,n,r,i,a){return _a(this.gl,t,0,0,0,i,a,this.textureConfig)},e.prototype.downloadFloat32MatrixFromBuffer=function(t,e){return Da(this.gl,t,e)},e.prototype.createBufferFromTexture=function(t,e,n){this.bindTextureToFrameBuffer(t);var r=Ta(this.gl,this.debug,e,n,this.textureConfig);return this.unbindTextureToFrameBuffer(),r},e.prototype.createAndWaitForFence=function(){var t=this.createFence(this.gl);return this.pollFence(t)},e.prototype.createFence=function(e){var n,r,i=this;if(t.ENV.getBool("WEBGL_FENCE_API_ENABLED")){var a=e,o=a.fenceSync(a.SYNC_GPU_COMMANDS_COMPLETE,0);e.flush(),r=function(){var t=a.clientWaitSync(o,0,0);return t===a.ALREADY_SIGNALED||t===a.CONDITION_SATISFIED},n=o}else t.ENV.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?(n=this.beginQuery(),this.endQuery(),r=function(){return i.isQueryAvailable(n,t.ENV.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))}):r=function(){return!0};return{query:n,isFencePassed:r}},e.prototype.downloadMatrixFromPackedTexture=function(t,e,n){var r=this;return this.downloadMatrixDriver(t,function(){return Fa(r.gl,r.debug,e,n)})},e.prototype.createProgram=function(t){this.throwIfDisposed();var e=this.gl,n=qt(e,this.debug,t),r=ya(e,this.debug),i=Yt(e,this.debug);return Bt(e,this.debug,function(){return e.attachShader(i,r)}),Bt(e,this.debug,function(){return e.attachShader(i,n)}),Jt(e,this.debug,i),this.debug&&Zt(e,this.debug,i),this.vertexAttrsAreBound||(this.setProgram(i),this.vertexAttrsAreBound=Ia(e,this.debug,this.program,this.vertexBuffer)),i},e.prototype.deleteProgram=function(t){var e=this;this.throwIfDisposed(),t===this.program&&(this.program=null),null!=t&&Bt(this.gl,this.debug,function(){return e.gl.deleteProgram(t)})},e.prototype.setProgram=function(t){var e=this;this.throwIfDisposed(),this.program=t,null!=this.program&&this.debug&&Zt(this.gl,this.debug,this.program),Bt(this.gl,this.debug,function(){return e.gl.useProgram(t)})},e.prototype.getUniformLocation=function(t,e,n){return void 0===n&&(n=!0),this.throwIfDisposed(),n?oe(this.gl,this.debug,t,e):se(this.gl,t,e)},e.prototype.getAttributeLocation=function(t,e){var n=this;return this.throwIfDisposed(),Bt(this.gl,this.debug,function(){return n.gl.getAttribLocation(t,e)})},e.prototype.getUniformLocationNoThrow=function(t,e){return this.throwIfDisposed(),this.gl.getUniformLocation(t,e)},e.prototype.setInputMatrixTexture=function(t,e,n){this.throwIfDisposed(),this.throwIfNoProgram(),ue(this.gl,this.debug,this.program,t,e,n)},e.prototype.setOutputMatrixTexture=function(t,e,n){this.setOutputMatrixTextureDriver(t,n,e)},e.prototype.setOutputPackedMatrixTexture=function(t,e,n){this.throwIfDisposed();var r=Lt(e,n),i=r[0],a=r[1];this.setOutputMatrixTextureDriver(t,i,a)},e.prototype.setOutputMatrixWriteRegion=function(t,e,n,r){this.setOutputMatrixWriteRegionDriver(n,t,r,e)},e.prototype.setOutputPackedMatrixWriteRegion=function(t,e,n,r){throw new Error("setOutputPackedMatrixWriteRegion not implemented.")},e.prototype.debugValidate=function(){null!=this.program&&Zt(this.gl,this.debug,this.program),pe(this.gl)},e.prototype.executeProgram=function(){this.throwIfDisposed(),this.throwIfNoProgram();var t=this.gl;this.debug&&this.debugValidate(),Bt(t,this.debug,function(){return t.drawElements(t.TRIANGLES,6,t.UNSIGNED_SHORT,0)})},e.prototype.blockUntilAllProgramsCompleted=function(){var t=this;this.throwIfDisposed(),Bt(this.gl,this.debug,function(){return t.gl.finish()})},e.prototype.getQueryTimerExtension=function(){return null==this.disjointQueryTimerExtension&&(this.disjointQueryTimerExtension=Gt(this.gl,this.debug,2===t.ENV.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")?"EXT_disjoint_timer_query_webgl2":"EXT_disjoint_timer_query")),this.disjointQueryTimerExtension},e.prototype.getQueryTimerExtensionWebGL2=function(){return this.getQueryTimerExtension()},e.prototype.getQueryTimerExtensionWebGL1=function(){return this.getQueryTimerExtension()},e.prototype.beginQuery=function(){if(2===t.ENV.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")){var e=this.gl,n=this.getQueryTimerExtensionWebGL2(),r=e.createQuery();return e.beginQuery(n.TIME_ELAPSED_EXT,r),r}var i=this.getQueryTimerExtensionWebGL1(),a=i.createQueryEXT();return i.beginQueryEXT(i.TIME_ELAPSED_EXT,a),a},e.prototype.endQuery=function(){if(2!==t.ENV.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")){var e=this.getQueryTimerExtensionWebGL1();e.endQueryEXT(e.TIME_ELAPSED_EXT)}else{var n=this.gl,r=this.getQueryTimerExtensionWebGL2();n.endQuery(r.TIME_ELAPSED_EXT)}},e.prototype.waitForQueryAndGetTime=function(e){return r(this,void 0,void 0,function(){var n=this;return i(this,function(r){switch(r.label){case 0:return[4,C(function(){return n.disposed||n.isQueryAvailable(e,t.ENV.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))})];case 1:return r.sent(),[2,this.getQueryTime(e,t.ENV.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))]}})})},e.prototype.getQueryTime=function(t,e){if(0===e)return null;if(2===e){var n=this.gl;return n.getQueryParameter(t,n.QUERY_RESULT)/1e6}var r=this.getQueryTimerExtensionWebGL1();return r.getQueryObjectEXT(t,r.QUERY_RESULT_EXT)/1e6},e.prototype.isQueryAvailable=function(t,e){if(0===e)return!0;if(2===e){var n=this.gl,r=this.getQueryTimerExtensionWebGL2(),i=n.getQueryParameter(t,n.QUERY_RESULT_AVAILABLE);return null==this.disjoint&&(this.disjoint=this.gl.getParameter(r.GPU_DISJOINT_EXT)),i&&!this.disjoint}return i=(r=this.getQueryTimerExtensionWebGL1()).getQueryObjectEXT(t,r.QUERY_RESULT_AVAILABLE_EXT),null==this.disjoint&&(this.disjoint=this.gl.getParameter(r.GPU_DISJOINT_EXT)),i&&!this.disjoint},e.prototype.pollFence=function(t){var e=this;return new Promise(function(n){e.addItemToPoll(function(){return t.isFencePassed()},function(){return n()})})},e.prototype.pollItems=function(){for(var t=function(t){for(var e=0;e1||C(function(){return n.pollItems(),0===n.itemsToPoll.length})},e.prototype.bindTextureToFrameBuffer=function(t){this.throwIfDisposed(),le(this.gl,this.debug,t,this.framebuffer),this.debug&&pe(this.gl)},e.prototype.unbindTextureToFrameBuffer=function(){null!=this.outputTexture?(le(this.gl,this.debug,this.outputTexture,this.framebuffer),this.debug&&pe(this.gl)):ce(this.gl,this.debug,this.framebuffer)},e.prototype.downloadMatrixDriver=function(t,e){this.bindTextureToFrameBuffer(t);var n=e();return this.unbindTextureToFrameBuffer(),n},e.prototype.setOutputMatrixTextureDriver=function(t,e,n){this.throwIfDisposed();var r=this.gl;le(r,this.debug,t,this.framebuffer),this.debug&&pe(r),this.outputTexture=t,Bt(r,this.debug,function(){return r.viewport(0,0,e,n)}),Bt(r,this.debug,function(){return r.scissor(0,0,e,n)})},e.prototype.setOutputMatrixWriteRegionDriver=function(t,e,n,r){var i=this;this.throwIfDisposed(),Bt(this.gl,this.debug,function(){return i.gl.scissor(t,e,n,r)})},e.prototype.throwIfDisposed=function(){if(this.disposed)throw new Error("Attempted to use disposed GPGPUContext.")},e.prototype.throwIfNoProgram=function(){if(null==this.program)throw new Error("No GPU program is currently set.")},e}();function La(t,e){if(t.length!==e.length)throw Error("Binary was compiled with "+t.length+" inputs, but was executed with "+e.length+" inputs");t.forEach(function(t,n){var r=t.logicalShape,i=e[n],a=i.shape;if(!y(r,a))throw Error("Binary was compiled with different shapes than the current args. Shapes "+r+" and "+a+" must match");if(!t.isUniform||!i.isUniform){var o=t.texShape,s=i.isUniform?null:i.texData.texShape;if(!y(o,s))throw Error("Binary was compiled with different texture shapes than the current args. Shape "+o+" and "+s+" must match")}})}var Pa=function(t,e,n){this.variableNames=["A"],this.usesPackedTextures=!0,this.outputShape=t;for(var r=n.filterWidth,i=n.inChannels,a=n.strideWidth,o=n.strideHeight,s=n.padInfo,u=n.outWidth,l=n.dilationWidth,c=n.dilationHeight,p=n.dataFormat,h=s.left,f=s.top,d=i*r,m=fi(),g="channelsLast"===p,v=g?0:1,y=g?1:2,b="",x=0;x<=1;x++)for(var w=0;w<=1;w++)b+="\n blockIndex = rc.y + "+w+";\n pos = rc.x + "+x+";\n\n if(blockIndex < "+t[1]+" && pos < "+t[0]+") {\n offsetY = int(blockIndex / ("+u+")) * "+o+" - "+f+";\n d0 = offsetY + "+c+" * (pos / "+d+");\n\n if(d0 < "+e[v]+" && d0 >= 0) {\n\n offsetX = int(mod(float(blockIndex), "+u+".) * "+a+". - "+h+".);\n d1 = offsetX + "+l+" * (int(mod(float(pos), "+d+".) / "+i+".));\n\n if(d1 < "+e[y]+" && d1 >= 0) {\n\n ch = int(mod(float(pos), "+i+".));\n\n if ("+g+") {\n innerDims = vec2(d1, ch);\n result["+(2*x+w)+"] = getChannel(\n getA(d0, int(innerDims.x),\n int(innerDims.y)), innerDims);\n } else {\n innerDims = vec2(d0, d1);\n result["+(2*x+w)+"] = getChannel(\n getA(ch, int(innerDims.x),\n int(innerDims.y)), innerDims);\n }\n }\n }\n }\n ";this.userCode="\n void main() {\n ivec2 rc = getOutputCoords();\n\n vec4 result = vec4(0);\n\n int blockIndex, pos, offsetY, d0, offsetX, d1, ch;\n vec2 innerDims;\n\n "+b+"\n\n "+m.output+" = result;\n }\n "},Ba=function(t,e,n,r,i){this.variableNames=["x"],this.outputShape=[];var a,o=e,s=t[3]-1;this.outputShape=t;var u="float("+n+") + float("+r+") * sum";a=.5===i?"inversesqrt("+u+")":1===i?"1.0/("+u+")":"exp(log("+u+") * float(-"+i+"));",this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int r = coords[1];\n int c = coords[2];\n int d = coords[3];\n float x = getX(b, r, c, d);\n float sum = 0.0;\n for (int j = -"+o+"; j <= "+o+"; j++) {\n int idx = d + j;\n if (idx >= 0 && idx <= "+s+") {\n float z = getX(b, r, c, idx);\n sum += z * z;\n }\n }\n float val = x * "+a+";\n setOutput(val);\n }\n "},Va=function(t,e,n,r,i){this.variableNames=["inputImage","outputImage","dy"],this.outputShape=[],this.outputShape=t,this.depth=t[3],this.depthRadius=e,this.bias=n,this.alpha=r,this.beta=i,this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int r = coords[1];\n int c = coords[2];\n\n float result = 0.0;\n for (int d = 0; d < "+this.depth+"; ++d) {\n int depthBegin = int(max(0.0, float(d - "+e+")));\n int depthEnd = int(min(float("+this.depth+"),\n float(d + "+e+" + 1)));\n\n const int MIN_DEPTH_BEGIN = 0;\n const int MAX_DEPTH_END = "+this.depth+";\n\n float norm = 0.0;\n for (int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k) {\n if (k < depthBegin){\n continue;\n }\n else if (k >= depthBegin && k < depthEnd) {\n norm += getInputImage(b, r, c, k) * getInputImage(b, r, c, k);\n }\n else {\n break;\n }\n }\n\n norm = float("+r+") * norm + float("+n+");\n\n for(int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k){\n if (k < depthBegin){\n continue;\n }\n else if (k >= depthBegin && k < depthEnd){\n float dyi = -2.0 * float("+r+")\n * float("+i+")\n * getInputImage(b ,r ,c, k) * getOutputImage(b, r, c, d)\n / norm;\n if (k == d) {\n dyi += pow(norm, -1.0 * "+i+");\n }\n if (k == coords[3]) {\n dyi *= getDy(b, r, c, d);\n result += dyi;\n }\n }\n else {\n break;\n }\n }\n }\n setOutput(result);\n }\n "},Wa=function(t,e,n,r,i){this.variableNames=["x"],this.outputShape=[],this.usesPackedTextures=!0;var a,o=e,s=t[3]-1;this.outputShape=t;var u="float("+n+") + float("+r+") * sum";a=.5===i?"inversesqrt("+u+")":1===i?"1.0/("+u+")":"exp(log("+u+") * float(-"+i+"));",this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords.x;\n int r = coords.y;\n int c = coords.z;\n int d = coords.w;\n\n bool hasNextCol = d < "+this.outputShape[3]+";\n bool hasNextRow = c < "+this.outputShape[2]+";\n\n vec4 sum = vec4(0.);\n vec4 xFragAtOutputCoords = getX(b, r, c, d);\n\n vec4 xAtOutputCoords = vec4(\n getChannel(xFragAtOutputCoords, vec2(c, d)),\n hasNextCol ?\n getChannel(xFragAtOutputCoords, vec2(c, d + 1)) : 0.0,\n hasNextRow ?\n getChannel(xFragAtOutputCoords , vec2(c + 1, d)) : 0.0,\n (hasNextRow && hasNextCol) ?\n getChannel(xFragAtOutputCoords, vec2(c + 1, d + 1)) : 0.0\n );\n\n int firstChannel = d - "+o+";\n vec2 cache = vec2(0.);\n if(firstChannel >= 0){\n vec4 firstChannelFrag = getX(b, r, c, firstChannel);\n cache.x = getChannel(firstChannelFrag, vec2(c, firstChannel));\n if(hasNextRow){\n cache.y = getChannel(firstChannelFrag, vec2(c + 1, firstChannel));\n }\n }\n\n ivec2 depth = ivec2(d, d + 1);\n for (int j = - "+o+"; j <= "+o+"; j++) {\n ivec2 idx = depth + j;\n bvec2 aboveLowerBound = greaterThanEqual(idx, ivec2(0));\n bvec2 belowUpperBound = lessThanEqual(idx, ivec2("+s+"));\n\n bool depthInRange = aboveLowerBound.x && belowUpperBound.x;\n bool depthPlusOneInRange = aboveLowerBound.y && belowUpperBound.y;\n\n if(depthInRange || depthPlusOneInRange){\n vec4 z = vec4(0.);\n vec4 xFragAtCurrentDepth;\n z.xz = cache.xy;\n if(depthPlusOneInRange && hasNextCol){\n xFragAtCurrentDepth = idx.y != d ?\n getX(b, r, c, idx.y) : xFragAtOutputCoords;\n z.y = getChannel(xFragAtCurrentDepth, vec2(c, idx.y));\n if(hasNextRow){\n z.w = getChannel(xFragAtCurrentDepth, vec2(c + 1, idx.y));\n }\n }\n cache.xy = z.yw;\n sum += z * z;\n }\n }\n vec4 result = xAtOutputCoords * "+a+";\n setOutput(result);\n }\n "},Ua=function(t){this.variableNames=["dy","maxPos"],this.outputShape=t.inShape;var e=t.strideHeight,n=t.strideWidth,r=t.dilationHeight,i=t.effectiveFilterHeight,a=t.effectiveFilterWidth,o=i-1-t.padInfo.top,s=a-1-t.padInfo.left,u=i*a-1;this.userCode="\n const ivec2 pads = ivec2("+o+", "+s+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n\n ivec2 dyRCCorner = coords.yz - pads;\n int dyRCorner = dyRCCorner.x;\n int dyCCorner = dyRCCorner.y;\n\n // Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < "+i+";\n wR += "+r+") {\n float dyR = float(dyRCorner + wR) / "+e+".0;\n\n if (dyR < 0.0 || dyR >= "+t.outHeight+".0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n for (int wC = 0; wC < "+a+"; wC++) {\n float dyC = float(dyCCorner + wC) / "+n+".0;\n\n if (dyC < 0.0 || dyC >= "+t.outWidth+".0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n float dyValue = getDy(b, idyR, idyC, d);\n int maxPosValue = "+u+" - int(getMaxPos(b, idyR, idyC, d));\n\n // Get the current value, check it against the value from the\n // position matrix.\n int curPosValue = wR * "+a+" + wC;\n float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);\n\n dotProd += dyValue * mask;\n }\n }\n setOutput(dotProd);\n }\n "},ja=function(t){this.variableNames=["dy","maxPos"],this.outputShape=t.inShape;var e=t.strideDepth,n=t.strideHeight,r=t.strideWidth,i=t.dilationDepth,a=t.dilationHeight,o=t.dilationWidth,s=t.effectiveFilterDepth,u=t.effectiveFilterHeight,l=t.effectiveFilterWidth,c=s-1-t.padInfo.front,p=u-1-t.padInfo.top,h=l-1-t.padInfo.left,f=s*u*l-1;this.userCode="\n const ivec3 pads = ivec3("+c+", "+p+", "+h+");\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int ch = coords.u;\n\n ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;\n int dyDCorner = dyCorner.x;\n int dyRCorner = dyCorner.y;\n int dyCCorner = dyCorner.z;\n\n // Convolve dy(?, ?, ?, ch) with pos mask(:, :, :, d) to get\n // dx(xD, xR, xC, ch).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n\n for (int wD = 0; wD < "+s+";\n wD += "+i+") {\n float dyD = float(dyDCorner + wD) / "+e+".0;\n\n if (dyD < 0.0 || dyD >= "+t.outDepth+".0 || fract(dyD) > 0.0) {\n continue;\n }\n int idyD = int(dyD);\n\n for (int wR = 0; wR < "+u+";\n wR += "+a+") {\n float dyR = float(dyRCorner + wR) / "+n+".0;\n\n if (dyR < 0.0 || dyR >= "+t.outHeight+".0 ||\n fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n for (int wC = 0; wC < "+l+";\n wC += "+o+") {\n float dyC = float(dyCCorner + wC) / "+r+".0;\n\n if (dyC < 0.0 || dyC >= "+t.outWidth+".0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n float dyValue = getDy(batch, idyD, idyR, idyC, ch);\n int maxPosValue = "+f+" -\n int(getMaxPos(batch, idyD, idyR, idyC, ch));\n\n // Get the current value, check it against the value from the\n // position matrix.\n int curPosValue =\n wD * "+u+" * "+l+" +\n wR * "+l+" + wC;\n float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);\n\n dotProd += dyValue * mask;\n }\n }\n }\n setOutput(dotProd);\n }\n "},Ga=function(t,e,n,r,i,a,o){void 0===n&&(n=!1),void 0===r&&(r=!1),void 0===i&&(i=!1),void 0===a&&(a=null),void 0===o&&(o=!1),this.variableNames=["matrixA","matrixB"],this.usesPackedTextures=!0,this.outputShape=e;var s=n?t[1]:t[2],u=Math.ceil(s/2),l=n?"i * 2, rc.y":"rc.y, i * 2",c=r?"rc.z, i * 2":"i * 2, rc.z",p=n?["a.xxyy","a.zzww"]:["a.xxzz","a.yyww"],h=r?["b.xzxz","b.ywyw"]:["b.xyxy","b.zwzw"],f="",d="";a&&(f=o?"vec4 activation(vec4 a) {\n vec4 b = getPreluActivationWeightsAtOutCoords();\n "+a+"\n }":"vec4 activation(vec4 x) {\n "+a+"\n }",d="result = activation(result);");var m=i?"result += getBiasAtOutCoords();":"";i&&this.variableNames.push("bias"),o&&this.variableNames.push("preluActivationWeights"),this.userCode="\n "+f+"\n\n const float sharedDimension = "+u+".0;\n\n vec4 dot2x2ARowBCol(ivec3 rc) {\n vec4 result = vec4(0);\n for (int i = 0; i < "+u+"; i++) {\n vec4 a = getMatrixA(rc.x, "+l+");\n vec4 b = getMatrixB(rc.x, "+c+");\n\n // These swizzled products need to be separately added.\n // See: https://github.com/tensorflow/tfjs/issues/1735\n result += ("+p[0]+" * "+h[0]+");\n result += ("+p[1]+" * "+h[1]+");\n }\n return result;\n }\n\n void main() {\n ivec3 rc = getOutputCoords();\n vec4 result = dot2x2ARowBCol(rc);\n\n "+m+"\n\n "+d+"\n\n setOutput(result);\n }\n "},Ha=function(){function t(t,e,n){this.variableNames=["probs"],this.outputShape=[t,n],this.userCode="\n uniform float seed;\n\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n\n float r = random(seed);\n float cdf = 0.0;\n\n for (int i = 0; i < "+(e-1)+"; i++) {\n cdf += getProbs(batch, i);\n\n if (r < cdf) {\n setOutput(float(i));\n return;\n }\n }\n\n // If no other event happened, last event happened.\n setOutput(float("+(e-1)+"));\n }\n "}return t.prototype.getCustomSetupFunc=function(t){var e=this;return function(n,r){null==e.seedLoc&&(e.seedLoc=n.getUniformLocation(r,"seed")),n.gl.uniform1f(e.seedLoc,t)}},t}(),qa=function(t,e,n,r){this.variableNames=["indices"],this.outputShape=[t,e],this.userCode="\n void main() {\n ivec2 coords = getOutputCoords();\n int index = round(getIndices(coords.x));\n setOutput(mix(float("+r+"), float("+n+"),\n float(index == coords.y)));\n }\n "},Ka=function(t){this.variableNames=["A"],this.outputShape=t;var e=t.length;if(0===e)this.userCode="\n void main() {\n setOutput(vec4(getA(), 0., 0., 0.));\n }\n ";else{var n=hi("rc",e),r=Ei(e),i=function(t,e,n){if(1===t)return"rc > "+e[0];for(var r="",i=t-2;i= "+e[i],i= "+e+";\n bool rEdge = rp1 >= "+n+";\n "}(e,t[t.length-1],t[t.length-2],n),o=function(t,e){var n=t.length,r=function(t,e){for(var n=[],r=0;r<=1;r++)for(var i=0;i<=1;i++){for(var a=(0===r?"r":"rp1")+", "+(0===i?"c":"cp1"),o=2;o= "+t[0]+" ? 0. : getA(rc + 1),\n 0, 0":"getA("+r[0]+"),\n cEdge ? 0. : getA("+r[1]+"),\n rEdge ? 0. : getA("+r[2]+"),\n rEdge || cEdge ? 0. : getA("+r[3]+")"}(t,n);this.userCode="\n void main() {\n "+r+" rc = getOutputCoords();\n\n if("+i+") {\n setOutput(vec4(0));\n } else {\n "+a+"\n\n setOutput(vec4("+o+"));\n }\n }\n "}},$a=function(t,e,n){this.variableNames=["x"],this.outputShape=e.map(function(e,n){return e[0]+t[n]+e[1]});var r=t.length,i=Ei(r),a=e.map(function(t){return t[0]}).join(","),o=e.map(function(e,n){return e[0]+t[n]}).join(","),s=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,r);this.userCode=1!==r?"\n "+i+" start = "+i+"("+a+");\n "+i+" end = "+i+"("+o+");\n\n void main() {\n "+i+" outC = getOutputCoords();\n if (any(lessThan(outC, start)) || any(greaterThanEqual(outC, end))) {\n setOutput(float("+n+"));\n } else {\n "+i+" coords = outC - start;\n setOutput(getX("+s+"));\n }\n }\n ":"\n int start = "+a+";\n int end = "+o+";\n\n void main() {\n int outC = getOutputCoords();\n if (outC < start || outC >= end) {\n setOutput(float("+n+"));\n } else {\n setOutput(getX(outC - start));\n }\n }\n "},Xa=function(t,e,n){this.variableNames=["x"],this.usesPackedTextures=!0,this.outputShape=e.map(function(e,n){return e[0]+t[n]+e[1]});for(var r=t.length,i=Ei(r),a=e.map(function(t){return t[0]}).join(","),o=e.map(function(e,n){return e[0]+t[n]}).join(","),s=hi("rc",r),u=hi("source",r),l=s[r-1]+" < "+this.outputShape[r-1],c=1===r?"source":"vec2("+u.slice(-2).join()+")",p=[i+" rc = outputLoc;",s[r-1]+" += 1;\n if("+l+") {\n ",1===r?"":"}\n rc = outputLoc;\n "+s[r-2]+" += 1;\n if("+s[r-2]+" < "+this.outputShape[r-2]+") {",1===r?"":" "+s[r-1]+" += 1;\n if("+l+") {"],h=1===r?"rc < start || rc >= end":"any(lessThan(rc, start)) || any(greaterThanEqual(rc, end))",f="",d=0,m=1===r?2:4;d= "+t.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+l+";\n wC += "+s+") {\n int xC = xCCorner + wC;\n\n if (xC < 0 || xC >= "+t.inWidth+") {\n continue;\n }\n\n float value = getX(batch, xR, xC, d);\n\n // If a min / max value has already been found, use it. If not,\n // use the current value.\n float currMinMaxValue = mix(\n value, minMaxValue, minMaxValueFound);\n if (value >= currMinMaxValue) {\n minMaxValue = value;\n minMaxValueFound = 1.0;\n minMaxPosition = wR * "+l+" + wC;\n }\n }\n }\n setOutput(float(minMaxPosition));\n }\n ";else{var d=e+"("+e+"("+e+"(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])";"avg"===e&&(d="avgValue / count");var m=4*Math.floor(r/4),g=r%4,v="\n if ("+h+") {\n avgValue += dot(values, ones);\n } else {\n minMaxValue = max(values, minMaxValue);\n }\n ";this.userCode="\n const ivec2 strides = ivec2("+i+", "+a+");\n const ivec2 pads = ivec2("+c+", "+p+");\n const float initializationValue = "+f+";\n const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n float count = 0.0;\n\n float getValue(int batch, int xR, int xC, int d) {\n if (xC < 0 || xC >= "+t.inWidth+") {\n return initializationValue;\n }\n count += 1.0;\n return getX(batch, xR, xC, d);\n }\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d = coords[3];\n\n ivec2 xRCCorner = coords.yz * strides - pads;\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n // max/min x(?, ?, d) to get y(yR, yC, d).\n // ? = to be determined\n vec4 minMaxValue = vec4("+f+");\n float avgValue = 0.0;\n count = 0.0;\n\n for (int wR = 0; wR < "+u+";\n wR += "+o+") {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= "+t.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+m+"; wC += 4) {\n int xC = xCCorner + wC * "+s+";\n\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + "+s+", d),\n getValue(batch, xR, xC + 2 * "+s+", d),\n getValue(batch, xR, xC + 3 * "+s+", d)\n );\n\n "+v+"\n }\n\n int xC = xCCorner + "+m+";\n if ("+(1===g)+") {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n "+v+"\n } else if ("+(2===g)+") {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + "+s+", d),\n initializationValue,\n initializationValue\n );\n\n "+v+"\n } else if ("+(3===g)+") {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + "+s+", d),\n getValue(batch, xR, xC + 2 * "+s+", d),\n initializationValue\n );\n\n "+v+"\n }\n }\n setOutput("+d+");\n }\n "}},Ja=function(t,e,n){if(this.variableNames=["x"],"avg"===e&&n)throw new Error("Cannot compute positions for average pool.");var r=t.filterWidth,i=t.strideDepth,a=t.strideHeight,o=t.strideWidth,s=t.dilationDepth,u=t.dilationHeight,l=t.dilationWidth,c=t.effectiveFilterDepth,p=t.effectiveFilterHeight,h=t.effectiveFilterWidth,f=t.padInfo.front,d=t.padInfo.top,m=t.padInfo.left;this.outputShape=t.outShape;var g="avg"===e,v="0.0";if(g||(v="-1.0 / 1e-20"),n)this.userCode="\n const ivec3 strides =\n ivec3("+i+", "+a+", "+o+");\n const ivec3 pads = ivec3("+f+", "+d+", "+m+");\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int ch = coords.u;\n\n ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;\n int xDCorner = xCorner.x;\n int xRCorner = xCorner.y;\n int xCCorner = xCorner.z;\n\n // max/min x(?, ?, ?, ch) to get y(yD, yR, yC, ch).\n // ? = to be determined\n float minMaxValue = 0.0;\n float minMaxValueFound = 0.0;\n int minMaxPosition = 0;\n\n for (int wD = 0; wD < "+c+";\n wD += "+s+") {\n int xD = xDCorner + wD;\n\n if (xD < 0 || xD >= "+t.inDepth+") {\n continue;\n }\n\n for (int wR = 0; wR < "+p+";\n wR += "+u+") {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= "+t.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+h+";\n wC += "+l+") {\n int xC = xCCorner + wC;\n\n if (xC < 0 || xC >= "+t.inWidth+") {\n continue;\n }\n\n float value = getX(batch, xD, xR, xC, ch);\n\n // If a min / max value has already been found, use it. If not,\n // use the current value.\n float currMinMaxValue = mix(\n value, minMaxValue, minMaxValueFound);\n if (value >= currMinMaxValue) {\n minMaxValue = value;\n minMaxValueFound = 1.0;\n minMaxPosition =\n wD * "+p+" * "+h+" +\n wR * "+h+" + wC;;\n }\n }\n }\n }\n setOutput(float(minMaxPosition));\n }\n ";else{var y=e+"("+e+"("+e+"(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])";"avg"===e&&(y="avgValue / count");var b=4*Math.floor(r/4),x=r%4,w="\n if ("+g+") {\n avgValue += dot(values, ones);\n } else {\n minMaxValue = max(values, minMaxValue);\n }\n ";this.userCode="\n const ivec3 strides =\n ivec3("+i+", "+a+", "+o+");\n const ivec3 pads = ivec3("+f+", "+d+", "+m+");\n const float initializationValue = "+v+";\n const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n float count = 0.0;\n\n float getValue(int batch, int xD, int xR, int xC, int ch) {\n if (xC < 0 || xC >= "+t.inWidth+") {\n return initializationValue;\n }\n count += 1.0;\n return getX(batch, xD, xR, xC, ch);\n }\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int ch = coords.u;\n\n ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;\n int xDCorner = xCorner.x;\n int xRCorner = xCorner.y;\n int xCCorner = xCorner.z;\n\n // max/min x(?, ?, ?, d) to get y(yD, yR, yC, ch).\n // ? = to be determined\n vec4 minMaxValue = vec4("+v+");\n float avgValue = 0.0;\n count = 0.0;\n\n for (int wD = 0; wD < "+c+";\n wD += "+s+") {\n int xD = xDCorner + wD;\n\n if (xD < 0 || xD >= "+t.inDepth+") {\n continue;\n }\n\n for (int wR = 0; wR < "+p+";\n wR += "+u+") {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= "+t.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+b+"; wC += 4) {\n int xC = xCCorner + wC * "+l+";\n\n vec4 values = vec4(\n getValue(batch, xD, xR, xC, ch),\n getValue(batch, xD, xR, xC + "+l+", ch),\n getValue(batch, xD, xR, xC + 2 * "+l+", ch),\n getValue(batch, xD, xR, xC + 3 * "+l+", ch)\n );\n\n "+w+"\n }\n\n int xC = xCCorner + "+b+";\n if ("+(1===x)+") {\n vec4 values = vec4(\n getValue(batch, xD, xR, xC, ch),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n "+w+"\n } else if ("+(2===x)+") {\n vec4 values = vec4(\n getValue(batch, xD, xR, xC, ch),\n getValue(batch, xD, xR, xC + "+l+", ch),\n initializationValue,\n initializationValue\n );\n\n "+w+"\n } else if ("+(3===x)+") {\n vec4 values = vec4(\n getValue(batch, xD, xR, xC, ch),\n getValue(batch, xD, xR, xC + "+l+", ch),\n getValue(batch, xD, xR, xC + 2 * "+l+", ch),\n initializationValue\n );\n\n "+w+"\n }\n }\n setOutput("+y+");\n }\n }\n "}},Za=function(t,e){this.variableNames=["x"];var n=t.windowSize,r=t.batchSize,i=t.inSize,a=Math.ceil(i/n);this.outputShape=[r,a];var o="0.0",s="";"prod"===e?o="1.0":"min"===e?(o="1.0 / 1e-20",s="min"):"max"===e&&(o="-1.0 / 1e-20",s="max");var u=e+"("+e+"("+e+"(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])";"sum"===e?u="sumValue":"prod"===e?u="prodValue":"all"===e?u="allValue":"any"===e&&(u="anyValue");var l=4*Math.floor(n/4),c=n%4,p="\n if ("+("sum"===e)+") {\n sumValue += dot(values, ones);\n } else if ("+("prod"===e)+") {\n vec2 tmp = vec2(values[0], values[1]) * vec2(values[2], values[3]);\n prodValue *= tmp[0] * tmp[1];\n } else {\n minMaxValue = "+s+"(values, minMaxValue);\n }\n ",h="vec4";"all"===e?(o="1.0",p="\n bool reducedAllValue = all(values);\n float floatedReducedAllValue = float(reducedAllValue);\n allValue = float(allValue >= 1.0 && floatedReducedAllValue >= 1.0);\n ",h="bvec4"):"any"===e&&(o="0.0",p="\n bool reducedAnyValue = any(values);\n float floatedReducedAnyValue = float(reducedAnyValue);\n anyValue = float(anyValue >= 1.0 || floatedReducedAnyValue >= 1.0);\n ",h="bvec4");var f="";i%n>0&&(f="\n if (inIdx < 0 || inIdx >= "+i+") {\n return initializationValue;\n }\n "),this.userCode="\n const float initializationValue = "+o+";\n const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n float getValue(int batch, int inIdx) {\n "+f+"\n return getX(batch, inIdx);\n }\n\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n int outIdx = coords[1];\n int inOffset = outIdx * "+n+";\n\n vec4 minMaxValue = vec4("+o+");\n float prodValue = 1.0;\n float sumValue = 0.0;\n float allValue = 1.0;\n float anyValue = 0.0;\n\n for (int i = 0; i < "+l+"; i += 4) {\n int inIdx = inOffset + i;\n "+h+" values = "+h+"(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n getValue(batch, inIdx + 3)\n );\n\n "+p+"\n }\n\n int inIdx = inOffset + "+l+";\n if ("+(1===c)+") {\n "+h+" values = "+h+"(\n getValue(batch, inIdx),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n "+p+"\n } else if ("+(2===c)+") {\n "+h+" values = "+h+"(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n initializationValue,\n initializationValue\n );\n\n "+p+"\n } else if ("+(3===c)+") {\n "+h+" values = "+h+"(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n initializationValue\n );\n\n "+p+"\n }\n setOutput("+u+");\n }\n "},Qa=function(t,e){this.variableNames=["A"],this.usesPackedTextures=!0,this.outputShape=t;for(var n="",r=0;r<4;r++){var i="thisRC = rc;";r%2==1&&(i+="thisRC.z += 1;"),r>1&&(i+="thisRC.y += 1;"),n+="\n "+i+"\n "+(r>0?"if(thisRC.y < rows && thisRC.z < cols){":"")+"\n int flatIndex = getFlatIndex(thisRC);\n\n ivec3 inputRC = inputCoordsFromReshapedOutCoords(flatIndex);\n vec2 inputRCInnerDims = vec2(float(inputRC.y),float(inputRC.z));\n\n result["+r+"] =\n getChannel(getA(inputRC.x, inputRC.y, inputRC.z), inputRCInnerDims);\n "+(r>0?"}":"")+"\n "}this.userCode="\n \n ivec3 inputCoordsFromReshapedOutCoords(int index) {\n "+di(["r","c","d"],e)+"\n return ivec3(r, c, d);\n }\n \n "+mi(t)+"\n\n void main() {\n ivec3 rc = getOutputCoords();\n\n vec4 result = vec4(0.);\n\n ivec3 thisRC;\n int rows = "+t[1]+";\n int cols = "+t[2]+";\n\n "+n+"\n\n setOutput(result);\n }\n "},to=function(t,e,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=e.shape;var r=e.shape,i=r[1],a=r[2],o=t.shape,s=o[1],u=o[2],l=[n&&s>1?i-1:i,n&&u>1?a-1:a],c=[n&&s>1?s-1:s,n&&u>1?u-1:u],p=l[0]/c[0],h=l[1]/c[1],f=1/p,d=1/h,m=2*Math.ceil(f)+2,g=2*Math.ceil(d)+2;this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n int r = coords[1];\n int c = coords[2];\n\n float accumulator = 0.0;\n\n const float heightScale = float("+p+");\n const float widthScale = float("+h+");\n\n const float invHeightScale = float("+f+");\n const float invWidthScale = float("+d+");\n\n const int winHeight = int("+m+");\n const int winWidth = int("+g+");\n\n // Compute bounds for where in dy we will look\n float startRLerp = floor(float(r) * invHeightScale);\n int startDyR = int(startRLerp - float(winHeight / 2));\n\n float startCLerp = floor(float(c) * invWidthScale);\n int startDyC = int(startCLerp - float(winWidth / 2));\n\n // Loop over dy\n for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {\n int dyR = dyROffset + startDyR;\n\n // Guard against the window exceeding the bounds of dy\n if (dyR < 0 || dyR >= "+s+") {\n continue;\n }\n\n for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {\n int dyC = dyCOffset + startDyC;\n\n // Guard against the window exceeding the bounds of dy\n if (dyC < 0 || dyC >= "+u+") {\n continue;\n }\n\n float dxR = float(dyR) * heightScale;\n int topDxRIndex = int(floor(dxR));\n int bottomDxRIndex = int(min(ceil(dxR), "+(i-1)+".0));\n float dxRLerp = dxR - float(topDxRIndex);\n float inverseDxRLerp = 1.0 - dxRLerp;\n\n float dxC = float(dyC) * widthScale;\n int leftDxCIndex = int(floor(dxC));\n int rightDxCIndex = int(min(ceil(dxC), "+(a-1)+".0));\n float dxCLerp = dxC - float(leftDxCIndex);\n float inverseDxCLerp = 1.0 - dxCLerp;\n\n if (r == topDxRIndex && c == leftDxCIndex) {\n // topLeft\n accumulator +=\n getDy(b, dyR, dyC, d) * inverseDxRLerp * inverseDxCLerp;\n }\n\n if (r == topDxRIndex && c == rightDxCIndex) {\n // topRight\n accumulator += getDy(b, dyR, dyC, d) * inverseDxRLerp * dxCLerp;\n }\n\n if (r == bottomDxRIndex && c == leftDxCIndex) {\n // bottomLeft\n accumulator += getDy(b, dyR, dyC, d) * dxRLerp * inverseDxCLerp;\n }\n\n if (r == bottomDxRIndex && c == rightDxCIndex) {\n // bottomRight\n accumulator += getDy(b, dyR, dyC, d) * dxRLerp * dxCLerp;\n }\n }\n }\n // End loop over dy\n\n setOutput(accumulator);\n }\n "},eo=function(t,e,n,r){this.variableNames=["A"],this.outputShape=[];var i=t[0],a=t[1],o=t[2],s=t[3];this.outputShape=[i,e,n,s];var u=[r&&e>1?a-1:a,r&&n>1?o-1:o],l=[r&&e>1?e-1:e,r&&n>1?n-1:n];this.userCode="\n const vec2 effectiveInputOverOutputRatioRC = vec2(\n "+u[0]/l[0]+",\n "+u[1]/l[1]+");\n const vec2 inputShapeRC = vec2("+a+".0, "+o+".0);\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n ivec2 yRC = coords.yz;\n\n // Fractional source index.\n vec2 sourceFracIndexRC = vec2(yRC) * effectiveInputOverOutputRatioRC;\n\n // Compute the four integer indices.\n ivec2 sourceFloorRC = ivec2(sourceFracIndexRC);\n ivec2 sourceCeilRC = ivec2(\n min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));\n\n float topLeft = getA(b, sourceFloorRC.x, sourceFloorRC.y, d);\n float bottomLeft = getA(b, sourceCeilRC.x, sourceFloorRC.y, d);\n float topRight = getA(b, sourceFloorRC.x, sourceCeilRC.y, d);\n float bottomRight = getA(b, sourceCeilRC.x, sourceCeilRC.y, d);\n\n vec2 fracRC = sourceFracIndexRC - vec2(sourceFloorRC);\n\n float top = topLeft + (topRight - topLeft) * fracRC.y;\n float bottom = bottomLeft + (bottomRight - bottomLeft) * fracRC.y;\n float newValue = top + (bottom - top) * fracRC.x;\n\n setOutput(newValue);\n }\n "},no=function(t,e,n,r){this.variableNames=["A"],this.usesPackedTextures=!0,this.outputShape=[];var i=t[0],a=t[1],o=t[2],s=t[3];this.outputShape=[i,e,n,s];var u=[r&&e>1?a-1:a,r&&n>1?o-1:o],l=[r&&e>1?e-1:e,r&&n>1?n-1:n];this.userCode="\n const vec3 effectiveInputOverOutputRatioRC = vec3(\n "+u[0]/l[0]+",\n "+u[1]/l[1]+",\n "+u[1]/l[1]+");\n const vec3 inputShapeRC = vec3("+a+".0, "+o+".0,\n "+o+".0);\n\n float getAValue(int b, int r, int c, int d) {\n return getChannel(getA(b, r, c, d), vec2(c, d));\n }\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n // Calculate values for next column in yRC.z.\n ivec3 yRC = coords.yzz + ivec3(0, 0, 1);\n\n // Fractional source index.\n vec3 sourceFracIndexRC = vec3(yRC) * effectiveInputOverOutputRatioRC;\n\n // Compute the four integer indices.\n ivec3 sourceFloorRC = ivec3(sourceFracIndexRC);\n ivec3 sourceCeilRC = ivec3(\n min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));\n \n // Should we calculate next column and row elements in 2x2 packed cell.\n bool hasNextCol = d < "+(s-1)+"; \n bool hasNextRow = coords.z < "+(n-1)+";\n\n // In parallel, construct four corners for all four components in\n // packed 2x2 cell.\n vec4 topLeft = vec4(\n getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d),\n hasNextCol ? getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d + 1)\n : 0.0,\n hasNextRow ? getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d)\n : 0.0,\n (hasNextRow && hasNextCol) ?\n getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d + 1) : 0.0);\n\n vec4 bottomLeft = vec4(\n getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d),\n hasNextCol ? getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d + 1)\n : 0.0,\n hasNextRow ? getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d)\n : 0.0,\n (hasNextRow && hasNextCol) ?\n getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d + 1) : 0.0);\n\n vec4 topRight = vec4(\n getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d),\n hasNextCol ? getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d + 1)\n : 0.0,\n hasNextRow ? getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d)\n : 0.0,\n (hasNextRow && hasNextCol) ?\n getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d + 1) : 0.0);\n\n vec4 bottomRight = vec4(\n getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d),\n hasNextCol ? getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d + 1)\n : 0.0,\n hasNextRow ? getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d)\n : 0.0,\n (hasNextRow && hasNextCol) ?\n getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d + 1) : 0.0);\n\n vec3 fracRC = sourceFracIndexRC - vec3(sourceFloorRC);\n\n vec4 top = mix(topLeft, topRight, fracRC.yyzz);\n vec4 bottom = mix(bottomLeft, bottomRight, fracRC.yyzz);\n vec4 newValue = mix(top, bottom, fracRC.x);\n\n setOutput(newValue);\n }\n "},ro=function(t,e,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=e.shape;var r=e.shape,i=r[1],a=r[2],o=t.shape,s=o[1],u=o[2],l=[n&&s>1?i-1:i,n&&u>1?a-1:a],c=[n&&s>1?s-1:s,n&&u>1?u-1:u],p=l[0]/c[0],h=l[1]/c[1],f=1/p,d=1/h,m=2*Math.ceil(f)+2,g=2*Math.ceil(d)+2;this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n int r = coords[1];\n int c = coords[2];\n\n float accumulator = 0.0;\n\n const float heightScale = float("+p+");\n const float widthScale = float("+h+");\n\n const float invHeightScale = float("+f+");\n const float invWidthScale = float("+d+");\n\n const int winHeight = int("+m+");\n const int winWidth = int("+g+");\n\n // Compute bounds for where in dy we will look\n float startRLerp = floor(float(r) * invHeightScale);\n int startDyR = int(floor(startRLerp - float(winHeight / 2)));\n\n float startCLerp = floor(float(c) * invWidthScale);\n int startDyC = int(floor(startCLerp - float(winWidth / 2)));\n\n // Loop over dy\n for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {\n int dyR = dyROffset + startDyR;\n\n // Guard against the window exceeding the bounds of dy\n if (dyR < 0 || dyR >= "+s+") {\n continue;\n }\n\n for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {\n int dyC = dyCOffset + startDyC;\n\n // Guard against the window exceeding the bounds of dy\n if (dyC < 0 || dyC >= "+u+") {\n continue;\n }\n\n float sourceFracRow =\n float("+l[0]+") *\n (float(dyR) / float("+c[0]+"));\n\n float sourceFracCol =\n float("+l[1]+") *\n (float(dyC) / float("+c[1]+"));\n\n int sourceNearestRow = int(min(\n float(int("+i+") - 1),\n "+n+" ? float(round(sourceFracRow)) :\n float(floor(sourceFracRow))));\n\n int sourceNearestCol = int(min(\n float(int("+a+") - 1),\n "+n+" ? float(round(sourceFracCol)) :\n float(floor(sourceFracCol))));\n\n if (r == sourceNearestRow && c == sourceNearestCol) {\n accumulator += getDy(b, dyR, dyC, d);\n }\n }\n }\n // End loop over dy\n\n setOutput(accumulator);\n }\n "},io=function(t,e,n,r){this.variableNames=["A"],this.outputShape=[];var i=t[0],a=t[1],o=t[2],s=t[3];this.outputShape=[i,e,n,s];var u=[r&&e>1?a-1:a,r&&n>1?o-1:o],l=[r&&e>1?e-1:e,r&&n>1?n-1:n],c=r?"0.5":"0.0";this.userCode="\n const vec2 effectiveInputOverOutputRatioRC = vec2(\n "+u[0]/l[0]+",\n "+u[1]/l[1]+");\n const vec2 inputShapeRC = vec2("+a+".0, "+o+".0);\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n ivec2 yRC = coords.yz;\n\n // Fractional source index.\n vec2 sourceFracIndexRC = vec2(yRC) * effectiveInputOverOutputRatioRC;\n\n // Compute the coordinators of nearest neighbor point.\n ivec2 sourceNearestRC = ivec2(\n min(inputShapeRC - 1.0, floor(sourceFracIndexRC + "+c+")));\n\n float newValue = getA(b, sourceNearestRC.x, sourceNearestRC.y, d);\n\n setOutput(newValue);\n }\n "},ao=function(t,e){this.variableNames=["x"];var n=t.length;if(n>4)throw new Error("WebGL backend: Reverse of rank-"+n+" tensor is not yet supported");if(this.outputShape=t,1!==n){var r=t.map(function(n,r){return function(n){return-1!==e.indexOf(n)&&1!==t[n]?t[n]+" - coords["+n+"] - 1":"coords["+n+"]"}(r)}).join(","),i=Ei(n);this.userCode="\n void main() {\n "+i+" coords = getOutputCoords();\n setOutput(getX("+r+"));\n }\n "}else this.userCode="\n void main() {\n int coord = getOutputCoords();\n setOutput(getX("+t[0]+" - coord - 1));\n }\n "},oo=function(t,e){this.variableNames=["x"],this.usesPackedTextures=!0;var n=t.length;if(n>4)throw new Error("WebGL backend: Reverse of rank-"+n+" tensor is not yet supported");this.outputShape=t;var r=hi("rc",n),i=r[n-1]+" + 1 < "+this.outputShape[n-1],a=r[n-2]+" + 1 < "+this.outputShape[n-2],o=Ei(n);function s(n){var r=t.map(function(r,i){return function(n,r){return-1!==e.indexOf(n)&&1!==t[n]?t[n]+" - "+r[n]+" - 1":""+r[n]}(i,n)});return"getChannel(getX("+r.join(",")+"), vec2("+r.slice(-2).join(",")+"))"}this.userCode=1===n?"\n void main(){\n int rc = getOutputCoords();\n vec4 result = vec4(0.);\n result.r = getChannel(getX("+t[0]+" - rc - 1),\n "+t[0]+" - rc - 1);\n if("+i+"){\n result.g = getChannel(getX("+t[0]+" - (rc + 1) - 1),\n "+t[0]+" - (rc + 1) - 1);\n }\n setOutput(result);\n }\n ":"\n void main() {\n "+o+" rc = getOutputCoords();\n vec4 result = vec4(0.);\n result.r = "+s(r.slice())+";\n if("+i+"){\n result.g = "+function(t){return t[n-1]="("+t[n-1]+" + 1)",s(t)}(r.slice())+";\n }\n if("+a+") {\n result.b = "+function(t){return t[n-2]="("+t[n-2]+" + 1)",s(t)}(r.slice())+";\n if("+i+") {\n result.a = "+function(t){return t[n-1]="("+t[n-1]+" + 1)",t[n-2]="("+t[n-2]+" + 1)",s(t)}(r.slice())+";\n }\n }\n setOutput(result);\n }\n "},so=function(t,e,n,r,i,a,o){void 0===o&&(o=!0),this.variableNames=["updates","indices","defaultValue"],this.outputShape=a;var s=Ei(i.length),u=Ei(a.length),l="";1===n?l="i":2===n&&(l="i, j");var c="getIndices("+l+")",p="";1===r?p="i":2===r&&(p="i, coords[1]");var h="getUpdates("+p+")",f=e>1?"strides[j]":"strides";this.userCode="\n "+s+" strides = "+s+"("+i+");\n\n void main() {\n "+u+" coords = getOutputCoords();\n float sum = 0.0;\n bool found = false;\n for (int i = 0; i < "+t+"; i++) {\n int flattenedIndex = 0;\n for (int j = 0; j < "+e+"; j++) {\n int index = round("+c+");\n flattenedIndex += index * "+f+";\n }\n if (flattenedIndex == coords[0]) {\n sum += "+h+";\n found = true;\n }\n }\n setOutput(mix(getDefaultValue(), sum, float(found)));\n }\n "},uo=function(t,e){this.variableNames=["x","segmentIds"];var n=t.windowSize,r=t.batchSize,i=t.inSize,a=t.numSegments,o=a*Math.ceil(i/n);this.outputShape=[r,o];var s=4*Math.floor(n/4),u=n%4,l="\n sumValue += dot(values, segFilter);\n ",c="";i%n>0&&(c="\n if (inIdx < 0 || inIdx >= "+i+") {\n return initializationValue;\n }\n ");var p="";i%n>0&&(p="\n if (inIdx < 0 || inIdx >= "+i+") {\n return -1.0;\n }\n "),this.userCode="\n const float initializationValue = 0.0;\n\n float getValue(int batch, int inIdx) {\n "+c+"\n return getX(batch, inIdx);\n }\n\n float getSegmentIdAtIndex(int inIdx) {\n "+p+"\n return getSegmentIds(inIdx);\n }\n\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n int outIdx = coords[1];\n int inOffset = int(floor(float(outIdx) / float(\n "+a+")) * float("+n+"));\n int currentSeg = int(mod(float(outIdx), float("+a+")));\n\n float sumValue = 0.0;\n\n for (int i = 0; i < "+s+"; i += 4) {\n int inIdx = inOffset + i;\n vec4 values = vec4(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n getValue(batch, inIdx + 3)\n );\n\n vec4 segFilter = vec4(\n int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 3)) == currentSeg ? 1 : 0\n );\n\n "+l+"\n }\n\n int inIdx = inOffset + "+s+";\n if ("+(1===u)+") {\n vec4 values = vec4(\n getValue(batch, inIdx),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n int inIdxSeg = int(getSegmentIdAtIndex(inIdx));\n\n vec4 segFilter = vec4(\n int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n 0,\n 0,\n 0\n );\n\n "+l+"\n } else if ("+(2===u)+") {\n vec4 values = vec4(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n initializationValue,\n initializationValue\n );\n\n vec4 segFilter = vec4(\n int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,\n 0,\n 0\n );\n\n "+l+"\n } else if ("+(3===u)+") {\n vec4 values = vec4(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n initializationValue\n );\n\n vec4 segFilter = vec4(\n int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,\n 0\n );\n\n "+l+"\n }\n setOutput(sumValue);\n }\n "},lo=function(t,e,n){var r,i;if(this.variableNames=["c","a","b"],this.outputShape=e,n>4)throw Error("Where for rank "+n+" is not yet supported");if(1===n)i="resRC",r="resRC";else{for(var a=["resRC.x","resRC.y","resRC.z","resRC.w"],o=[],s=[],u=0;u= 1.0) {\n setOutput(getA("+i+"));\n } else {\n setOutput(getB("+i+"));\n }\n }\n "},co=function(){function t(t){this.variableNames=["source"],this.outputShape=t,this.rank=t.length;var e,n=Ei(this.rank),r="uniform int start["+this.rank+"];",i=function(t){if(1===t)return"sourceLoc";if(t<=6)return po.slice(0,t).map(function(t){return"sourceLoc."+t}).join(",");throw Error("Slicing for rank "+t+" is not yet supported")}(this.rank);e="\n "+n+" sourceLoc;\n "+n+" coords = getOutputCoords();\n "+t.map(function(t,e){return"sourceLoc."+po[e]+" = start["+e+"] + coords."+po[e]+";"}).join("\n")+"\n ",this.userCode="\n "+r+"\n void main() {\n "+e+"\n setOutput(getSource("+i+"));\n }\n "}return t.prototype.getCustomSetupFunc=function(t){var e=this;if(t.length!==this.rank)throw Error("The rank ("+this.rank+") of the program must match the length of start ("+t.length+")");return function(n,r){null==e.startLoc&&(e.startLoc=n.getUniformLocationNoThrow(r,"start"),null==e.startLoc)||n.gl.uniform1iv(e.startLoc,t)}},t}(),po=["x","y","z","w","u","v"],ho=function(){function t(t){this.variableNames=["source"],this.usesPackedTextures=!0,this.outputShape=t,this.rank=t.length;var e=Ei(this.rank),n=hi("coords",this.rank),r=hi("sourceLoc",this.rank),i=1===this.rank?"sourceLoc":"vec2("+r.slice(-2).join()+")",a="getChannel(getSource("+r.join()+"), "+i+")",o="\n result.x = "+a+";\n if (++"+n[this.rank-1]+" < "+t[this.rank-1]+") {\n ++"+r[this.rank-1]+";\n result.y = "+a+";\n --"+r[this.rank-1]+";\n }\n ",s=1===this.rank?"":"\n --"+n[this.rank-1]+";\n if (++"+n[this.rank-2]+" < "+t[this.rank-2]+") {\n ++"+r[this.rank-2]+";\n result.z = "+a+";\n if (++"+n[this.rank-1]+" < "+t[this.rank-1]+") {\n ++"+r[this.rank-1]+";\n result.w = "+a+";\n }\n }\n ",u=this.rank<=4?"sourceLoc = coords +\n "+e+"("+t.map(function(t,e){return"start["+e+"]"}).join()+");":t.map(function(t,e){return r[e]+" = "+n[e]+" + start["+e+"];"}).join("\n");this.userCode="\n uniform int start["+this.rank+"];\n void main() {\n "+e+" coords = getOutputCoords();\n "+e+" sourceLoc;\n "+u+" \n vec4 result = vec4(0.);\n "+o+"\n "+s+"\n setOutput(result);\n }\n "}return t.prototype.getCustomSetupFunc=function(t){var e=this;if(t.length!==this.rank)throw Error("The rank ("+this.rank+") of the program must match the length of start ("+t.length+")");return function(n,r){null==e.startLoc&&(e.startLoc=n.getUniformLocationNoThrow(r,"start"),null==e.startLoc)||n.gl.uniform1iv(e.startLoc,t)}},t}(),fo=function(t,e,n){this.variableNames=["x"],this.outputShape=n;var r=n.length,i=Ei(n.length),a=Ei(n.length),o="";if(1===r)o="coords * strides + begin";else{var s=0;o=n.map(function(t,e){return s++,1===n.length?"coords * strides["+e+"] + begin["+e+"]":"coords["+(s-1)+"] * strides["+e+"] + begin["+e+"]"}).join(",")}this.userCode="\n "+i+" begin = "+i+"("+t+");\n "+i+" strides = "+i+"("+e+");\n\n void main() {\n "+a+" coords = getOutputCoords();\n setOutput(getX("+o+"));\n }\n "},mo=function(){function t(t){this.gpgpu=t,this.numUsedTextures=0,this.numFreeTextures=0,this.freeTextures={},this.logEnabled=!1,this.usedTextures={}}return t.prototype.acquireTexture=function(t,e,n){var r,i=go(e,n),a=vo(t,i,n);if(a in this.freeTextures||(this.freeTextures[a]=[]),a in this.usedTextures||(this.usedTextures[a]=[]),this.freeTextures[a].length>0){this.numFreeTextures--,this.numUsedTextures++,this.log();var o=this.freeTextures[a].shift();return this.usedTextures[a].push(o),o}return this.numUsedTextures++,this.log(),i===Rt.PACKED_2X2_FLOAT32?r=this.gpgpu.createPackedMatrixTexture(t[0],t[1]):i===Rt.PACKED_2X2_FLOAT16?r=this.gpgpu.createFloat16PackedMatrixTexture(t[0],t[1]):i===Rt.UNPACKED_FLOAT32?r=this.gpgpu.createFloat32MatrixTexture(t[0],t[1]):i===Rt.UNPACKED_FLOAT16?r=this.gpgpu.createFloat16MatrixTexture(t[0],t[1]):i===Rt.PACKED_4X1_UNSIGNED_BYTE&&(r=this.gpgpu.createUnsignedBytesMatrixTexture(t[0],t[1])),this.usedTextures[a].push(r),r},t.prototype.releaseTexture=function(t,e,n,r){if(null!=this.freeTextures){var i=vo(e,go(n,r),r);i in this.freeTextures||(this.freeTextures[i]=[]),this.freeTextures[i].push(t),this.numFreeTextures++,this.numUsedTextures--;var a=this.usedTextures[i],o=a.indexOf(t);if(o<0)throw new Error("Cannot release a texture that was never provided by this texture manager");a.splice(o,1),this.log()}},t.prototype.log=function(){if(this.logEnabled){var t=this.numFreeTextures+this.numUsedTextures;console.log("Free/Used",this.numFreeTextures+" / "+this.numUsedTextures,"("+t+")")}},t.prototype.getNumUsedTextures=function(){return this.numUsedTextures},t.prototype.getNumFreeTextures=function(){return this.numFreeTextures},t.prototype.dispose=function(){var t=this;if(null!=this.freeTextures){for(var e in this.freeTextures)this.freeTextures[e].forEach(function(e){t.gpgpu.deleteMatrixTexture(e)});for(var e in this.usedTextures)this.usedTextures[e].forEach(function(e){t.gpgpu.deleteMatrixTexture(e)});this.freeTextures=null,this.usedTextures=null,this.numUsedTextures=0,this.numFreeTextures=0}},t}();function go(e,n){if(e===At.UPLOAD)return Rt.PACKED_2X2_FLOAT32;if(e===At.RENDER||null==e)return function(e){return t.ENV.getBool("WEBGL_RENDER_FLOAT32_ENABLED")?e?Rt.PACKED_2X2_FLOAT32:Rt.UNPACKED_FLOAT32:e?Rt.PACKED_2X2_FLOAT16:Rt.UNPACKED_FLOAT16}(n);if(e===At.DOWNLOAD||e===At.PIXELS)return Rt.PACKED_4X1_UNSIGNED_BYTE;throw new Error("Unknown logical texture type "+e)}function vo(t,e,n){return t[0]+"_"+t[1]+"_"+e+"_"+n}var yo=function(t,e){this.variableNames=["A"];for(var n=new Array(t.length),r=0;r5)throw Error("Tile for rank "+e+" is not yet supported");if(1===e)return"imod(resRC, "+t[0]+")";for(var n=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u"],r=[],i=0;i6)throw Error("Transpose for rank "+e+" is not yet supported");for(var n=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u","resRC.v"],r=new Array(e),i=0;i6)throw Error("Packed transpose for rank "+this.rank+" is not yet supported.");var i=Ei(this.rank),a=pi("rc",this.rank),o=new Array(this.rank);for(r=0;r0?this.gpgpu.beginQuery():{startMs:q(),endMs:null}},e.prototype.endTimer=function(e){return t.ENV.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?(this.gpgpu.endQuery(),e):(e.endMs=q(),e)},e.prototype.getQueryTime=function(e){return r(this,void 0,void 0,function(){var n;return i(this,function(r){return t.ENV.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?[2,this.gpgpu.waitForQueryAndGetTime(e)]:[2,(n=e).endMs-n.startMs]})})},e.prototype.disposeData=function(t){if(!this.pendingDisposal.has(t))if(this.pendingRead.has(t))this.pendingDisposal.add(t);else if(this.texData.has(t)){this.releaseGPUData(t);var e=this.texData.get(t).complexTensors;null!=e&&(e.real.dispose(),e.imag.dispose()),this.texData.delete(t)}},e.prototype.releaseGPUData=function(t){var e=this.texData.get(t),n=e.texture,r=e.dtype,i=e.texShape,a=e.usage,o=e.isPacked,s=e.slice,u=s&&s.origDataId||t,l=this.dataRefCount.get(u);l>1?this.dataRefCount.set(u,l-1):(this.dataRefCount.delete(u),null!=n&&(this.numBytesInGPU-=this.computeBytes(i,r),this.textureManager.releaseTexture(n,i,a,o)));var c=this.texData.get(t);c.texture=null,c.texShape=null,c.isPacked=!1,c.slice=null},e.prototype.getTexture=function(t){return this.uploadToGPU(t),this.texData.get(t).texture},e.prototype.getDataInfo=function(t){return this.texData.get(t)},e.prototype.getCPUBackend=function(){return t.ENV.getBool("WEBGL_CPU_FORWARD")?(null==this.cpuBackend&&(this.cpuBackend=kt.findBackend("cpu")),this.cpuBackend):null},e.prototype.shouldExecuteOnCPU=function(t,e){var n=this;return void 0===e&&(e=128),null!=this.getCPUBackend()&&t.every(function(t){return null==n.texData.get(t.dataId).texture&&t.sizet.ENV.getNumber("WEBGL_MAX_TEXTURES_IN_SHADER")){var a=Math.floor(e.length/2),o=this.concat(e.slice(0,a),n),s=this.concat(e.slice(a),n);return this.concat([o,s],n)}if(t.ENV.getBool("WEBGL_PACK_ARRAY_OPERATIONS")&&e[0].rank>1){var u=new Gi(e.map(function(t){return t.shape}),n);return this.compileAndRun(u,e)}var l=Je(e.map(function(t){return t.shape}),n),c=e.map(function(t){return t.as2D(-1,v(t.shape.slice(n)))}),p=new ji(c.map(function(t){return t.shape}));return this.compileAndRun(p,c).reshape(l)},e.prototype.neg=function(e){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.neg(e);if(t.ENV.getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,Ro,e.dtype);var n=new Co(e.shape,Ro);return this.compileAndRun(n,[e])},e.prototype.batchMatMul=function(t,e,n,r){var i=n?t.shape[2]:t.shape[1],a=r?e.shape[1]:e.shape[2],o=n?t.shape[1]:t.shape[2],s=t.shape[0];if((1===i||1===a)&&o>1e3){n&&(t=t.transpose([0,2,1])),r&&(e=e.transpose([0,2,1]));var u=1===a?t:t.as3D(s,o,1),l=1===a?2:1,c=1===a?e.as3D(s,1,o):e;return this.multiply(u,c).sum(l,!0)}var p=vt(t.dtype,e.dtype),h=new Ga(t.shape,[s,i,a],n,r),f=this.makePackedTensor(h.outputShape,p);return this.compileAndRun(h,[t,e],f)},e.prototype.fusedBatchMatMul=function(t){var e=t.a,n=t.b,r=t.transposeA,i=t.transposeB,a=t.bias,o=t.activation,s=t.preluActivationWeights,u=r?e.shape[2]:e.shape[1],l=i?n.shape[1]:n.shape[2],c=e.shape[0],p=vt(e.dtype,n.dtype),h=null!=a,f=null!=s,d=o?Wo(o,!0):null,m=new Ga(e.shape,[c,u,l],r,i,h,d,f),g=this.makePackedTensor(m.outputShape,p),v=[e,n];return a&&v.push(a),s&&v.push(s),this.compileAndRun(m,v,g)},e.prototype.multiply=function(e,n){if("complex64"===e.dtype){var r=this.texData.get(e.dataId),i=this.texData.get(n.dataId),a=new Oi("return areal * breal - aimag * bimag;",e.shape,n.shape),o=new Oi("return areal * bimag + aimag * breal;",e.shape,n.shape),s=[this.makeComplexComponentTensorHandle(e,r.complexTensors.real),this.makeComplexComponentTensorHandle(e,r.complexTensors.imag),this.makeComplexComponentTensorHandle(n,i.complexTensors.real),this.makeComplexComponentTensorHandle(n,i.complexTensors.imag)],u=this.compileAndRun(a,s),l=this.compileAndRun(o,s),c=this.complex(u,l);return u.dispose(),l.dispose(),c}if(this.shouldExecuteOnCPU([e,n]))return this.cpuBackend.multiply(e,n);if(t.ENV.getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,n,Mi,e.dtype);var p=new Li(Mi,e.shape,n.shape),h=this.makeOutputArray(p.outputShape,e.dtype);return this.compileAndRun(p,[e,n],h)},e.prototype.batchNormalization=function(e,n,r,i,a,o){var s=[e,n,r],u=null;null!=o&&(u=o.shape,s.push(o));var l=null;if(null!=a&&(l=a.shape,s.push(a)),t.ENV.getBool("WEBGL_PACK_NORMALIZATION")){var c=new Di(e.shape,n.shape,r.shape,u,l,i);return this.compileAndRun(c,s)}var p=new Ti(e.shape,n.shape,r.shape,u,l,i);return this.compileAndRun(p,s)},e.prototype.localResponseNormalization4D=function(e,n,r,i,a){var o=t.ENV.getBool("WEBGL_PACK_NORMALIZATION")?new Wa(e.shape,n,r,i,a):new Ba(e.shape,n,r,i,a);return this.compileAndRun(o,[e])},e.prototype.LRNGrad=function(t,e,n,r,i,a,o){var s=new Va(e.shape,r,i,a,o);return this.compileAndRun(s,[e,n,t])},e.prototype.tile=function(t,e){if("string"===t.dtype){var n=this.readSync(t.dataId).map(function(t){return X(t)});return ai(Ln(t.shape,t.dtype,n),e)}var r=new yo(t.shape,e);return this.compileAndRun(r,[t])},e.prototype.pad=function(e,n,r){var i=t.ENV.getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new Xa(e.shape,n,r):new $a(e.shape,n,r);return this.compileAndRun(i,[e])},e.prototype.transpose=function(e,n){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.transpose(e,n);var r=t.ENV.getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new xo(e.shape,n):new bo(e.shape,n);return this.compileAndRun(r,[e])},e.prototype.gather=function(t,e,n){if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.gather(t,e,n);var r=new ga(t.shape,e.size,n);return this.compileAndRun(r,[t,e])},e.prototype.batchToSpaceND=function(t,e,n){f(t.rank<=4,function(){return"batchToSpaceND for rank > 4 with a WebGL backend not implemented yet"});var r=e.reduce(function(t,e){return t*e}),i=pr(t.shape,e,r),a=hr(i.length,e.length),o=fr(t.shape,e,r),s=dr(n,e.length),u=mr(o,n,e.length);return t.reshape(i).transpose(a).reshape(o).slice(s,u)},e.prototype.spaceToBatchND=function(t,e,n){f(t.rank<=4,function(){return"spaceToBatchND for rank > 4 with a WebGL backend not implemented yet"});var r=e.reduce(function(t,e){return t*e}),i=[[0,0]];i.push.apply(i,n);for(var a=1+e.length;ae||n===t?r=!0:n=V(t,n+1);return n}(o,i),u=new uo({windowSize:s,inSize:o,batchSize:a,numSegments:i},e),l=u.outputShape,c=l[0],p=l[1],h=this.makeOutputArray([c,p],r);return this.compileAndRun(u,[t,n],h),h.shape[1]===i?h:(n=gn(0,i).tile([o/s]),this.segOpCompute(h,e,n,r,i))},e.prototype.argMinMaxReduce=function(e,n,r){var i=[n];if(qe("arg"+r.charAt(0).toUpperCase()+r.slice(1),i,e.rank),!t.ENV.getBool("WEBGL_PACK_REDUCE")||e.rank<=2){var a=Ge(e.shape,i),o=a[0],s=v(a[1]),u=e.as2D(-1,s);return this.argReduce(u,r).reshape(o)}return this.argReducePacked(e,r)},e.prototype.argMin=function(t,e){return this.argMinMaxReduce(t,e,"min")},e.prototype.argMax=function(t,e){return this.argMinMaxReduce(t,e,"max")},e.prototype.cumsum=function(t,e,n,r){if(e!==t.rank-1)throw new Error("WebGL cumsum shader expects an inner-most axis="+(t.rank-1)+" but got axis="+e);var i=new na(t.shape,n,r);return this.compileAndRun(i,[t])},e.prototype.equal=function(e,n){if(t.ENV.getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,n,"\n return vec4(equal(a, b));\n","bool");var r=new Li("return float(a == b);",e.shape,n.shape),i=this.makeOutputArray(r.outputShape,"bool");return this.compileAndRun(r,[e,n],i)},e.prototype.notEqual=function(e,n){if(t.ENV.getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,n,"\n return vec4(notEqual(a, b));\n","bool");var r=new Li("return float(a != b);",e.shape,n.shape),i=this.makeOutputArray(r.outputShape,"bool");return this.compileAndRun(r,[e,n],i)},e.prototype.less=function(e,n){if(this.shouldExecuteOnCPU([e,n]))return this.cpuBackend.less(e,n);if(t.ENV.getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,n,"\n return vec4(lessThan(a, b));\n","bool");var r=new Li("return float(a < b);",e.shape,n.shape),i=this.makeOutputArray(r.outputShape,"bool");return this.compileAndRun(r,[e,n],i)},e.prototype.lessEqual=function(e,n){if(t.ENV.getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,n,"\n return vec4(lessThanEqual(a, b));\n","bool");var r=new Li("return float(a <= b);",e.shape,n.shape),i=this.makeOutputArray(r.outputShape,"bool");return this.compileAndRun(r,[e,n],i)},e.prototype.greater=function(e,n){if(this.shouldExecuteOnCPU([e,n]))return this.cpuBackend.greater(e,n);if(t.ENV.getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,n,"\n return vec4(greaterThan(a, b));\n","bool");var r=new Li("return float(a > b);",e.shape,n.shape),i=this.makeOutputArray(r.outputShape,"bool");return this.compileAndRun(r,[e,n],i)},e.prototype.greaterEqual=function(e,n){if(t.ENV.getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,n,"\n return vec4(greaterThanEqual(a, b));\n","bool");var r=new Li("return float(a >= b);",e.shape,n.shape),i=this.makeOutputArray(r.outputShape,"bool");return this.compileAndRun(r,[e,n],i)},e.prototype.logicalNot=function(t){var e=new Co(t.shape,"return float(!(x >= 1.0));");return this.compileAndRun(e,[t])},e.prototype.logicalAnd=function(e,n){if(t.ENV.getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,n,"\n return vec4(\n vec4(greaterThanEqual(a, vec4(1.0))) *\n vec4(greaterThanEqual(b, vec4(1.0))));\n","bool");var r=new Li("return float(a >= 1.0 && b >= 1.0);",e.shape,n.shape),i=this.makeOutputArray(r.outputShape,"bool");return this.compileAndRun(r,[e,n],i)},e.prototype.logicalOr=function(e,n){if(t.ENV.getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,n,"\n return min(\n vec4(greaterThanEqual(a, vec4(1.0))) +\n vec4(greaterThanEqual(b, vec4(1.0))),\n vec4(1.0));\n","bool");var r=new Li("return float(a >= 1.0 || b >= 1.0);",e.shape,n.shape),i=this.makeOutputArray(r.outputShape,"bool");return this.compileAndRun(r,[e,n],i)},e.prototype.select=function(t,e,n){var r=new lo(t.rank,e.shape,e.rank),i=this.makeOutputArray(r.outputShape,vt(e.dtype,n.dtype));return this.compileAndRun(r,[t,e,n],i)},e.prototype.where=function(t){Le("tf.where() in webgl locks the UI thread. Call tf.whereAsync() instead");var e=t.dataSync();return si(t.shape,e)},e.prototype.topk=function(t,e,n){return oi(t.dataSync(),t.shape,t.dtype,e)},e.prototype.min=function(t,e){qe("min",e,t.rank);var n=Ge(t.shape,e),r=n[0],i=v(n[1]),a=t.as2D(-1,i);return this.reduce(a,"min",a.dtype).reshape(r)},e.prototype.minimum=function(e,n){if(this.shouldExecuteOnCPU([e,n]))return this.cpuBackend.minimum(e,n);var r=t.ENV.getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Bi("\n vec4 result = vec4(min(a, b));\n vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));\n \n result.r = isNaN.r > 0. ? NAN : result.r;\n result.g = isNaN.g > 0. ? NAN : result.g;\n result.b = isNaN.b > 0. ? NAN : result.b;\n result.a = isNaN.a > 0. ? NAN : result.a;\n\n return result;\n",e.shape,n.shape):new Li("\n if (isnan(a)) return a;\n if (isnan(b)) return b;\n\n return min(a, b);\n",e.shape,n.shape);return this.compileAndRun(r,[e,n])},e.prototype.mod=function(e,n){var r=t.ENV.getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Bi("\n vec4 result = mod(a, b);\n vec4 isNaN = vec4(equal(b, vec4(0.0)));\n \n result.r = isNaN.r > 0. ? NAN : result.r;\n result.g = isNaN.g > 0. ? NAN : result.g;\n result.b = isNaN.b > 0. ? NAN : result.b;\n result.a = isNaN.a > 0. ? NAN : result.a;\n\n return result;\n",e.shape,n.shape):new Li("if (b == 0.0) return NAN;\n return mod(a, b);",e.shape,n.shape);return this.compileAndRun(r,[e,n])},e.prototype.max=function(t,e){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.max(t,e);qe("max",e,t.rank);var n=Ge(t.shape,e),r=n[0],i=v(n[1]),a=t.as2D(-1,i);return this.reduce(a,"max",a.dtype).reshape(r)},e.prototype.maximum=function(e,n){if(this.shouldExecuteOnCPU([e,n]))return this.cpuBackend.maximum(e,n);var r=t.ENV.getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Bi("\n vec4 result = vec4(max(a, b));\n vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));\n \n result.r = isNaN.r > 0. ? NAN : result.r;\n result.g = isNaN.g > 0. ? NAN : result.g;\n result.b = isNaN.b > 0. ? NAN : result.b;\n result.a = isNaN.a > 0. ? NAN : result.a;\n\n return result;\n",e.shape,n.shape):new Li("\n if (isnan(a)) return a;\n if (isnan(b)) return b;\n\n return max(a, b);\n",e.shape,n.shape);return this.compileAndRun(r,[e,n])},e.prototype.all=function(t,e){qe("all",e,t.rank);var n=Ge(t.shape,e),r=n[0],i=v(n[1]),a=t.as2D(-1,i);return this.reduce(a,"all",a.dtype).reshape(r)},e.prototype.any=function(t,e){qe("any",e,t.rank);var n=Ge(t.shape,e),r=n[0],i=v(n[1]),a=t.as2D(-1,i);return this.reduce(a,"any",a.dtype).reshape(r)},e.prototype.squaredDifference=function(e,n){var r=t.ENV.getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Bi("return (a - b) * (a - b);",e.shape,n.shape):new Li("return (a - b) * (a - b);",e.shape,n.shape);return this.compileAndRun(r,[e,n])},e.prototype.realDivide=function(e,n){if(t.ENV.getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,n,"\n // vec4 one = vec4(equal(a, b));\n // return one + (vec4(1.0) - one) * a / b;\n vec4 result = a / b;\n if(b.x == 0.0) {\n result.x = NAN;\n } else if(a.x == b.x) {\n result.x = 1.;\n }\n if(b.y == 0.0) {\n result.y = NAN;\n } else if(a.y == b.y) {\n result.y = 1.;\n }\n if(b.z == 0.0) {\n result.z = NAN;\n } else if(a.z == b.z) {\n result.z = 1.;\n }\n if(b.w == 0.0) {\n result.w = NAN;\n } else if(a.w == b.w) {\n result.w = 1.;\n }\n\n return result;\n","float32",!0);var r=new Li("\nif (b == 0.0) {\n return NAN;\n}\nif (a == b) {\n return 1.0;\n};\nreturn a / b;",e.shape,n.shape),i=this.makeOutputArray(r.outputShape,"float32");return this.compileAndRun(r,[e,n],i)},e.prototype.floorDiv=function(e,n){if(t.ENV.getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,n,"\n ivec4 ia = round(a);\n ivec4 ib = round(b);\n bvec4 cond = notEqual(ib, ivec4(0));\n ivec4 result = ivec4(0);\n vec4 s = sign(a) * sign(b);\n\n // Windows (D3D) wants guaranteed non-zero int division at compile-time.\n if (cond[0]) {\n result[0] = idiv(ia[0], ib[0], s[0]);\n }\n if (cond[1]) {\n result[1] = idiv(ia[1], ib[1], s[1]);\n }\n if (cond[2]) {\n result[2] = idiv(ia[2], ib[2], s[2]);\n }\n if (cond[3]) {\n result[3] = idiv(ia[3], ib[3], s[3]);\n }\n return vec4(result);\n","int32");var r=new Li("\n float s = sign(a) * sign(b);\n int ia = round(a);\n int ib = round(b);\n if (ib != 0) {\n // Windows (D3D) wants guaranteed non-zero int division at compile-time.\n return float(idiv(ia, ib, s));\n } else {\n return NAN;\n }\n",e.shape,n.shape),i=this.makeOutputArray(r.outputShape,"int32");return this.compileAndRun(r,[e,n],i)},e.prototype.add=function(e,n){if("complex64"===e.dtype&&"complex64"===n.dtype)return this.complexSeparableBinaryOp(e,n,_i);if(this.shouldExecuteOnCPU([e,n]))return this.cpuBackend.add(e,n);var r=vt(e.dtype,n.dtype);if(t.ENV.getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,n,_i,r);var i=new Li(_i,e.shape,n.shape),a=this.makeOutputArray(i.outputShape,r);return this.compileAndRun(i,[e,n],a)},e.prototype.packedUnaryOp=function(t,e,n){var r=new Po(t.shape,e),i=this.makePackedTensor(r.outputShape,n);return this.compileAndRun(r,[t],i)},e.prototype.packedBinaryOp=function(t,e,n,r,i){void 0===i&&(i=!1);var a=new Bi(n,t.shape,e.shape,i),o=this.makePackedTensor(a.outputShape,r);return this.compileAndRun(a,[t,e],o)},e.prototype.complexSeparableBinaryOp=function(t,e,n){var r=this,i=this.texData.get(t.dataId),a=this.texData.get(e.dataId),o=[[i.complexTensors.real,a.complexTensors.real],[i.complexTensors.imag,a.complexTensors.imag]].map(function(i){var a=i[0],o=i[1],s=r.makeComplexComponentTensorHandle(t,a),u=r.makeComplexComponentTensorHandle(e,o),l=new Li(n,t.shape,e.shape),c=r.makeOutputArray(l.outputShape,vt(a.dtype,o.dtype));return r.compileAndRun(l,[s,u],c)}),s=o[0],u=o[1],l=this.complex(s,u);return s.dispose(),u.dispose(),l},e.prototype.makeComplexComponentTensorHandle=function(t,e){return{dataId:e.dataId,dtype:e.dtype,shape:t.shape}},e.prototype.addN=function(e){if(1===e.length)return e[0];if(e.length>t.ENV.get("WEBGL_MAX_TEXTURES_IN_SHADER")){var n=Math.floor(e.length/2),r=this.addN(e.slice(0,n)),i=this.addN(e.slice(n));return this.addN([r,i])}var a=e.map(function(t){return t.dtype}).reduce(function(t,e){return vt(t,e)}),o=e.map(function(t){return t.shape}),s=t.ENV.getBool("WEBGL_PACK"),u=s?new li(e[0].shape,o):new ui(e[0].shape,o),l=s?this.makePackedTensor(u.outputShape,a):this.makeOutputArray(u.outputShape,a);return this.compileAndRun(u,e,l)},e.prototype.subtract=function(e,n){if("complex64"===e.dtype&&"complex64"===n.dtype)return this.complexSeparableBinaryOp(e,n,Fi);if(this.shouldExecuteOnCPU([e,n]))return this.cpuBackend.subtract(e,n);var r=vt(e.dtype,n.dtype);if(t.ENV.getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,n,Fi,e.dtype);var i=new Li(Fi,e.shape,n.shape),a=this.makeOutputArray(i.outputShape,r);return this.compileAndRun(i,[e,n],a)},e.prototype.pow=function(e,n){var r=t.ENV.getBool("WEBGL_PACK_BINARY_OPERATIONS"),i=r?new Bi("\n // isModRound1 has 1 for components with round(mod(b, 2.0)) == 1, 0 otherwise.\n vec4 isModRound1 = vec4(equal(round(mod(b, 2.0)), ivec4(1)));\n vec4 multiplier = sign(a) * isModRound1 + (vec4(1.0) - isModRound1);\n vec4 result = multiplier * pow(abs(a), b);\n\n // Ensure that a^0 = 1, including 0^0 = 1 as this correspond to TF and JS\n bvec4 isExpZero = equal(b, vec4(0.0));\n result.r = isExpZero.r ? 1.0 : result.r;\n result.g = isExpZero.g ? 1.0 : result.g;\n result.b = isExpZero.b ? 1.0 : result.b;\n result.a = isExpZero.a ? 1.0 : result.a;\n\n vec4 isNaN = vec4(lessThan(a, vec4(0.0))) * vec4(lessThan(floor(b), b));\n \n result.r = isNaN.r > 0. ? NAN : result.r;\n result.g = isNaN.g > 0. ? NAN : result.g;\n result.b = isNaN.b > 0. ? NAN : result.b;\n result.a = isNaN.a > 0. ? NAN : result.a;\n\n return result;\n",e.shape,n.shape):new Li("\nif(a < 0.0 && floor(b) < b){\n return NAN;\n}\nif (b == 0.0) {\n return 1.0;\n}\nreturn (round(mod(b, 2.0)) != 1) ?\n pow(abs(a), b) : sign(a) * pow(abs(a), b);\n",e.shape,n.shape),a=vt(e.dtype,n.dtype),o=r?this.makePackedTensor(i.outputShape,a):this.makeOutputArray(i.outputShape,a);return this.compileAndRun(i,[e,n],o)},e.prototype.ceil=function(e){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.ceil(e);if(t.ENV.getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,To,e.dtype);var n=new Co(e.shape,To);return this.compileAndRun(n,[e])},e.prototype.floor=function(e){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.floor(e);if(t.ENV.getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,Do,e.dtype);var n=new Co(e.shape,Do);return this.compileAndRun(n,[e])},e.prototype.sign=function(t){var e=new Co(t.shape,"\n if (isnan(x)) { return 0.0; }\n return sign(x);\n");return this.compileAndRun(e,[t])},e.prototype.isNaN=function(t){var e=new Co(t.shape,"return float(isnan(x));"),n=this.makeOutputArray(e.outputShape,"bool");return this.compileAndRun(e,[t],n)},e.prototype.isInf=function(t){var e=new Co(t.shape,"return float(isinf(x));"),n=this.makeOutputArray(e.outputShape,"bool");return this.compileAndRun(e,[t],n)},e.prototype.isFinite=function(t){var e=new Co(t.shape,"return float(!isnan(x) && !isinf(x));"),n=this.makeOutputArray(e.outputShape,"bool");return this.compileAndRun(e,[t],n)},e.prototype.round=function(t){var e=new Co(t.shape,"\n // OpenGL ES does not support round function.\n // The algorithm is based on banker's rounding.\n float base = floor(x);\n if ((x - base) < 0.5) {\n return floor(x);\n } else if ((x - base) > 0.5) {\n return ceil(x);\n } else {\n if (mod(base, 2.0) == 0.0) {\n return base;\n } else {\n return base + 1.0;\n }\n }\n");return this.compileAndRun(e,[t])},e.prototype.exp=function(e){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.exp(e);if(t.ENV.getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,Oo,e.dtype);var n=new Co(e.shape,Oo);return this.compileAndRun(n,[e])},e.prototype.expm1=function(e){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.expm1(e);if(t.ENV.getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,_o,e.dtype);var n=new Co(e.shape,_o);return this.compileAndRun(n,[e])},e.prototype.log=function(e){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.log(e);if(t.ENV.getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,"\n vec4 result = log(x);\n vec4 isNaN = vec4(lessThan(x, vec4(0.0)));\n result.r = isNaN.r == 1.0 ? NAN : result.r;\n result.g = isNaN.g == 1.0 ? NAN : result.g;\n result.b = isNaN.b == 1.0 ? NAN : result.b;\n result.a = isNaN.a == 1.0 ? NAN : result.a;\n\n return result;\n",e.dtype);var n=new Co(e.shape,"if (x < 0.0) return NAN;\n return log(x);");return this.compileAndRun(n,[e])},e.prototype.log1p=function(t){var e=new Co(t.shape,"return log(1.0 + x);");return this.compileAndRun(e,[t])},e.prototype.sqrt=function(t){var e=new Co(t.shape,"return sqrt(x);");return this.compileAndRun(e,[t])},e.prototype.rsqrt=function(t){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.rsqrt(t);var e=new Co(t.shape,"return inversesqrt(x);");return this.compileAndRun(e,[t])},e.prototype.square=function(t){var e=new Co(t.shape,"return x * x;");return this.compileAndRun(e,[t])},e.prototype.reciprocal=function(t){var e=new Co(t.shape,"return 1.0 / x;");return this.compileAndRun(e,[t])},e.prototype.relu=function(e){var n;return n=t.ENV.getBool("WEBGL_PACK")?new Po(e.shape,zo):new Co(e.shape,Io),this.compileAndRun(n,[e])},e.prototype.prelu=function(e,n){var r=t.ENV.getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Bi(Pi,e.shape,n.shape):new Li(zi,e.shape,n.shape);return this.compileAndRun(r,[e,n])},e.prototype.elu=function(e){if(t.ENV.getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,Lo,e.dtype);var n=new Co(e.shape,Ao);return this.compileAndRun(n,[e])},e.prototype.eluDer=function(e,n){var r=t.ENV.getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Bi("\n vec4 bGTEZero = vec4(greaterThanEqual(b, vec4(0.)));\n return (bGTEZero * a) + ((vec4(1.0) - bGTEZero) * (a * (b + vec4(1.0))));\n",e.shape,n.shape):new Li("return (b >= 1.0) ? a : a * (b + 1.0);",e.shape,n.shape);return this.compileAndRun(r,[e,n])},e.prototype.selu=function(t){var e=new Co(t.shape,"\n // Stable and Attracting Fixed Point (0, 1) for Normalized Weights.\n // see: https://arxiv.org/abs/1706.02515\n float scaleAlpha = 1.7580993408473768;\n float scale = 1.0507009873554805;\n return (x >= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0);\n");return this.compileAndRun(e,[t])},e.prototype.int=function(t){var e=new Co(t.shape,"return float(int(x));"),n=this.makeOutputArray(e.outputShape,"int32");return this.compileAndRun(e,[t],n)},e.prototype.clip=function(e,n,r){var i,a=(i=t.ENV.getBool("WEBGL_PACK_CLIP")?new Wi(e.shape):new Vi(e.shape)).getCustomSetupFunc(n,r);return this.compileAndRun(i,[e],null,a)},e.prototype.abs=function(e){if(this.shouldExecuteOnCPU([e]))return this.cpuBackend.abs(e);if(t.ENV.getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,ko,e.dtype);var n=new Co(e.shape,ko);return this.compileAndRun(n,[e])},e.prototype.complexAbs=function(t){var e=this.texData.get(t.dataId),n=new Ui(t.shape),r=[this.makeComplexComponentTensorHandle(t,e.complexTensors.real),this.makeComplexComponentTensorHandle(t,e.complexTensors.imag)];return this.compileAndRun(n,r)},e.prototype.sigmoid=function(t){var e=new Co(t.shape,"return 1.0 / (1.0 + exp(-1.0 * x));");return this.compileAndRun(e,[t])},e.prototype.softplus=function(t){var e=new Co(t.shape,"\n float epsilon = 1.1920928955078125e-7;\n float threshold = log(epsilon) + 2.0;\n\n bool too_large = x > -threshold;\n bool too_small = x < threshold;\n\n float result;\n float exp_x = exp(x);\n\n if (too_large){\n result = x;\n }\n else if (too_small){\n result = exp_x;\n }\n else{\n result = log(exp_x + 1.0);\n }\n return result;\n");return this.compileAndRun(e,[t])},e.prototype.sin=function(t){var e=new Co(t.shape,"if (isnan(x)) return x;\n return sin(x);\n");return this.compileAndRun(e,[t])},e.prototype.cos=function(t){var e=new Co(t.shape,"if (isnan(x)) return x;\n return cos(x);\n");return this.compileAndRun(e,[t])},e.prototype.tan=function(t){var e=new Co(t.shape,"return tan(x);");return this.compileAndRun(e,[t])},e.prototype.asin=function(t){var e=new Co(t.shape,"return asin(x);");return this.compileAndRun(e,[t])},e.prototype.acos=function(t){var e=new Co(t.shape,"return acos(x);");return this.compileAndRun(e,[t])},e.prototype.atan=function(t){var e=new Co(t.shape,"if (isnan(x)) return x;\n return atan(x);\n");return this.compileAndRun(e,[t])},e.prototype.atan2=function(e,n){var r=t.ENV.getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Bi("\n vec4 result = atan(a, b);\n vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));\n \n result.r = isNaN.r > 0. ? NAN : result.r;\n result.g = isNaN.g > 0. ? NAN : result.g;\n result.b = isNaN.b > 0. ? NAN : result.b;\n result.a = isNaN.a > 0. ? NAN : result.a;\n\n return result;\n",e.shape,n.shape):new Li("\n if (isnan(a)) return a;\n if (isnan(b)) return b;\n\n return atan(a, b);\n",e.shape,n.shape);return this.compileAndRun(r,[e,n])},e.prototype.sinh=function(t){var e=new Co(t.shape,"\n float e2x = exp(x);\n return (e2x - 1.0 / e2x) / 2.0;\n");return this.compileAndRun(e,[t])},e.prototype.cosh=function(t){var e=new Co(t.shape,"\n float e2x = exp(-x);\n return (e2x + 1.0 / e2x) / 2.0;\n");return this.compileAndRun(e,[t])},e.prototype.tanh=function(t){var e=new Co(t.shape,"\n float e2x = exp(-2.0 * abs(x));\n return sign(x) * (1.0 - e2x) / (1.0 + e2x);\n");return this.compileAndRun(e,[t])},e.prototype.asinh=function(t){var e=new Co(t.shape,"return log(x + sqrt(x * x + 1.0));");return this.compileAndRun(e,[t])},e.prototype.acosh=function(t){var e=new Co(t.shape,"if (isnan(x)) return x;\n if (x < 1.0) return NAN;\n return log(x + sqrt(x * x - 1.0));");return this.compileAndRun(e,[t])},e.prototype.atanh=function(t){var e=new Co(t.shape,"if (isnan(x)) return x;\n if ((x < -1.0) || (x > 1.0)) return NAN;\n return (log(1.0 + x) - log(1.0 - x)) / 2.0;");return this.compileAndRun(e,[t])},e.prototype.erf=function(t){var e=new Co(t.shape,'\n // Error function is calculated approximately with elementary function.\n // See "Handbook of Mathematical Functions with Formulas,\n // Graphs, and Mathematical Tables", Abramowitz and Stegun.\n float p = 0.3275911;\n float a1 = 0.254829592;\n float a2 = -0.284496736;\n float a3 = 1.421413741;\n float a4 = -1.453152027;\n float a5 = 1.061405429;\n\n float t = 1.0 / (1.0 + p * x);\n return 1.0 - (((((a5*t + a4)*t) + a3)*t + a2)*t + a1)*t*exp(-x*x);\n');return this.compileAndRun(e,[t])},e.prototype.step=function(t,e){var n=new Co(t.shape,function(t){return void 0===t&&(t=0),Eo+"\n return x > 0.0 ? 1.0 : float("+t+");\n "}(e));return this.compileAndRun(n,[t])},e.prototype.conv2dByMatMul=function(e,n,r,i,a,o){var s=e.shape,u=this.texData.get(e.dataId),l=r.inChannels,c=s[0]*s[1]*s[2],p=r.outChannels,h="channelsLast"===r.dataFormat,d=(1===c||1===p)&&l>1e3,m=s[2]%2!=0&&!!u.isPacked;if(d||!t.ENV.getBool("WEBGL_LAZILY_UNPACK")||!t.ENV.getBool("WEBGL_PACK_BINARY_OPERATIONS")||!m){var g=h?s[0]*s[1]*s[2]:s[0]*s[2]*s[3],v=this.reshape(e,[1,g,r.inChannels]),y=this.reshape(n,[1,r.inChannels,r.outChannels]);return this.reshape(this.fusedBatchMatMul({a:v,b:y,transposeA:!1,transposeB:!1,bias:i,activation:a,preluActivationWeights:o}),r.outShape)}var b=h?s[0]*s[1]*(s[2]+1):s[0]*s[2]*(s[3]+1),x=lt.make([1,b,r.inChannels],{dataId:e.dataId},e.dtype,this),w=u.shape;u.shape=u.shape.slice(),u.shape[u.shape.length-2]++,f(xe(u.shape,x.shape),function(){return"packed reshape "+u.shape+" to "+x.shape+" isn't free"});var N=this.reshape(n,[1,r.inChannels,r.outChannels]),C=this.fusedBatchMatMul({a:x,b:N,transposeA:!1,transposeB:!1,bias:i,activation:a,preluActivationWeights:o}),E=this.texData.get(C.dataId);return f(E.isPacked,function(){return"batchMatMul result is expected to be packed"}),u.shape=w,E.shape=r.outShape,lt.make(r.outShape,{dataId:C.dataId},C.dtype,this)},e.prototype.conv2dWithIm2Row=function(t,e,n,r,i,a){var o=n.filterWidth,s=n.filterHeight,u=n.inChannels,l=n.outWidth,c=n.outHeight,p="channelsLast"===n.dataFormat,h=o*s*u,f=c*l,d=[h,f],m=t.squeeze([0]),g=e.reshape([1,h,-1]),v=new Pa(d,m.shape,n),y=this.compileAndRun(v,[m]).reshape([1,d[0],d[1]]),b=null!=r,x=null!=a,w=i?Wo(i,!0):null,N=new Ga(y.shape,[1,f,n.outChannels],!0,!1,b,w,x),C=[y,g];r&&C.push(r),x&&C.push(a);var E=this.compileAndRun(N,C);return p?E.reshape([1,c,l,n.outChannels]):E.reshape([1,n.outChannels,c,l])},e.prototype.fusedConv2d=function(e,n,r,i,a,o){if(1===r.filterHeight&&1===r.filterWidth&&1===r.dilationHeight&&1===r.dilationWidth&&1===r.strideHeight&&1===r.strideWidth&&("SAME"===r.padInfo.type||"VALID"===r.padInfo.type))return this.conv2dByMatMul(e,n,r,i,a,o);if(t.ENV.getBool("WEBGL_CONV_IM2COL")&&1===e.shape[0])return this.conv2dWithIm2Row(e,n,r,i,a,o);var s=null!=i,u=null!=o,l=a?Wo(a,!1):null,c=new Ji(r,s,l,u),p=[e,n];return i&&p.push(i),o&&p.push(o),this.compileAndRun(c,p)},e.prototype.conv2d=function(e,n,r){if(1===r.filterHeight&&1===r.filterWidth&&1===r.dilationHeight&&1===r.dilationWidth&&1===r.strideHeight&&1===r.strideWidth&&("SAME"===r.padInfo.type||"VALID"===r.padInfo.type))return this.conv2dByMatMul(e,n,r);if(t.ENV.getBool("WEBGL_CONV_IM2COL")&&1===e.shape[0])return this.conv2dWithIm2Row(e,n,r);var i=new Ji(r);return this.compileAndRun(i,[e,n])},e.prototype.conv2dDerInput=function(t,e,n){var r=new qi(n);return this.compileAndRun(r,[t,e])},e.prototype.conv2dDerFilter=function(t,e,n){var r=new Hi(n);return this.compileAndRun(r,[t,e])},e.prototype.depthwiseConv2D=function(e,n,r){var i;return t.ENV.getBool("WEBGL_PACK_DEPTHWISECONV")&&r.strideWidth<=2&&r.outChannels/r.inChannels==1?(i=new ta(r),this.compileAndRun(i,[e,n],this.makePackedTensor(r.outShape,e.dtype))):(i=new Qi(r),this.compileAndRun(i,[e,n]))},e.prototype.depthwiseConv2DDerInput=function(t,e,n){var r=new Yi(n);return this.compileAndRun(r,[t,e])},e.prototype.depthwiseConv2DDerFilter=function(t,e,n){var r=new Xi(n);return this.compileAndRun(r,[t,e])},e.prototype.conv3d=function(t,e,n){var r=new Zi(n);return this.compileAndRun(r,[t,e])},e.prototype.conv3dDerInput=function(t,e,n){var r=new $i(n);return this.compileAndRun(r,[t,e])},e.prototype.conv3dDerFilter=function(t,e,n){var r=new Ki(n);return this.compileAndRun(r,[t,e])},e.prototype.maxPool=function(t,e){var n=new Ya(e,"max",!1),r=this.makeOutputArray(n.outputShape,t.dtype);return this.compileAndRun(n,[t],r)},e.prototype.avgPool=function(t,e){var n=new Ya(e,"avg",!1),r=this.makeOutputArray(n.outputShape,"float32");return this.compileAndRun(n,[t],r)},e.prototype.maxPoolBackprop=function(t,e,n,r){var i=new Ya(r,"max",!0),a=this.compileAndRun(i,[e]),o=new Ua(r),s=this.makeOutputArray(o.outputShape,e.dtype),u=this.compileAndRun(o,[t,a],s);return a.dispose(),u},e.prototype.avgPoolBackprop=function(t,e,n){var r=new Ai(n),i=this.makeOutputArray(r.outputShape,e.dtype);return this.compileAndRun(r,[t],i)},e.prototype.cast=function(t,e){return $r(t,e,this)},e.prototype.unstack=function(t,e){for(var n=t.shape[e],r=new Array(t.rank-1),i=0,a=0;a1,function(){return"blockSize should be > 1 for depthToSpace, but was: "+e});var r=t.shape[0],i="NHWC"===n?t.shape[1]:t.shape[2],a="NHWC"===n?t.shape[2]:t.shape[3],o="NHWC"===n?t.shape[3]:t.shape[1],s=i*e,u=a*e,l=o/(e*e),c=new oa("NHWC"===n?[r,s,u,l]:[r,l,s,u],e,n);return this.compileAndRun(c,[t])},e.prototype.split=function(t,e,n){return ii(t,e,n)},e.prototype.scatterND=function(t,e,n){var r=br(0,t,n),i=r.sliceRank,a=r.numUpdates,o=r.sliceSize,s=r.strides,u=r.outputSize,l=[u/o,o],c=t.reshape([a,i]),p=e.reshape([a,o]);if(0===u)return Xr(nn([]),n);var h=an(0),f=new so(a,i,c.rank,p.rank,s,l);return this.compileAndRun(f,[p,c,h]).reshape(n)},e.prototype.sparseToDense=function(t,e,n,r){var i=br(0,t,n),a=i.sliceRank,o=i.numUpdates,s=i.strides,u=i.outputSize,l=new so(o,a,t.rank,e.rank,s,[u,1],!1);return this.compileAndRun(l,[e,t,r]).reshape(n)},e.prototype.fft=function(t){return this.fftImpl(t,!1)},e.prototype.ifft=function(t){return this.fftImpl(t,!0)},e.prototype.fftImpl=function(t,e){var n=this.texData.get(t.dataId),r=new ha("return real * expR - imag * expI;",t.shape,e),i=new ha("return real * expI + imag * expR;",t.shape,e),a=[this.makeComplexComponentTensorHandle(t,n.complexTensors.real),this.makeComplexComponentTensorHandle(t,n.complexTensors.imag)],o=this.compileAndRun(r,a),s=this.compileAndRun(i,a),u=this.complex(o,s).as2D(t.shape[0],t.shape[1]);return o.dispose(),s.dispose(),u},e.prototype.gatherND=function(t,e){var n=e.shape,r=n[n.length-1],i=gr(t,e),a=i[0],o=i[1],s=i[2],u=i[3],l=e.reshape([o,r]),c=t.reshape([t.size/s,s]),p=new va(r,u,[o,s]);return this.compileAndRun(p,[c,l]).reshape(a)},e.prototype.fill=function(t,e,n){if("string"===(n=n||P(e))){var r=A(n,v(t));return r.fill(e),lt.make(t,{values:r},n)}var i=new fa(t,e),a=i.getCustomSetupFunc(e),o=this.makeOutputArray(t,n);return this.compileAndRun(i,[],o,a)},e.prototype.onesLike=function(t){if("string"===t.dtype)throw new Error("onesLike is not supported under string dtype");return this.fill(t.shape,1,t.dtype)},e.prototype.zerosLike=function(t){return this.fill(t.shape,"string"===t.dtype?"":0,t.dtype)},e.prototype.linspace=function(t,e,n){return Yr(t,e,n)},e.prototype.makeOutputArray=function(t,e){return lt.make(t,{},e,this)},e.prototype.makePackedTensor=function(t,e){var n=lt.make(t,{},e,this);return this.texData.get(n.dataId).isPacked=!0,n},e.prototype.unpackTensor=function(t){var e=new Bo(t.shape);return this.compileAndRun(e,[t],lt.make(e.outputShape,{},t.dtype,this))},e.prototype.packTensor=function(t){var e=new Ka(t.shape);return this.compileAndRun(e,[t],this.makePackedTensor(t.shape,t.dtype),null,!0)},e.prototype.packedReshape=function(t,e){var n=t.reshape([me(t.shape)].concat(ge(t.shape))),r=[me(e)].concat(ge(e)),i=new Qa(r,n.shape);return this.compileAndRun(i,[n]).reshape(e)},e.prototype.decode=function(t){var e,n=this.texData.get(t),r=n.isPacked,i=n.shape,a=n.dtype,o=ve(i),s=zt(i),u=this.makeTensorHandle(i,"float32");return this.texData.get(u.dataId).isPacked=!0,this.texData.get(u.dataId).dtype=a,this.texData.get(u.dataId).texShape=s.map(function(t){return 2*t}),e=r?new aa(o,s):new ia(o,s),this.compileAndRun(e,[{shape:o,dtype:a,dataId:t}],u,null,!0),u},e.prototype.compileAndRun=function(e,n,r,i,a){var o=this;if(void 0===a&&(a=!1),null==r&&(r=e.usesPackedTextures?this.makePackedTensor(e.outputShape,n[0].dtype):this.makeOutputArray(e.outputShape,n[0].dtype)),0===r.size)return this.texData.get(r.dataId).values=I(r.dtype,0),r;var s=n.map(function(n){if("complex64"===n.dtype)throw new Error("GPGPUProgram does not support complex64 input. For complex64 dtypes, please separate the program into real and imaginary parts.");var r=o.texData.get(n.dataId);if(null==r.texture){if(!e.usesPackedTextures&&v(n.shape)<=t.ENV.getNumber("WEBGL_SIZE_UPLOAD_UNIFORM"))return{shape:n.shape,texData:null,isUniform:!0,uniformValues:r.values};e.usesPackedTextures&&(r.isPacked=!0,r.shape=n.shape)}else if(!!r.isPacked!=!!e.usesPackedTextures)n=r.isPacked?o.unpackTensor(n):o.packTensor(n),r=o.texData.get(n.dataId);else if(r.isPacked&&!xe(r.shape,n.shape)){var i=n,a=n.shape;n.shape=r.shape,n=o.packedReshape(n,a),r=o.texData.get(n.dataId),i.shape=a}return o.uploadToGPU(n.dataId),{shape:n.shape,texData:r,isUniform:!1}});this.uploadToGPU(r.dataId);var u,l={shape:r.shape,texData:this.texData.get(r.dataId),isUniform:!1},c=function(t,e,n){var r="";s.concat(n).forEach(function(t){var e=null!=t.texData&&null!=t.texData.slice&&t.texData.slice.flatOffset>0,n=t.isUniform?"uniform":t.texData.texShape;r+=t.shape+"_"+n+"_"+e});var i=t.userCode;return t.constructor.name+"_"+r+"_"+i}(e,0,l),p=this.getAndSaveBinary(c,function(){return function(e,n,r,i){var a=n.userCode,o=r.map(function(t,e){var r={logicalShape:t.shape,texShape:t.isUniform?null:t.texData.texShape,isUniform:t.isUniform,isPacked:!t.isUniform&&t.texData.isPacked,flatOffset:null};return null!=t.texData&&null!=t.texData.slice&&t.texData.slice.flatOffset>0&&(r.flatOffset=t.texData.slice.flatOffset),{name:n.variableNames[e],shapeInfo:r}}),s=o.map(function(t){return t.shapeInfo}),u={logicalShape:i.shape,texShape:i.texData.texShape,isUniform:!1,isPacked:i.texData.isPacked,flatOffset:null},l=vi(o,u,a,n.usesPackedTextures),c=e.createProgram(l),p=null,h=e.getUniformLocation(c,"NAN",!1);1===t.ENV.getNumber("WEBGL_VERSION")&&(p=e.getUniformLocation(c,"INFINITY",!1));for(var f={},d=0;d0)return 32}return 16})),this.floatPrecisionValue},e.prototype.epsilon=function(){return 32===this.floatPrecision()?1e-7:1e-4},e.prototype.uploadToGPU=function(t){var e,n=this.texData.get(t),r=n.shape,i=n.dtype,a=n.values,o=n.texture,s=n.usage,u=n.isPacked;if(null==o){var l,c=null!=this.activeTimers;c&&(l=q());var p=n.texShape;if(null==p&&(p=ye(r,u),n.texShape=p),null!=a){var h=ve(r),f=void 0,d=p[1],m=p[0],g=a instanceof Uint8Array;u?(d=(e=Lt(p[0],p[1]))[0],m=e[1],f=new pa(h,[m,d],g)):f=new ca(h,[m,d],g);var y=this.makeTensorHandle([m,d],i);this.texData.get(y.dataId).usage=g?At.PIXELS:At.UPLOAD,this.gpgpu.uploadDenseMatrixToTexture(this.getTexture(y.dataId),d,m,a);var b=this.makeTensorHandle(f.outputShape,y.dtype);b.size=v(f.outputShape),this.texData.get(b.dataId).isPacked=u,this.compileAndRun(f,[y],b);var x=this.texData.get(b.dataId);n.texture=x.texture,n.texShape=x.texShape,n.isPacked=x.isPacked,n.usage=x.usage,this.disposeData(y.dataId),this.texData.delete(b.dataId),n.values=null,c&&(this.uploadWaitMs+=q()-l)}else{var w=this.acquireTexture(p,s,i,u);n.texture=w}}},e.prototype.convertAndCacheOnCPU=function(t,e){var n=this.texData.get(t),r=n.dtype;return this.releaseGPUData(t),null!=e&&(n.values=function(t,e){if("float32"===e||"complex64"===e)return t;if("int32"===e||"bool"===e){for(var n="int32"===e?new Int32Array(t.length):new Uint8Array(t.length),r=0;r1024*this.numMBBeforeWarning*1024){var i=(this.numBytesInGPU/1024/1024).toFixed(2);this.warnedAboutMemory=!0,console.warn("High memory usage in GPU: "+i+" MB, most likely due to a memory leak")}return this.textureManager.acquireTexture(t,e,r)},e.prototype.computeBytes=function(t,e){return t[0]*t[1]*_(e)},e}();It()&&kt.registerBackend("webgl",function(){return new jo},2);var Go=Ze({abs_:function(t){var e=Ve(t,"x","abs");return"complex64"===e.dtype?kt.runKernel(function(t){return t.complexAbs(e)},{$x:e}):kt.runKernel(function(t,n){var r=t.abs(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.mul(n.toFloat().step(-1))}}})}}),Ho=Ze({acos_:function(t){var e=Ve(t,"x","acos");return kt.runKernel(function(t,n){var r=t.acos(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.divStrict(an(1).sub(n.toFloat().square()).sqrt()).neg()}}})}}),qo=Ze({acosh_:function(t){var e=Ve(t,"x","acosh");return kt.runKernel(function(t,n){var r=t.acosh(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.divStrict(n.toFloat().square().sub(1).sqrt())}}})}}),Ko=Ze({asin_:function(t){var e=Ve(t,"x","asin");return kt.runKernel(function(t,n){var r=t.asin(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.divStrict(an(1).sub(n.toFloat().square()).sqrt())}}})}}),$o=Ze({asinh_:function(t){var e=Ve(t,"x","asinh");return kt.runKernel(function(t,n){var r=t.asinh(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.divStrict(an(1).add(n.toFloat().square()).sqrt())}}})}}),Xo=Ze({atan_:function(t){var e=Ve(t,"x","atan");return kt.runKernel(function(t,n){var r=t.atan(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.div(n.toFloat().square().add(1))}}})}}),Yo=Ze({atanh_:function(t){var e=Ve(t,"x","atanh");return kt.runKernel(function(t,n){var r=t.atanh(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.div(an(1).sub(n.toFloat().square()))}}})}}),Jo=Ze({ceil_:function(t){var e=Ve(t,"x","ceil");return kt.runKernel(function(t){return t.ceil(e)},{$x:e},function(t){return{$x:function(){return yn(t)}}})}}),Zo=Ze({clipByValue_:function(t,e,n){var r=Ve(t,"x","clipByValue");return f(e<=n,function(){return"Error in clip: min ("+e+") must be less than or equal to max ("+n+")."}),kt.runKernel(function(t,i){var a=t.clip(r,e,n);return i([r]),a},{$x:r},function(t,r){var i=r[0];return{$x:function(){return t.where(i.greaterEqual(e).logicalAnd(i.lessEqual(n)),yn(t))}}})}}),Qo=Ze({cos_:function(t){var e=Ve(t,"x","cos");return kt.runKernel(function(t,n){var r=t.cos(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return n.toFloat().sin().neg().mul(t)}}})}}),ts=Ze({cosh_:function(t){var e=Ve(t,"x","cosh");return kt.runKernel(function(t,n){var r=t.cosh(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return n.toFloat().sinh().mulStrict(t)}}})}}),es=Ze({erf_:function(t){var e=Ve(t,"x","erf");return f("int32"===e.dtype||"float32"===e.dtype,function(){return"Input dtype must be `int32` or `float32`."}),"int32"===e.dtype&&(e=e.toFloat()),kt.runKernel(function(t,n){var r=t.erf(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.mul(n.square().neg().exp().mul(2/Math.sqrt(Math.PI)))}}})}}),ns=Ze({exp_:function(t){var e=Ve(t,"x","exp");return kt.runKernel(function(t,n){var r=t.exp(e);return n([r]),r},{$x:e},function(t,e){return{$x:function(){return t.mulStrict(e[0])}}})}}),rs=Ze({expm1_:function(t){var e=Ve(t,"x","expm1");return kt.runKernel(function(t,n){var r=t.expm1(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.mul(n.exp())}}})}}),is=Ze({floor_:function(t){var e=Ve(t,"x","floor");return kt.runKernel(function(t){return t.floor(e)},{$x:e},function(t){return{$x:function(){return yn(t)}}})}}),as=Ze({log_:function(t){var e=Ve(t,"x","log");return kt.runKernel(function(t,n){var r=t.log(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.div(n.toFloat())}}})}}),os=Ze({log1p_:function(t){var e=Ve(t,"x","log1p");return kt.runKernel(function(t,n){var r=t.log1p(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.div(n.add(1))}}})}}),ss=Ze({logSigmoid_:function(t){var e=Ve(t,"x","logSigmoid");return kt.runKernel(function(t,n){var r=t.softplus(e.neg()).neg();return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.mul(n.neg().sigmoid())}}})}}),us=Ze({neg_:function(t){var e=Ve(t,"x","neg");return kt.runKernel(function(t){return t.neg(e)},{$x:e},function(t){return{$x:function(){return t.neg()}}})}}),ls=Ze({reciprocal_:function(t){var e=Ve(t,"x","reciprocal");return kt.runKernel(function(t,n){var r=t.reciprocal(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.div(n.square().neg())}}})}}),cs=Ze({round_:function(t){var e=Ve(t,"x","round");return kt.runKernel(function(t){return t.round(e)},{$x:e},function(t){return{$x:function(){return yn(t)}}})}}),ps=Ze({rsqrt_:function(t){var e=Ve(t,"x","rsqrt");return kt.runKernel(function(t,n){var r=t.rsqrt(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.div(n.pow(1.5).mul(2)).neg()}}})}}),hs=Ze({sigmoid_:function(t){var e=Ve(t,"x","sigmoid");return kt.runKernel(function(t,n){var r=t.sigmoid(e);return n([r]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.mul(n.mul(an(1).sub(n)))}}})}}),fs=Ze({sign_:function(t){var e=Ve(t,"x","sign");return kt.runKernel(function(t){return t.sign(e)},{$x:e},function(t){return{$x:function(){return yn(t)}}})}}),ds=Ze({isNaN_:function(t){var e=Ve(t,"x","isNaN");return kt.runKernel(function(t){return t.isNaN(e)},{$x:e},function(t){return{$x:function(){return yn(t)}}})}}),ms=Ze({isInf_:function(t){var e=Ve(t,"x","isInf");return kt.runKernel(function(t){return t.isInf(e)},{$x:e},function(t){return{$x:function(){return yn(t)}}})}}),gs=Ze({isFinite_:function(t){var e=Ve(t,"x","isFinite");return kt.runKernel(function(t){return t.isFinite(e)},{$x:e},function(t){return{$x:function(){return yn(t)}}})}}),vs=Ze({sin_:function(t){var e=Ve(t,"x","sin");return kt.runKernel(function(t,n){var r=t.sin(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return n.toFloat().cos().mul(t)}}})}}),ys=Ze({sinh_:function(t){var e=Ve(t,"x","sinh");return kt.runKernel(function(t,n){var r=t.sinh(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return n.toFloat().cosh().mulStrict(t)}}})}}),bs=Ze({softplus_:function(t){var e=Ve(t,"x","softplus");return kt.runKernel(function(t,n){var r=t.softplus(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.mul(n.sigmoid())}}})}}),xs=Ze({sqrt_:function(t){var e=Ve(t,"x","sqrt");return kt.runKernel(function(t,n){var r=t.sqrt(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.div(n.toFloat().sqrt().mul(2))}}})}}),ws=Ze({square_:function(t){var e=Ve(t,"x","square");return kt.runKernel(function(t,n){return n([e]),t.square(e)},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.mul(n.toFloat().mul(2))}}})}}),Ns=Ze({step_:function(t,e){void 0===e&&(e=0);var n=Ve(t,"x","step");return kt.runKernel(function(t){return t.step(n,e)},{$x:n},function(t){return{$x:function(){return yn(t)}}})}}),Cs=Ze({tan_:function(t){var e=Ve(t,"x","tan");return kt.runKernel(function(t,n){var r=t.tan(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.div(n.cos().square())}}})}}),Es=Ze({tanh_:function(t){var e=Ve(t,"x","tanh");return kt.runKernel(function(t,n){var r=t.tanh(e);return n([r]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return an(1).sub(n.square()).mulStrict(t)}}})}});function Ss(t,e,n,r,i,a){var o,s,u=Ve(t,"x","batchNorm"),l=Ve(e,"mean","batchNorm"),c=Ve(n,"variance","batchNorm");return null!=i&&(o=Ve(i,"scale","batchNorm")),null!=r&&(s=Ve(r,"offset","batchNorm")),f(2===u.rank,function(){return"Error in batchNorm3D: x must be rank 3 but got rank "+u.rank+"."}),f(2===l.rank||1===l.rank,function(){return"Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank "+l.rank+"."}),f(2===c.rank||1===c.rank,function(){return"Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank "+c.rank+"."}),null!=o&&f(2===o.rank||1===o.rank,function(){return"Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank "+o.rank+"."}),null!=s&&f(2===s.rank||1===s.rank,function(){return"Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank "+s.rank+"."}),As(u,l,c,s,o,a)}function ks(t,e,n,r,i,a){var o,s,u=Ve(t,"x","batchNorm"),l=Ve(e,"mean","batchNorm"),c=Ve(n,"variance","batchNorm");return null!=i&&(o=Ve(i,"scale","batchNorm")),null!=r&&(s=Ve(r,"offset","batchNorm")),f(3===u.rank,function(){return"Error in batchNorm3D: x must be rank 3 but got rank "+u.rank+"."}),f(3===l.rank||1===l.rank,function(){return"Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank "+l.rank+"."}),f(3===c.rank||1===c.rank,function(){return"Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank "+c.rank+"."}),null!=o&&f(3===o.rank||1===o.rank,function(){return"Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank "+o.rank+"."}),null!=s&&f(3===s.rank||1===s.rank,function(){return"Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank "+s.rank+"."}),As(u,l,c,s,o,a)}function Is(t,e,n,r,i,a){var o,s,u=Ve(t,"x","batchNorm"),l=Ve(e,"mean","batchNorm"),c=Ve(n,"variance","batchNorm");return null!=i&&(o=Ve(i,"scale","batchNorm")),null!=r&&(s=Ve(r,"offset","batchNorm")),f(4===u.rank,function(){return"Error in batchNorm4D: x must be rank 4 but got rank "+u.rank+"."}),f(4===l.rank||1===l.rank,function(){return"Error in batchNorm4D: mean must be rank 4 or rank 1 but got rank "+l.rank+"."}),f(4===c.rank||1===c.rank,function(){return"Error in batchNorm4D: variance must be rank 4 or rank 1 but got rank "+c.rank+"."}),null!=o&&f(4===o.rank||1===o.rank,function(){return"Error in batchNorm4D: scale must be rank 4 or rank 1 but got rank "+o.rank+"."}),null!=s&&f(4===s.rank||1===s.rank,function(){return"Error in batchNorm4D: offset must be rank 4 or rank 1 but got rank "+s.rank+"."}),As(u,l,c,s,o,a)}function As(t,e,n,r,i,a){null==a&&(a=.001);var o,s,u,l=Ve(t,"x","batchNorm"),c=Ve(e,"mean","batchNorm"),p=Ve(n,"variance","batchNorm");return null!=i&&(o=Ve(i,"scale","batchNorm")),null!=r&&(s=Ve(r,"offset","batchNorm")),f(c.rank===p.rank,function(){return"Batch normalization gradient requires mean and variance to have equal ranks."}),f(null==s||c.rank===s.rank,function(){return"Batch normalization gradient requires mean and offset to have equal ranks."}),f(null==o||c.rank===o.rank,function(){return"Batch normalization gradient requires mean and scale to have equal ranks."}),u=0===l.rank||1===l.rank?l.as4D(1,1,1,l.size):2===l.rank?l.as4D(1,1,l.shape[0],l.shape[1]):3===l.rank?l.as4D(1,l.shape[0],l.shape[1],l.shape[2]):l,kt.runKernel(function(t,e){var n=t.batchNormalization(u,Rs(c),Rs(p),a,Rs(o),Rs(s));return e([l,c,p,o]),n},{$x:l,$mean:c,$variance:p,$scale:o,$offset:s},function(t,e){var n=e,r=n[0],i=n[1],o=n[2],s=n[3],l=null==s?an(1):s,c=Fr(i.shape,u.shape),p=[];if(1===i.rank){for(var h=0;h0&&(e=e.sum(n)),e.reshape(r.shape)},$b:function(){var e=t,n=Fr(i.shape,a);return n.length>0&&(e=e.sum(n)),e.reshape(i.shape)}}})}}),qs=Ze({addN_:function(t){f(Array.isArray(t),function(){return"The argument passed to tf.addN() must be a list of tensors"}),f(t.length>=1,function(){return"Must pass at least one tensor to tf.addN(), but got "+t.length});var e=t.map(function(t,e){return Ve(t,"tensors"+e,"addN")}),n=e[0];e.forEach(function(t){if(t.dtype!==n.dtype)throw new Error("All tensors passed to tf.addN() must have the same dtype")}),e.forEach(function(t){if(!y(t.shape,n.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")});var r=e;return kt.runKernel(function(t){return t.addN(e)},r,function(t){var n={};return e.forEach(function(e,r){n[r]=function(){return t.clone()}}),n})}}),Ks=Ze({addStrict_:function(t,e){var n=Ve(t,"a","addStrict"),r=Ve(e,"b","addStrict");return d(n.shape,r.shape,"Error in addStrict: "),n.add(r)}}),$s=Ze({atan2_:function(t,e){var n,r=Ve(t,"a","atan2"),i=Ve(e,"b","atan2");n=bt(r,i),r=n[0],i=n[1];var a=Mr(r.shape,i.shape);return kt.runKernel(function(t,e){var n=t.atan2(r,i);return e([r,i]),n},{$a:r,$b:i},function(t,e){var n=e[0],r=e[1];return{$a:function(){var e=Hs(n.square(),r.square()),i=t.mul(r.div(e)),o=Fr(n.shape,a);return o.length>0&&(i=i.sum(o)),i.reshape(n.shape)},$b:function(){var e=Hs(n.square(),r.square()),i=us(t.mul(n.div(e))),o=Fr(r.shape,a);return o.length>0&&(i=i.sum(o)),i.reshape(r.shape)}}})}}),Xs=Ze({div_:function(t,e){var n,r=Ve(t,"a","div"),i=Ve(e,"b","div");if(n=bt(r,i),r=n[0],i=n[1],"int32"===r.dtype&&"int32"===i.dtype)return Js(r,i);var a=Mr(r.shape,i.shape);return kt.runKernel(function(t,e){var n=t.realDivide(r,i);return e([r,i]),n},{$a:r,$b:i},function(t,e){var n=e[0],r=e[1];return{$a:function(){var e=t.div(r.toFloat()),i=Fr(n.shape,a);return i.length>0?e.sum(i).reshape(n.shape):e},$b:function(){var e=t.mul(n.toFloat()),i=Fr(r.shape,a);i.length>0&&(e=e.sum(i).reshape(r.shape));var o=r.square();return e.div(o.toFloat()).neg()}}})}}),Ys=Ze({divStrict_:function(t,e){var n=Ve(t,"a","div"),r=Ve(e,"b","div");return d(n.shape,r.shape,"Error in divideStrict: "),n.div(r)}}),Js=Ze({floorDiv_:function(t,e){var n,r=Ve(t,"a","floorDiv"),i=Ve(e,"b","floorDiv");n=bt(r,i),r=n[0],i=n[1];var a=Mr(r.shape,i.shape);return kt.runKernel(function(t,e){var n=t.floorDiv(r,i);return e([r,i]),n},{$a:r,$b:i},function(t,e){var n=e[0],r=e[1];return{$a:function(){var e=t.div(r.toFloat()),i=Fr(n.shape,a);return i.length>0?e.sum(i).reshape(n.shape):e},$b:function(){var e=t.mul(n.toFloat()),i=Fr(r.shape,a);i.length>0&&(e=e.sum(i).reshape(r.shape));var o=r.square();return e.div(o.toFloat()).neg()}}})}}),Zs=Ze({maximum_:function(t,e){var n,r=Ve(t,"a","maximum"),i=Ve(e,"b","maximum");return n=bt(r,i),r=n[0],i=n[1],"bool"===r.dtype&&(r=r.toInt(),i=i.toInt()),Mr(r.shape,i.shape),kt.runKernel(function(t,e){var n=t.maximum(r,i);return e([r,i]),n},{$a:r,$b:i},function(t,e){var n=e[0],r=e[1];return{$a:function(){return t.mul(n.greaterEqual(r).toFloat())},$b:function(){return t.mul(n.less(r).toFloat())}}})}}),Qs=Ze({maximumStrict_:function(t,e){var n=Ve(t,"a","maximumStrict"),r=Ve(e,"b","maximumStrict");return d(n.shape,r.shape,"Error in maximumStrict: "),n.maximum(r)}}),tu=Ze({minimum_:function(t,e){var n,r=Ve(t,"a","minimum"),i=Ve(e,"b","minimum");return n=bt(r,i),r=n[0],i=n[1],"bool"===r.dtype&&(r=r.toInt(),i=i.toInt()),Mr(r.shape,i.shape),kt.runKernel(function(t,e){var n=t.minimum(r,i);return e([r,i]),n},{$a:r,$b:i},function(t,e){var n=e[0],r=e[1];return{$a:function(){return t.mul(n.lessEqual(r).toFloat())},$b:function(){return t.mul(n.greater(r).toFloat())}}})}}),eu=Ze({minimumStrict_:function(t,e){var n=Ve(t,"a","minimumStrict"),r=Ve(e,"b","minimumStrict");return d(n.shape,r.shape,"Error in minimumStrict: "),n.minimum(r)}}),nu=Ze({mod_:function(t,e){var n,r=Ve(t,"a","mod"),i=Ve(e,"b","mod");n=bt(r,i),r=n[0],i=n[1];var a=Mr(r.shape,i.shape);return kt.runKernel(function(t,e){var n=t.mod(r,i);return e([r,i]),n},{$a:r,$b:i},function(t,e){var n=e[0],r=e[1];return{$a:function(){var e=Fr(n.shape,a);return e.length>0?t.sum(e).reshape(n.shape):t},$b:function(){var e=t.mul(n.div(r).floor().neg()),i=Fr(r.shape,a);return i.length>0?e.sum(i).reshape(r.shape):e}}})}}),ru=Ze({modStrict_:function(t,e){var n=Ve(t,"a","modStrict"),r=Ve(e,"b","modStrict");return d(n.shape,r.shape,"Error in modStrict: "),n.mod(r)}}),iu=Ze({mul_:function(t,e){var n,r=Ve(t,"a","mul"),i=Ve(e,"b","mul");n=bt(r,i),r=n[0],i=n[1];var a=Mr(r.shape,i.shape);return kt.runKernel(function(t,e){var n=t.multiply(r,i);return e([r,i]),n},{$a:r,$b:i},function(t,e){var n=e[0],r=e[1];return{$a:function(){var e=t.mul(r.toFloat()),i=Fr(n.shape,a);return i.length>0?e.sum(i).reshape(n.shape):e},$b:function(){var e=t.mul(n.toFloat()),i=Fr(r.shape,a);return i.length>0?e.sum(i).reshape(r.shape):e}}})}}),au=Ze({mulStrict_:function(t,e){var n=Ve(t,"a","mul"),r=Ve(e,"b","mul");return d(n.shape,r.shape,"Error in multiplyStrict: "),n.mul(r)}}),ou=Ze({pow_:function(t,e){var n=Ve(t,"base","pow"),r=Ve(e,"exp","pow"),i=Mr(n.shape,r.shape);return t=n.cast(vt(n.dtype,r.dtype)),e=r.cast(vt(n.dtype,r.dtype)),kt.runKernel(function(t,e){var i=t.pow(n,r);return e([n,r,i]),i},{$base:n,$exp:r},function(t,e){var n=e[0],r=e[1],a=e[2];return{$base:function(){var e=r.toFloat(),a=t.mul(e.mul(n.pow(e.sub(an(1))))),o=Fr(n.shape,i);return o.length>0&&(a=a.sum(o)),a.reshape(n.shape)},$exp:function(){var e=n.greater(0),o=n.log().where(e,yn(n)),s=t.mul(a.mul(o)),u=Fr(r.shape,i);return u.length>0&&(s=s.sum(u)),s.reshape(r.shape)}}})}}),su=Ze({powStrict_:function(t,e){return d(t.shape,e.shape,"Error in powStrict: "),t.pow(e)}}),uu=Ze({squaredDifference_:function(t,e){var n,r=Ve(t,"a","squaredDifference"),i=Ve(e,"b","squaredDifference");return n=bt(r,i),r=n[0],i=n[1],Mr(r.shape,i.shape),kt.runKernel(function(t,e){var n=t.squaredDifference(r,i);return e([r,i]),n},{$a:r,$b:i},function(t,e){var n=e[0],r=e[1],i=an(2);return{$a:function(){return t.mul(n.sub(r).mul(i))},$b:function(){return t.mul(r.sub(n).mul(i))}}})}}),lu=Ze({squaredDifferenceStrict_:function(t,e){var n=Ve(t,"a","squaredDifferenceStrict"),r=Ve(e,"b","squaredDifferenceStrict");return d(n.shape,r.shape,"Error in squaredDifferenceStrict: "),n.squaredDifference(r)}}),cu=Ze({sub_:function(t,e){var n,r=Ve(t,"a","sub"),i=Ve(e,"b","sub");n=bt(r,i),r=n[0],i=n[1];var a=Mr(r.shape,i.shape);return kt.runKernel(function(t){return t.subtract(r,i)},{$a:r,$b:i},function(t){return{$a:function(){var e=t,n=Fr(r.shape,a);return n.length>0&&(e=e.sum(n)),e.reshape(r.shape)},$b:function(){var e=t,n=Fr(i.shape,a);return n.length>0&&(e=e.sum(n)),e.neg().reshape(i.shape)}}})}}),pu=Ze({subStrict_:function(t,e){var n=Ve(t,"a","subStrict"),r=Ve(e,"b","subStrict");return d(n.shape,r.shape,"Error in subStrict: "),n.sub(r)}}),hu=Ze({equal_:function(t,e){var n,r=Ve(t,"a","equal"),i=Ve(e,"b","equal");return n=bt(r,i),r=n[0],i=n[1],Mr(r.shape,i.shape),kt.runKernel(function(t){return t.equal(r,i)},{$a:r,$b:i})}}),fu=Ze({equalStrict_:function(t,e){var n=Ve(t,"a","equalStrict"),r=Ve(e,"b","equalStrict");return d(n.shape,r.shape,"Error in equalStrict: "),n.equal(r)}}),du=Ze({greater_:function(t,e){var n,r=Ve(t,"a","greater"),i=Ve(e,"b","greater");return n=bt(r,i),r=n[0],i=n[1],Mr(r.shape,i.shape),kt.runKernel(function(t){return t.greater(r,i)},{$a:r,$b:i})}}),mu=Ze({greaterEqual_:function(t,e){var n,r=Ve(t,"a","greaterEqual"),i=Ve(e,"b","greaterEqual");return n=bt(r,i),r=n[0],i=n[1],Mr(r.shape,i.shape),kt.runKernel(function(t,e){var n=t.greaterEqual(r,i);return e([r,i]),n},{$a:r,$b:i},function(t,e){var n=e[0],r=e[1];return{$a:function(){return yn(n)},$b:function(){return yn(r)}}})}}),gu=Ze({greaterEqualStrict_:function(t,e){var n=Ve(t,"a","greaterEqualStrict"),r=Ve(e,"b","greaterEqualStrict");return d(n.shape,r.shape,"Error in greaterEqualStrict: "),n.greaterEqual(r)}}),vu=Ze({greaterStrict_:function(t,e){var n=Ve(t,"a","greaterStrict"),r=Ve(e,"b","greaterStrict");return d(n.shape,r.shape,"Error in greaterStrict: "),n.greater(r)}}),yu=Ze({less_:function(t,e){var n,r=Ve(t,"a","less"),i=Ve(e,"b","less");return n=bt(r,i),r=n[0],i=n[1],Mr(r.shape,i.shape),kt.runKernel(function(t){return t.less(r,i)},{$a:r,$b:i})}}),bu=Ze({lessEqual_:function(t,e){var n,r=Ve(t,"a","lessEqual"),i=Ve(e,"b","lessEqual");return n=bt(r,i),r=n[0],i=n[1],Mr(r.shape,i.shape),kt.runKernel(function(t){return t.lessEqual(r,i)},{$a:r,$b:i})}}),xu=Ze({lessEqualStrict_:function(t,e){var n=Ve(t,"a","lessEqualStrict"),r=Ve(e,"b","lessEqualStrict");return d(n.shape,r.shape,"Error in lessEqualStrict: "),n.lessEqual(r)}}),wu=Ze({lessStrict_:function(t,e){var n=Ve(t,"a","lessStrict"),r=Ve(e,"b","lessStrict");return d(n.shape,r.shape,"Error in lessStrict: "),n.less(r)}}),Nu=Ze({notEqual_:function(t,e){var n,r=Ve(t,"a","notEqual"),i=Ve(e,"b","notEqual");return n=bt(r,i),r=n[0],i=n[1],Mr(r.shape,i.shape),kt.runKernel(function(t){return t.notEqual(r,i)},{$a:r,$b:i})}}),Cu=Ze({notEqualStrict_:function(t,e){var n=Ve(t,"a","notEqualStrict"),r=Ve(e,"b","notEqualStrict");return d(n.shape,r.shape,"Error in notEqualStrict: "),n.notEqual(r)}});function Eu(t,e){for(var n=[],r=t;r0,function(){return"mask cannot be scalar"}),d(u.slice(o,o+s),a.shape,"mask's shape must match the first K dimensions of tensor's shape,"),l=1,c=o;c=2&&o.rank>=2&&a.rank===o.rank,function(){return"Error in matMul: inputs must have the same rank of at least 2, got ranks "+a.rank+" and "+o.rank+"."}),f(y(p,h),function(){return"Error in matMul: outer dimensions ("+p+") and ("+h+") of Tensors with shapes "+a.shape+" and "+o.shape+" must match."}),f(s===u,function(){return"Error in matMul: inner shapes ("+s+") and ("+u+") of Tensors with shapes "+a.shape+" and "+o.shape+" and transposeA="+n+" and transposeB="+r+" must match."});var g=a.shape.slice(0,-2).concat([l,c]),b=n?a.as3D(d,s,l):a.as3D(d,l,s),x=r?o.as3D(m,c,u):o.as3D(m,u,c);return kt.runKernel(function(t,e){var i=t.batchMatMul(b,x,n,r);return e([b,x]),i},{$a:b,$b:x},function(t,e){var i=e,a=i[0],o=i[1];return n||r?!n&&r?{$a:function(){return t.matMul(o,!1,!1)},$b:function(){return t.matMul(a,!0,!1)}}:n&&!r?{$a:function(){return o.matMul(t,!1,!0)},$b:function(){return a.matMul(t,!1,!1)}}:{$a:function(){return o.matMul(t,!0,!0)},$b:function(){return t.matMul(a,!0,!0)}}:{$a:function(){return t.matMul(o,!1,!0)},$b:function(){return a.matMul(t,!0,!1)}}}).reshape(g)}}),ju=Ze({dot_:function(t,e){var n=Ve(t,"t1","dot"),r=Ve(e,"t2","dot");f(!(1!==n.rank&&2!==n.rank||1!==r.rank&&2!==r.rank),function(){return"Error in dot: inputs must all be rank 1 or 2, but got ranks "+n.rank+" and "+r.rank+"."});var i=1===n.rank?n.size:n.shape[1],a=1===r.rank?r.size:r.shape[0];return f(i===a,function(){return"Error in dot: inner dimensions of inputs must match, but got "+i+" and "+a+"."}),1===n.rank&&1===r.rank?n.as2D(1,-1).matMul(r.as2D(-1,1)).asScalar():1===n.rank&&2===r.rank?n.as2D(1,-1).matMul(r.as2D(r.shape[0],r.shape[1])).as1D():2===n.rank&&1===r.rank?n.matMul(r.as2D(-1,1)).as1D():n.matMul(r.as2D(r.shape[0],r.shape[1]))}}),Gu=Ze({outerProduct_:function(t,e){var n=Ve(t,"v1","outerProduct"),r=Ve(e,"v2","outerProduct");return f(1===n.rank&&1===r.rank,function(){return"Error in outerProduct: inputs must be rank 1, but got ranks "+n.rank+" and "+r.rank+"."}),n.as2D(-1,1).matMul(r.as2D(1,-1))}}),Hu=Ze({reverse_:function(t,e){var n=Ve(t,"x","reverse");if(0===n.rank)return n.clone();var r=S(e,n.shape);return kt.runKernel(function(t){return t.reverse(n,r)},{$x:n},function(t){return{$x:function(){return t.reverse(r)}}}).reshapeAs(n)}}),qu=Ze({reverse1d_:function(t){var e=Ve(t,"x","reverse");return f(1===e.rank,function(){return"Error in reverse1D: x must be rank 1 but got rank "+e.rank+"."}),Hu(e,0)}}),Ku=Ze({reverse2d_:function(t,e){var n=Ve(t,"x","reverse");return f(2===n.rank,function(){return"Error in reverse2D: x must be rank 2 but got rank "+n.rank+"."}),Hu(n,e)}}),$u=Ze({reverse3d_:function(t,e){var n=Ve(t,"x","reverse");return f(3===n.rank,function(){return"Error in reverse3D: x must be rank 3 but got rank "+n.rank+"."}),Hu(n,e)}}),Xu=Ze({reverse4d_:function(t,e){var n=Ve(t,"x","reverse");return f(4===n.rank,function(){return"Error in reverse4D: x must be rank 4 but got rank "+n.rank+"."}),Hu(n,e)}});function Yu(t,e,n,r,i,a){var o=Ve(t,"x","maxPool"),s=o,u=!1;3===o.rank&&(u=!0,s=o.as4D(1,o.shape[0],o.shape[1],o.shape[2])),null==r&&(r=[1,1]),f(4===s.rank,function(){return"Error in maxPool: input must be rank 4 but got rank "+s.rank+"."}),f(qr(n,r),function(){return"Error in maxPool: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+r+"'"}),null!=a&&f(b(i),function(){return"Error in maxPool: pad must be an integer when using, dimRoundingMode "+a+" but got pad "+i+"."});var l=zr(s.shape,e,n,r,i,a),c=kt.runKernel(function(t,e){var n=t.maxPool(s,l);return e([s,n]),n},{x:s},function(t,a){var o=a[0],s=a[1];return{x:function(){return function(t,e,n,r,i,a,o,s){var u=Ve(t,"dy","maxPoolBackprop"),l=Ve(e,"input","maxPoolBackprop"),c=Ve(n,"output","maxPoolBackprop");f(l.rank===u.rank,function(){return"Rank of input ("+l.rank+") does not match rank of dy ("+u.rank+")"}),null==a&&(a=[1,1]),f(qr(i,a),function(){return"Error in maxPoolBackProp: Either strides or dilations must be 1. Got strides "+i+" and dilations '"+a+"'"}),f(4===u.rank,function(){return"Error in maxPoolBackprop: dy must be rank 4 but got rank "+u.rank+"."}),f(4===l.rank,function(){return"Error in maxPoolBackprop: input must be rank 4 but got rank "+l.rank+"."});var p=zr(l.shape,r,i,a,o,s);return kt.runKernel(function(t){return t.maxPoolBackprop(u,l,c,p)},{$dy:u,$input:l})}(t,o,s,e,n,r,i)}}});return u?c.as3D(c.shape[1],c.shape[2],c.shape[3]):c}function Ju(t,e,n,r,i,a){var o=Ve(t,"x","avgPool","float32");null==r&&(r=[1,1]),f(qr(n,r),function(){return"Error in avgPool: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+r+"'"});var s=o,u=!1;3===o.rank&&(u=!0,s=o.as4D(1,o.shape[0],o.shape[1],o.shape[2])),f(4===s.rank,function(){return"Error in avgPool: x must be rank 4 but got rank "+s.rank+"."}),null!=a&&f(b(i),function(){return"Error in avgPool: pad must be an integer when using, dimRoundingMode "+a+" but got pad "+i+"."});var l=zr(s.shape,e,n,r,i,a),c=kt.runKernel(function(t){return t.avgPool(s,l)},{x:s},function(t){return{x:function(){return function(t,e,n,r,i,a){var o=Ve(t,"dy","avgPoolBackprop"),s=Ve(e,"input","avgPoolBackprop");f(s.rank===o.rank,function(){return"Rank of input ("+s.rank+") does not match rank of dy ("+o.rank+")"}),null==i&&(i=[1,1]),f(qr(r,i),function(){return"Error in avgPoolBackprop: Either strides or dilations must be 1. Got strides "+r+" and dilations '"+i+"'"});var u=s,l=o,c=!1;3===s.rank&&(c=!0,u=s.as4D(1,s.shape[0],s.shape[1],s.shape[2]),l=o.as4D(1,o.shape[0],o.shape[1],o.shape[2])),f(4===l.rank,function(){return"Error in avgPoolBackprop: dy must be rank 4 but got rank "+l.rank+"."}),f(4===u.rank,function(){return"Error in avgPoolBackprop: input must be rank 4 but got rank "+u.rank+"."});var p=zr(u.shape,n,r,i,a),h=kt.runKernel(function(t){return t.avgPoolBackprop(l,u,p)},{dy4D:l,input4D:u});return c?h.as3D(h.shape[1],h.shape[2],h.shape[3]):h}(t,s,e,n,r,i)}}});return c=c.cast(o.dtype),u?c.as3D(c.shape[1],c.shape[2],c.shape[3]):c}var Zu=Ze({maxPool_:function(t,e,n,r,i){return Yu(t,e,n,1,r,i)}}),Qu=Ze({avgPool_:function(t,e,n,r,i){return Ju(t,e,n,1,r,i)}}),tl=Ze({pool_:function(t,e,n,r,i,a){null==i&&(i=[1,1]),null==a&&(a=1),0===r&&(r="valid");var o=Ve(t,"x","maxPool"),s=o,u=!1;3===o.rank&&(u=!0,s=o.as4D(1,o.shape[0],o.shape[1],o.shape[2])),f(qr(a,i),function(){return"Error in pool: Either strides or dilations must be 1. Got strides "+a+" and dilations '"+i+"'"});var l,c=zr(s.shape,e,a,i,r),p=[c.dilationHeight,c.dilationWidth];l="same"===r?function(t,e){var n=t.map(function(t,n){return t+(t-1)*(e[n]-1)}).map(function(t){return t-1}),r=n.map(function(t){return Math.floor(t/2)}),i=n.map(function(t,e){return t-r[e]});return n.map(function(t,e){return[r[e],i[e]]})}([c.filterHeight,c.filterWidth],p):[[0,0],[0,0]];var h=1===p[0]&&1===p[1],d=function(t,e,n){var r=n.map(function(t){return t[0]}),i=n.map(function(t){return t[1]}),a=t.concat(r,i),o=e.map(function(t,e){return(t-a[e]%t)%t}),s=i.map(function(t,e){return t+o[e]});return[e.map(function(t,e){return[r[e],s[e]]}),e.map(function(t,e){return[0,o[e]]})]}([c.inHeight,c.inWidth],p,l),m=d[0],g=d[1],v=h?r:"valid",y=h?s:ir(s,p,m),b=("avg"===n?function(){return Ju(y,e,a,1,v)}:function(){return Yu(y,e,a,1,v)})(),x=h?b:Bn(b,p,g);return u?x.as3D(x.shape[1],x.shape[2],x.shape[3]):x}}),el=Ze({maxPool3d_:function(t,e,n,r,i,a,o){void 0===a&&(a="NDHWC");var s=Ve(t,"x","maxPool3d"),u=s,l=!1;4===s.rank&&(l=!0,u=s.as5D(1,s.shape[0],s.shape[1],s.shape[2],s.shape[3])),null==o&&(o=[1,1,1]),f(5===u.rank,function(){return"Error in maxPool3d: x must be rank 5 but got rank "+u.rank+"."}),f("NDHWC"===a,function(){return"Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of "+a}),f(qr(n,o),function(){return"Error in maxPool3d: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+o+"'"}),null!=i&&f(b(r),function(){return"Error in maxPool3d: pad must be an integer when using, dimRoundingMode "+i+" but got pad "+r+"."});var c=Lr(u.shape,e,n,o,r,i,a),p=kt.runKernel(function(t,e){var n=t.maxPool3d(u,c);return e([u,n]),n},{x:u},function(t,a){var s=a[0],u=a[1];return{x:function(){return function(t,e,n,r,i,a,o,s){var u=Ve(t,"dy","maxPool3dBackprop"),l=Ve(e,"input","maxPool3dBackprop"),c=Ve(n,"output","maxPool3dBackprop"),p=u,h=l,d=c,m=!1;4===l.rank&&(m=!0,p=u.as5D(1,u.shape[0],u.shape[1],u.shape[2],u.shape[3]),h=l.as5D(1,l.shape[0],l.shape[1],l.shape[2],l.shape[3]),d=c.as5D(1,c.shape[0],c.shape[1],c.shape[2],c.shape[3])),f(5===p.rank,function(){return"Error in maxPool3dBackprop: dy must be rank 5 but got rank "+p.rank+"."}),f(5===h.rank,function(){return"Error in maxPool3dBackprop: input must be rank 5 but got rank "+h.rank+"."}),f(5===d.rank,function(){return"Error in maxPool3dBackprop: output must be rank 5 but got rank "+d.rank+"."}),null==a&&(a=[1,1,1]),f(qr(i,a),function(){return"Error in maxPool3dBackprop: Either strides or dilations must be 1. Got strides "+i+" and dilations '"+a+"'"}),null!=s&&f(b(o),function(){return"Error in maxPool3dBackprop: pad must be an integer when using, dimRoundingMode "+s+" but got pad "+o+"."});var g=Lr(h.shape,r,i,a,o,s),v=kt.runKernel(function(t){return t.maxPool3dBackprop(p,h,d,g)},{dy5D:p,input5D:h});return m?v.as4D(v.shape[1],v.shape[2],v.shape[3],v.shape[4]):v}(t,s,u,e,n,o,r,i)}}});return l?p.as4D(p.shape[1],p.shape[2],p.shape[3],p.shape[4]):p}}),nl=Ze({avgPool3d_:function(t,e,n,r,i,a,o){void 0===a&&(a="NDHWC");var s=Ve(t,"x","avgPool3d","float32"),u=s,l=!1;4===s.rank&&(l=!0,u=s.as5D(1,s.shape[0],s.shape[1],s.shape[2],s.shape[3])),null==o&&(o=[1,1,1]),f(5===u.rank,function(){return"Error in avgPool3d: x must be rank 5 but got rank "+u.rank+"."}),f("NDHWC"===a,function(){return"Error in avgPool3d: Only NDHWC is currently supported, but got dataFormat of "+a}),f(qr(n,o),function(){return"Error in avgPool3d: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+o+"'"}),null!=i&&f(b(r),function(){return"Error in avgPool3d: pad must be an integer when using, dimRoundingMode "+i+" but got pad "+r+"."});var c=Lr(u.shape,e,n,o,r,i,a),p=kt.runKernel(function(t){return t.avgPool3d(u,c)},{x:u},function(t){return{x:function(){return function(t,e,n,r,i,a,o){var s=Ve(t,"dy","avgPool3dBackprop"),u=Ve(e,"input","avgPool3dBackprop"),l=s,c=u,p=!1;4===u.rank&&(p=!0,l=s.as5D(1,s.shape[0],s.shape[1],s.shape[2],s.shape[3]),c=u.as5D(1,u.shape[0],u.shape[1],u.shape[2],u.shape[3])),f(5===l.rank,function(){return"Error in avgPool3dBackprop: dy must be rank 5 but got rank "+l.rank+"."}),f(5===c.rank,function(){return"Error in avgPool3dBackprop: input must be rank 5 but got rank "+c.rank+"."}),null==i&&(i=[1,1,1]),f(qr(r,i),function(){return"Error in avgPool3dBackprop: Either strides or dilations must be 1. Got strides "+r+" and dilations '"+i+"'"}),null!=o&&f(b(a),function(){return"Error in maxPool3dBackprop: pad must be an integer when using, dimRoundingMode "+o+" but got pad "+a+"."});var h=Lr(c.shape,n,r,i,a,o),d=kt.runKernel(function(t){return t.avgPool3dBackprop(l,c,h)},{dy5D:l,input5D:c});return p?d.as4D(d.shape[1],d.shape[2],d.shape[3],d.shape[4]):d}(t,u,e,n,o,r,i)}}});return p=p.cast(u.dtype),l?p.as4D(p.shape[1],p.shape[2],p.shape[3],p.shape[4]):p}}),rl=Ze({slice_:function(t,e,n){var r,i,a=Ve(t,"x","slice");if(0===a.rank)throw new Error("Slicing scalar is not possible");(r="number"==typeof e?[e].concat(new Array(a.rank-1).fill(0)):e.length=0?t:(f(-1===t,function(){return"Negative size values should be exactly -1 but got "+t+" for the slice() size at index "+e+"."}),a.shape[e]-r[e])}),function(t,e,n){f(t.rank===e.length,function(){return"Error in slice"+t.rank+"D: Length of begin "+e+" must match the rank of the array ("+t.rank+")."}),f(t.rank===n.length,function(){return"Error in slice"+t.rank+"D: Length of size "+n+" must match the rank of the array ("+t.rank+")."});for(var r=function(r){f(e[r]+n[r]<=t.shape[r],function(){return"Error in slice"+t.rank+"D: begin["+r+"] + size["+r+"] ("+(e[r]+n[r])+") would overflow input.shape["+r+"] ("+t.shape[r]+")"})},i=0;i0&&(e=e.sum(a)),e.reshape(r.shape)}}})}}),Cl=Ze({relu_:function(t){var e=Ve(t,"x","relu");return"bool"===e.dtype?e.toInt():kt.runKernel(function(t,n){var r=t.relu(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.mulStrict(n.step().toFloat())}}})}}),El=Ze({selu_:function(t){var e=Ve(t,"x","selu");return kt.runKernel(function(t,n){var r=t.selu(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){var e=n.greater(an(0)),r=an(wo),i=an(No),a=t.mul(i),o=t.mul(r).mul(n.toFloat().exp());return js(e,a,o)}}})}}),Sl=Ze({transpose_:function(t,e){var n=Ve(t,"x","transpose");return null==e&&(e=n.shape.map(function(t,e){return e}).reverse()),f(n.rank===e.length,function(){return"Error in transpose: rank of input "+n.rank+" must match length of perm "+e+"."}),e.forEach(function(t){f(t>=0&&ti)throw new Error("'k' passed to topk() must be <= the last dimension ("+i+") but got "+e);var a=kt.runKernel(function(t){return t.topk(r,e,n)},{$x:r});return{values:a[0],indices:a[1]}}}),_l=Ze({scatterND_:function(t,e,n){var r=Ve(t,"indices","scatterND","int32"),i=Ve(e,"updates","scatterND");return function(t,e,n){if(e.rank<1)throw new Error("tf.scatterND() expects the indices to be rank 1 or higher, but the rank was "+e.rank+".");if(t.rank<1)throw new Error("tf.scatterND() expects the updates to be rank 1 or higher, but the rank was "+t.rank+".");if("int32"!==e.dtype)throw new Error("The dtype of 'indices' should be int32, but got dtype: "+e.dtype);if(n.length<1)throw new Error("Output rank must be greater or equal to 1, but got shape: "+n);if(0===n.length){if(0===e.size)throw new Error("Indices specified for empty output. indices shape: "+e.shape);if(0===t.size)throw new Error("Updates specified for empty output. updates shape: "+t.shape)}!function(t,e,n){var r=e.rank>1?e.shape[e.rank-1]:1,i=e.rank>1?e.rank-1:1,a="Must have updates.shape = indices.shape[:batchDim] + shape[sliceDim:], got updates.shape: "+n.shape+", indices.shape: "+e.shape+", shape: "+t+", sliceDim: "+r+", and batchDim: "+i+".";if(n.rankr){var s=t.shape.map(function(t){return t});s[t.shape.length-1]=e-r,n=t.concat(fn(s),t.shape.length-1),r=e}else n=t;var u=n.zerosLike(),l=Qe(n,u).as2D(i,r),c=Fl(l),p=Math.floor(r/2)+1,h=tn(c),d=en(c),m=h.split([p,r-p],h.shape.length-1),g=d.split([p,r-p],d.shape.length-1),v=n.shape.slice();return v[n.shape.length-1]=p,Qe(m[0],g[0]).reshape(v)}}),Ll=Ze({irfft_:function(t){var e=t.shape[t.shape.length-1],n=t.size/e;if(e<=2){var r=t.as2D(n,e),i=Ml(r);return tn(i)}var a=[n,2*(e-1)],o=tn(t).as2D(n,e),s=en(t).as2D(n,e),u=o.slice([0,1],[n,e-2]).reverse(1),l=s.slice([0,1],[n,e-2]).reverse(1).mul(an(-1)),c=o.concat(u,1),p=s.concat(l,1);return r=Qe(c,p).as2D(a[0],a[1]),i=Ml(r),tn(i)}}),Pl=Object.freeze({fft:Fl,ifft:Ml,rfft:zl,irfft:Ll}),Bl=Ze({sparseToDense_:function(t,e,n,r){void 0===r&&(r=0);var i=Ve(t,"sparseIndices","sparseToDense","int32"),a=Ve(e,"sparseValues","sparseToDense"),o=Ve(r,"defaultValue","sparseToDense",a.dtype);return function(t,e,n,r){if("int32"!==t.dtype)throw new Error("tf.sparseToDense() expects the indices to be int32 type, but the dtype was "+t.dtype+".");if(t.rank>2)throw new Error("sparseIndices should be a scalar, vector, or matrix, but got shape "+t.shape+".");var i=t.rank>0?t.shape[0]:1,a=t.rank>1?t.shape[1]:1;if(n.length!==a)throw new Error("outputShape has incorrect number of elements:, "+n.length+", should be: "+a+".");var o=e.size;if(0!==e.rank&&(1!==e.rank||o!==i))throw new Error("sparseValues has incorrect shape "+e.shape+", should be [] or ["+i+"]");if(e.dtype!==r.dtype)throw new Error("sparseValues.dtype must match defaultValues.dtype")}(i,a,n,o),kt.runKernel(function(t){return t.sparseToDense(i,a,n,o)},{$sparseIndices:i,$sparseValues:a,$defaultValue:o})}}),Vl=Ze({gatherND_:function(t,e){var n=Ve(e,"indices","gatherND","int32"),r=Ve(t,"x","gatherND");return kt.runKernel(function(t){return t.gatherND(r,n)},{$x:r,$indices:n})}}),Wl=Ze({diag_:function(t){var e=Ve(t,"x","diag").flatten(),n=t.shape.concat(t.shape);return kt.runKernel(function(t){return t.diag(e)},{$x:e}).reshape(n)}}),Ul=Ze({dropout_:function(t,e,n,r){var i=Ve(t,"x","dropout");if(f("float32"===i.dtype,function(){return"x has to be a floating point tensor since it's going to be scaled, but got a "+i.dtype+" tensor instead."}),f(e>=0&&e<1,function(){return"rate must be a float in the range [0, 1), but got "+e+"."}),0===e)return t instanceof lt?i.clone():i;var a=function(t,e){if(null==e)return t.shape.slice();if(y(t.shape,e))return e;if(t.shape.length===e.length){for(var n=[],r=0;r1,function(){return"inTopK() expects the predictions to be of rank 2 or higher, but got "+r.rank}),f(r.rank-1===a.rank,function(){return"predictions rank should be 1 larger than targets rank, but got predictions rank "+r.rank+" and targets rank "+a.rank}),d(r.shape.slice(0,r.shape.length-1),a.shape,"predictions's shape should be align with the targets' shape, except the last dimension."),o=r.shape[r.shape.length-1],f(n>0&&n<=o,function(){return"'k' passed to inTopK() must be > 0 && <= the predictions last dimension ("+o+"), but got "+n}),[4,r.data()];case 1:return s=i.sent(),[4,a.data()];case 2:for(u=i.sent(),l=[s.length/o,o],p=l[1],h=I("bool",c=l[0]),m=0;m1?u.div(an(s)):u}if(r===t.Reduction.SUM_BY_NONZERO_WEIGHTS){if(null==a)return o.sum().div(an(i.size));var l=a.mul(hn(i.shape)).notEqual(an(0)).sum().toFloat();return o.sum().div(l)}throw Error("Unknown reduction: "+r)}}),Zl=Ze({cosineDistance_:function(e,n,r,i,a){void 0===a&&(a=t.Reduction.SUM_BY_NONZERO_WEIGHTS);var o=Ve(e,"labels","cosineDistance"),s=Ve(n,"predictions","cosineDistance"),u=null;null!=i&&(u=Ve(i,"weights","cosineDistance")),d(o.shape,s.shape,"Error in cosineDistance: ");var l=an(1).sub(o.mul(s).sum(r,!0));return Jl(l,u,a)}}),Ql=Ze({hingeLoss_:function(e,n,r,i){void 0===i&&(i=t.Reduction.SUM_BY_NONZERO_WEIGHTS);var a=Ve(e,"labels","hingeLoss"),o=Ve(n,"predictions","hingeLoss"),s=null;null!=r&&(s=Ve(r,"weights","hingeLoss")),d(a.shape,o.shape,"Error in hingeLoss: ");var u=an(1);a=an(2).mul(a).sub(u);var l=u.sub(a.mul(o)).relu();return Jl(l,s,i)}}),tc=Ze({huberLoss_:function(e,n,r,i,a){void 0===i&&(i=1),void 0===a&&(a=t.Reduction.SUM_BY_NONZERO_WEIGHTS);var o=Ve(e,"labels","huberLoss"),s=Ve(n,"predictions","huberLoss"),u=null;null!=r&&(u=Ve(r,"weights","huberLoss")),d(o.shape,s.shape,"Error in huberLoss: ");var l=an(i),c=s.sub(o).abs(),p=tu(c,l),h=c.sub(p),f=an(.5).mul(p.square()).add(l.mul(h));return Jl(f,u,a)}}),ec=Ze({logLoss_:function(e,n,r,i,a){void 0===i&&(i=1e-7),void 0===a&&(a=t.Reduction.SUM_BY_NONZERO_WEIGHTS);var o=Ve(e,"labels","logLoss"),s=Ve(n,"predictions","logLoss"),u=null;null!=r&&(u=Ve(r,"weights","logLoss")),d(o.shape,s.shape,"Error in logLoss: ");var l=an(1),c=an(i),p=o.mul(s.add(c).log()).neg().sub(l.sub(o).mul(l.sub(s).add(c).log()));return Jl(p,u,a)}}),nc=Ze({meanSquaredError_:function(e,n,r,i){void 0===i&&(i=t.Reduction.SUM_BY_NONZERO_WEIGHTS);var a=Ve(e,"labels","meanSquaredError"),o=Ve(n,"predictions","meanSquaredError"),s=null;null!=r&&(s=Ve(r,"weights","meanSquaredError")),d(a.shape,o.shape,"Error in meanSquaredError: ");var u=a.squaredDifference(o);return Jl(u,s,i)}}),rc=Ze({sigmoidCrossEntropy_:function(e,n,r,i,a){void 0===i&&(i=0),void 0===a&&(a=t.Reduction.SUM_BY_NONZERO_WEIGHTS);var o=Ve(e,"multiClassLabels","sigmoidCrossEntropy"),s=Ve(n,"logits","sigmoidCrossEntropy"),u=null;if(null!=r&&(u=Ve(r,"weights","sigmoidCrossEntropy")),d(o.shape,s.shape,"Error in sigmoidCrossEntropy: "),i>0){var l=an(i),c=an(1),p=an(.5);o=o.mul(c.sub(l)).add(p.mul(l))}var h=function(t,e){var n=Ve(t,"labels","sigmoidCrossEntropyWithLogits"),r=Ve(e,"logits","sigmoidCrossEntropyWithLogits");d(n.shape,r.shape,"Error in sigmoidCrossEntropyWithLogits: ");var i=r.relu(),a=r.mul(n),o=r.abs().neg().exp().log1p();return i.sub(a).add(o)}(o,s);return Jl(h,u,a)}}),ic=Ze({softmaxCrossEntropy_:function(e,n,r,i,a){void 0===i&&(i=0),void 0===a&&(a=t.Reduction.SUM_BY_NONZERO_WEIGHTS);var o=Ve(e,"onehotLabels","softmaxCrossEntropy"),s=Ve(n,"logits","softmaxCrossEntropy"),u=null;if(null!=r&&(u=Ve(r,"weights","softmaxCrossEntropy")),d(o.shape,s.shape,"Error in softmaxCrossEntropy: "),i>0){var l=an(i),c=an(1),p=an(o.shape[1]);o=o.mul(c.sub(l)).add(l.div(p))}var h=function(t,e,n){if(void 0===n&&(n=-1),-1===n&&(n=e.rank-1),n!==e.rank-1)throw Error("Softmax cross entropy along a non-last dimension is not yet supported. Labels / logits was rank "+e.rank+" and dim was "+n);return Ir(function(t,e,r){var i=e.logSumExp([n],!0),a=e.toFloat().sub(i);return r([t,a]),{value:a.mul(t).neg().sum([n]),gradFunc:function(t,e){var r=e[0],i=e[1],a=He(t.shape,[n]);return[t.reshape(a).mul(r.toFloat().sub(i.exp())),t.reshape(a).mul(i.exp().sub(r.toFloat()))]}}})(t,e)}(o,s);return Jl(h,u,a)}}),ac=Object.freeze({get Reduction(){return t.Reduction},absoluteDifference:Yl,computeWeightedLoss:Jl,cosineDistance:Zl,hingeLoss:Ql,huberLoss:tc,logLoss:ec,meanSquaredError:nc,sigmoidCrossEntropy:rc,softmaxCrossEntropy:ic});function oc(t,e){return void 0===e&&(e=!1),kt.tidy(function(){if(2!==t.shape.length)throw new Error("qr2d() requires a 2D Tensor, but got a "+t.shape.length+"D Tensor.");for(var n=t.shape[0],r=t.shape[1],i=Hn(n),a=t.clone(),o=sn([[1]],[1,1]),s=o.clone(),u=n>=r?r:n,l=function(t){var e,u=a,l=s,c=i;e=kt.tidy(function(){var e=a.slice([t,t],[n-t,1]),u=e.norm(),l=a.slice([t,t],[1,1]),c=sn([[-1]]).where(l.greater(0),sn([[1]])),p=l.sub(c.mul(u)),h=e.div(p);s=1===h.shape[0]?o.clone():o.concat(h.slice([1,0],[h.shape[0]-1,h.shape[1]]),0);var f=c.matMul(p).div(u).neg(),d=a.slice([t,0],[n-t,r]),m=f.mul(s);if(0===t)a=d.sub(m.matMul(s.transpose().matMul(d)));else{var g=d.sub(m.matMul(s.transpose().matMul(d)));a=a.slice([0,0],[t,r]).concat(g,0)}var v=i.slice([0,t],[n,i.shape[1]-t]);if(0===t)i=v.sub(v.matMul(s).matMul(m.transpose()));else{var y=v.sub(v.matMul(s).matMul(m.transpose()));i=i.slice([0,0],[n,t]).concat(y,1)}return[s,a,i]}),s=e[0],a=e[1],i=e[2],Fe([u,l,c])},c=0;cr&&(i=i.slice([0,0],[n,r]),a=a.slice([0,0],[r,r])),[i,a]})}var sc=Ze({gramSchmidt_:function(t){var e;if(Array.isArray(t)){e=!1,f(null!=t&&t.length>0,function(){return"Gram-Schmidt process: input must not be null, undefined, or empty"});for(var n=t[0].shape[0],r=function(e){f(t[e].shape[0]===n,function(){return"Gram-Schmidt: Non-unique lengths found in the input vectors: ("+t[e].shape[0]+" vs. "+n+")"})},i=1;i0)for(var n=0;n= 2, but got rank "+t.rank);if(2===t.rank)return oc(t,e);var n=t.shape.slice(0,t.shape.length-2).reduce(function(t,e){return t*e}),r=[],i=[];return lr(t.reshape([n,t.shape[t.shape.length-2],t.shape[t.shape.length-1]]),0).forEach(function(t){var n=oc(t,e),a=n[0],o=n[1];r.push(a),i.push(o)}),[or(r,0).reshape(t.shape),or(i,0).reshape(t.shape)]}}),lc=Object.freeze({gramSchmidt:sc,qr:uc});function cc(t,e,n,r,i){null==r&&(r=.5),null==i&&(i=Number.NEGATIVE_INFINITY);var a=t.shape[0];return n=Math.min(n,a),f(0<=r&&r<=1,function(){return"iouThreshold must be in [0, 1], but was '"+r+"'"}),f(2===t.rank,function(){return"boxes must be a 2D tensor, but was of rank '"+t.rank+"'"}),f(4===t.shape[1],function(){return"boxes must have 4 columns, but 2nd dimension was "+t.shape[1]}),f(1===e.rank,function(){return"scores must be a 1D tensor"}),f(e.shape[0]===a,function(){return"scores has incompatible shape with boxes. Expected "+a+", but was "+e.shape[0]}),{maxOutputSize:n,iouThreshold:r,scoreThreshold:i}}var pc=Ze({resizeBilinear_:function(t,e,n){void 0===n&&(n=!1);var r=Ve(t,"images","resizeBilinear");f(3===r.rank||4===r.rank,function(){return"Error in resizeBilinear: x must be rank 3 or 4, but got rank "+r.rank+"."}),f(2===e.length,function(){return"Error in resizeBilinear: new shape must 2D, but got shape "+e+"."});var i=r,a=!1;3===r.rank&&(a=!0,i=r.as4D(1,r.shape[0],r.shape[1],r.shape[2]));var o=e[0],s=e[1],u=kt.runKernel(function(t,e){return e([i]),t.resizeBilinear(i,o,s,n)},{batchImages:i},function(t,e){return{batchImages:function(){return kt.runKernel(function(r){return r.resizeBilinearBackprop(t,e[0],n)},{})}}});return a?u.as3D(u.shape[1],u.shape[2],u.shape[3]):u}}),hc=Ze({resizeNearestNeighbor_:function(t,e,n){void 0===n&&(n=!1);var r=Ve(t,"images","resizeNearestNeighbor");f(3===r.rank||4===r.rank,function(){return"Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank "+r.rank+"."}),f(2===e.length,function(){return"Error in resizeNearestNeighbor: new shape must 2D, but got shape "+e+"."}),f("float32"===r.dtype||"int32"===r.dtype,function(){return"`images` must have `int32` or `float32` as dtype"});var i=r,a=!1;3===r.rank&&(a=!0,i=r.as4D(1,r.shape[0],r.shape[1],r.shape[2]));var o=e[0],s=e[1],u=kt.runKernel(function(t,e){return e([i]),t.resizeNearestNeighbor(i,o,s,n)},{batchImages:i},function(t,e){return{batchImages:function(){return kt.runKernel(function(r){return r.resizeNearestNeighborBackprop(t,e[0],n)},{})}}});return a?u.as3D(u.shape[1],u.shape[2],u.shape[3]):u}}),fc=Ze({nonMaxSuppression_:function(t,e,n,r,i){void 0===r&&(r=.5),void 0===i&&(i=Number.NEGATIVE_INFINITY);var a=Ve(t,"boxes","nonMaxSuppression"),o=Ve(e,"scores","nonMaxSuppression"),s=cc(a,o,n,r,i);return n=s.maxOutputSize,r=s.iouThreshold,i=s.scoreThreshold,kt.runKernel(function(t){return t.nonMaxSuppression(a,o,n,r,i)},{$boxes:a})}}),dc=Ze({cropAndResize_:function(t,e,n,r,i,a){var o=Ve(t,"image","cropAndResize","float32"),s=Ve(e,"boxes","cropAndResize","float32"),u=Ve(n,"boxInd","cropAndResize","int32");i=i||"bilinear",a=a||0;var l=s.shape[0];return f(4===o.rank,function(){return"Error in cropAndResize: image must be rank 4,but got rank "+o.rank+"."}),f(2===s.rank&&4===s.shape[1],function(){return"Error in cropAndResize: boxes must be have size ["+l+",4] but had shape "+s.shape+"."}),f(1===u.rank&&u.shape[0]===l,function(){return"Error in cropAndResize: boxInd must be have size ["+l+"] but had shape "+s.shape+"."}),f(2===r.length,function(){return"Error in cropAndResize: cropSize must be of length 2, but got length "+r.length+"."}),f(r[0]>=1&&r[1]>=1,function(){return"cropSize must be atleast [1,1], but was "+r}),f("bilinear"===i||"nearest"===i,function(){return"method must be bilinear or nearest, but was "+i}),kt.runKernel(function(t,e){return t.cropAndResize(o,s,u,r,i,a)},{$image:o,$boxes:s})}}),mc=Object.freeze({resizeBilinear:pc,resizeNearestNeighbor:hc,nonMaxSuppression:fc,nonMaxSuppressionAsync:function(t,e,n,a,o){return void 0===a&&(a=.5),void 0===o&&(o=Number.NEGATIVE_INFINITY),r(this,void 0,void 0,function(){var r,s,u,l,c,p,h;return i(this,function(i){switch(i.label){case 0:return r=Ve(t,"boxes","nonMaxSuppressionAsync"),s=Ve(e,"scores","nonMaxSuppressionAsync"),u=cc(r,s,n,a,o),n=u.maxOutputSize,a=u.iouThreshold,o=u.scoreThreshold,[4,Promise.all([r.data(),s.data()])];case 1:return l=i.sent(),c=l[0],p=l[1],h=ni(c,p,n,a,o),r!==t&&r.dispose(),s!==e&&s.dispose(),[2,h]}})})},cropAndResize:dc}),gc=Ze({matMul_:function(t){var e,n=t.a,r=t.b,i=t.transposeA,a=void 0!==i&&i,o=t.transposeB,s=void 0!==o&&o,u=t.bias,l=t.activation,c=void 0===l?"linear":l,p=t.preluActivationWeights,h=Ve(n,"a","fused matMul"),d=Ve(r,"b","fused matMul");e=bt(h,d),h=e[0],d=e[1];var m=a?h.shape[h.rank-2]:h.shape[h.rank-1],g=s?d.shape[d.rank-1]:d.shape[d.rank-2],b=a?h.shape[h.rank-1]:h.shape[h.rank-2],x=s?d.shape[d.rank-2]:d.shape[d.rank-1],w=h.shape.slice(0,-2),N=d.shape.slice(0,-2),C=v(w),E=v(N);f(h.rank>=2&&d.rank>=2&&h.rank===d.rank,function(){return"Error in fused matMul: inputs must have the same rank of at least 2, got ranks "+h.rank+" and "+d.rank+"."}),f(y(w,N),function(){return"Error in fused matMul: outer dimensions ("+w+") and ("+N+") of Tensors with shapes "+h.shape+" and "+d.shape+" must match."}),f(m===g,function(){return"Error in fused matMul: inner shapes ("+m+") and ("+g+") of Tensors with shapes "+h.shape+" and "+d.shape+" and transposeA="+a+" and transposeB="+s+" must match."});var S,k,I=h.shape.slice(0,-2).concat([b,x]),A=a?h.as3D(C,m,b):h.as3D(C,b,m),R=s?d.as3D(E,x,g):d.as3D(E,g,x);null!=u&&Mr(I,(S=bt(S=Ve(u,"bias","fused matMul"),h)[0]).shape),null!=p&&(k=Ve(p,"prelu weights","fused matMul"));var T={$a:A,$b:R};return null!=u&&(T.$bias=S),null!=p&&(T.$preluActivationWeights=k),kt.runKernel(function(t,e){var n=t.fusedBatchMatMul({a:A,b:R,transposeA:a,transposeB:s,bias:S,activation:c,preluActivationWeights:k});return e([A,R,n]),n},T,function(t,e){var n,r=e[0],i=e[1],o=e[2];if(null==c||"linear"===c)n=t;else{if("relu"!==c)throw new Error("Gradient for activation "+c+" has not been implemented yet.");n=t.mul(o.step())}var l={};return null!=u&&(l={$bias:function(){var t=n,e=Fr(S.shape,n.shape);return e.length>0&&(t=t.sum(e)),t.reshape(S.shape)}}),a||s?!a&&s?Object.assign({$a:function(){return n.matMul(i,!1,!1)},$b:function(){return n.matMul(r,!0,!1)}},l):a&&!s?Object.assign({$a:function(){return i.matMul(n,!1,!0)},$b:function(){return r.matMul(n,!1,!1)}},l):Object.assign({$a:function(){return i.matMul(n,!0,!0)},$b:function(){return n.matMul(r,!0,!0)}},l):Object.assign({$a:function(){return n.matMul(i,!1,!0)},$b:function(){return r.matMul(n,!0,!1)}},l)}).reshape(I)}}),vc=Ze({conv2d_:function(t){var e=t.x,n=t.filter,r=t.strides,i=t.pad,a=t.dataFormat,o=void 0===a?"NHWC":a,s=t.dilations,u=void 0===s?[1,1]:s,l=t.dimRoundingMode,c=t.bias,p=t.activation,h=void 0===p?"linear":p,d=t.preluActivationWeights,m=Ve(e,"x","conv2d"),g=Ve(n,"filter","conv2d"),v=m,y=!1;3===m.rank&&(y=!0,v=m.as4D(1,m.shape[0],m.shape[1],m.shape[2])),f(4===v.rank,function(){return"Error in fused conv2d: input must be rank 4, but got rank "+v.rank+"."}),f(4===g.rank,function(){return"Error in fused conv2d: filter must be rank 4, but got rank "+g.rank+"."}),null!=l&&f(b(i),function(){return"Error in fused conv2d: pad must be an integer when using, dimRoundingMode "+l+" but got pad "+i+"."}),f(v.shape[3]===g.shape[2],function(){return"Error in conv2d: depth of input ("+v.shape[3]+") must match input depth for filter "+g.shape[2]+"."}),f(qr(r,u),function(){return"Error in conv2D: Either strides or dilations must be 1. Got strides "+r+" and dilations '"+u+"'"}),f("NHWC"===o,function(){return"Error in conv2d: got dataFormat of "+o+" but only NHWC is currently supported."});var x,w,N=Pr(v.shape,g.shape,r,u,i,l);null!=c&&(x=bt(x=Ve(c,"bias","fused conv2d"),m)[0],Mr(N.outShape,x.shape)),null!=d&&(w=Ve(d,"prelu weights","fused conv2d"));var C={x:v,$filter:g};null!=c&&(C.$bias=x),null!=d&&(C.$preluActivationWeights=w);var E=kt.runKernel(function(t,e){var n=t.fusedConv2d(v,g,N,x,h,w);return e([g,v,n]),n},C,function(t,e){var n,a=e,o=a[0],s=a[1],l=a[2];if(null==h||"linear"===h)n=t;else{if("relu"!==h)throw new Error("Gradient for activation "+h+" has not been implemented yet.");n=t.mul(l.step())}f(Hr(u),function(){return"Error in gradient of fused conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '"+u+"'"});var p={};return null!=c&&(p={$bias:function(){var t=n,e=Fr(x.shape,n.shape);return e.length>0&&(t=t.sum(e)),t.reshape(x.shape)}}),Object.assign({x:function(){return Lu(s.shape,n,o,r,i)},$filter:function(){return zu(s,n,o.shape,r,i)}},p)});return y?E.as3D(E.shape[1],E.shape[2],E.shape[3]):E}}),yc=Object.freeze({matMul:gc,conv2d:vc}),bc=Object.freeze({image:mc,linalg:lc,losses:ac,spectral:Pl,fused:yc,signal:$l,op:Ze,batchNormalization2d:Ds,batchNormalization3d:Os,batchNormalization4d:_s,batchNormalization:Fs,batchNorm:Ms,batchNorm2d:zs,batchNorm3d:Ls,batchNorm4d:Ps,booleanMaskAsync:Au,complex:Qe,real:tn,imag:en,concat:bn,concat1d:xn,concat2d:wn,concat3d:Nn,concat4d:Cn,split:En,conv1d:_u,conv2d:Fu,conv3d:Mu,conv2dDerFilter:zu,conv2dDerInput:Lu,depthwiseConv2d:Pu,separableConv2d:Bu,conv2dTranspose:Vu,conv3dTranspose:Wu,matMul:Uu,dot:ju,outerProduct:Gu,reverse:Hu,reverse1d:qu,reverse2d:Ku,reverse3d:$u,reverse4d:Xu,maxPool:Zu,avgPool:Qu,pool:tl,maxPool3d:el,avgPool3d:nl,slice:rl,slice1d:il,slice2d:al,slice3d:ol,slice4d:sl,abs:Go,acos:Ho,acosh:qo,asin:Ko,asinh:$o,atan:Xo,atanh:Yo,ceil:Jo,clipByValue:Zo,cos:Qo,cosh:ts,erf:es,exp:ns,expm1:rs,floor:is,log:as,log1p:os,logSigmoid:ss,neg:us,reciprocal:ls,round:cs,rsqrt:ps,sigmoid:hs,sign:fs,isNaN:ds,isInf:ms,isFinite:gs,sin:vs,sinh:ys,softplus:bs,sqrt:xs,square:ws,step:Ns,tan:Cs,tanh:Es,all:ll,any:cl,argMax:pl,argMin:hl,logSumExp:fl,max:dl,mean:ml,min:gl,moments:vl,sum:yl,prod:bl,equal:hu,equalStrict:fu,greater:du,greaterEqual:mu,greaterEqualStrict:gu,greaterStrict:vu,less:yu,lessEqual:bu,lessEqualStrict:xu,lessStrict:wu,notEqual:Nu,notEqualStrict:Cu,add:Hs,addN:qs,addStrict:Ks,atan2:$s,div:Xs,divStrict:Ys,floorDiv:Js,maximum:Zs,maximumStrict:Qs,minimum:tu,minimumStrict:eu,mod:nu,modStrict:ru,mul:iu,mulStrict:au,pow:ou,powStrict:su,squaredDifference:uu,squaredDifferenceStrict:lu,sub:cu,subStrict:pu,elu:xl,leakyRelu:wl,prelu:Nl,relu:Cl,selu:El,logicalAnd:Bs,logicalNot:Vs,logicalOr:Ws,logicalXor:Us,where:js,whereAsync:Gs,buffer:Ln,print:Pn,batchToSpaceND:Bn,cast:Vn,clone:Wn,cumsum:Un,depthToSpace:jn,expandDims:Gn,eye:Hn,multinomial:qn,oneHot:Kn,pad:$n,pad1d:Xn,pad2d:Yn,pad3d:Jn,pad4d:Zn,rand:Qn,randomNormal:tr,randomGamma:er,randomUniform:nr,reshape:rr,spaceToBatchND:ir,squeeze:ar,stack:or,tile:sr,truncatedNormal:ur,unstack:lr,setdiff1dAsync:cr,fill:dn,linspace:mn,ones:hn,range:gn,scalar:an,tensor:nn,tensor1d:on,tensor2d:sn,tensor3d:un,tensor4d:ln,tensor5d:cn,tensor6d:pn,zeros:fn,onesLike:vn,zerosLike:yn,transpose:Sl,softmax:Rr,logSoftmax:Tr,localResponseNormalization:kl,norm:Il,gather:ku,unsortedSegmentSum:Iu,basicLSTMCell:Al,multiRNNCell:Rl,movingAverage:Tl,stridedSlice:Dl,topk:Ol,scatterND:_l,fft:Fl,ifft:Ml,rfft:zl,irfft:Ll,sparseToDense:Bl,gatherND:Vl,diag:Wl,dropout:Ul,hannWindow:Gl,hammingWindow:Hl,frame:ql,stft:Kl,inTopKAsync:Xl});function xc(t,e,n,r){if("linear"===n)return t.linear(e);if("relu"===n)return t.relu(e);if("elu"===n)return t.elu(e);if("prelu"===n)return t.prelu(e,r);throw new Error("Activation "+n+" has not been implemented for the CPU backend.")}var wc=function(){function e(){if(this.blockSize=48,this.firstUse=!0,t.ENV.get("IS_BROWSER")){var e="undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(300,150):"undefined"!=typeof document?document.createElement("canvas"):null;null!==e&&(this.fromPixels2DContext=e.getContext("2d"))}this.data=new Dr(this,kt)}return e.prototype.register=function(e,n,r){if(this.firstUse&&(this.firstUse=!1,t.ENV.get("IS_NODE")&&Le("\n============================\nHi there 👋. Looks like you are running TensorFlow.js in Node.js. To speed things up dramatically, install our node backend, which binds to TensorFlow C++, by running npm i @tensorflow/tfjs-node, or npm i @tensorflow/tfjs-node-gpu if you have CUDA. Then call require('@tensorflow/tfjs-node'); (-gpu suffix for CUDA) at the start of your program. Visit https://github.com/tensorflow/tfjs-node for more details.\n============================\n")),this.data.has(e))throw new Error("Data buffer is already registered");this.data.set(e,{dtype:r})},e.prototype.write=function(t,e){if(null==e)throw new Error("MathBackendCPU.write(): values can not be null");this.data.get(t).values=e},e.prototype.fromPixels=function(e,n){if(null==e)throw new Error("pixels passed to tf.browser.fromPixels() can not be null");var r,i,a=e.data instanceof Uint8Array,o="undefined"!=typeof ImageData&&e instanceof ImageData,s="undefined"!=typeof HTMLVideoElement&&e instanceof HTMLVideoElement,u="undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement,l=s?[e.videoWidth,e.videoHeight]:[e.width,e.height],c=l[0],p=l[1];if(t.ENV.get("IS_NODE")&&null==e.getContext)throw new Error("When running in node, pixels must be an HTMLCanvasElement like the one returned by the `canvas` npm package");if(null!=e.getContext)r=e.getContext("2d").getImageData(0,0,c,p).data;else if(o||a)r=e.data;else{if(!u&&!s)throw new Error("pixels passed to tf.browser.fromPixels() must be either an HTMLVideoElement, HTMLImageElement, HTMLCanvasElement, ImageData or {data: Uint32Array, width: number, height: number}, but was "+e.constructor.name);if(null==this.fromPixels2DContext)throw new Error("Can't read pixels from HTMLImageElement outside the browser.");this.fromPixels2DContext.canvas.width=c,this.fromPixels2DContext.canvas.height=p,this.fromPixels2DContext.drawImage(e,0,0,c,p),r=this.fromPixels2DContext.getImageData(0,0,c,p).data}if(4===n)i=new Int32Array(r);else{var h=c*p;i=new Int32Array(h*n);for(var f=0;fh&&(h=m,f=d)}u[c]=f}return o},e.prototype.cumsum=function(t,e,n,r){if(this.assertNotComplex(t,"cumsum"),e!==t.rank-1)throw new Error("backend.cumsum in CPU expects an inner-most axis="+(t.rank-1)+" but got axis="+e);for(var i=vt(t.dtype,"int32"),a=fn(t.shape,i),o=this.readSync(a.dataId),s=this.readSync(t.dataId),u=t.shape[t.rank-1],l=r?function(t,e){return t+u-e-1}:function(t,e){return t+e},c=0;ce?1:0})},e.prototype.greaterEqual=function(t,e){return this.assertNotComplex([t,e],"greaterEqual"),this.broadcastedBinaryOp(t,e,"bool",function(t,e){return t>=e?1:0})},e.prototype.logicalNot=function(t){this.assertNotComplex(t,"logicalNot");for(var e=this.readSync(t.dataId),n=new Uint8Array(e.length),r=0;r1||1===e.rank?1:e.shape[1],c=0;c=0&&e>=0?n:(n+e)%e})},e.prototype.max=function(t,e){this.assertNotComplex(t,"max"),qe("max",e,t.rank);for(var n=Ge(t.shape,e),r=n[0],i=n[1],a=fn(r,t.dtype),o=v(i),s=this.readSync(a.dataId),u=this.readSync(t.dataId),l=0;lp&&(p=f)}s[l]=p}return a},e.prototype.maximum=function(t,e){return this.assertNotComplex([t,e],"maximum"),this.broadcastedBinaryOp(t,e,t.dtype,function(t,e){return Math.max(t,e)})},e.prototype.all=function(t,e){this.assertNotComplex(t,"all"),qe("all",e,t.rank);for(var n=Ge(t.shape,e),r=n[0],i=n[1],a=fn(r,t.dtype),o=v(i),s=this.readSync(a.dataId),u=this.readSync(t.dataId),l=0;l0?n[r]=1:n[r]=0;return lt.make(t.shape,{values:n})},e.prototype.isNaN=function(t){this.assertNotComplex(t,"x");for(var e=this.readSync(t.dataId),n=new Uint8Array(e.length),r=0;r.5?n[r]=Math.ceil(e[r]):n[r]=i%2==0?i:i+1}return lt.make(t.shape,{values:n})},e.prototype.exp=function(t){this.assertNotComplex(t,"exp");for(var e=this.readSync(t.dataId),n=new Float32Array(e.length),r=0;r=0?i:Math.exp(i)-1}return lt.make(t.shape,{values:e})},e.prototype.eluDer=function(t,e){this.assertNotComplex([t,e],"eluDer");for(var n=new Float32Array(e.size),r=this.readSync(e.dataId),i=this.readSync(t.dataId),a=0;a=1?i[a]:i[a]*(o+1)}return lt.make(e.shape,{values:n})},e.prototype.selu=function(t){this.assertNotComplex(t,"selu");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r=0?1.0507009873554805*i:1.7580993408473768*(Math.exp(i)-1)}return lt.make(t.shape,{values:e})},e.prototype.clip=function(t,e,n){this.assertNotComplex(t,"clip");for(var r=new Float32Array(t.size),i=this.readSync(t.dataId),a=0;an?n:o-e,s=r[i]0?1:e}return lt.make(t.shape,{values:n})},e.prototype.fusedConv2d=function(t,e,n,r,i,a){var o=this.conv2d(t,e,n);return r&&(o=this.add(o,r)),i&&(o=xc(this,o,i,a)),o},e.prototype.conv2d=function(t,e,n){this.assertNotComplex([t,e],"conv2d");for(var r=n.filterHeight,i=n.filterWidth,a=n.dilationHeight,o=n.dilationWidth,s=n.padInfo.left,u=n.padInfo.top,l="channelsLast"===n.dataFormat,c=Ln(n.outShape,t.dtype),p=t.strides[0],h=l?t.strides[1]:t.strides[2],f=l?t.strides[2]:1,d=l?1:t.strides[1],m=c.strides[0],g=l?c.strides[1]:c.strides[2],v=l?c.strides[2]:1,y=l?1:c.strides[1],b=this.readSync(t.dataId),x=this.readSync(e.dataId),w=c.values,N=0;N=n.inHeight))for(var T=A*e.strides[0],D=C+R*h,O=0;O=n.inWidth))for(var L=D+z*f,P=T+M*e.strides[1],B=0;B=n.inDepth))for(var E=N*e.strides[0],S=v+C*t.strides[1],k=0;k=n.inHeight))for(var D=E+R*e.strides[1],O=S+T*t.strides[2],_=0;_=n.inWidth))for(var P=D+z*e.strides[2],B=O+L*n.inChannels,V=P,W=0;W=n.inHeight))for(var N=x*e.strides[0],C=m+w*t.strides[1],E=0;E=n.inWidth))for(var R=N+I*e.strides[1],T=C+A*n.inChannels,D=S,O=R,_=0;_D?D=L:"avg"===n&&(O+=L,_++)}if(isNaN(D))break}d[k+I*v+w]="avg"===n?O/_:D}return f.toTensor()},e.prototype.maxPool=function(t,e){return this.pool(t,e,"max")},e.prototype.maxPoolPositions=function(t,e){for(var n=Ln(e.outShape,"int32"),r=e.strideHeight,i=e.strideWidth,a=e.dilationHeight,o=e.dilationWidth,s=e.effectiveFilterHeight,u=e.effectiveFilterWidth,l=e.padInfo.top,c=e.padInfo.left,p=this.bufferSync(t),h=0;hN&&(N=A,C=S*u+I)}n.set(C,h,d,y,f)}}return n.toTensor()},e.prototype.maxPoolBackprop=function(t,e,n,r){this.assertNotComplex([e,n],"maxPoolBackprop");for(var i=this.maxPoolPositions(e,r),a=r.strideHeight,o=r.strideWidth,s=r.dilationHeight,u=r.dilationWidth,l=r.effectiveFilterHeight,c=r.effectiveFilterWidth,p=c-1-r.padInfo.left,h=l-1-r.padInfo.top,f=Ln(e.shape,"float32"),d=this.bufferSync(i),m=this.bufferSync(t),g=0;g=r.outHeight||Math.floor(E)!==E))for(var S=0;S=r.outWidth||Math.floor(k)!==k)){var I=l*c-1-d.get(g,E,k,v)===C*c+S?1:0;0!==I&&(N+=m.get(g,E,k,v)*I)}}}f.set(N,g,y,b,v)}return f.toTensor()},e.prototype.avgPoolBackprop=function(t,e,n){this.assertNotComplex([t,e],"avgPoolBackprop");for(var r=n.strideHeight,i=n.strideWidth,a=n.filterHeight,o=n.filterWidth,s=n.dilationHeight,u=n.dilationWidth,l=n.effectiveFilterHeight,c=n.effectiveFilterWidth,p=c-1-n.padInfo.left,h=l-1-n.padInfo.top,f=Ln(e.shape,"float32"),d=1/(a*o),m=this.bufferSync(t),g=0;g=n.outHeight||Math.floor(E)!==E))for(var S=0;S=n.outWidth||Math.floor(k)!==k||(N+=m.get(g,E,k,v))}}f.set(N*d,g,y,b,v)}return f.toTensor()},e.prototype.pool3d=function(t,e,n){this.assertNotComplex(t,"pool3d");for(var r=e.strideDepth,i=e.strideHeight,a=e.strideWidth,o=e.dilationDepth,s=e.dilationHeight,u=e.dilationWidth,l=e.effectiveFilterDepth,c=e.effectiveFilterHeight,p=e.effectiveFilterWidth,h=e.padInfo.front,f=e.padInfo.top,d=e.padInfo.left,m="max"===n?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,g=this.readSync(t.dataId),v=Ln(e.outShape,t.dtype),y=v.values,b=e.outShape[1]*e.outShape[2]*e.outShape[3]*e.outShape[4],x=e.outShape[2]*e.outShape[3]*e.outShape[4],w=e.outShape[3]*e.outShape[4],N=e.outShape[4],C=0;CU?U=Y:"avg"===n&&(j+=Y,G++),isNaN(U))break}if(isNaN(U))break}if(isNaN(U))break}y[W+k]="avg"===n?j/G:U}}}return v.toTensor()},e.prototype.avgPool3d=function(t,e){return this.assertNotComplex(t,"avgPool3d"),this.pool3d(t,e,"avg").toFloat()},e.prototype.avgPool3dBackprop=function(t,e,n){this.assertNotComplex([t,e],"avgPool3dBackprop");for(var r=n.strideDepth,i=n.strideHeight,a=n.strideWidth,o=n.filterDepth,s=n.filterHeight,u=n.filterWidth,l=n.dilationDepth,c=n.dilationHeight,p=n.dilationWidth,h=n.effectiveFilterDepth,f=n.effectiveFilterHeight,d=n.effectiveFilterWidth,m=h-1-n.padInfo.front,g=d-1-n.padInfo.left,v=f-1-n.padInfo.top,y=Ln(e.shape,"float32"),b=1/(o*s*u),x=this.bufferSync(t),w=0;w=n.outDepth||Math.floor(D)!==D))for(var O=0;O=n.outHeight||Math.floor(_)!==_))for(var F=0;F=n.outWidth||Math.floor(M)!==M||(R+=x.get(w,D,_,M,N))}}}y.set(R*b,w,C,E,S,N)}return y.toTensor()},e.prototype.maxPool3d=function(t,e){return this.assertNotComplex(t,"maxPool3d"),this.pool3d(t,e,"max").toFloat()},e.prototype.maxPool3dPositions=function(t,e){for(var n=Ln(e.outShape,"int32"),r=e.strideDepth,i=e.strideHeight,a=e.strideWidth,o=e.dilationDepth,s=e.dilationHeight,u=e.dilationWidth,l=e.effectiveFilterDepth,c=e.effectiveFilterHeight,p=e.effectiveFilterWidth,h=e.padInfo.front,f=e.padInfo.top,d=e.padInfo.left,m=this.bufferSync(t),g=0;g=T&&(T=P,D=_*c*p+M*c+L)}n.set(D,g,y,N,k,v)}}}return n.toTensor()},e.prototype.maxPool3dBackprop=function(t,e,n,r){this.assertNotComplex([e,n],"maxPool3dBackprop");for(var i=this.maxPool3dPositions(e,r),a=r.strideDepth,o=r.strideHeight,s=r.strideWidth,u=r.dilationDepth,l=r.dilationHeight,c=r.dilationWidth,p=r.effectiveFilterDepth,h=r.effectiveFilterHeight,f=r.effectiveFilterWidth,d=p-1-r.padInfo.front,m=f-1-r.padInfo.left,g=h-1-r.padInfo.top,v=Ln(e.shape,"float32"),y=this.bufferSync(i),b=this.bufferSync(t),x=0;x=r.outDepth||Math.floor(T)!==T))for(var D=0;D=r.outHeight||Math.floor(O)!==O))for(var _=0;_=r.outWidth||Math.floor(F)!==F)){var M=p*h*f-1-y.get(x,T,O,F,w)===R*h*f+D*f+_?1:0;0!==M&&(A+=b.get(x,T,O,F,w)*M)}}}}v.set(A,x,N,C,E,w)}return v.toTensor()},e.prototype.cast=function(t,e){return $r(t,e,this)},e.prototype.reshape=function(t,e){return Xr(t,e)},e.prototype.avgPool=function(t,e){return this.assertNotComplex(t,"avgPool"),this.pool(t,e,"avg").toFloat()},e.prototype.resizeBilinear=function(t,e,n,r){this.assertNotComplex(t,"resizeBilinear");for(var i=t.shape,a=i[0],o=i[1],s=i[2],u=i[3],l=this.readSync(t.dataId),c=new Float32Array(v([a,e,n,u])),p=[r&&e>1?o-1:o,r&&n>1?s-1:s],h=[r&&e>1?e-1:e,r&&n>1?n-1:n],f=0,d=p[0]/h[0],m=p[1]/h[1],g=0;g1?a-1:a,n&&c>1?o-1:o],f=[n&&l>1?l-1:l,n&&c>1?c-1:c],d=h[0]/f[0],m=h[1]/f[1],g=this.readSync(t.dataId),v=0,y=0;y1?o-1:o,r&&n>1?s-1:s],h=[r&&e>1?e-1:e,r&&n>1?n-1:n],f=p[0]/h[0],d=p[1]/h[1],m=0,g=0;g1?a-1:a,n&&c>1?o-1:o],d=[n&&l>1?l-1:l,n&&c>1?c-1:c],m=f[0]/d[0],g=f[1]/d[1],v=1/m,y=1/g,b=2*Math.ceil(v)+2,x=2*Math.ceil(y)+2,w=0;w=l)){var M=N+F*t.strides[1],z=F*m;if(C===Math.min(a-1,n?Math.round(z):Math.floor(z)))for(var L=0;L=c)){var B=M+P*t.strides[2],V=P*g;I===Math.min(o-1,n?Math.round(V):Math.floor(V))&&(O+=h[B+D])}}}}p[A+D]=O}return ln(p,e.shape,e.dtype)},e.prototype.batchNormalization=function(t,e,n,r,i,a){this.assertNotComplex([t,e,n,i,a],"batchNorm");for(var o=this.readSync(t.dataId),s=this.readSync(e.dataId),u=this.readSync(n.dataId),l=i?this.readSync(i.dataId):new Float32Array([1]),c=a?this.readSync(a.dataId):new Float32Array([0]),p=new Float32Array(o.length),h=c.length,f=l.length,d=u.length,m=s.length,g=0,v=0,y=0,b=0,x=0;x=h&&(g=0),v>=m&&(v=0),y>=f&&(y=0),b>=d&&(b=0);return ln(p,t.shape)},e.prototype.localResponseNormalization4D=function(t,e,n,r,i){this.assertNotComplex(t,"localResponseNormalization4D");var a=t.shape[3],o=a-1,s=this.readSync(t.dataId),u=t.size,l=new Float32Array(u);function c(t){for(var n=t%a,r=t-n+Math.max(0,n-e),i=t-n+Math.min(n+e,o),u=0;r<=i;r++){var l=s[r];u+=l*l}return u}for(var p=0;p=0&&a[o]1,function(){return"blockSize should be > 1 for depthToSpace, but was: "+e});for(var r=t.shape[0],i=t.shape[1],a=t.shape[2],o=t.shape[3],s=i*e,u=a*e,l=o/(e*e),c=this.readSync(t.dataId),p=new Float32Array(r*s*u*l),h=0,d=0;d=s))for(var I=h>1?(E-N)*(u-1)/(h-1):0,A=f>1?(S-C)*(l-1)/(f-1):0,R=0;R1?N*(u-1)+R*I:.5*(N+E)*(u-1);if(T<0||T>u-1)for(var D=0;D1?C*(l-1)+D*A:.5*(C+S)*(l-1))<0||H>l-1)for(O=0;O1?C*(l-1)+D*A:.5*(C+S)*(l-1))<0||H>l-1)for(O=0;O=t.size/s)throw new Error("Invalid indices: "+f+" does not index into "+t.shape);for(var v=0;v=r/i)throw new Error("Invalid indices: "+m+" does not index into "+n);for(var b=0;b0,function(){return"scheme must not be an empty string."});var r=t.getInstance();f(null==r.managers[e],function(){return"A model store manager is already registered for scheme '"+e+"'."}),r.managers[e]=n},t.getManager=function(t){var e=this.getInstance().managers[t];if(null==e)throw new Error("Cannot find model manager for scheme '"+t+"'");return e},t.getSchemes=function(){return Object.keys(this.getInstance().managers)},t}();function zc(t){if(-1===t.indexOf(Fc))throw new Error("The url string provided does not contain a scheme. Supported schemes are: "+Mc.getSchemes().join(","));return{scheme:t.split(Fc)[0],path:t.split(Fc)[1]}}function Lc(t,e,n){return void 0===n&&(n=!1),r(this,void 0,void 0,function(){var r,a,o,s,u,l,c,p,h;return i(this,function(i){switch(i.label){case 0:return f(t!==e,function(){return"Old path and new path are the same: '"+t+"'"}),f((r=_c.getLoadHandlers(t)).length>0,function(){return"Copying failed because no load handler is found for source URL "+t+"."}),f(r.length<2,function(){return"Copying failed because more than one ("+r.length+") load handlers for source URL "+t+"."}),a=r[0],f((o=_c.getSaveHandlers(e)).length>0,function(){return"Copying failed because no save handler is found for destination URL "+e+"."}),f(o.length<2,function(){return"Copying failed because more than one ("+r.length+") save handlers for destination URL "+e+"."}),s=o[0],u=zc(t).scheme,l=zc(t).path,c=u===zc(t).scheme,[4,a.load()];case 1:return p=i.sent(),n&&c?[4,Mc.getManager(u).removeModel(l)]:[3,3];case 2:i.sent(),i.label=3;case 3:return[4,s.save(p)];case 4:return h=i.sent(),!n||c?[3,6]:[4,Mc.getManager(u).removeModel(l)];case 5:i.sent(),i.label=6;case 6:return[2,h.modelArtifactsInfo]}})})}var Pc="models_store",Bc="model_info_store";function Vc(){if(!t.ENV.getBool("IS_BROWSER"))throw new Error("Failed to obtain IndexedDB factory because the current environmentis not a web browser.");var e=window,n=e.indexedDB||e.mozIndexedDB||e.webkitIndexedDB||e.msIndexedDB||e.shimIndexedDB;if(null==n)throw new Error("The current browser does not appear to support IndexedDB.");return n}function Wc(t){var e=t.result;e.createObjectStore(Pc,{keyPath:"modelPath"}),e.createObjectStore(Bc,{keyPath:"modelPath"})}var Uc=function(){function t(t){if(this.indexedDB=Vc(),null==t||!t)throw new Error("For IndexedDB, modelPath must not be null, undefined or empty.");this.modelPath=t}return t.prototype.save=function(t){return r(this,void 0,void 0,function(){return i(this,function(e){if(t.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");return[2,this.databaseAction(this.modelPath,t)]})})},t.prototype.load=function(){return r(this,void 0,void 0,function(){return i(this,function(t){return[2,this.databaseAction(this.modelPath)]})})},t.prototype.databaseAction=function(t,e){var n=this;return new Promise(function(t,r){var i=n.indexedDB.open("tensorflowjs",1);i.onupgradeneeded=function(){return Wc(i)},i.onsuccess=function(){var a=i.result;if(null==e){var o=a.transaction(Pc,"readonly"),s=o.objectStore(Pc).get(n.modelPath);s.onsuccess=function(){if(null==s.result)return a.close(),r(new Error("Cannot find model with path '"+n.modelPath+"' in IndexedDB."));t(s.result.modelArtifacts)},s.onerror=function(t){return a.close(),r(s.error)},o.oncomplete=function(){return a.close()}}else{var u,l=Oc(e),c=a.transaction(Bc,"readwrite"),p=c.objectStore(Bc),h=p.put({modelPath:n.modelPath,modelArtifactsInfo:l});h.onsuccess=function(){var i=(u=a.transaction(Pc,"readwrite")).objectStore(Pc).put({modelPath:n.modelPath,modelArtifacts:e,modelArtifactsInfo:l});i.onsuccess=function(){return t({modelArtifactsInfo:l})},i.onerror=function(t){var e=(p=c.objectStore(Bc)).delete(n.modelPath);e.onsuccess=function(){return a.close(),r(i.error)},e.onerror=function(t){return a.close(),r(i.error)}}},h.onerror=function(t){return a.close(),r(h.error)},c.oncomplete=function(){null==u?a.close():u.oncomplete=function(){return a.close()}}}},i.onerror=function(t){return r(i.error)}})},t.URL_SCHEME="indexeddb://",t}(),jc=function(e){return t.ENV.getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(Uc.URL_SCHEME)?(n=e.slice(Uc.URL_SCHEME.length),new Uc(n)):null;var n};_c.registerSaveRouter(jc),_c.registerLoadRouter(jc);var Gc=function(){function t(){this.indexedDB=Vc()}return t.prototype.listModels=function(){return r(this,void 0,void 0,function(){var t=this;return i(this,function(e){return[2,new Promise(function(e,n){var r=t.indexedDB.open("tensorflowjs",1);r.onupgradeneeded=function(){return Wc(r)},r.onsuccess=function(){var t=r.result,i=t.transaction(Bc,"readonly"),a=i.objectStore(Bc).getAll();a.onsuccess=function(){for(var t={},n=0,r=a.result;n0,function(){return"promises must be a none empty array"})}(t),function(t,e){f(t>=0&&t<=1,function(){return"Progress fraction must be in range [0, 1], but got startFraction "+t}),f(e>=0&&e<=1,function(){return"Progress fraction must be in range [0, 1], but got endFraction "+e}),f(e>=t,function(){return"startFraction must be no more than endFraction, but got startFraction "+t+" and endFraction "+e})}(n=null==n?0:n,r=null==r?1:r);var i=0;return Promise.all(t.map(function(a){return a.then(function(a){var o=n+ ++i/t.length*(r-n);return e(o),a}),a}))}function cp(e,n){return r(this,void 0,void 0,function(){var r,a,o,s,u,l,c,p,h;return i(this,function(i){switch(i.label){case 0:return null==n&&(n={}),r=null==n.fetchFunc?t.ENV.platform.fetch:n.fetchFunc,a=e.map(function(t){return r(t,n.requestInit,{isBinary:!0})}),o=0,s=.5,null!=n.onProgress?[3,2]:[4,Promise.all(a)];case 1:return u=i.sent(),[3,4];case 2:return[4,lp(a,n.onProgress,o,s)];case 3:u=i.sent(),i.label=4;case 4:return l=u.map(function(t){return t.arrayBuffer()}),c=.5,p=1,null!=n.onProgress?[3,6]:[4,Promise.all(l)];case 5:return h=i.sent(),[3,8];case 6:return[4,lp(l,n.onProgress,c,p)];case 7:h=i.sent(),i.label=8;case 8:return[2,h]}})})}function pp(t){var e=this;return function(n,a,o){return void 0===a&&(a=""),r(e,void 0,void 0,function(){var e,r,s,u,l,c,p,h,f,d;return i(this,function(i){switch(i.label){case 0:if(e=n.map(function(){return!1}),r={},s=null!=o?o.map(function(){return!1}):[],u=[],n.forEach(function(t,n){var i=0;t.weights.forEach(function(t){var a="quantization"in t?t.quantization.dtype:t.dtype,l=Sc[a]*v(t.shape),c=function(){e[n]=!0,null==r[n]&&(r[n]=[]),r[n].push({manifestEntry:t,groupOffset:i,sizeBytes:l})};null!=o?o.forEach(function(e,n){e===t.name&&(c(),s[n]=!0)}):c(),u.push(t.name),i+=l})}),!s.every(function(t){return t}))throw l=o.filter(function(t,e){return!s[e]}),new Error("Could not find weights in manifest with names: "+l.join(", ")+". \nManifest JSON has weights with names: "+u.join(", ")+".");return c=e.reduce(function(t,e,n){return e&&t.push(n),t},[]),p=[],c.forEach(function(t){n[t].paths.forEach(function(t){var e=a+(a.endsWith("/")?"":"/")+t;p.push(e)})}),[4,t(p)];case 1:return h=i.sent(),f={},d=0,c.forEach(function(t){for(var e=n[t].paths.length,i=0,a=0;a0,function(){return"URL path for http must not be null, undefined or empty."}),Array.isArray(e)&&f(2===e.length,function(){return"URL paths for http must have a length of 2, (actual length is "+e.length+")."}),this.path=e,null!=n.requestInit&&null!=n.requestInit.body)throw new Error("requestInit is expected to have no pre-existing body, but has one.");this.requestInit=n.requestInit||{}}return e.prototype.save=function(t){return r(this,void 0,void 0,function(){var e,n,r,a;return i(this,function(i){switch(i.label){case 0:if(t.modelTopology instanceof ArrayBuffer)throw new Error("BrowserHTTPRequest.save() does not support saving model topology in binary formats yet.");return(e=Object.assign({method:this.DEFAULT_METHOD},this.requestInit)).body=new FormData,n=[{paths:["./model.weights.bin"],weights:t.weightSpecs}],r={modelTopology:t.modelTopology,format:t.format,generatedBy:t.generatedBy,convertedBy:t.convertedBy,weightsManifest:n},e.body.append("model.json",new Blob([JSON.stringify(r)],{type:"application/json"}),"model.json"),null!=t.weightData&&e.body.append("model.weights.bin",new Blob([t.weightData],{type:"application/octet-stream"}),"model.weights.bin"),[4,this.fetch(this.path,e)];case 1:if((a=i.sent()).ok)return[2,{modelArtifactsInfo:Oc(t),responses:[a]}];throw new Error("BrowserHTTPRequest.save() failed due to HTTP response status "+a.status+".")}})})},e.prototype.load=function(){return r(this,void 0,void 0,function(){var t,e,n,r,a,o,s,u;return i(this,function(i){switch(i.label){case 0:return[4,this.fetch(this.path,this.requestInit)];case 1:if(!(t=i.sent()).ok)throw new Error("Request to "+this.path+" failed with status code "+t.status+". Please verify this URL points to the model JSON of the model to load.");i.label=2;case 2:return i.trys.push([2,4,,5]),[4,t.json()];case 3:return e=i.sent(),[3,5];case 4:throw i.sent(),n="Failed to parse model JSON of response from "+this.path+".",this.path.endsWith(".pb")?n+=" Your path contains a .pb file extension. Support for .pb models have been removed in TensorFlow.js 1.0 in favor of .json models. You can re-convert your Python TensorFlow model using the TensorFlow.js 1.0 conversion scripts or you can convert your.pb models with the 'pb2json'NPM script in the tensorflow/tfjs-converter repository.":n+=" Please make sure the server is serving valid JSON for this request.",new Error(n);case 5:if(r=e.modelTopology,a=e.weightsManifest,null==r&&null==a)throw new Error("The JSON from HTTP path "+this.path+" contains neither model topology or manifest for weights.");return null==a?[3,7]:[4,this.loadWeights(a)];case 6:u=i.sent(),o=u[0],s=u[1],i.label=7;case 7:return[2,{modelTopology:r,weightSpecs:o,weightData:s}]}})})},e.prototype.loadWeights=function(t){return r(this,void 0,void 0,function(){var e,n,r,a,o,s,u,l,c,p,h;return i(this,function(i){switch(i.label){case 0:for(e=Array.isArray(this.path)?this.path[1]:this.path,n=function(t){var e=t.lastIndexOf("/"),n=t.lastIndexOf("?");return[t.substring(0,e)+"/",n>e?t.substring(n):""]}(e),r=n[0],a=n[1],o=this.weightPathPrefix||r,s=[],u=0,l=t;u0&&Number.isInteger(n),function(){return"If provided, numClasses must be a positive integer, but got "+n}),f(1===r.rank,function(){return"Expected the rank of labels to be 1, but got "+r.rank}),f(1===i.rank,function(){return"Expected the rank of predictions to be 1, but got "+i.rank}),f(r.shape[0]===i.shape[0],function(){return"Mismatch in the number of examples: "+r.shape[0]+" vs. "+i.shape[0]+". Labels and predictions should have the same number of elements."}),f(n>0&&Number.isInteger(n),function(){return"numClasses is required to be a positive integer, but got "+n});var a=Kn(r.asType("int32"),n),o=Kn(i.asType("int32"),n);return a.transpose().matMul(o).asType("int32")}}),xp=Object.freeze({confusionMatrix:bp}),wp=Ze({fromPixels_:function(t,e){if(void 0===e&&(e=3),e>4)throw new Error("Cannot construct Tensor with more than 4 channels from pixels.");var n="undefined"!=typeof HTMLVideoElement&&t instanceof HTMLVideoElement;if(n&&n&&t.readyState<2)throw new Error("The video element has not loaded data yet. Please wait for `loadeddata` event on the