Saravanan666/pypi-org huggingface dataset:
Package: treelogger4mongo
treelogger4mongo================The treelogger4mongo is a simple module that allows you to lo debug data into a mongo database. The only difference is that this module supports logging in a tree-like structure.## How does it work?Lets imagine we have a process that has to loop through all your user database. Adding the mongo logger would only have to be something like this:import treelogger4mongo as treelogdef process_users(users):branch = treelog.info("About to process %s users." % len(users))for user in users:sub = branch.info("Processing: %s" % user.username,{'username': user.username,'email': user.email})#do something with user.sub.info("Did something with user.")#something elseif user.is_special:some_heavy_function(user, sub.info("Starting some_heavy_function."))sub.info("Finished processing.")What we get from this is a root log entry with the message "About to process ... users.". However, this is where treelogger comes strong in, each log message after that is applied like a branch to that root log entry.A sample output would be a log structure in mongo that looks something like this:About to process 2 users├───Processing John Doe {username: johndoe, email: }│   ├───Did something with user.│   └───Finished processing└───Processing John Smith├───Did something with user.├───Starting some_heavy_function.│   └───....└───Finished processingWith this, you get a nice tree structure for your logs in mongo that makes it easier to read the log and trace each function.**Hint:**Each branch can, including a simple message, contain any arbitrary information in the data parameter. This accepts any object and is automatically saved with the log entry.## Getting it to runIn order to be able to dynamically call treelogger4mongo, you need to have initialized it atlease once somewhere. The treelogger4mongo automatically saves the configuration and allows you to call its static functions.from treelogger4mongo import TreeTree("host", "port", "database", "collection")
Package: tree-lstm
Tree LSTMThis repository contains a Pytorch Implementation of "Improved Semantic Representations From Tree-Structured Long Short-Term Memory Networks "
(https://arxiv.org/abs/1503.00075).This contains two type of tree-lstm (Child sum, N-ary). This was tested by Python 3.6, Pytorch 1.3.0., and this internally uses dgl 0.4.0This repository referencedhttps://github.com/dmlc/dgl/blob/master/examples/pytorch/tree_lstm/tree_lstm.pyInstallationpip install tree-lstmafter installed, you can use this viaimport TreeLSTM, Tree, BatchedTreeUsagemake Tree object (initialize with arbitrary tensor)make BatchedTree object using list of Tree objectmake TreeLSTM object (inherited from torch.nn.Module)pass BatchedTree object into TreeLSTM objectFor more detailed usage, please seetest.pyThanks for reporting issues / contributions / starts / watches!
Package: treem
treem - neuron morphology processing toolModule provides data structure and command-line tools for accessing and
manipulating the digital reconstructions of the neuron morphology in
Stockley-Wheal-Cannon format (SWC).Main classesAccess to morphological data from the source code is supported by the
classesTree,Node,MorphandSWC.Tree- Recursive tree data structureNode- Morphology data storageMorph- Neuron morphology representationSWC- Definitions of the data formatCommandsCommon operations with SWC files are possible via theswccommand-line
tool:swc <command> [options] fileor sometimes more convenient asswc <command> file [file ...] [options]List ofswccommands:check- Test morphology reconstruction for structural consistencyconvert- Convert morphology to compliant SWC formatfind- Locate single nodes in the reconstructionmeasure- Calculate morphometric featuresmodify- Manipulate morphology reconstructionrender- Display 3D model of the reconstructionrepair- Correct reconstruction errorsview- Show morphology structureInstallationInstall the latest stable release:pip3 install treemInstall a development version:pip3 install git+https://github.com/a1eko/treemSee alsopip3documentation for installation alternatives.DependenciesModuletreemhas minimal runtime dependencies:python>= 3.7matplotlibnumpyPyOpenGL(optional) enablesswc rendercommandFor testing and documentation,treemneeds development packages with
third-party extensions:sphinxwithnapoleonandprogramoutputpytestwithpytest-covcoverageDocumentationDocumentation is available online atRead the Docs.FundingHorizon 2020 Framework Programme (785907, HBP SGA2); Horizon 2020 Framework Programme (945539, HBP SGA3); Vetenskapsrådet (VR-M-2017-02806, VR-M-2020-01652); Swedish e-science Research Center (SeRC); KTH Digital Futures.We acknowledge the use of Fenix Infrastructure resources, which are partially funded from the European Union's Horizon 2020 research and innovation programme through the ICEI project under the grant agreement No. 800858.The computations and testing were enabled by resources provided by the Swedish National Infrastructure for Computing (SNIC) at PDC KTH partially funded by the Swedish Research Council through grant agreement no. 2018-05973.
Package: tree-matching-distance
tree_matching_distanceAn implementation of the tree distance metric suggested by Lin, Rajan, and Moret, at ISBRA 2011.DescriptionThis package contains a function to import and provides a command-line tool that compares two given
trees and return a distance between them.UsageRun the program liketree_matching_distancet1.treet2.treewhere the two file parameters contain trees in Newick format on the same taxa.To use the distance method from within your own code, writefromete3importTreefromtree_matching_distanceimportdistancet1=Tree('((a, b), (c, d));')t2=Tree('((a, c), (b, d));')d=distance(t1,t2)print(d)for a simple test. Note that this package requires ETE3 trees.
Package: treemirror
TreeMirrorTreeMirror is a Python program that creates a mirrored copy of a directory structure, allowing users to easily duplicate and transfer directory trees.RequirementsTo run TreeMirror, you will need to have Python 3.x installed on your machine. You can check if you have Python installed by running the following command in your terminal:python --versionInstallationTo install TreeMirror, you can simply clone this repository to your local machine:git clone https://github.com/samyak-jn/treemirror.gitOnce cloned, you can navigate to thetreemirrordirectory and install the program's dependencies using the following command:pip install -r requirements.txtUsageTo use TreeMirror, you can run the program using the following command:python treemirror/treemirror.py <input_directory> <output_directory><input_directory>: the path to the directory structure to be copied.<output_directory>: the path to the directory where the copy will be created.Replace<input_directory>with the path to the directory whose structure you want to mirror, and<output_directory>with the path to the directory where you want to create the mirrored copy.If the<output_directory>already exists, the program will ask if you want to overwrite its contents.When the program is run, it will first display a CLI interface to visualize the directory structure of the input directory. The interface will show each directory as a node, with the parent directories above the child directories. Each node will be indented to indicate its level in the directory hierarchy.After displaying the directory structure, the program will prompt the user to confirm if they want to overwrite the files in the output directory. If the user confirms, the program will create a copy of the input directory structure in the output directory. If the output directory already exists, the program will ask the user if they want to overwrite the files in the directory.TestingTo run the unit tests for TreeMirror, navigate to thetestdirectory and run the following command:python -m unittestLicenseTreeMirror is licensed under the MIT License. See theLICENSEfile for more information.
Package: treeop
collection of operations for nested dict, list and tuple.Usageapplyto>>>applyto(print,{"a":[1,2],"b":[3,4],level=1)[1,2][3,4]>>>applyto(print,{"a":[1,2],"b":[3,4],level=2)1234mapto>>>mapto(sum,{"a":[1,2],"b":[3,4],level=1){'a':3,'b':7}>>>mapto(lambdax:2*x,{"a":[1,2],"b":[3,4],level=2){'a':[2,4],'b':[6,8]}transpose>>>transpose({"a":[1,2],"b":[3,4],levels=[1,0])[{"a":1,"b":3},{"a":2,"b",4}]LicenseThese codes are licensed underCC0.Tips
Package: tree_output
tree_output===========[![Build Status](https://travis-ci.org/ewiger/tree_output.svg?branch=master)](https://travis-ci.org/ewiger/tree_output)Python library to simplify building of tree output with command-line interfaces.Supported output format options are:- json- ascii- ansi- nullexamples--------```pythontree_output = HierarchicalOutput.factory('ansi')import coloramatree_output.emit('foo')tree_output.add_level()tree_output.emit('foO')tree_output.add_level()tree_output.emit('bar')tree_output.add_level()for num in range(10):tree_output.emit(num)tree_output.emit(10, closed=True)tree_output.remove_level()tree_output.emit('baz', closed=True)tree_output.emit('foo2')```this will draw a colorful ANSI output like this```.├── foo│   ├── foO│   │   ├── bar│   │   │   ├── 0│   │   │   ├── 1│   │   │   ├── 2│   │   │   ├── 3│   │   │   ├── 4│   │   │   ├── 5│   │   │   ├── 6│   │   │   ├── 7│   │   │   ├── 8│   │   │   ├── 9│   │   │   └── 10│   └── baz├── foo2```logging-------Another option is to integrate with logging and pass hierarchical meta instructions via optional **extra** argument, e.g.```pythonhoutput = HierarchicalOutput.factory(format='json')#houtput = HierarchicalOutput.factory(format='ansi')handler = HierarchicalOutputHandler(houtput=houtput)logger = logging.getLogger('foo')logging.root.addHandler(handler)# Emission.logger.info('foo')logger.info('bar', extra={'add_hlevel': True})logger.info('foo2')logger.info('bar', extra={'add_hlevel': True})logger.info('foo2')logger.info('Numbers', extra={'add_hlevel': True})for num in range(10):logger.warn(num)logger.warn('end of numbers', extra={'hclosed': True})logger.debug('level up', extra={'remove_hclosed': True})```produces```json["foo", ["bar", "foo2", ["bar", "foo2", ["Numbers","0","1","2","3","4","5","6","7","8","9","end of numbers"],"level up"]]]```tests-----For tests we use *nose*, i.e. usage would be:```bashcd tests && nosetests```
Package: treeparser
Tree ParserA simple tree parser for trees in bracket notation written in python. For example the following code (with default values forfontdictandtextkwargsexplicitly specified)fromtreeparserimportTreeParserimportmatplotlib.pyplotaspltfig,ax=plt.subplots(1,1,figsize=(20,10))string="[C[C[C[C[C][C[G7[Dm7][G7]][C]]][G[G[D7[Am][D7]][G]][G[D7[Am[CM7][Am]][D7]][G]]]][C[C[Bo7[Dm[C#o7][Dm]][Bo7]][C]][C[G7[Dm7[FM7][Dm7]][G7]][C [C][C[G7[FM7[C7][FM7]][G7[G7[F#o7][G7[Fm6][G7]]][G7[G7[G64][G7[G47][G7]]][G7[G47[G64[F#o7][G64]][G47]][G7]]]]][C[G7[C64[C7][C64]][G7]][C]]]]]]]]"parser=TreeParser(string,True)parser.plot(ax=ax,padding=1,fontdict={'fontsize':12},textkwargs={'bbox':{'facecolor':'red','pad':10},'style':'italic'})results in:
Package: tree-peb
Directory TreeList contents of directories in tree-like format.InstallationExample$ python .\tree.py
.\
|
├── tree\
│   ├── __init__.py
│   ├── cli.py
│   └── tree_util.py
│
├── LICENSE
├── README.md
└── tree.pyCLI Optionsusage: tree [-h] [-v] [-d] [-o OUTPUT_FILE] [ROOT_DIR]

positional arguments:
  ROOT_DIR              Generate a full directory tree from the given ROOT_DIR

optional arguments:
  -h, --help            show this help message and exit
  -v, --version         show program's version number and exit
  -d, --dir-only        Generate a directory-only tree
  -o OUTPUT_FILE, --output-file OUTPUT_FILE
                        Store the tree output in a file
Package: treepick
CURSES TREE STYLE PATH PICKERA Curses based, tree style, path picker. For use as a terminal based file dialog.INSTALLATIONpip install treepickCLI USAGEusage: treepick [-h] [-a] [-r] [path]

Select paths from a directory tree.

positional arguments:
  path            A valid path.

optional arguments:
  -h, --help      show this help message and exit
  -a, --hidden    Show all hidden paths too.
  -r, --relative  Output relative paths.PYTHON USAGEfromtreepickimportpickhidden=Trueparent_path='/path/to/directory'my_list_of_paths=pick(parent_path,hidden)my_amazing_function(my_list_of_paths)KEYBINDINGSKEYACTIONUP, kStep up one line.DOWN, jStep down one line.KJump to previous parent directory.JJump to next parent directory.PGDN, fJump down a page of lines.PGUP, bJump up a page of lines.HOME, gJump to first line.END, GJump to last line.TAB, RETToggle expansion/collapse of directory.RIGHT, lExpand and step into directory.LEFT, hCollapse directory.SHIFT RIGHT, LExpand directory and child directories.SHIFT LEFT, HJump to parent directory and collapse all.SPCToggle picking of paths.vToggle picking of all currently expanded paths.:Toggle picking based on entered globs.pView all currently picked paths./Search for string in currently expanded paths.nJump to next occurrence of search string.NJump to previous occurrence of search string..Toggle display of dotfiles.sDisplay total size of path, recursivelySDisplay totol size of all currently expanded paths.F5, rReset marking and expansion.F1, ?View all keybindings.q, ESCQuit and display all marked paths.TODOSupport window resizing.Page for viewing all current picksFix permission exception handling in my du package.Retain traversal position when toggling hidden directories.Different colors for sizes.Prompt to pick via entered globs.Search for string and navigate results.
Package: treeplot
treeplot - Plot tree based machine learning models.treeplotis Python package to easily plot the tree derived from models such as decisiontrees, randomforest and xgboost.
Developing explainable machine learning models is becoming more important in many domains. The most popular and classical explainable models are still tree based. Think of decision trees or random forest. The tree that is learned can be visualized and then explained. However, it can be a challange to simply plot the tree. Think of configuration issues with dot files, path locations to graphviz, differences across operating systems, differences across editors such as jupyter notebook, colab, spyder etc. This frustration led to this library, an easy way to plot the decision trees 🌲. It works for Random-forest, decission trees, xgboost and gradient boosting models. Under the hood it makes many checks, downloads graphviz, sets the path and then plots the tree.Functions in treeplotTreeplot can plot the tree for Random-forest, decission trees, xgboost and gradient boosting models:.plot         : Generic function to plot the tree of any of the four models with default settings.randomforest : Plot the randomforest model. Parameters can be specified..xgboost      : Plot the xgboost model. Parameters can be specified..import_example('iris') : Import example dataset⭐️ Star this repo if you like it ⭐️Install treeplot from PyPIpipinstalltreeplotImport treeplot packageimporttreeplotastreeDocumentation pagesOn thedocumentation pagesyou can find detailed information about the working of thetreeplotwith examples.ExamplesExample: RandomForestExample: XGbootExample: gradientboostingclassifierExample: lightbmExample: Explore other trees such as second best tree etcMaintainersErdogan Taskesen, github:erdogantContributeContributions are welcome.If you wish to buy me aCoffeefor this work, it is very appreciated :)
Package: treeplotter
treeplotterTree plotting is really hard in Python. Thetreeplotterpackage aims to make the process easier. It wraps the TreantJS library to plot trees and saves them to a rendered HTML file. This HTML file is then also exported to a high-res PNG by wrapping R'swebshotpackage. The package requires some complicated installs, but this is the price to pay to not use any R, Javascript, or CSS ;)UsageThis library hasNodeandTreeclasses in thetreeplotter.treemodule.Nodeobjects can store various items. We can then specify the node children and parents. ATreeis then defined by a root node. From this, we can create tree visualizations. Seeherefor a complete demo.This package is used in thedecitalapackage (seehere) to makeFragmentTreediagrams, like the following one of the Greek Prosodic Feet:InstallationThe basic package can be installed with$ pip3 install treeplotterTo create the tree diagrams, however, some additional installs are required. Seeherefor the complete instructions.
Package: tree-print
pytreeSimplified clone of the Linuxtreecommand.Supports displaying directory tree structure with colored output, icons, filesizes, filtered views and more. This utility prints as it scans the directories and can be interrupted anytime by pressing CTRL+C.Example output$ python -m pytree -is
📂 pytree
├── 🐍 setup.py [303]
├── 📄 LICENSE [1065]
├── 📄 .gitignore [1799]
├── 📄 README.md [818]
├── 📂 tests
│   └── 📄 requirements.txt [187]
└── 📂 pytree
    ├── 🐍 __main__.py [4699]
    ├── 🐍 formatter.py [223]
    ├── 🐍 common.py [1205]
    ├── 🐍 sizes.py [334]
    ├── 🐍 __init__.py [34]
    ├── 🐍 fonts.py [1458]
    └── 🐍 icons.py [541]

2 directories, 12 filesInstallationFrom PYPIpip install tree-printFrom sourcegit clone https://github.com/maxcurzi/pytree.git
python -m pip install -e pytreeTest if it works$ cd pytree
$ python -m pytree
pytree
├── setup.py
├── LICENSE
├── .gitignore
├── README.md
├── tests
│   └── requirements.txt
└── pytree
    ├── __main__.py
    ├── formatter.py
    ├── common.py
    ├── sizes.py
    ├── __init__.py
    ├── fonts.py
    └── icons.py

2 directories, 12 filesUsagepython -m pytree [-h] [-d] [-f FILT] [-i] [-c] [-s] [path]

positional arguments:
  path                  Path to print (defaults to current)

options:
  -h, --help            show this help message and exit
  -d, --dir             Only show directories
  -f FILT, --filt FILT  Filter out files and folders (supports shell-style wildcards such as ? and *)
  -i, --icons           Display icons
  -c, --color           Color output
  -s, --size            Show the file sizeCompatibility notesShould work on both Windows and Linux.Icons are UTF-8 encoded and may not display correctly on your terminal.ContributingPull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.Please make sure to update tests as appropriate.LicenseMIT
Package: treeprinter
Tree printer============This library provides a tree printer class for easy tree displaying## Installation``` sh$ pip install treeprinter```## Basic usage### Printer instance``` pythonfrom treeprinter import TreePrinterclass Tree(object):def __init__(self, tag, children=None):self.children = children or []self.tag = tagtree = Tree("animal", [Tree("cat"),Tree("dog", [Tree("chihuahua"), Tree("dalmatian")]),Tree("wolf")])printer = TreePrinter('children', 'tag')printer.pprint(tree)``````animal|---------------------------|             |             |cat           dog          wolf|----------|          |chihuahua  dalmatian```### Printer decoratorYou could also get the same result by decorating your class like so to implement the \_\_str\_\_ method``` python@TreePrinter('children', 'tag')class Tree(object):def __init__(self, tag, children=None):self.children = children or []self.tag = tagprint(tree)```## ExtensionsYou can extend the library by implementing the base displayer(see printers/json_printer.py)``` pythonfrom treeprinter import JsonPrinterprinter = JsonPrinter()json = {"fruits": ["Apple", "Banana", "Pear"],"presidents": {"France": ["Sarkozy", "Hollande"],"USA": ["Trump", "Obama"]},"star": "Sun"}printer.pprint(json)``````{}|--------------------------------------|                         |            |{presidents}                [fruits]       star|                         |            |----------------           --------------     Sun|                |         |       |      |[France]           [USA]     Apple  Banana  Pear|                |---------         ------|         |       |      |Sarkozy  Hollande  Trump  Obama```
Package: treeprompt
Tree PromptingTree Prompting: Efficient Task Adaptation without Fine-Tuning, code for theTree-prompt paper.Tree Prompting uses training examples to learn a tree of prompts to make a classification, yielding higher accuracy and better efficiency that baseline ensembles.QuickstartInstallation:pip install treeprompt(or clone this repo andpip install -e .)fromtreeprompt.treepromptimportTreePromptClassifierimportdatasetsimportnumpyasnpfromsklearn.treeimportplot_treeimportmatplotlib.pyplotasplt# set up datarng=np.random.default_rng(seed=42)dset_train=datasets.load_dataset('rotten_tomatoes')['train']dset_train=dset_train.select(rng.choice(len(dset_train),size=100,replace=False))dset_val=datasets.load_dataset('rotten_tomatoes')['validation']dset_val=dset_val.select(rng.choice(len(dset_val),size=100,replace=False))# set up argumentsprompts=["This movie is"," Positive or Negative? The movie was"," The sentiment of the movie was"," The plot of the movie was really"," The acting in the movie was",]verbalizer={0:" Negative.",1:" Positive."}checkpoint="gpt2"# fit modelm=TreePromptClassifier(checkpoint=checkpoint,prompts=prompts,verbalizer=verbalizer,cache_prompt_features_dir=None,# 'cache_prompt_features_dir/gp2',)m.fit(dset_train["text"],dset_train["label"])# compute accuracypreds=m.predict(dset_val['text'])print('\nTree-Prompt acc (val) ->',np.mean(preds==dset_val['label']))# -> 0.7# compare to accuracy for individual promptsfori,promptinenumerate(prompts):print(i,prompt,'->',m.prompt_accs_[i])# -> 0.65, 0.5, 0.5, 0.56, 0.51# visualize decision treeplot_tree(m.clf_,fontsize=10,feature_names=m.feature_names_,class_names=list(verbalizer.values()),filled=True,)plt.show()Reference:@misc{ch2022augmenting,title={TreePrompting:EfficientTaskAdaptationwithoutFine-Tuning},year={2023},archivePrefix={arXiv},primaryClass={cs.AI}}Reproducing experimentsSee the full code for reproducing all experiments in the paper athttps://github.com/csinva/tree-prompt-experiments
Package: tree-ring-watermark
Tree-Ring Watermarks: Fingerprints for Diffusion Images that are Invisible and RobustThis code is the official implementation ofTree-Ring Watermarks.If you have any questions, feel free to email Yuxin (ywen@umd.edu).AboutWe propose Tree-Ring Watermarking to watermark diffusion model outputs. Tree-Ring Watermarking chooses the initial noise array so that its Fourier transform contains a carefully constructed pattern near its center. This pattern is called the key. This initial noise vector is then converted into an image using the standard diffusion pipeline with no modifications. To detect the watermark in an image, the diffusion model is inverted to retrieve the original noise array used for generation. This array is then checked to see whether the key is present.DependenciesPyTorch == 1.13.0transformers == 4.23.1diffusers == 0.11.1Note: higher diffusers version may not be compatible with the DDIM inversion code.UsagePerform main experiments and calculate CLIP ScoreFor non-adversarial case, you can simply run:python run_tree_ring_watermark.py --run_name no_attack --w_channel 3 --w_pattern ring --start 0 --end 1000 --with_tracking --reference_model ViT-g-14 --reference_model_pretrain laion2b_s12b_b42kYou can modify arguments to perform attack. For example, for rotation with 75 degrees:python run_tree_ring_watermark.py --run_name rotation --w_channel 3 --w_pattern ring --r_degree 75 --start 0 --end 1000 --with_trackingFor more adversarial cases, seehere.For other watermark types mentioned in the paper, you can checkscripts/.Calculate FIDYou can download 5000 COCO examples used in the paperhere. Feel free to add more data or other datasets according to the format offid_outputs/coco/meta_data.json.Then, to calculate FID, you may run:python latent_watermark_fourier_fid.py --run_name fid_run --w_channel 3 --w_pattern ring --start 0 --end 5000 --with_tracking --run_no_wParametersCrucial hyperparameters for Tree-Ring:w_channel: the index of the watermarked channel. If set as -1, watermark all channels.w_pattern: watermark type: zeros, rand, ring.w_radius: watermark radius.Suggestions and Pull Requests are welcome!