code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
def encode_ordinary(self, text):
"""Encoding that ignores any special tokens."""
# split text into chunks of text by categories defined in regex pattern
text_chunks = re.findall(self.compiled_pattern, text)
# all chunks of text are encoded separately, then results are joined
ids ... | Encoding that ignores any special tokens. | encode_ordinary | python | karpathy/minbpe | minbpe/regex.py | https://github.com/karpathy/minbpe/blob/master/minbpe/regex.py | MIT |
def encode(self, text, allowed_special="none_raise"):
"""
Unlike encode_ordinary, this function handles special tokens.
allowed_special: can be "all"|"none"|"none_raise" or a custom set of special tokens
if none_raise, then an error is raised if any special token is encountered in text
... |
Unlike encode_ordinary, this function handles special tokens.
allowed_special: can be "all"|"none"|"none_raise" or a custom set of special tokens
if none_raise, then an error is raised if any special token is encountered in text
this is the default tiktoken behavior right now as well
... | encode | python | karpathy/minbpe | minbpe/regex.py | https://github.com/karpathy/minbpe/blob/master/minbpe/regex.py | MIT |
def test_wikipedia_example(tokenizer_factory):
"""
Quick unit test, following along the Wikipedia example:
https://en.wikipedia.org/wiki/Byte_pair_encoding
According to Wikipedia, running bpe on the input string:
"aaabdaaabac"
for 3 merges will result in string:
"XdXac"
where:
X=Z... |
Quick unit test, following along the Wikipedia example:
https://en.wikipedia.org/wiki/Byte_pair_encoding
According to Wikipedia, running bpe on the input string:
"aaabdaaabac"
for 3 merges will result in string:
"XdXac"
where:
X=ZY
Y=ab
Z=aa
Keep in mind that for us a=97... | test_wikipedia_example | python | karpathy/minbpe | tests/test_tokenizer.py | https://github.com/karpathy/minbpe/blob/master/tests/test_tokenizer.py | MIT |
def __init__(
self,
width,
height,
resize_target=True,
keep_aspect_ratio=False,
ensure_multiple_of=1,
resize_method='lower_bound',
image_interpolation_method=cv2.INTER_AREA,
):
"""Init.
Args:
width (int): desired output wid... | Init.
Args:
width (int): desired output width
height (int): desired output height
resize_target (bool, optional):
True: Resize the full sample (image, mask, target).
False: Resize image only.
Defaults to True.
keep_... | __init__ | python | ali-vilab/VACE | vace/annotators/midas/transforms.py | https://github.com/ali-vilab/VACE/blob/master/vace/annotators/midas/transforms.py | Apache-2.0 |
def _resize_crop(self, img, oh, ow, normalize=True):
"""
Resize, center crop, convert to tensor, and normalize.
"""
# resize and crop
iw, ih = img.size
if iw != ow or ih != oh:
# resize
scale = max(ow / iw, oh / ih)
img = img.resize(
... |
Resize, center crop, convert to tensor, and normalize.
| _resize_crop | python | ali-vilab/VACE | vace/models/utils/preprocessor.py | https://github.com/ali-vilab/VACE/blob/master/vace/models/utils/preprocessor.py | Apache-2.0 |
def resize_crop(video: torch.Tensor, oh: int, ow: int):
"""
Resize, center crop and normalize for decord loaded video (torch.Tensor type)
Parameters:
video - video to process (torch.Tensor): Tensor from `reader.get_batch(frame_ids)`, in shape of (T, H, W, C)
oh - target heig... |
Resize, center crop and normalize for decord loaded video (torch.Tensor type)
Parameters:
video - video to process (torch.Tensor): Tensor from `reader.get_batch(frame_ids)`, in shape of (T, H, W, C)
oh - target height (int)
ow - target width (int)
Returns:
... | resize_crop | python | ali-vilab/VACE | vace/models/utils/preprocessor.py | https://github.com/ali-vilab/VACE/blob/master/vace/models/utils/preprocessor.py | Apache-2.0 |
def __init__(
self,
config,
checkpoint_dir,
device_id=0,
rank=0,
t5_fsdp=False,
dit_fsdp=False,
use_usp=False,
t5_cpu=False,
):
r"""
Initializes the Wan text-to-video generation model components.
Args:
confi... |
Initializes the Wan text-to-video generation model components.
Args:
config (EasyDict):
Object containing model parameters initialized from config.py
checkpoint_dir (`str`):
Path to directory containing model checkpoints
device_id (`i... | __init__ | python | ali-vilab/VACE | vace/models/wan/wan_vace.py | https://github.com/ali-vilab/VACE/blob/master/vace/models/wan/wan_vace.py | Apache-2.0 |
def generate(self,
input_prompt,
input_frames,
input_masks,
input_ref_images,
size=(1280, 720),
frame_num=81,
context_scale=1.0,
shift=5.0,
sample_solver='unipc',
... |
Generates video frames from text prompt using diffusion process.
Args:
input_prompt (`str`):
Text prompt for content generation
size (tupele[`int`], *optional*, defaults to (1280,720)):
Controls video resolution, (width,height).
frame... | generate | python | ali-vilab/VACE | vace/models/wan/wan_vace.py | https://github.com/ali-vilab/VACE/blob/master/vace/models/wan/wan_vace.py | Apache-2.0 |
def usp_dit_forward(
self,
x,
t,
vace_context,
context,
seq_len,
vace_context_scale=1.0,
clip_fea=None,
y=None,
):
"""
x: A list of videos each with shape [C, T, H, W].
t: [B].
context: A list of text embeddings each with shape [L, C].... |
x: A list of videos each with shape [C, T, H, W].
t: [B].
context: A list of text embeddings each with shape [L, C].
| usp_dit_forward | python | ali-vilab/VACE | vace/models/wan/distributed/xdit_context_parallel.py | https://github.com/ali-vilab/VACE/blob/master/vace/models/wan/distributed/xdit_context_parallel.py | Apache-2.0 |
def get_html_video_template(file_url_path, file_name, width="auto", height="auto"):
"""
Generate an HTML code snippet for embedding and downloading a video.
Parameters:
file_url_path (str): The URL or path to the video file.
file_name (str): The name of the video file.
w... |
Generate an HTML code snippet for embedding and downloading a video.
Parameters:
file_url_path (str): The URL or path to the video file.
file_name (str): The name of the video file.
width (str, optional): The width of the video. Defaults to "auto".
height (str, optional... | get_html_video_template | python | RayVentura/ShortGPT | gui/ui_components_html.py | https://github.com/RayVentura/ShortGPT/blob/master/gui/ui_components_html.py | MIT |
def __verify_and_add_youtube_asset(self, asset_name, yt_url, type):
'''Verify and add a youtube asset to the database'''
self.__validate_asset_name(asset_name)
self.__validate_youtube_url(yt_url)
return self.__add_youtube_asset(asset_name, yt_url, type) | Verify and add a youtube asset to the database | __verify_and_add_youtube_asset | python | RayVentura/ShortGPT | gui/ui_tab_asset_library.py | https://github.com/RayVentura/ShortGPT/blob/master/gui/ui_tab_asset_library.py | MIT |
def __get_asset_embed(self, data, row):
'''Get the embed html for the asset at the given row'''
embed_height = 300
embed_width = 300
asset_link = data.iloc[row]['link']
embed_html = ''
if 'youtube.com' in asset_link:
asset_link_split = asset_link.split('?v=')
... | Get the embed html for the asset at the given row | __get_asset_embed | python | RayVentura/ShortGPT | gui/ui_tab_asset_library.py | https://github.com/RayVentura/ShortGPT/blob/master/gui/ui_tab_asset_library.py | MIT |
def __verify_and_upload_local_asset(self, upload_type, upload_name, video_path, audio_path, image_path):
'''Verify and upload a local asset to the database'''
self.__validate_asset_name(upload_name)
path_dict = {
AssetType.VIDEO.value: video_path,
AssetType.BACKGROUND_VID... | Verify and upload a local asset to the database | __verify_and_upload_local_asset | python | RayVentura/ShortGPT | gui/ui_tab_asset_library.py | https://github.com/RayVentura/ShortGPT/blob/master/gui/ui_tab_asset_library.py | MIT |
def on_show(self, button_text, textbox, button):
'''Show or hide the API key'''
if button_text == "Show":
return gr.update(type="text"), gr.update(value="Hide")
return gr.update(type="password"), gr.update(value="Show") | Show or hide the API key | on_show | python | RayVentura/ShortGPT | gui/ui_tab_config.py | https://github.com/RayVentura/ShortGPT/blob/master/gui/ui_tab_config.py | MIT |
def save_keys(self, openai_key, eleven_key, pexels_key, gemini_key):
'''Save the keys in the database'''
if (self.api_key_manager.get_api_key("OPENAI_API_KEY") != openai_key):
self.api_key_manager.set_api_key("OPENAI_API_KEY", openai_key)
if (self.api_key_manager.get_api_key("PEXELS_... | Save the keys in the database | save_keys | python | RayVentura/ShortGPT | gui/ui_tab_config.py | https://github.com/RayVentura/ShortGPT/blob/master/gui/ui_tab_config.py | MIT |
def get_eleven_remaining(self,):
'''Get the remaining characters from ElevenLabs API'''
if (self.eleven_labs_api):
try:
return self.eleven_labs_api.get_remaining_characters()
except Exception as e:
return e.args[0]
return "" | Get the remaining characters from ElevenLabs API | get_eleven_remaining | python | RayVentura/ShortGPT | gui/ui_tab_config.py | https://github.com/RayVentura/ShortGPT/blob/master/gui/ui_tab_config.py | MIT |
def get_voices(self):
'''Get the list of voices available'''
url = self.url_base + 'voices'
headers = {'accept': 'application/json'}
if self.api_key:
headers['xi-api-key'] = self.api_key
response = requests.get(url, headers=headers)
self.voices = {voice['name'... | Get the list of voices available | get_voices | python | RayVentura/ShortGPT | shortGPT/api_utils/eleven_api.py | https://github.com/RayVentura/ShortGPT/blob/master/shortGPT/api_utils/eleven_api.py | MIT |
def get_remaining_characters(self):
'''Get the number of characters remaining'''
url = self.url_base + 'user'
headers = {'accept': '*/*', 'xi-api-key': self.api_key, 'Content-Type': 'application/json'}
response = requests.get(url, headers=headers)
if response.status_code == 200:... | Get the number of characters remaining | get_remaining_characters | python | RayVentura/ShortGPT | shortGPT/api_utils/eleven_api.py | https://github.com/RayVentura/ShortGPT/blob/master/shortGPT/api_utils/eleven_api.py | MIT |
def sync_local_assets(cls):
"""
Loads all local assets from the static-assets folder into the database.
"""
local_assets = cls.local_assets._get()
local_paths = {asset['path'] for asset in local_assets.values()}
for path in Path('public').rglob('*'):
if path.... |
Loads all local assets from the static-assets folder into the database.
| sync_local_assets | python | RayVentura/ShortGPT | shortGPT/config/asset_db.py | https://github.com/RayVentura/ShortGPT/blob/master/shortGPT/config/asset_db.py | MIT |
def get_asset_link(cls, key: str) -> str:
"""
Get the link to an asset.
Args:
key (str): Name of the asset.
Returns:
str: Link to the asset.
"""
if key in cls.local_assets._get():
return cls._update_local_asset_timestamp_and_get_link(... |
Get the link to an asset.
Args:
key (str): Name of the asset.
Returns:
str: Link to the asset.
| get_asset_link | python | RayVentura/ShortGPT | shortGPT/config/asset_db.py | https://github.com/RayVentura/ShortGPT/blob/master/shortGPT/config/asset_db.py | MIT |
def get_asset_duration(cls, key: str) -> str:
"""
Get the duration of an asset.
Args:
key (str): Name of the asset.
Returns:
str: Duration of the asset.
"""
if key in cls.local_assets._get():
return cls._get_local_asset_duration(key)
... |
Get the duration of an asset.
Args:
key (str): Name of the asset.
Returns:
str: Duration of the asset.
| get_asset_duration | python | RayVentura/ShortGPT | shortGPT/config/asset_db.py | https://github.com/RayVentura/ShortGPT/blob/master/shortGPT/config/asset_db.py | MIT |
def _remove_local_asset(cls, name: str):
"""
Remove a local asset from the database.
Args:
name (str): Name of the asset.
"""
asset = cls.local_assets._get(name)
if 'required' not in asset:
try:
Path(asset['path']).unlink()
... |
Remove a local asset from the database.
Args:
name (str): Name of the asset.
| _remove_local_asset | python | RayVentura/ShortGPT | shortGPT/config/asset_db.py | https://github.com/RayVentura/ShortGPT/blob/master/shortGPT/config/asset_db.py | MIT |
def _add_local_asset_from_path(cls, path: Path):
"""
Add a local asset to the database from a file path.
Args:
path (Path): Path to the asset.
"""
file_ext = path.suffix
if file_ext in AUDIO_EXTENSIONS:
asset_type = AssetType.AUDIO
elif fi... |
Add a local asset to the database from a file path.
Args:
path (Path): Path to the asset.
| _add_local_asset_from_path | python | RayVentura/ShortGPT | shortGPT/config/asset_db.py | https://github.com/RayVentura/ShortGPT/blob/master/shortGPT/config/asset_db.py | MIT |
def _update_local_asset_timestamp_and_get_link(cls, key: str) -> str:
"""
Update the timestamp of a local asset and get its link.
Args:
key (str): Name of the asset.
Returns:
str: Link to the asset.
"""
asset = cls.local_assets._get(key)
... |
Update the timestamp of a local asset and get its link.
Args:
key (str): Name of the asset.
Returns:
str: Link to the asset.
| _update_local_asset_timestamp_and_get_link | python | RayVentura/ShortGPT | shortGPT/config/asset_db.py | https://github.com/RayVentura/ShortGPT/blob/master/shortGPT/config/asset_db.py | MIT |
def _get_remote_asset_link(cls, key: str) -> str:
"""
Get the link to a remote asset.
Args:
key (str): Name of the asset.
Returns:
str: Link to the asset.
"""
asset = cls.remote_assets._get(key)
asset['ts'] = datetime.now().strftime("%Y-%... |
Get the link to a remote asset.
Args:
key (str): Name of the asset.
Returns:
str: Link to the asset.
| _get_remote_asset_link | python | RayVentura/ShortGPT | shortGPT/config/asset_db.py | https://github.com/RayVentura/ShortGPT/blob/master/shortGPT/config/asset_db.py | MIT |
def _get_local_asset_duration(cls, key: str) -> str:
"""
Get the duration of a local asset.
Args:
key (str): Name of the asset.
Returns:
str: Duration of the asset.
"""
asset = cls.local_assets._get(key)
asset['ts'] = datetime.now().strft... |
Get the duration of a local asset.
Args:
key (str): Name of the asset.
Returns:
str: Duration of the asset.
| _get_local_asset_duration | python | RayVentura/ShortGPT | shortGPT/config/asset_db.py | https://github.com/RayVentura/ShortGPT/blob/master/shortGPT/config/asset_db.py | MIT |
def _get_remote_asset_duration(cls, key: str) -> str:
"""
Get the duration of a remote asset.
Args:
key (str): Name of the asset.
Returns:
str: Duration of the asset.
"""
asset = cls.remote_assets._get(key)
asset['ts'] = datetime.now().st... |
Get the duration of a remote asset.
Args:
key (str): Name of the asset.
Returns:
str: Duration of the asset.
| _get_remote_asset_duration | python | RayVentura/ShortGPT | shortGPT/config/asset_db.py | https://github.com/RayVentura/ShortGPT/blob/master/shortGPT/config/asset_db.py | MIT |
def _update_local_asset_duration(cls, key: str) -> str:
"""
Update the duration of a local asset.
Args:
key (str): Name of the asset.
Returns:
str: Duration of the asset.
"""
asset = cls.local_assets._get(key)
path = Path(asset['path'])
... |
Update the duration of a local asset.
Args:
key (str): Name of the asset.
Returns:
str: Duration of the asset.
| _update_local_asset_duration | python | RayVentura/ShortGPT | shortGPT/config/asset_db.py | https://github.com/RayVentura/ShortGPT/blob/master/shortGPT/config/asset_db.py | MIT |
def _update_youtube_asset_duration(cls, key: str) -> str:
"""
Update the duration of a Youtube asset.
Args:
key (str): Name of the asset.
Returns:
str: Duration of the asset.
"""
asset = cls.remote_assets._get(key)
youtube_url = asset['ur... |
Update the duration of a Youtube asset.
Args:
key (str): Name of the asset.
Returns:
str: Duration of the asset.
| _update_youtube_asset_duration | python | RayVentura/ShortGPT | shortGPT/config/asset_db.py | https://github.com/RayVentura/ShortGPT/blob/master/shortGPT/config/asset_db.py | MIT |
def _get_youtube_asset_link(cls, key: str, asset: dict) -> str:
"""
Get the link to a Youtube asset.
Args:
key (str): Name of the asset.
asset (dict): Asset data.
Returns:
str: Link to the asset.
"""
if any(t in asset['type'] for t in... |
Get the link to a Youtube asset.
Args:
key (str): Name of the asset.
asset (dict): Asset data.
Returns:
str: Link to the asset.
| _get_youtube_asset_link | python | RayVentura/ShortGPT | shortGPT/config/asset_db.py | https://github.com/RayVentura/ShortGPT/blob/master/shortGPT/config/asset_db.py | MIT |
def read_yaml_config(file_path: str) -> dict:
"""Reads and returns the contents of a YAML file as dictionary"""
with open(file_path, 'r') as file:
contents = yaml.safe_load(file)
return contents | Reads and returns the contents of a YAML file as dictionary | read_yaml_config | python | RayVentura/ShortGPT | shortGPT/config/config.py | https://github.com/RayVentura/ShortGPT/blob/master/shortGPT/config/config.py | MIT |
def load_editing_assets() -> dict:
"""Loads all local assets from the static-assets folder specified in the yaml_config"""
yaml_config = read_yaml_config("public.yaml")
if yaml_config['local-assets'] == None:
yaml_config['local-assets'] = {}
# Create a copy of the dictionary before iterating ove... | Loads all local assets from the static-assets folder specified in the yaml_config | load_editing_assets | python | RayVentura/ShortGPT | shortGPT/config/config.py | https://github.com/RayVentura/ShortGPT/blob/master/shortGPT/config/config.py | MIT |
def extract_random_clip_from_video(video_url, video_duration, clip_duration, output_file):
"""Extracts a clip from a video using a signed URL.
Args:
video_url (str): The signed URL of the video.
video_url (int): Duration of the video.
start_time (int): The start time of the clip in secon... | Extracts a clip from a video using a signed URL.
Args:
video_url (str): The signed URL of the video.
video_url (int): Duration of the video.
start_time (int): The start time of the clip in seconds.
clip_duration (int): The duration of the clip in seconds.
output_file (str): T... | extract_random_clip_from_video | python | RayVentura/ShortGPT | shortGPT/editing_utils/handle_videos.py | https://github.com/RayVentura/ShortGPT/blob/master/shortGPT/editing_utils/handle_videos.py | MIT |
def _generateScript(self):
"""
Implements Abstract parent method to generate the script for the reddit short
"""
self.logger("Generating reddit question & entertaining story")
self._db_script, _ = self.__getRealisticStory(max_tries=1)
self._db_reddit_question = reddit_gpt... |
Implements Abstract parent method to generate the script for the reddit short
| _generateScript | python | RayVentura/ShortGPT | shortGPT/engine/reddit_short_engine.py | https://github.com/RayVentura/ShortGPT/blob/master/shortGPT/engine/reddit_short_engine.py | MIT |
def _prepareCustomAssets(self):
"""
Override parent method to generate custom reddit image asset
"""
self.logger("Rendering short: (3/4) preparing custom reddit image...")
self.verifyParameters(question=self._db_reddit_question,)
title, header, n_comments, n_upvotes = red... |
Override parent method to generate custom reddit image asset
| _prepareCustomAssets | python | RayVentura/ShortGPT | shortGPT/engine/reddit_short_engine.py | https://github.com/RayVentura/ShortGPT/blob/master/shortGPT/engine/reddit_short_engine.py | MIT |
def _editAndRenderShort(self):
"""
Override parent method to customize video rendering sequence by adding a Reddit image
"""
self.verifyParameters(
voiceover_audio_url=self._db_audio_path,
video_duration=self._db_background_vide... |
Override parent method to customize video rendering sequence by adding a Reddit image
| _editAndRenderShort | python | RayVentura/ShortGPT | shortGPT/engine/reddit_short_engine.py | https://github.com/RayVentura/ShortGPT/blob/master/shortGPT/engine/reddit_short_engine.py | MIT |
def getVideoSearchQueriesTimed(captions_timed):
"""
Generate timed video search queries based on caption timings.
Returns list of [time_range, search_queries] pairs.
"""
err = ""
for _ in range(4):
try:
# Get total video duration from last caption
end_time = capt... |
Generate timed video search queries based on caption timings.
Returns list of [time_range, search_queries] pairs.
| getVideoSearchQueriesTimed | python | RayVentura/ShortGPT | shortGPT/gpt/gpt_editing.py | https://github.com/RayVentura/ShortGPT/blob/master/shortGPT/gpt/gpt_editing.py | MIT |
def display_header():
'''Display the header of the CLI'''
CLI.display_green_text('''
.d88888b dP dP .88888. 888888ba d888888P .88888. 888888ba d888888P
88. "' 88 88 d8' `8b 88 `8b 88 d8' `88 88 `8b 88
`Y88888b. 88aaaaa88 88 88 88aaaa8P' 88 88 ... | Display the header of the CLI | display_header | python | RayVentura/ShortGPT | shortGPT/utils/cli.py | https://github.com/RayVentura/ShortGPT/blob/master/shortGPT/utils/cli.py | MIT |
def display_requirements_check():
'''Display information about the system and requirements'''
print("Checking requirements...")
requirements_manager = Requirements()
print(" - Requirements : List of requirements and installed version:")
all_req_versions = requirements_manager.get... | Display information about the system and requirements | display_requirements_check | python | RayVentura/ShortGPT | shortGPT/utils/cli.py | https://github.com/RayVentura/ShortGPT/blob/master/shortGPT/utils/cli.py | MIT |
def display_error(error_message, stack_trace):
'''Display an error message in the console'''
print(CLI.bcolors.FAIL + "ERROR : " + error_message + CLI.bcolors.ENDC)
print(stack_trace)
print("If the problem persists, don't hesitate to contact our support. We're here to assist you.")
... | Display an error message in the console | display_error | python | RayVentura/ShortGPT | shortGPT/utils/cli.py | https://github.com/RayVentura/ShortGPT/blob/master/shortGPT/utils/cli.py | MIT |
def get_list_requirements(self):
'''Get the list of requirements packages from requirements.txt'''
with open(self.requirements_path) as f:
requirements = f.read().splitlines()
# remove comments and empty lines
requirements = [line for line in requirements if not line.startsw... | Get the list of requirements packages from requirements.txt | get_list_requirements | python | RayVentura/ShortGPT | shortGPT/utils/requirements.py | https://github.com/RayVentura/ShortGPT/blob/master/shortGPT/utils/requirements.py | MIT |
def is_all_requirements_installed(self):
'''Check if all requirements are installed'''
requirements = self.get_list_requirements()
for requirement in requirements:
if not self.is_requirement_installed(requirement):
return False
return True | Check if all requirements are installed | is_all_requirements_installed | python | RayVentura/ShortGPT | shortGPT/utils/requirements.py | https://github.com/RayVentura/ShortGPT/blob/master/shortGPT/utils/requirements.py | MIT |
def get_all_requirements_versions(self):
'''Get the versions of all requirements'''
requirements = self.get_list_requirements()
versions = {}
for requirement in requirements:
versions[requirement] = self.get_version(requirement)
return versions | Get the versions of all requirements | get_all_requirements_versions | python | RayVentura/ShortGPT | shortGPT/utils/requirements.py | https://github.com/RayVentura/ShortGPT/blob/master/shortGPT/utils/requirements.py | MIT |
def get_all_requirements_not_installed(self):
'''Get the list of all requirements not installed'''
requirements = self.get_list_requirements()
not_installed = {}
for requirement in requirements:
# if version is None then the package is not installed
if self.get_ve... | Get the list of all requirements not installed | get_all_requirements_not_installed | python | RayVentura/ShortGPT | shortGPT/utils/requirements.py | https://github.com/RayVentura/ShortGPT/blob/master/shortGPT/utils/requirements.py | MIT |
def validate_user(username, minlen):
"""Checks if the received username matches the required conditions."""
if type(username) != str:
raise TypeError("username must be a string")
if minlen < 1:
raise ValueError("minlen must be at least 1")
# Usernames can't be shorter than minlen
... | Checks if the received username matches the required conditions. | validate_user | python | google/it-cert-automation-practice | Course3/Lab4/validations.py | https://github.com/google/it-cert-automation-practice/blob/master/Course3/Lab4/validations.py | Apache-2.0 |
def __getitem__(self, idx):
"""
Output:
- target: dict of multiple items
- boxes: Tensor[num_box, 4]. \
Init type: x0,y0,x1,y1. unnormalized data.
Final type: cx,cy,w,h. normalized data.
"""
try:
img, target... |
Output:
- target: dict of multiple items
- boxes: Tensor[num_box, 4]. Init type: x0,y0,x1,y1. unnormalized data.
Final type: cx,cy,w,h. normalized data.
| __getitem__ | python | IDEA-Research/DINO | datasets/coco.py | https://github.com/IDEA-Research/DINO/blob/master/datasets/coco.py | Apache-2.0 |
def slcopytree(src, dst, symlinks=False, ignore=None, copy_function=shutil.copyfile,
ignore_dangling_symlinks=False):
"""
modified from shutil.copytree without copystat.
Recursively copy a directory tree.
The destination directory must not already exist.
If exception(s) occur, an ... |
modified from shutil.copytree without copystat.
Recursively copy a directory tree.
The destination directory must not already exist.
If exception(s) occur, an Error is raised with a list of reasons.
If the optional symlinks flag is true, symbolic links in the
source tree result in symbol... | slcopytree | python | IDEA-Research/DINO | datasets/data_util.py | https://github.com/IDEA-Research/DINO/blob/master/datasets/data_util.py | Apache-2.0 |
def intersect(boxes1, boxes2):
'''
Find intersection of every box combination between two sets of box
boxes1: bounding boxes 1, a tensor of dimensions (n1, 4)
boxes2: bounding boxes 2, a tensor of dimensions (n2, 4)
Out: Intersection each of boxes1 with respect to each of bo... |
Find intersection of every box combination between two sets of box
boxes1: bounding boxes 1, a tensor of dimensions (n1, 4)
boxes2: bounding boxes 2, a tensor of dimensions (n2, 4)
Out: Intersection each of boxes1 with respect to each of boxes2,
a tensor of dimens... | intersect | python | IDEA-Research/DINO | datasets/random_crop.py | https://github.com/IDEA-Research/DINO/blob/master/datasets/random_crop.py | Apache-2.0 |
def random_crop(image, boxes, labels, difficulties=None):
'''
image: A PIL image
boxes: Bounding boxes, a tensor of dimensions (#objects, 4)
labels: labels of object, a tensor of dimensions (#objects)
difficulties: difficulties of detect object, a tensor of dimensions (#objects)
... |
image: A PIL image
boxes: Bounding boxes, a tensor of dimensions (#objects, 4)
labels: labels of object, a tensor of dimensions (#objects)
difficulties: difficulties of detect object, a tensor of dimensions (#objects)
Out: cropped image , new boxes, new labels, new diff... | random_crop | python | IDEA-Research/DINO | datasets/random_crop.py | https://github.com/IDEA-Research/DINO/blob/master/datasets/random_crop.py | Apache-2.0 |
def __call__(self, img, target):
"""
img (PIL Image or Tensor): Image to be adjusted.
"""
_contrast_factor = ((random.random() + 1.0) / 2.0) * self.contrast_factor
img = F.adjust_contrast(img, _contrast_factor)
return img, target |
img (PIL Image or Tensor): Image to be adjusted.
| __call__ | python | IDEA-Research/DINO | datasets/sltransform.py | https://github.com/IDEA-Research/DINO/blob/master/datasets/sltransform.py | Apache-2.0 |
def lighting_noise(image):
'''
color channel swap in image
image: A PIL image
'''
new_image = image
perms = ((0, 1, 2), (0, 2, 1), (1, 0, 2),
(1, 2, 0), (2, 0, 1), (2, 1, 0))
swap = perms[random.randint(0, len(perms)- 1)]
new_image = F.to_tensor(new_image)
new_i... |
color channel swap in image
image: A PIL image
| lighting_noise | python | IDEA-Research/DINO | datasets/sltransform.py | https://github.com/IDEA-Research/DINO/blob/master/datasets/sltransform.py | Apache-2.0 |
def rotate(image, boxes, angle):
'''
Rotate image and bounding box
image: A Pil image (w, h)
boxes: A tensors of dimensions (#objects, 4)
Out: rotated image (w, h), rotated boxes
'''
new_image = image.copy()
new_boxes = boxes.clone()
#Rotate image, expan... |
Rotate image and bounding box
image: A Pil image (w, h)
boxes: A tensors of dimensions (#objects, 4)
Out: rotated image (w, h), rotated boxes
| rotate | python | IDEA-Research/DINO | datasets/sltransform.py | https://github.com/IDEA-Research/DINO/blob/master/datasets/sltransform.py | Apache-2.0 |
def __call__(self, img, target, p=1.0):
"""
Input:
target['boxes']: xyxy, unnormalized data.
"""
boxes_raw = target['boxes']
labels_raw = target['labels']
img_np = np.array(img)
if self.transform and random.random() < p:
new_res = ... |
Input:
target['boxes']: xyxy, unnormalized data.
| __call__ | python | IDEA-Research/DINO | datasets/sltransform.py | https://github.com/IDEA-Research/DINO/blob/master/datasets/sltransform.py | Apache-2.0 |
def build_backbone(args):
"""
Useful args:
- backbone: backbone name
- lr_backbone:
- dilation
- return_interm_indices: available: [0,1,2,3], [1,2,3], [3]
- backbone_freeze_keywords:
- use_checkpoint: for swin only for now
"""
position_embedding = build... |
Useful args:
- backbone: backbone name
- lr_backbone:
- dilation
- return_interm_indices: available: [0,1,2,3], [1,2,3], [3]
- backbone_freeze_keywords:
- use_checkpoint: for swin only for now
| build_backbone | python | IDEA-Research/DINO | models/dino/backbone.py | https://github.com/IDEA-Research/DINO/blob/master/models/dino/backbone.py | Apache-2.0 |
def forward(self, srcs, masks, refpoint_embed, pos_embeds, tgt, attn_mask=None):
"""
Input:
- srcs: List of multi features [bs, ci, hi, wi]
- masks: List of multi masks [bs, hi, wi]
- refpoint_embed: [bs, num_dn, 4]. None in infer
- pos_embeds: List of mul... |
Input:
- srcs: List of multi features [bs, ci, hi, wi]
- masks: List of multi masks [bs, hi, wi]
- refpoint_embed: [bs, num_dn, 4]. None in infer
- pos_embeds: List of multi pos embeds [bs, ci, hi, wi]
- tgt: [bs, num_dn, d_model]. None in infer
... | forward | python | IDEA-Research/DINO | models/dino/deformable_transformer.py | https://github.com/IDEA-Research/DINO/blob/master/models/dino/deformable_transformer.py | Apache-2.0 |
def forward(self,
src: Tensor,
pos: Tensor,
spatial_shapes: Tensor,
level_start_index: Tensor,
valid_ratios: Tensor,
key_padding_mask: Tensor,
ref_token_index: Optional[Tensor]=None,
ref_token_coord: Optional[Tensor]=N... |
Input:
- src: [bs, sum(hi*wi), 256]
- pos: pos embed for src. [bs, sum(hi*wi), 256]
- spatial_shapes: h,w of each level [num_level, 2]
- level_start_index: [num_level] start point of level in sum(hi*wi).
- valid_ratios: [bs, num_level, 2]
... | forward | python | IDEA-Research/DINO | models/dino/deformable_transformer.py | https://github.com/IDEA-Research/DINO/blob/master/models/dino/deformable_transformer.py | Apache-2.0 |
def forward(self, outputs, targets, return_indices=False):
""" This performs the loss computation.
Parameters:
outputs: dict of tensors, see the output specification of the model for the format
targets: list of dicts, such that len(targets) == batch_size.
... | This performs the loss computation.
Parameters:
outputs: dict of tensors, see the output specification of the model for the format
targets: list of dicts, such that len(targets) == batch_size.
The expected keys in each dict depends on the losses applied, see each... | forward | python | IDEA-Research/DINO | models/dino/dino.py | https://github.com/IDEA-Research/DINO/blob/master/models/dino/dino.py | Apache-2.0 |
def prepare_for_cdn(dn_args, training, num_queries, num_classes, hidden_dim, label_enc):
"""
A major difference of DINO from DN-DETR is that the author process pattern embedding pattern embedding in its detector
forward function and use learnable tgt embedding, so we change this function a little bi... |
A major difference of DINO from DN-DETR is that the author process pattern embedding pattern embedding in its detector
forward function and use learnable tgt embedding, so we change this function a little bit.
:param dn_args: targets, dn_number, label_noise_ratio, box_noise_scale
:param... | prepare_for_cdn | python | IDEA-Research/DINO | models/dino/dn_components.py | https://github.com/IDEA-Research/DINO/blob/master/models/dino/dn_components.py | Apache-2.0 |
def get_shape(val: object) -> typing.List[int]:
"""
Get the shapes from a jit value object.
Args:
val (torch._C.Value): jit value object.
Returns:
list(int): return a list of ints.
"""
if val.isCompleteTensor(): # pyre-ignore
r = val.type().sizes() # pyre-ignore
... |
Get the shapes from a jit value object.
Args:
val (torch._C.Value): jit value object.
Returns:
list(int): return a list of ints.
| get_shape | python | IDEA-Research/DINO | tools/benchmark.py | https://github.com/IDEA-Research/DINO/blob/master/tools/benchmark.py | Apache-2.0 |
def addmm_flop_jit(
inputs: typing.List[object], outputs: typing.List[object]
) -> typing.Counter[str]:
"""
This method counts the flops for fully connected layers with torch script.
Args:
inputs (list(torch._C.Value)): The input shape in the form of a list of
jit object.
out... |
This method counts the flops for fully connected layers with torch script.
Args:
inputs (list(torch._C.Value)): The input shape in the form of a list of
jit object.
outputs (list(torch._C.Value)): The output shape in the form of a list
of jit object.
Returns:
... | addmm_flop_jit | python | IDEA-Research/DINO | tools/benchmark.py | https://github.com/IDEA-Research/DINO/blob/master/tools/benchmark.py | Apache-2.0 |
def conv_flop_count(
x_shape: typing.List[int],
w_shape: typing.List[int],
out_shape: typing.List[int],
) -> typing.Counter[str]:
"""
This method counts the flops for convolution. Note only multiplication is
counted. Computation for addition and bias is ignored.
Args:
x_shape (list(i... |
This method counts the flops for convolution. Note only multiplication is
counted. Computation for addition and bias is ignored.
Args:
x_shape (list(int)): The input shape before convolution.
w_shape (list(int)): The filter shape.
out_shape (list(int)): The output shape after convol... | conv_flop_count | python | IDEA-Research/DINO | tools/benchmark.py | https://github.com/IDEA-Research/DINO/blob/master/tools/benchmark.py | Apache-2.0 |
def conv_flop_jit(
inputs: typing.List[object], outputs: typing.List[object]
) -> typing.Counter[str]:
"""
This method counts the flops for convolution using torch script.
Args:
inputs (list(torch._C.Value)): The input shape in the form of a list of
jit object before convolution.
... |
This method counts the flops for convolution using torch script.
Args:
inputs (list(torch._C.Value)): The input shape in the form of a list of
jit object before convolution.
outputs (list(torch._C.Value)): The output shape in the form of a list
of jit object after convol... | conv_flop_jit | python | IDEA-Research/DINO | tools/benchmark.py | https://github.com/IDEA-Research/DINO/blob/master/tools/benchmark.py | Apache-2.0 |
def einsum_flop_jit(
inputs: typing.List[object], outputs: typing.List[object]
) -> typing.Counter[str]:
"""
This method counts the flops for the einsum operation. We currently support
two einsum operations: "nct,ncp->ntp" and "ntg,ncg->nct".
Args:
inputs (list(torch._C.Value)): The input sh... |
This method counts the flops for the einsum operation. We currently support
two einsum operations: "nct,ncp->ntp" and "ntg,ncg->nct".
Args:
inputs (list(torch._C.Value)): The input shape in the form of a list of
jit object before einsum.
outputs (list(torch._C.Value)): The outpu... | einsum_flop_jit | python | IDEA-Research/DINO | tools/benchmark.py | https://github.com/IDEA-Research/DINO/blob/master/tools/benchmark.py | Apache-2.0 |
def matmul_flop_jit(
inputs: typing.List[object], outputs: typing.List[object]
) -> typing.Counter[str]:
"""
This method counts the flops for matmul.
Args:
inputs (list(torch._C.Value)): The input shape in the form of a list of
jit object before matmul.
outputs (list(torch._C... |
This method counts the flops for matmul.
Args:
inputs (list(torch._C.Value)): The input shape in the form of a list of
jit object before matmul.
outputs (list(torch._C.Value)): The output shape in the form of a list
of jit object after matmul.
Returns:
Counte... | matmul_flop_jit | python | IDEA-Research/DINO | tools/benchmark.py | https://github.com/IDEA-Research/DINO/blob/master/tools/benchmark.py | Apache-2.0 |
def batchnorm_flop_jit(
inputs: typing.List[object], outputs: typing.List[object]
) -> typing.Counter[str]:
"""
This method counts the flops for batch norm.
Args:
inputs (list(torch._C.Value)): The input shape in the form of a list of
jit object before batch norm.
outputs (li... |
This method counts the flops for batch norm.
Args:
inputs (list(torch._C.Value)): The input shape in the form of a list of
jit object before batch norm.
outputs (list(torch._C.Value)): The output shape in the form of a list
of jit object after batch norm.
Returns:
... | batchnorm_flop_jit | python | IDEA-Research/DINO | tools/benchmark.py | https://github.com/IDEA-Research/DINO/blob/master/tools/benchmark.py | Apache-2.0 |
def elementwise_flop_counter(input_scale: float = 1, output_scale: float = 0) -> Handle:
"""
Count flops by
input_tensor.numel() * input_scale + output_tensor.numel() * output_scale
Args:
input_scale: scale of the input tensor (first argument)
output_scale: scale of the output tenso... |
Count flops by
input_tensor.numel() * input_scale + output_tensor.numel() * output_scale
Args:
input_scale: scale of the input tensor (first argument)
output_scale: scale of the output tensor (first element in outputs)
| elementwise_flop_counter | python | IDEA-Research/DINO | tools/benchmark.py | https://github.com/IDEA-Research/DINO/blob/master/tools/benchmark.py | Apache-2.0 |
def flop_count(
model: nn.Module,
inputs: typing.Tuple[object, ...],
whitelist: typing.Union[typing.List[str], None] = None,
customized_ops: typing.Union[typing.Dict[str, typing.Callable], None] = None,
) -> typing.DefaultDict[str, float]:
"""
Given a model and an input to the model, compute the... |
Given a model and an input to the model, compute the Gflops of the given
model. Note the input should have a batch size of 1.
Args:
model (nn.Module): The model to compute flop counts.
inputs (tuple): Inputs that are passed to `model` to count flops.
Inputs need to be in a tuple... | flop_count | python | IDEA-Research/DINO | tools/benchmark.py | https://github.com/IDEA-Research/DINO/blob/master/tools/benchmark.py | Apache-2.0 |
def get_dataset(coco_path):
"""
Gets the COCO dataset used for computing the flops on
"""
class DummyArgs:
pass
args = DummyArgs()
args.dataset_file = "coco"
args.coco_path = coco_path
args.masks = False
dataset = build_dataset(image_set="val", args=args)
return dataset |
Gets the COCO dataset used for computing the flops on
| get_dataset | python | IDEA-Research/DINO | tools/benchmark.py | https://github.com/IDEA-Research/DINO/blob/master/tools/benchmark.py | Apache-2.0 |
def add_box_to_img(img, boxes, colorlist, brands=None):
"""[summary]
Args:
img ([type]): np.array, H,W,3
boxes ([type]): list of list(4)
colorlist: list of colors.
brands: text.
Return:
img: np.array. H,W,3.
"""
H, W = img.shape[:2]
for _i, (box, color) ... | [summary]
Args:
img ([type]): np.array, H,W,3
boxes ([type]): list of list(4)
colorlist: list of colors.
brands: text.
Return:
img: np.array. H,W,3.
| add_box_to_img | python | IDEA-Research/DINO | util/vis_utils.py | https://github.com/IDEA-Research/DINO/blob/master/util/vis_utils.py | Apache-2.0 |
def plot_dual_img(img, boxes, labels, idxs, probs=None):
"""[summary]
Args:
img ([type]): 3,H,W. tensor.
boxes (): tensor(Kx4) or list of tensor(1x4).
labels ([type]): list of ints.
idxs ([type]): list of ints.
probs (optional): listof floats.
Returns:
img_c... | [summary]
Args:
img ([type]): 3,H,W. tensor.
boxes (): tensor(Kx4) or list of tensor(1x4).
labels ([type]): list of ints.
idxs ([type]): list of ints.
probs (optional): listof floats.
Returns:
img_classcolor: np.array. H,W,3. img with class-wise label.
i... | plot_dual_img | python | IDEA-Research/DINO | util/vis_utils.py | https://github.com/IDEA-Research/DINO/blob/master/util/vis_utils.py | Apache-2.0 |
def plot_raw_img(img, boxes, labels):
"""[summary]
Args:
img ([type]): 3,H,W. tensor.
boxes ([type]): Kx4. tensor
labels ([type]): K. tensor.
return:
img: np.array. H,W,3. img with bbox annos.
"""
img = (renorm(img.cpu()).permute(1,2,0).numpy() * 255).astype(n... | [summary]
Args:
img ([type]): 3,H,W. tensor.
boxes ([type]): Kx4. tensor
labels ([type]): K. tensor.
return:
img: np.array. H,W,3. img with bbox annos.
| plot_raw_img | python | IDEA-Research/DINO | util/vis_utils.py | https://github.com/IDEA-Research/DINO/blob/master/util/vis_utils.py | Apache-2.0 |
def capture_logger(name):
"""Context manager to capture a logger output with a StringIO stream."""
import logging
logger = logging.getLogger(name)
try:
import StringIO
stream = StringIO.StringIO()
except ImportError:
stream = io.StringIO()
handler = logging.StreamHandle... | Context manager to capture a logger output with a StringIO stream. | capture_logger | python | fonttools/fonttools | setup.py | https://github.com/fonttools/fonttools/blob/master/setup.py | MIT |
def git_tag(self, version, message, sign=False):
"""Create annotated git tag with given 'version' and 'message'.
Optionally 'sign' the tag with the user's GPG key.
"""
log.info(
"creating %s git tag '%s'" % ("signed" if sign else "annotated", version)
)
if sel... | Create annotated git tag with given 'version' and 'message'.
Optionally 'sign' the tag with the user's GPG key.
| git_tag | python | fonttools/fonttools | setup.py | https://github.com/fonttools/fonttools/blob/master/setup.py | MIT |
def bumpversion(self, part, commit=False, message=None, allow_dirty=None):
"""Run bumpversion.main() with the specified arguments, and return the
new computed version string (cf. 'bumpversion --help' for more info)
"""
import bumpversion.cli
args = (
(["--verbose"] i... | Run bumpversion.main() with the specified arguments, and return the
new computed version string (cf. 'bumpversion --help' for more info)
| bumpversion | python | fonttools/fonttools | setup.py | https://github.com/fonttools/fonttools/blob/master/setup.py | MIT |
def format_changelog(self, version):
"""Write new header at beginning of changelog file with the specified
'version' and the current date.
Return the changelog content for the current release.
"""
from datetime import datetime
log.info("formatting changelog")
ch... | Write new header at beginning of changelog file with the specified
'version' and the current date.
Return the changelog content for the current release.
| format_changelog | python | fonttools/fonttools | setup.py | https://github.com/fonttools/fonttools/blob/master/setup.py | MIT |
def __init__(self, path=None):
"""AFM file reader.
Instantiating an object with a path name will cause the file to be opened,
read, and parsed. Alternatively the path can be left unspecified, and a
file can be parsed later with the :meth:`read` method."""
self._attrs = {}
... | AFM file reader.
Instantiating an object with a path name will cause the file to be opened,
read, and parsed. Alternatively the path can be left unspecified, and a
file can be parsed later with the :meth:`read` method. | __init__ | python | fonttools/fonttools | Lib/fontTools/afmLib.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/afmLib.py | MIT |
def write(self, path, sep="\r"):
"""Writes out an AFM font to the given path."""
import time
lines = [
"StartFontMetrics 2.0",
"Comment Generated by afmLib; at %s"
% (time.strftime("%m/%d/%Y %H:%M:%S", time.localtime(time.time()))),
]
# write... | Writes out an AFM font to the given path. | write | python | fonttools/fonttools | Lib/fontTools/afmLib.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/afmLib.py | MIT |
def myKey(a):
"""Custom key function to make sure unencoded chars (-1)
end up at the end of the list after sorting."""
if a[0] == -1:
a = (0xFFFF,) + a[1:] # 0xffff is an arbitrary large number
return a | Custom key function to make sure unencoded chars (-1)
end up at the end of the list after sorting. | myKey | python | fonttools/fonttools | Lib/fontTools/afmLib.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/afmLib.py | MIT |
def _uniToUnicode(component):
"""Helper for toUnicode() to handle "uniABCD" components."""
match = _re_uni.match(component)
if match is None:
return None
digits = match.group(1)
if len(digits) % 4 != 0:
return None
chars = [int(digits[i : i + 4], 16) for i in range(0, len(digits)... | Helper for toUnicode() to handle "uniABCD" components. | _uniToUnicode | python | fonttools/fonttools | Lib/fontTools/agl.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/agl.py | MIT |
def _uToUnicode(component):
"""Helper for toUnicode() to handle "u1ABCD" components."""
match = _re_u.match(component)
if match is None:
return None
digits = match.group(1)
try:
value = int(digits, 16)
except ValueError:
return None
if (value >= 0x0000 and value <= 0x... | Helper for toUnicode() to handle "u1ABCD" components. | _uToUnicode | python | fonttools/fonttools | Lib/fontTools/agl.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/agl.py | MIT |
def __init__(self, unitsPerEm=None, font=None, isTTF=True, glyphDataFormat=0):
"""Initialize a FontBuilder instance.
If the `font` argument is not given, a new `TTFont` will be
constructed, and `unitsPerEm` must be given. If `isTTF` is True,
the font will be a glyf-based TTF; if `isTTF`... | Initialize a FontBuilder instance.
If the `font` argument is not given, a new `TTFont` will be
constructed, and `unitsPerEm` must be given. If `isTTF` is True,
the font will be a glyf-based TTF; if `isTTF` is False it will be
a CFF-based OTF.
The `glyphDataFormat` argument corr... | __init__ | python | fonttools/fonttools | Lib/fontTools/fontBuilder.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/fontBuilder.py | MIT |
def setupCharacterMap(self, cmapping, uvs=None, allowFallback=False):
"""Build the `cmap` table for the font. The `cmapping` argument should
be a dict mapping unicode code points as integers to glyph names.
The `uvs` argument, when passed, must be a list of tuples, describing
Unicode Va... | Build the `cmap` table for the font. The `cmapping` argument should
be a dict mapping unicode code points as integers to glyph names.
The `uvs` argument, when passed, must be a list of tuples, describing
Unicode Variation Sequences. These tuples have three elements:
(unicodeValue, v... | setupCharacterMap | python | fonttools/fonttools | Lib/fontTools/fontBuilder.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/fontBuilder.py | MIT |
def setupOS2(self, **values):
"""Create a new `OS/2` table and initialize it with default values,
which can be overridden by keyword arguments.
"""
self._initTableWithValues("OS/2", _OS2Defaults, values)
if "xAvgCharWidth" not in values:
assert (
"hmtx... | Create a new `OS/2` table and initialize it with default values,
which can be overridden by keyword arguments.
| setupOS2 | python | fonttools/fonttools | Lib/fontTools/fontBuilder.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/fontBuilder.py | MIT |
def setupGlyf(self, glyphs, calcGlyphBounds=True, validateGlyphFormat=True):
"""Create the `glyf` table from a dict, that maps glyph names
to `fontTools.ttLib.tables._g_l_y_f.Glyph` objects, for example
as made by `fontTools.pens.ttGlyphPen.TTGlyphPen`.
If `calcGlyphBounds` is True, the... | Create the `glyf` table from a dict, that maps glyph names
to `fontTools.ttLib.tables._g_l_y_f.Glyph` objects, for example
as made by `fontTools.pens.ttGlyphPen.TTGlyphPen`.
If `calcGlyphBounds` is True, the bounds of all glyphs will be
calculated. Only pass False if your glyph objects ... | setupGlyf | python | fonttools/fonttools | Lib/fontTools/fontBuilder.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/fontBuilder.py | MIT |
def setupAvar(self, axes, mappings=None):
"""Adds an axis variations table to the font.
Args:
axes (list): A list of py:class:`.designspaceLib.AxisDescriptor` objects.
"""
from .varLib import _add_avar
if "fvar" not in self.font:
raise KeyError("'fvar' t... | Adds an axis variations table to the font.
Args:
axes (list): A list of py:class:`.designspaceLib.AxisDescriptor` objects.
| setupAvar | python | fonttools/fonttools | Lib/fontTools/fontBuilder.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/fontBuilder.py | MIT |
def calcGlyphBounds(self):
"""Calculate the bounding boxes of all glyphs in the `glyf` table.
This is usually not called explicitly by client code.
"""
glyphTable = self.font["glyf"]
for glyph in glyphTable.glyphs.values():
glyph.recalcBounds(glyphTable) | Calculate the bounding boxes of all glyphs in the `glyf` table.
This is usually not called explicitly by client code.
| calcGlyphBounds | python | fonttools/fonttools | Lib/fontTools/fontBuilder.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/fontBuilder.py | MIT |
def setupPost(self, keepGlyphNames=True, **values):
"""Create a new `post` table and initialize it with default values,
which can be overridden by keyword arguments.
"""
isCFF2 = "CFF2" in self.font
postTable = self._initTableWithValues("post", _postDefaults, values)
if (... | Create a new `post` table and initialize it with default values,
which can be overridden by keyword arguments.
| setupPost | python | fonttools/fonttools | Lib/fontTools/fontBuilder.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/fontBuilder.py | MIT |
def setupMaxp(self):
"""Create a new `maxp` table. This is called implicitly by FontBuilder
itself and is usually not called by client code.
"""
if self.isTTF:
defaults = _maxpDefaultsTTF
else:
defaults = _maxpDefaultsOTF
self._initTableWithValues(... | Create a new `maxp` table. This is called implicitly by FontBuilder
itself and is usually not called by client code.
| setupMaxp | python | fonttools/fonttools | Lib/fontTools/fontBuilder.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/fontBuilder.py | MIT |
def setupDummyDSIG(self):
"""This adds an empty DSIG table to the font to make some MS applications
happy. This does not properly sign the font.
"""
values = dict(
ulVersion=1,
usFlag=0,
usNumSigs=0,
signatureRecords=[],
)
s... | This adds an empty DSIG table to the font to make some MS applications
happy. This does not properly sign the font.
| setupDummyDSIG | python | fonttools/fonttools | Lib/fontTools/fontBuilder.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/fontBuilder.py | MIT |
def addOpenTypeFeatures(self, features, filename=None, tables=None, debug=False):
"""Add OpenType features to the font from a string containing
Feature File syntax.
The `filename` argument is used in error messages and to determine
where to look for "include" files.
The optiona... | Add OpenType features to the font from a string containing
Feature File syntax.
The `filename` argument is used in error messages and to determine
where to look for "include" files.
The optional `tables` argument can be a list of OTL tables tags to
build, allowing the caller to... | addOpenTypeFeatures | python | fonttools/fonttools | Lib/fontTools/fontBuilder.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/fontBuilder.py | MIT |
def addFeatureVariations(self, conditionalSubstitutions, featureTag="rvrn"):
"""Add conditional substitutions to a Variable Font.
See `fontTools.varLib.featureVars.addFeatureVariations`.
"""
from .varLib import featureVars
if "fvar" not in self.font:
raise KeyError(... | Add conditional substitutions to a Variable Font.
See `fontTools.varLib.featureVars.addFeatureVariations`.
| addFeatureVariations | python | fonttools/fonttools | Lib/fontTools/fontBuilder.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/fontBuilder.py | MIT |
def setupCOLR(
self,
colorLayers,
version=None,
varStore=None,
varIndexMap=None,
clipBoxes=None,
allowLayerReuse=True,
):
"""Build new COLR table using color layers dictionary.
Cf. `fontTools.colorLib.builder.buildCOLR`.
"""
fr... | Build new COLR table using color layers dictionary.
Cf. `fontTools.colorLib.builder.buildCOLR`.
| setupCOLR | python | fonttools/fonttools | Lib/fontTools/fontBuilder.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/fontBuilder.py | MIT |
def setupCPAL(
self,
palettes,
paletteTypes=None,
paletteLabels=None,
paletteEntryLabels=None,
):
"""Build new CPAL table using list of palettes.
Optionally build CPAL v1 table using paletteTypes, paletteLabels and
paletteEntryLabels.
Cf. `fo... | Build new CPAL table using list of palettes.
Optionally build CPAL v1 table using paletteTypes, paletteLabels and
paletteEntryLabels.
Cf. `fontTools.colorLib.builder.buildCPAL`.
| setupCPAL | python | fonttools/fonttools | Lib/fontTools/fontBuilder.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/fontBuilder.py | MIT |
def setupStat(self, axes, locations=None, elidedFallbackName=2):
"""Build a new 'STAT' table.
See `fontTools.otlLib.builder.buildStatTable` for details about
the arguments.
"""
from .otlLib.builder import buildStatTable
assert "name" in self.font, "name must to be set u... | Build a new 'STAT' table.
See `fontTools.otlLib.builder.buildStatTable` for details about
the arguments.
| setupStat | python | fonttools/fonttools | Lib/fontTools/fontBuilder.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/fontBuilder.py | MIT |
def main(args=None):
"""Convert OpenType fonts to XML and back"""
from fontTools import configLogger
if args is None:
args = sys.argv[1:]
try:
jobs, options = parseOptions(args)
except getopt.GetoptError as e:
print("%s\nERROR: %s" % (__doc__, e), file=sys.stderr)
sy... | Convert OpenType fonts to XML and back | main | python | fonttools/fonttools | Lib/fontTools/ttx.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttx.py | MIT |
def _convertCFF2ToCFF(cff, otFont):
"""Converts this object from CFF2 format to CFF format. This conversion
is done 'in-place'. The conversion cannot be reversed.
The CFF2 font cannot be variable. (TODO Accept those and convert to the
default instance?)
This assumes a decompiled CFF table. (i.e. t... | Converts this object from CFF2 format to CFF format. This conversion
is done 'in-place'. The conversion cannot be reversed.
The CFF2 font cannot be variable. (TODO Accept those and convert to the
default instance?)
This assumes a decompiled CFF table. (i.e. that the object has been
filled via :met... | _convertCFF2ToCFF | python | fonttools/fonttools | Lib/fontTools/cffLib/CFF2ToCFF.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/cffLib/CFF2ToCFF.py | MIT |
def main(args=None):
"""Convert CFF OTF font to CFF2 OTF font"""
if args is None:
import sys
args = sys.argv[1:]
import argparse
parser = argparse.ArgumentParser(
"fonttools cffLib.CFFToCFF2",
description="Upgrade a CFF font to CFF2.",
)
parser.add_argument(
... | Convert CFF OTF font to CFF2 OTF font | main | python | fonttools/fonttools | Lib/fontTools/cffLib/CFF2ToCFF.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/cffLib/CFF2ToCFF.py | MIT |
def _convertCFFToCFF2(cff, otFont):
"""Converts this object from CFF format to CFF2 format. This conversion
is done 'in-place'. The conversion cannot be reversed.
This assumes a decompiled CFF table. (i.e. that the object has been
filled via :meth:`decompile` and e.g. not loaded from XML.)"""
# Cl... | Converts this object from CFF format to CFF2 format. This conversion
is done 'in-place'. The conversion cannot be reversed.
This assumes a decompiled CFF table. (i.e. that the object has been
filled via :meth:`decompile` and e.g. not loaded from XML.) | _convertCFFToCFF2 | python | fonttools/fonttools | Lib/fontTools/cffLib/CFFToCFF2.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/cffLib/CFFToCFF2.py | MIT |
def commandsToProgram(commands):
"""Takes a commands list as returned by programToCommands() and converts
it back to a T2CharString program list."""
program = []
for op, args in commands:
if any(isinstance(arg, list) for arg in args):
args = _flattenBlendArgs(args)
program.ex... | Takes a commands list as returned by programToCommands() and converts
it back to a T2CharString program list. | commandsToProgram | python | fonttools/fonttools | Lib/fontTools/cffLib/specializer.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/cffLib/specializer.py | MIT |
def _everyN(el, n):
"""Group the list el into groups of size n"""
l = len(el)
if l % n != 0:
raise ValueError(el)
for i in range(0, l, n):
yield el[i : i + n] | Group the list el into groups of size n | _everyN | python | fonttools/fonttools | Lib/fontTools/cffLib/specializer.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/cffLib/specializer.py | MIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.