Package: codeart
Code ArtI wanted a way to culminate the last decade of programming that I've done, and realized
it would be much more fun to create a tool that others could use as well. Specifically, I want to be able to:Have a class that parses over repos on my local machine, and organizes files based on extension..Builds a word2vec model, one per extension, the idea being that each language has it's own model. The word2vec model should have three dimensions so that we can map it to an RGB colorspace. This will mean that the embeddings for each character, along with being unique for the language, will also have a unique color. We should also be able to build one model across extensions, and map each extension to it.At the end, I should be able to visualize any particular script (or some other graphic) using these embeddings. I'd like to add in some variable / dimension to represent age / date too.ProgressWhat I have so far is an ability to do the above, and then to produce a tiny image for
each code file, where the words are colored by their word2vec (3 dimensional, RGB) embedding. Here
is a small example of a Python script from spack:And here is a randomly placed grid with all python files from the spack repository:And seeExample 5: Generate a Color Mapfor a more organized rendering of just the color space.
What I'm working towards is being able to derive and organize the above images as well,
possibly based on an average color or similar.UsageInstallYou can install from pypipipinstallcodeartor install from the repository directly:$gitclonehttps://github.com/vsoch/codeart
$pythonsetup.pyinstallThe following examples are also provided in thecodeart examplesrepository.Example 1: Galleries and Interactive VisualizationsGenerate an Abstract GalleryYou can generate a web gallery for a root folder (including all files beneath it) or
a repository:fromcodeart.mainimportCodeBasecode=CodeBase()# How to add a foldercode.add_folder('/home/vanessa/code')# How to add a repositorycode.add_repo("https://github.com/spack/spack")# See languages with >100 filescode.threshold_files(100)# Generate a web report (one page per language above this threshold)gallery=code.make_gallery(groups=['','.py','.patch'])Trainingmodelwithgroups|.py|.patchGeneratingweboutputfor''Generatingweboutputfor'.py'Generatingweboutputfor'.patch'Finishedwebfilesarein/tmp/code-art-xp73v5jiAnd then the example files for each of:allpythonpatchempty spaceYou can also browse raw imageshere.Generate RGB VectorsIf you want to generate RGB vectors for a code base, you can use these
for your own machine learning projects. Here is how to do that
for a repository.fromcodeart.mainimportCodeBasecode=CodeBase()code.add_repo("https://github.com/spack/spack")The codebase will have codefiles added, a lookup in code.codefiles for each
extension found. You'll want to take a look at these and choose some subset above
a given threshold.# Look at extractors, one added per extensioncode.codefiles# Find those with >100 filescode.threshold_files(thresh=100)# {'': [codeart-files:115],# '.py': [codeart-files:4227],# '.patch': [codeart-files:531]}And then train a word2vec model, one for each group / extension, with size of 3
so that we can map to the RGB colorspace.code.train(groups=['.py','','.patch'])You can also train a single model for those extensionscode.train_all(groups=['.py','','.patch'])Or train using all groups.code.train_all()We now have a model for each extension (and all)code.modelscode.models['all']Here is how to get a panda frame for a particular extension (or all)vectors=code.get_vectors(".py")vectors=code.get_vectors("all")Generate Interactive ColormapLet's say that we extracted the spack codebase (shown above) and then
wanted to visualize the vectors. What do I mean? I want to see how the
terms that are part of the embeddings model (each corresponding to
a word/term found in a code file with some extension) correspond to each
extension. To do this, I can extract counts and vectors:fromcodeart.graphicsimportgenerate_interactive_colormapvectors=code.get_vectors('all')counts=code.get_color_percentages(groups=list(code.codefiles.keys()),vectors=vectors)# Save if desired!vectors.to_csv("spack-colormap-vectors.csv")counts.to_csv("spack-color-percentages.csv")tmpdir=generate_interactive_colormap(vectors=vectors,counts=counts,width=1000)The early interactive version ishereand this was updated to be better sorted, seenhere.Basically, each term in the model is represented with its color, and the color transparency
is based on the prevalence of each term for any given extension. You can click on a
different extension to see the colors change.For the second plot (sorted) since the color RGB values are sorted based on similarity,
you can also deduce that similar colors indicate similar terms, which indicates similar
context in the code files.Example 2: Generate a PlotYou might just want to get vectors and plot the RGB space. You can do:importmatplotlib.pyplotaspltfrommpl_toolkits.mplot3dimportAxes3Dfig=plt.figure()ax=Axes3D(fig)ax.scatter(vectors[0].tolist(),vectors[1].tolist(),vectors[2].tolist(),c=vectors.to_numpy()/255)# Optionally add text (a bit crowded)forrowinvectors.iterrows():ax.text(row[1][0],row[1][1],row[1][2],row[0])plt.show()plt.savefig("img/spack-python.png")Example 3: Generate Code ImagesIf you want to generate raw images for some extension, you can do that too.
These can be used in some image processing project, to generate other images,
or some other kind of clustering analysis.# Generate images for all filesifnotos.path.exists('images'):os.mkdir('images')# Create folder of code images (if you want to work with them directly)code.make_art(extension=".py",outdir='images',vectors=vectors)Example 4: Generate a Color Lookup GridI haven't developed this in detail, but you can also generate a grid of colors
for a given image. The idea here would be to have a grid that
can be used as a legend. Here we again load in the spack code base,
and generate a lookup for the ".py" (python) extension.fromcodeart.mainimportCodeBasefromcodeart.graphicsimportsave_vectors_gradient_gridcode=CodeBase()code.add_repo("https://github.com/spack/spack")vectors=code.get_vectors(".py")save_vectors_gradient_grid(vectors=vectors,outfile='spack-image-gradient.png')An example gradient image is the following:And a much larger one (you'll need to click and zoom in):which is generated fromthis datathat I created by building a model across all the Python code on my computer (note there are many different
file extensions in the model beyond Python!).You can of course adjust the dimensions, the row height, and the column width
and font size depending on your needs or matrix size.Example 5: Generate a Color MapYou canfollow this notebookto see how you might generate a colormap. For example, here is an entire colormap for my Python (and associated files)
code base, without altering opacity, but just plotting the colors (these are the colors
that align with the color lookup grid above).And if we do dimensionality reduction, we can plot this in 2d:And finally, we can assess counts for any particular extension across
the codebase to derive images that use transparency to show the prevalence of any given term.
Here is for .yml and .rst (restructured syntax) files.We can also generate an animation to loop through each language.But note that this data would benefit greatly from interactive visualization,
akin to theinteractive colormap exampleexample mentioned previously.Example 6: Parse Folders by a Custom FunctionYou might want to organize groups in some logical way that goes beyond an extension,
or just using all files. For this reason, each of the functions add_folder, and add_repo
can be given a custom "func" that will return a group name based on a file.
For example, fromutilswe can import a function that will
group files by year:defgroup_by_year_created(filename):"""Given a filename, return the year it was created.This function is called after testing the file for read access."""stat=os.stat(filename)returndatetime.fromtimestamp(stat.st_ctime).yearAnd then when adding a folder or repo, we might do:code.add_folder(folder,func=group_by_year_created)code.add_repo(folder,func=group_by_year_created)You can also just provide a string or group directly (takes preference over func):code.add_repo(repo,group="2017")The function you provide should take the file name as the main argument.
A more complex example (parsing GitHub repos by creation date using the GitHub
API) is provided atparse_by_year.py.Example 7: Generate CodeArt TextA simple use case is to, given a repository or folder, generate a text image using it.fromcodeart.graphicsimportgenerate_codeart_textfromcodeart.colorsimportgenerate_color_lookup# either works herecode.add_repo("https://github.com/vsoch/codeart")code.add_folder("/path/to/folder")images=code.make_art(group="all",outdir=os.getcwd())images=glob("%s/*"%os.path.join(os.getcwd(),"images"))color_lookup=generate_color_lookup(images)# Generate an image with text (dinosaur!)generate_codeart_text("dinosaur",color_lookup,outfile="index.html")A similar function (not as well used / developed) is to generate a mapping
to an image.fromcodeart.graphicsimportgenerate_codeartgenerate_codeart('sunset.jpg',color_lookup,sample=10,top=100,outfile="index.html")For more details on text generation, see theExample 8: Basic Client UsageFor the text generation, I've created a simple client that will drive the interaction:>codeart--help
usage:codeart[-h][--version]{textart}...

CodeArtGenerator

optionalarguments:-h,--helpshowthishelpmessageandexit--versionprinttheversionandexit.

actions:actionsforCodeArtgenerator{textart}codeartactionstextartextractimagesfromGitHuborlocalfilesystem.Currently the only simple command is to generate a code art text graphic.
Be aware that this generates one image per code file, and should be done
for small code bases, or larger ones with caution.codearttextart--help
usage:codearttextart[-h][--githubGITHUB][--rootROOT][--outdirOUTDIR][--textTEXT]optionalarguments:-h,--helpshowthishelpmessageandexit--githubGITHUBGitHubusernametodownloadrepositoriesfor.--rootROOTrootdirectorytoparseforfiles.--outdirOUTDIRoutputdirectorytoextractimages(defaultstotemporarydirectory)For an example, you can see the .github actions workflow incodeart-examples.Do you have a question? Or want to suggest a feature to make it better?
Pleaseopen an issue!