Debian Codegraph @

examples/debtags/tagminer

raw
1 #!/usr/bin/python3
2 #
3 # Copyright (C) 2007 Enrico Zini <[email protected]>
4 #
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful, but
11 # WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 # General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with this program. If not, see <http://www.gnu.org/licenses/>.
17
18 # Given a file, search Debian packages that can somehow handle it
19
20 import sys
21
22 # Requires python-extractor, python-magic and python-debtags
23 import extractor
24 import magic
25 from debian import debtags
26 import re
27 from optparse import OptionParser
28 import apt
29
30
31 VERSION="0.1"
32
33 mime_map = (
34 ( r'text/html\b', ("works-with::text","works-with-format::html") ),
35 ( r'text/plain\b', ("works-with::text","works-with-format::plaintext") ),
36 ( r'text/troff\b', ("works-with::text", "works-with-format::man") ),
37 ( r'image/', ("works-with::image",) ),
38 ( r'image/jpeg\b', ("works-with::image:raster","works-with-format::jpg") ),
39 ( r'image/png\b', ("works-with::image:raster","works-with-format::png") ),
40 ( r'application/pdf\b', ("works-with::text","works-with-format::pdf")),
41 ( r'application/postscript\b', ("works-with::text","works-with-format::postscript")),
42 ( r'application/x-iso9660\b', ('works-with-format::iso9660',)),
43 ( r'application/zip\b', ('works-with::archive', 'works-with-format::zip')),
44 ( r'application/x-tar\b', ('works-with::archive', 'works-with-format::tar')),
45 ( r'audio/', ("works-with::audio",) ),
46 ( r'audio/mpeg\b', ("works-with-format::mp3",) ),
47 ( r'audio/x-wav\b', ("works-with-format::wav",) ),
48 ( r'message/rfc822\b', ("works-with::mail",) ),
49 ( r'video/', ("works-with::video",)),
50 ( r'application/x-debian-package\b', ("works-with::software:package",)),
51 ( r'application/vnd.oasis.opendocument.text\b', ("works-with::text",)),
52 ( r'application/vnd.oasis.opendocument.graphics\b', ("works-with::image:vector",)),
53 ( r'application/vnd.oasis.opendocument.spreadsheet\b', ("works-with::spreadsheet",)),
54 ( r'application/vnd.sun.xml.base\b', ("works-with::db",)),
55 ( r'application/rtf\b', ("works-with::text",)),
56 ( r'application/x-dbm\b', ("works-with::db",)),
57
58 # How do we tell these two apart?
59 # ( 'application/ogg', ('works-with-format::oggvorbis',)),
60 # ( 'application/ogg', ('works-with-format::oggtheora',)),
61
62 # Missing tags
63 # ( 'application/vnd.oasis.opendocument.presentation', ),
64
65 # Still unhandled/unhandlable:
66 # works-with::3dmodel - 3D Model
67 # works-with::dictionary - Dictionaries
68 # works-with::dtp - Desktop Publishing (DTP)
69 # works-with::fax - Faxes
70 # works-with::file - Files
71 # works-with::font - Fonts
72 # works-with::logfile - System Logs
73 # works-with::music-notation - Music Notation
74 # works-with::people - People
75 # works-with::pim - Personal Information
76 # works-with::software:source - Source code
77 # works-with::spreadsheet - Spreadsheet
78 # works-with::text - Text
79 # works-with::unicode - Unicode
80 # works-with-format::docbook - Docbook
81 # works-with-format::info - Documentation in Info format
82 # works-with-format::ldif - LDIF
83 # works-with-format::sgml - SGML, Standard Generalized Markup Language
84 # works-with-format::svg - SVG, Scalable Vector Graphics
85 # works-with-format::tex - TeX, LaTeX and DVI
86 # works-with-format::vrml - VRML 3D Model
87 # works-with-format::xml - XML
88 # works-with-format::xml:rss - RSS Rich Site Summary
89 # works-with-format::xml:xslt - XSL Transformations (XSLT)
90 )
91
92 extractor = extractor.Extractor()
93 magic = magic.open(magic.MAGIC_MIME)
94 magic.load()
95
96 def mimetype(fname):
97 keys = extractor.extract(fname)
98 xkeys = {}
99 for k, v in keys:
100 if k in xkeys:
101 xkeys[k].append(v)
102 else:
103 xkeys[k] = [v]
104 namemagic = magic.file(fname)
105 contentmagic = magic.buffer(open(fname, "r").read(4096))
106 return "mimetype" in xkeys and xkeys['mimetype'][0] or contentmagic or namemagic
107
108
109 class Parser(OptionParser):
110 def __init__(self, *args, **kwargs):
111 OptionParser.__init__(self, *args, **kwargs)
112
113 def error(self, msg):
114 sys.stderr.write("%s: error: %s\n\n" % (self._get_prog_name(), msg))
115 self.print_help(sys.stderr)
116 sys.exit(2)
117
118 if __name__ == '__main__':
119 parser = Parser(usage="usage: %prog [options] filename",
120 version="%prog "+ VERSION,
121 description="search Debian packages that can handle a given file")
122 parser.add_option("--tagdb", default="/var/lib/debtags/package-tags", help="Tag database to use (default: %default)")
123 parser.add_option("--action", default=None, help="Show the packages that allow the given action on the file (default: %default)")
124
125 (options, args) = parser.parse_args()
126
127 if len(args) == 0:
128 parser.error("Please provide the name of a file to scan")
129
130 # Read full database
131 fullcoll = debtags.DB()
132 tag_filter = re.compile(r"^special::.+$|^.+::TODO$")
133 fullcoll.read(open(options.tagdb, "r"), lambda x: not tag_filter.match(x))
134
135 type = mimetype(args[0])
136 #print("Mime type:", type, file=sys.stderr)
137 found = set()
138 for match, tags in mime_map:
139 match = re.compile(match)
140 if match.match(type):
141 for t in tags:
142 found.add(t)
143 if len(found) == 0:
144 print("Unhandled mime type:", type, file=sys.stderr)
145 else:
146 if options.action != None:
147 apt_cache = apt.Cache()
148 query = found.copy()
149 query.add("role::program")
150 query.add("use::"+options.action)
151 print("Debtags query:", " && ".join(query))
152 subcoll = fullcoll.filter_packages_tags(lambda pt: query.issubset(pt[1]))
153 for i in subcoll.iter_packages():
154 aptpkg = apt_cache[i]
155 desc = aptpkg.raw_description.split("\n")[0]
156 print(i, "-", desc)
157 else:
158 print("Debtags query:", " && ".join(found))
159
160 query = found.copy()
161 query.add("role::program")
162 subcoll = fullcoll.filter_packages_tags(lambda pt: query.issubset(pt[1]))
163 uses = map(lambda x:x[5:], filter(lambda x:x.startswith("use::"), subcoll.iter_tags()))
164 print("Available actions:", ", ".join(uses))
165
166 # vim:set ts=4 sw=4: