Saravanan666/pypi-org huggingface dataset:
Package: cjkcms-cache
Wagtail (CJKCMS) CacheProject forked from [https://github.com/coderedcorp/wagtail-cache](Wagtail Cache) to add support for Wagtail 6.
Original project is still at Wagtail 5 compatibility, making it unusable withhttps://github.com/cjkpl/wagtail-cjkcms.git.Package name is left without change (wagtailcache), so it can be used as drop-in replacement for original package.===========A fast and simple page cache for Wagtail, inspired by the Django cache
middleware.Documentation|Source code on GitHub|PyPIStatusPython PackageBuildQuick StartFollow theInstallation GuideWhy Wagtail Cache?Django has a robust cache middleware that already has the functionality
needed to cache web pages effectively. But turning the cache middleware
on will blindly cache every request and does not work well with a Wagtail site.Wagtail Cache provides a middleware, decorator, and mixin that works well with
Wagtail pages, Django views, or even manually on any request/response to
efficiently cache and serve from cache.The end result is ultra-fast page serving that requires zero database hits
to serve cached pages. Other solutions such as template caching still require
database hits for Wagtail to serve a page.Wagtail Cache also does not require any additional infrastructure such as Redis,
Memcached, proxies, etc. It can work directly off the filesystem, or using any
of Django's built-in cache backends.ContributingFollow thecontributing guideAttributionIcon file "wagtailcache-bolt.svg":Was sourced from the Fork Awesome project athttps://github.com/ForkAwesome/Fork-Awesome.Is licensed under the Creative Commons Attribution 3.0 Unported license,
a copy of which is available athttps://creativecommons.org/licenses/by/3.0/Has been modified from the original sources.
Package: cjkcms-color-panel
Wagtail-Color-PanelIntroduces panels for selecting colors in Wagtail.FeaturesNativeColorPanel that can be used in your edit handlerNativeColorBlock for usage in a StreamFieldBased on the native HTML5 color pickerA custom db field for improved validationPolyfillColorPanel for cases that require IE11 support (built onSpectrum)Examplefromwagtail.modelsimportPagefromwagtail_color_panel.fieldsimportColorFieldfromwagtail_color_panel.edit_handlersimportNativeColorPanelclassMyPage(Page):color=ColorField()content_panels=Page.content_panels+[NativeColorPanel('color'),]DocumentationGetting startedAdding panel to a PageAdding to a StreamFieldReferenceContributingWant to contribute? Awesome. Just send a pull request.LicenseWagtail-Color-Panel is released under theMIT License.
Package: cjkcms-seo
CJKCMS Wagtail SEOProject forked from [https://github.com/coderedcorp/wagtail-seo](Wagtail SEO) to add support for Wagtail 5 and upcoming Wagtail 6.
Original project is still at Wagtail 4 compatibility, making it unusable withhttps://github.com/cjkpl/wagtail-cjkcms.git.===========Search engine and social media optimization for Wagtail.Source code on GitHub|Documentation|PyPIStatusPython PackageBuildGetting StartedFollow thegetting started guide.ContributingThe goal of Wagtail SEO is to become the most complete, go-to package for doing
SEO on Wagtail. This means it will not only provide the features, but will
continually stay up to date with evolving SEO practices and data standards (and
Google's whims). That being said we heartily welcome contributions!Follow thecontributing guideto get your development environment setup.AttributionIcon file "wagtailseo-line-chart.svg":Was sourced from the Fork Awesome project athttps://github.com/ForkAwesome/Fork-Awesome.Is licensed under the Creative Commons Attribution 3.0 Unported license,
a copy of which is available athttps://creativecommons.org/licenses/by/3.0/Has been modified from the original sources.
Package: cjkformat
CJK FormatThis Python 3 module provides utility functions for formatting fixed-width CJK strings. One of the most important features of tihs module is to align Latin and CJK characters using%{width}sspecifiers. For example, the following linesprint('%-10s|%-10s|'%('ab','cd'))print('%-10s|%-10s|'%('가나다라','마바사아'))will print misaligned lines between Latin and CJK characters even with the%-10sspecifiers.Now, using this module'sf()function, the above example would befromcjkformatimportfprint(f('%-10s|%-10s|','ab','cd'))print(f('%-10s|%-10s|','가나다라','마바사아'))which will print nicely aligned output.The module also defines a shortcut functionprintf()to minic the same function in the C language. For example,fromcjkformatimportprintfprintf('%-10s|%-10s|\n','ab','cd')printf('%-10s|%-10s|\n','가나다라','마바사아')For more information, please visitthe GitHub repository.
Package: cjkfuzz
CJKfuzzPrerequisitesPython 3.9+InstallationFrom PyPIpipinstallcjkfuzzFrom Sourcepipinstallgit+https://github.com/eddielin0926/cjkfuzz.gitUsagefromcjkfuzzimportfuzzfuzz.ratio('你好','你好嗎?')LicenseThis project is licensed under the terms of theMIT License
Package: cjkjust
cjkjustHaving strings containing CJK characters left-, right-justified or centered conveniently.Installationpip install cjkjustFunctionsis_wide(char) -> bool: returns whether a charactercharis widecjklen(string) -> int: returns the display width of astringcontaining CJK characterscjkljust(string, width: int, fillbyte=' '): hasstringleft-justifiedcjkrjust(string, width: int, fillbyte=' '): hasstringright-justifiedcjkcenter(string, width: int, fillbyte=' '): hasstringcenteredCaveat:<TAB>instringruins the print-out.Examplesimportcjkjust# right-justify a column of stringsprint(cjkjust.cjkrjust('hello 世界',20))print(cjkjust.cjkrjust('你好world',20))print(cjkjust.cjkrjust('again and again',20))Optional dependencywcwidth: if installed, 0-width characters will also be well handled incjkljust,cjkrjust, andcjkcenter.
Caveat: installingwcwidthand explicitly setcjkjust.raises_on_indeterminatetoTrueimplies thatValueErrorwill be raised if indeterminate-width-characters (e.g.<TAB>) is instringIt can be installed along withcjkjustby:pip install cjkjust[allchars]
Package: cjkradlib
CJKradlibGenerate compositions, supercompositions and variants for a given Hanzi / Kanji, based oncjkvi-ids. (Previously,cjk-decomp.)Installationpip install cjkradlibAlso, IDS sequences use full range of CJK ideographs, so the fonts
that covers all encoded ideographs (such
asHanaMinorHanamin AFDKO)
should be used.UsagefromcjkradlibimportRadicalFinderfinder=RadicalFinder(lang='zh')# default is 'zh'result=finder.search('麻')print(result.compositions)# ['广', '林']print(result.supercompositions)# ['摩', '魔', '磨', '嘛', '麽', '靡', '糜', '麾']print(result.variants)# ['菻']Supercompositions are based on the character frequency in each language, so altering the language give slightly different results.fromcjkradlibimportRadicalFinderfinder=RadicalFinder(lang='jp')result=finder.search('麻')print(result.supercompositions)# ['摩', '磨', '魔', '麿']Related projectsChineseViewerHanziLevelUpCJKrelatePlanUsehttps://github.com/cjkvi/cjkvi-idsas the source for CJK-decomposition.
Package: cjkstr
CJKStr -- A Simple Package for Processing CJK stringIn Python, the string formatting function will treat a CJK characters as wide as a english letter.This make the result weired. For example:print("1234567890"*4)a="測試"w=10print(f"{a:{w}s}|")produce output as this:1234567890123456789012345678901234567890測試|The width is setting to 10 in the formatting string. Since the 2 Chinese characters occupies 2 more spaces, the bar is printed in position 13.To avoid this problem, we need to know how many CJK Chinese characters in the string and resuce the width accorantly.This package has only one funcion:count_cjk_chars(s)# return number of chinese characters in string sexampleimportcjkstrprint("1234567890"*4)a="測試"w=10print(f"{a:{w}s}|")w=10-cjkstr.count_cjk_chars(a)print(f"{a:{w}s}|")ouput:1234567890123456789012345678901234567890測試|測試|
Package: cjk-textwrap
CJK Textwrapcjk-textwrap是Python 3.6textwrap模块的中日韩字符兼容版本。此外，它提供了灵活的接口以便用户自定义分词器（如结巴分词）。cjk-textwrapis aCJK characterscompatible version of Python 3.6'stextwrapmodule. Moreover, it provides flexible interfaces which allows users to define their own text segmentation for text wrapping likejieba.Installation 安装pip:pipinstallcjk-textwrappoetry:poetryaddcjk-textwrapFeature 功能特性Although user can get various language support by adding their custom splitter,cjk-textwrapprovides built-inEnglish-Chinesemixed text phrase wrapping support.虽然可以通过自定义分词器添加各种语言的支持，但是cjk-textwrap提供了原生的中-英文混合句支持。Chinese Support 中文支持Japanese Support 日文支持Korean Support 韩文支持LICENSE 协议许可This project is licensed under MIT.
Package: cjlpytoolkit
python环境备份与迁移原环境执行以下命令，备份环境所需pip freeze > requirements.txt新环境执行以下命令还原pip install -r requirements.txtPython argparse模块使用步骤样例importargparseparser=argparse.ArgumentParser(proj='cmd',description='Process some integers.')parser.add_argument('integers',metavar='N',type=int,nargs='+',help='an integer for the accumulator')parser.add_argument('--sum',dest='accumulate',action='store_const',const=sum,default=max,help='sum the integers (default: find the max)')args=parser.parse_args()print(args.accumulate(args.integers))ArgumentParser对象详解classargparse.ArgumentParser(prog=None,# 设定程序名称 (defaul: sys.argv[0])usage=None,# 替换默认的Usage信息description=None,# 程序简要信息说明(参数说明前)epilog=None,# 附加信息说明(参数说明后)parents=[],# 继承父解析器(parser)formatter_class=argparse.HelpFormatter,# 自定义帮忙信息显示格式(4种)prefix_chars='-',# 参数前缀符号(默认为-,如：-h/--help)fromfile_prefix_chars=None,# 从文件中引用参数（与在命令行直接写作用一致，解决参数过多的情况）argument_default=None,# 可设置argparse.SUPPRESS阻止默认参数默认值conflict_handler='error',# 参数冲突处理add_help=True,# 帮助信息中默认添加"-h, --help"描述allow_abbrev=True# 允许参数缩写)add_argument()方法ArgumentParser.add_argument(nameorflags...# 选项的名称或列表,例如：foo/-f/--foo[,action]# 采取的基本操作store(默认)存储参数值store_const使用该字符串选项时，取用const值store_true使用该字符串选项时，参数值置为Truestore_false使用该字符串选项时，参数值置为Falseappend同一个命令行中多次使用该字符串选项时，以追加的方式将值添加到list中append_const将多个字符串选项的const值合并到一个listcount统计选项出现的次数（如："-vvv",则最终值为3）helpparser默认会添加一个helpaction。(一般不用理会)version打印版本信息也可以自定义action类[,nargs]# 该参数值要求的数量数值指明参数个数?提供了参数则取参数值；无参数但声明了选项字符串则取const值；无参数也未声明选择字符串则取default值*所有参数存入list+与*类似，但参数个数不能为空argparse.REMAINDER原封不动的记录参数到list中，通常用于将这些参数传递到其它的命令行工具。[,const]# action/nargs部分要求的常值1、当action="store_const"或者"append_const"时需要设置2、当选项为(-f/--foo),nargs='?'，同时未提供具体参数时，取用该值。[,default]# 参数默认值[,type]# 参数类型（内建参数或者函数，也可是自定义函数）[,choices]# 允许的参数值（白名单）,tuple/range[,required]# 选项是否必须，设置为True表示选项必填。[,help]# 参数说明,可以用其它类似 %(prog)s 格式调用prog值；可设置argparse.SUPPRESS使该选项在帮助信息中不可见。[,metavar]# 定义参数在Usage信息中的名称[,dest]# 解析后的属性名称)git .gitignore 忽略规则#注释           .gitignore的注释
*.txt           忽略所有 .txt 后缀的文件
!src.a          忽略除 src.a 外的其他文件
/todo           仅忽略项目根目录下的 todo 文件，不包括 src/todo
build/          忽略 build/目录下的所有文件，过滤整个build文件夹；
doc/*.txt       忽略doc目录下所有 .txt 后缀的文件，但不包括doc子目录的 .txt 的文件
  
bin/:           忽略当前路径下的 bin 文件夹，该文件夹下的所有内容都会被忽略，不忽略 bin 文件
/bin:           忽略根目录下的 bin 文件
/*.c:           忽略 cat.c，不忽略 build/cat.c
debug/*.obj:    忽略debug/io.obj，不忽略 debug/common/io.obj和tools/debug/io.obj
**/foo:         忽略/foo, a/foo, a/b/foo等
a/**/b:         忽略a/b, a/x/b, a/x/y/b等
!/bin/run.sh    不忽略bin目录下的run.sh文件
*.log:          忽略所有 .log 文件
config.js:      忽略当前路径的 config.js 文件
  
/mtk/           忽略整个文件夹
*.zip           忽略所有.zip文件
/mtk/do.c       忽略某个具体文件git rm -r --cached有时候，gitignore考虑不全面，发现有不该提交的文件已经提交后，仅仅在.gitignore中加入忽略是不行的。这个时候需要执行:git rm -r --cached 文件/文件夹名字去掉已经托管的文件，然后提交即可。
Package: cjm-byte-track
cjm-byte-trackA standalone Python implementation of theByteTrackmulti-object tracker based
on theofficial
implementation.Installpipinstallcjm_byte_trackTutorial:Real-Time Object Tracking with YOLOX and
ByteTrack:Learn how to track objects across video frames with YOLOX and
ByteTrack.How to use# Import ByteTrack packagefromcjm_byte_track.coreimportBYTETrackerfromcjm_byte_track.matchingimportmatch_detections_with_tracks# Initialize a ByteTracker objecttracker=BYTETracker(track_thresh=0.25,track_buffer=30,match_thresh=0.8,frame_rate=frame_fps)withtqdm(total=frames,desc="Processing frames")aspbar:whilevideo_capture.isOpened():ret,frame=video_capture.read()ifret:# Prepare an input image for inferencergb_img,input_dims,offsets,min_img_scale,input_img=prepare_image_for_inference(frame,test_sz,max_stride)# Convert the existing input image to NumPy formatinput_tensor_np=np.array(input_img,dtype=np.float32).transpose((2,0,1))[None]/255# Start performance counter`mstart_time=time.perf_counter()# Run inferenceoutputs=session.run(None,{"input":input_tensor_np})[0]# Process the model outputproposals=process_outputs(outputs,input_tensor_np.shape[input_dim_slice],bbox_conf_thresh)# Apply non-max suppression to the proposals with the specified thresholdproposal_indices=nms_sorted_boxes(calc_iou(proposals[:,:-2]),iou_thresh)proposals=proposals[proposal_indices]bbox_list=(proposals[:,:4]+[*offsets,0,0])*min_img_scalelabel_list=[class_names[int(idx)]foridxinproposals[:,4]]probs_list=proposals[:,5]# Update tracker with detections.track_ids=[-1]*len(bbox_list)# Convert to tlbr formattlbr_boxes=bbox_list.copy()tlbr_boxes[:,2:4]+=tlbr_boxes[:,:2]# Update tracker with detectionstracks=tracker.update(output_results=np.concatenate([tlbr_boxes,probs_list[:,np.newaxis]],axis=1),img_info=rgb_img.size,img_size=rgb_img.size)track_ids=match_detections_with_tracks(tlbr_boxes=tlbr_boxes,track_ids=track_ids,tracks=tracks)# End performance counterend_time=time.perf_counter()# Calculate the combined FPS for object detection and trackingfps=1/(end_time-start_time)# Display the frame rate in the progress barpbar.set_postfix(fps=fps)# Filter object detections based on tracking resultsbbox_list,label_list,probs_list,track_ids=zip(*[(bbox,label,prob,track_id)forbbox,label,prob,track_idinzip(bbox_list,label_list,probs_list,track_ids)iftrack_id!=-1])# Annotate the current frame with bounding boxes and tracking IDsannotated_img=draw_bboxes_pil(image=rgb_img,boxes=bbox_list,labels=[f"{track_id}-{label}"fortrack_id,labelinzip(track_ids,label_list)],probs=probs_list,colors=[int_colors[class_names.index(i)]foriinlabel_list],font=font_file,)annotated_frame=cv2.cvtColor(np.array(annotated_img),cv2.COLOR_RGB2BGR)video_writer.write(annotated_frame)pbar.update(1)else:breakvideo_capture.release()video_writer.release()
Package: cjm-diffusers-utils
cjm-diffusers-utilsInstallpipinstallcjm_diffusers_utilsHow to useimporttorchfromcjm_pytorch_utils.coreimportget_torch_devicedevice=get_torch_device()dtype=torch.float16ifdevice=='cuda'elsetorch.float16device,dtype('cuda', torch.float16)pil_to_latentfromcjm_diffusers_utils.coreimportpil_to_latentfromPILimportImagefromdiffusersimportAutoencoderKLmodel_name="stabilityai/stable-diffusion-2-1"vae=AutoencoderKL.from_pretrained(model_name,subfolder="vae").to(device=device,dtype=dtype)img_path=img_path='../images/cat.jpg'src_img=Image.open(img_path).convert('RGB')print(f"Source Image Size:{src_img.size}")img_latents=pil_to_latent(src_img,vae)print(f"Latent Dimensions:{img_latents.shape}")Source Image Size: (768, 512)
Latent Dimensions: torch.Size([1, 4, 64, 96])latent_to_pilfromcjm_diffusers_utils.coreimportlatent_to_pildecoded_img=latent_to_pil(img_latents,vae)print(f"Decoded Image Size:{decoded_img.size}")Decoded Image Size: (768, 512)text_to_embfromcjm_diffusers_utils.coreimporttext_to_embfromtransformersimportCLIPTextModel,CLIPTokenizer# Load the tokenizer for the specified modeltokenizer=CLIPTokenizer.from_pretrained(model_name,subfolder="tokenizer")# Load the text encoder for the specified modeltext_encoder=CLIPTextModel.from_pretrained(model_name,subfolder="text_encoder").to(device=device,dtype=dtype)prompt="A cat sitting on the floor."text_emb=text_to_emb(prompt,tokenizer,text_encoder)text_emb.shapetorch.Size([2, 77, 1024])prepare_noise_schedulerfromcjm_diffusers_utils.coreimportprepare_noise_schedulerfromdiffusersimportDEISMultistepSchedulernoise_scheduler=DEISMultistepScheduler.from_pretrained(model_name,subfolder='scheduler')print(f"Number of timesteps:{len(noise_scheduler.timesteps)}")print(noise_scheduler.timesteps[:10])noise_scheduler=prepare_noise_scheduler(noise_scheduler,70,1.0)print(f"Number of timesteps:{len(noise_scheduler.timesteps)}")print(noise_scheduler.timesteps[:10])Number of timesteps: 1000
tensor([999., 998., 997., 996., 995., 994., 993., 992., 991., 990.])
Number of timesteps: 70
tensor([999, 985, 970, 956, 942, 928, 913, 899, 885, 871])prepare_depth_maskfromcjm_diffusers_utils.coreimportprepare_depth_maskdepth_map_path='../images/depth-cat.png'depth_map=Image.open(depth_map_path)print(f"Depth map size:{depth_map.size}")depth_mask=prepare_depth_mask(depth_map).to(device=device,dtype=dtype)depth_mask.shape,depth_mask.min(),depth_mask.max()Depth map size: (768, 512)

(torch.Size([1, 1, 64, 96]),
 tensor(-1., device='cuda:0', dtype=torch.float16),
 tensor(1., device='cuda:0', dtype=torch.float16))
Package: cjm-kaggle-utils
cjm-kaggle-utilsInstallpipinstallcjm_kaggle_utilsHow to usesave_kaggle_credsfromcjm_kaggle_utils.coreimportsave_kaggle_credsusername="name"key="12345"save_kaggle_creds(username,key,overwrite=False)Credentials already present. Set `overwrite=True` to replace them.dl_kagglefromcjm_kaggle_utils.coreimportdl_kagglefrompathlibimportPath# Get the path to the directory where datasets are storeddataset_dir=Path("./Datasets/")dataset_dir.mkdir(parents=True,exist_ok=True)print(f"Dataset Directory:{dataset_dir}")# Create the path to the data directoryarchive_dir=dataset_dir/'../Archive'archive_dir.mkdir(parents=True,exist_ok=True)print(f"Archive Directory:{archive_dir}")Dataset Directory: Datasets
Archive Directory: Datasets/../Archive# Set the name of the datasetdataset_name='style-image-samples'# Construct the Kaggle dataset name by combining the username and dataset namekaggle_dataset=f'innominate817/{dataset_name}'# Create the path to the zip file that contains the datasetarchive_path=Path(f'{archive_dir}/{dataset_name}.zip')print(f"Archive Path:{archive_path}")# Create the path to the directory where the dataset will be extracteddataset_path=Path(f'{dataset_dir}/{dataset_name}')print(f"Dataset Path:{dataset_path}")Archive Path: Datasets/../Archive/style-image-samples.zip
Dataset Path: Datasets/style-image-samplesdl_kaggle(kaggle_dataset,archive_path,dataset_path)Downloading style-image-samples.zip to Datasets/../Archive

100%|██████████████████████████████████████████████████████████████████████████████████████████████| 16.2M/16.2M [00:00<00:00, 44.0MB/s]!ls{dataset_path}images
Package: cjm-pandas-utils
cjm-pandas-utilsThis file will become your README and also the index of your
documentation.Installpipinstallcjm_pandas_utilsHow to usemarkdown_to_pandasfromcjm_pandas_utils.coreimportmarkdown_to_pandasmd_table_str="""| Name | Age | Occupation || ---- | --- | ---------- || John | 35  | Engineer    || Jane | 29  | Teacher     || Bob  | 42  | Doctor      |"""markdown_df=markdown_to_pandas(md_table_str)markdown_df.iloc[1]Name             Jane
Age                29
Occupation    Teacher
Name: 1, dtype: object
Package: cjm-parallel-utils
cjm-parallel-utilsInstallpipinstallcjm_parallel_utilsHow to useparallelfromcjm_parallel_utils.coreimportparallelfromfunctoolsimportpartialtest_array=list(range(10))print(test_array)deftest_func(index,array):array[index]*=2partial_func=partial(test_func,array=test_array)parallel(partial_func,arr=range(len(test_array)),leave=True);print(test_array)[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

  0%|          | 0/10 [00:00<?, ?it/s]

[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
Package: cjm-pil-utils
cjm-pil-utilsInstallpipinstallcjm_pil_utilsHow to useget_img_filesfromcjm_pil_utils.coreimportget_img_filesfrompathlibimportPathimg_dir=Path('../images/')img_paths=get_img_files(img_dir)img_paths[PosixPath('../images/cat.jpg'), PosixPath('../images/depth-cat.png')]resize_imgfromcjm_pil_utils.coreimportresize_imgfromPILimportImage# For working with imagesimg_path=img_paths[0]src_img=Image.open(img_path).convert('RGB')print(f"Image Size:{src_img.size}")resized_img=resize_img(src_img,target_sz=384,divisor=32)print(f"New Image Size:{resized_img.size}")Image Size: (768, 512)
New Image Size: (576, 384)stack_imgsfromcjm_pil_utils.coreimportstack_imgsstacked_imgs=stack_imgs([resized_img,resized_img])print(f"Stacked Image Size:{stacked_imgs.size}")Stacked Image Size: (576, 768)avg_imagesfromcjm_pil_utils.coreimportavg_imagesimg_1,img_2=(Image.open(path)forpathinimg_paths)avg_img=avg_images(img_1,img_2,0.5)crop_squarefromcjm_pil_utils.coreimportcrop_squarecrop_square(src_img).size(512, 512)
Package: cjm-psl-utils
cjm-psl-utilsThis file will become your README and also the index of your
documentation.Installpipinstallcjm_psl_utilsHow to useget_source_codefromcjm_psl_utils.coreimportget_source_codeget_source_code(get_source_code,markdown=True)defget_source_code(obj:object,# The object whose source code you want to retrieve.markdown=False,# Return the source code formatted as markdownremove_documentation=False):# Remove docstrings and comments"""Returns the source code of an object, with an optional markdown formatting."""# Get the source code of the objectsource=inspect.getsource(obj)# If the remove_documentation flag is set to True, remove docstrings and commentsifremove_documentation:in_docstring=Falselines=source.split('\n')source=''# Remove docstringsforlineinlines:ifline.strip().startswith(('\'\'\'','\"\"\"')):in_docstring=notin_docstringelifnotin_docstring:source+=line+'\n'# Remove commentssource='\n'.join([lineforlineinsource.split('\n')ifnotline.strip().startswith(('#'))])source=source.replace('\n\n','\n')ifmarkdown:# Format the source code as markdown code blocksource=f"```python\n{source}\n```"# Check if the code is running in Jupyter Notebooktry:get_ipythonfromIPython.displayimportMarkdown# Format the source code as an IPython Markdown objectsource=Markdown(source)exceptNameError:# If not in Jupyter Notebook, do nothingpass# Return the formatted source codereturnsourcefile_extractfromcjm_psl_utils.coreimportfile_extractfrompathlibimportPathfname="../images/images.zip"dest=Path("./images")print(dest.exists())file_extract(fname,dest)print(dest.exists())print(list(os.walk(dest))[0][2])False
True
['cat.jpg']
Package: cjm-pytorch-utils
cjm-pytorch-utilsInstallpipinstallcjm_pytorch_utilsHow to useset_seedfromcjm_pytorch_utils.coreimportset_seedseed=1234set_seed(seed)pil_to_tensorfromcjm_pytorch_utils.coreimportpil_to_tensorfromPILimportImagefromtorchvisionimporttransformsimg_path=img_path='../images/cat.jpg'src_img=Image.open(img_path).convert('RGB')print(f"Source Image Size:{src_img.size}")img_tensor=pil_to_tensor(src_img,[0.5],[0.5])img_tensor.shape,img_tensor.min(),img_tensor.max()Source Image Size: (768, 512)

(torch.Size([1, 3, 512, 768]), tensor(-1.), tensor(1.))tensor_to_pilfromcjm_pytorch_utils.coreimporttensor_to_piltensor_img=tensor_to_pil(transforms.ToTensor()(src_img))tensor_imgiterate_modulesfromcjm_pytorch_utils.coreimportiterate_modulesimporttorchfromtorchvisionimportmodelsvgg=models.vgg16(weights=models.VGG16_Weights.IMAGENET1K_V1).featuresforindex,moduleinenumerate(iterate_modules(vgg)):iftype(module)==torch.nn.modules.activation.ReLU:print(f"{index}:{module}")1: ReLU(inplace=True)
3: ReLU(inplace=True)
6: ReLU(inplace=True)
8: ReLU(inplace=True)
11: ReLU(inplace=True)
13: ReLU(inplace=True)
15: ReLU(inplace=True)
18: ReLU(inplace=True)
20: ReLU(inplace=True)
22: ReLU(inplace=True)
25: ReLU(inplace=True)
27: ReLU(inplace=True)
29: ReLU(inplace=True)tensor_stats_dffromcjm_pytorch_utils.coreimporttensor_stats_dftensor_stats_df(torch.randn(1,3,256,256))<style scoped>
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }

    .dataframe thead th {
        text-align: right;
    }
</style>0mean0.003342std0.99868min-4.558271max4.815985shape(1, 3, 256, 256)get_torch_devicefromcjm_pytorch_utils.coreimportget_torch_deviceget_torch_device()'cuda'denorm_img_tensorfromcjm_pytorch_utils.coreimportdenorm_img_tensortensor_to_pil(img_tensor)tensor_to_pil(denorm_img_tensor(img_tensor,[0.5],[0.5]))