Note
Click here to download the full example code
02. Visualizing Python Library Favicons
This script identifies installed Python packages, fetches their homepage URLs, and downloads their favicons. It then uses a custom HTML representation to display these icons in a grid.
Note
The command cut is not available in windows! Thus, the
code will not run in te standard Windows Command Prompt. However,
it might be available on Cygwin o Git for windows.
Note
The visual output of this script is generated via a special _repr_html_() method. This method is automatically detected and rendered in rich display environments (Jupyter Notebook/Lab & IPython). If you run this as a regular .py file, no images will appear in your terminal. To see the output, you must manually get
the HTML content and save it to a file:
21 # Libraries
22 import favicon
23 import subprocess as sp
24
25
26 class IconHTML:
27 """Class to display html in sphinx-gallery."""
28 TMP0 = '<img src={url} style="{s}", width={w} height={h}>'
29 TMP1 = '<div>'+TMP0+' <span>{name}</span></div>'
30
31 """Class to display icons on sphinx-gallery."""
32 def __init__(self, d, width=25, height=25, verbose=0):
33 self.d = d
34 self.width = width
35 self.height = height
36 self.style = "display: inline; vertical-align:middle;"
37 self.verbose = verbose
38
39 def _repr_html_short_(self):
40 return ' '.join([self.TMP0.format(url=v,
41 w=self.width, h=self.height, s=self.style)
42 for k,v in self.d.items()])
43
44 def _repr_html_long_(self):
45 return ' '.join([self.TMP1.format(url=v,
46 w=self.width, h=self.height, s=self.style, name=k.lower())
47 for k, v in self.d.items()])
48
49 def _repr_html_(self):
50 if self.verbose == 0:
51 return self._repr_html_short_()
52 return self._repr_html_long_()
53
54
55 # List of libraries for which the icon (if found)
56 # should be included in the output.
57 INCLUDE = [
58 'pandas',
59 'Flask',
60 'imblearn',
61 'numba',
62 'numpy',
63 'plotly',
64 'PyYAML',
65 'scipy',
66 'seaborn',
67 'statsmodels',
68 'alabaster',
69 'attrs',
70 'Babel',
71 'bokeh',
72 'joblib',
73 'nltk',
74 'notebook',
75 'torch',
76 'matplotlib',
77 'pillow',
78 'pygments',
79 'pytest',
80 'tqdm',
81 'urllib3',
82 'future'
83 ]
84
85 def list_packages_command():
86 """List packages using linux <cut>."""
87 # Define command to list packages and urls
88 COMMAND = "pip list --format=freeze | cut -d= -f1 | xargs pip show | "
89 COMMAND+= "awk '/^Name/{printf $2} /^Home-page/{print \": \"$2}'"
90 # List of package name and url.
91 output = sp.getoutput(COMMAND)
92 # Return
93 return output.split("\n")[2:]
94
95
96 def list_packages_importlib():
97 """List packages using importlib."""
98 # --- ADD THIS NEW BLOCK ---
99 import importlib.metadata
100
101 lines = []
102 # Iterate through all installed packages
103 for dist in importlib.metadata.distributions():
104 # Get package metadata
105 meta = dist.metadata
106 name = meta['Name']
107 url = meta.get('Home-page', '') # Use .get() for safety
108
109 # Check if the package is in our include list and has a valid URL
110 if name in INCLUDE and url.startswith('https'):
111 lines.append(f"{name}: {url}")
112
113 return lines
114
115
116
117 import platform
118
119 system = platform.system()
120
121 if system == 'Windows':
122 print("This is a Windows system.")
123 elif system == 'Darwin':
124 print("This is a macOS system.")
125 elif system == 'Linux':
126 print("This is a Linux system.")
127 else:
128 print(f"This is a different system: {system}")
129
130 # Get packages
131 packages = list_packages_importlib()
132
133 # Show
134 print("\nCommand output:")
135 print(packages)
136
137 # Create dictionary
138 d = {}
139 for line in packages:
140 # Find name and url
141 name, url = line.split(': ')
142 if not url.startswith('https:'):
143 continue
144 if name not in INCLUDE:
145 continue
146 # Store name and url
147 icons = favicon.get(url)
148 for i, ico in enumerate(icons):
149 d['%s-%s' % (name, i)] = ico.url
Out:
This is a Windows system.
Command output:
['numba: https://numba.pydata.org', 'numpy: https://numpy.org', 'PyYAML: https://pyyaml.org/', 'statsmodels: https://www.statsmodels.org/', 'torch: https://pytorch.org/']
154 aux = IconHTML(d)
155 aux
159 aux = IconHTML(d, verbose=1)
160 aux
165 # Create dictionary
166 d = {}
167 for line in packages:
168 # Find name and url
169 name, url = line.split(': ')
170 if not url.startswith('https:'):
171 continue
172 # Store name and url
173 icons = favicon.get(url)
174 for i, ico in enumerate(icons):
175 d['%s-%s' % (name, i)] = ico.url
179 aux = IconHTML(d, verbose=1)
180 aux
Write the string to a file
185 #
186 from pathlib import Path
187 output_dir = Path('./objects/main02')
188 output_dir.mkdir(parents=True, exist_ok=True)
189
190 with open("%s/icons.html" % output_dir, "w") as f:
191 f.write(aux._repr_html_())
Total running time of the script: ( 0 minutes 4.264 seconds)