Debian Codegraph @

weblogo/_cgi.py

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 # Copyright (c) 2003-2004 The Regents of the University of California.
2 # Copyright (c) 2005 Gavin E. Crooks
3 # Copyright (c) 2006-2015, The Regents of the University of California, through
4 # Lawrence Berkeley National Laboratory (subject to receipt of any required
5 # approvals from the U.S. Dept. of Energy). All rights reserved.
6
7 # This software is distributed under the new BSD Open Source License.
8 # <http://www.opensource.org/licenses/bsd-license.html>
9 #
10 # Redistribution and use in source and binary forms, with or without
11 # modification, are permitted provided that the following conditions are met:
12 #
13 # (1) Redistributions of source code must retain the above copyright notice,
14 # this list of conditions and the following disclaimer.
15 #
16 # (2) Redistributions in binary form must reproduce the above copyright
17 # notice, this list of conditions and the following disclaimer in the
18 # documentation and or other materials provided with the distribution.
19 #
20 # (3) Neither the name of the University of California, Lawrence Berkeley
21 # National Laboratory, U.S. Dept. of Energy nor the names of its contributors
22 # may be used to endorse or promote products derived from this software
23 # without specific prior written permission.
24 #
25 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
26 # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27 # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28 # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
29 # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
30 # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
31 # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
32 # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
33 # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
34 # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
35 # POSSIBILITY OF SUCH DAMAGE.
36
37 import os.path
38 import shutil
39 import sys
40 from io import BytesIO, StringIO, TextIOWrapper
41 from string import Template
42 from typing import Any, Callable, List, Optional, Union
43
44 import importlib_resources
45
46 import weblogo
47 from weblogo._ext import cgi as cgilib
48 from weblogo._ext import cgitb
49 from weblogo.colorscheme import ColorScheme, SymbolColor
50
51 cgitb.enable() # type: ignore
52
53
54 # TODO: Check units
55
56 # TODO: In WebLogo2: why slash create.cgi? I think this was a workaround
57 # for some browser quirk
58 # <form method="post" action="/create.cgi" enctype="multipart/form-data">
59
60
61 mime_type = {
62 "eps": "application/postscript",
63 "pdf": "application/pdf",
64 "svg": "image/svg+xml",
65 "png": "image/png",
66 "png_print": "image/png",
67 "logodata": "text/plain",
68 "csv": "text/plain",
69 "jpeg": "image/jpeg",
70 }
71
72 extension = {
73 "eps": "eps",
74 "pdf": "pdf",
75 "png": "png",
76 "svg": "svg",
77 "png_print": "png",
78 "logodata": "txt",
79 "csv": "csv",
80 "jpeg": "jpeg",
81 }
82
83 alphabets = {
84 "alphabet_auto": None,
85 "alphabet_protein": weblogo.unambiguous_protein_alphabet,
86 "alphabet_rna": weblogo.unambiguous_rna_alphabet,
87 "alphabet_dna": weblogo.unambiguous_dna_alphabet,
88 }
89
90 color_schemes = {}
91 for k in weblogo.std_color_schemes.keys():
92 color_schemes["color_" + k.replace(" ", "_")] = weblogo.std_color_schemes[k]
93
94 composition = {
95 "comp_none": "none",
96 "comp_auto": "auto",
97 "comp_equiprobable": "equiprobable",
98 "comp_CG": "percentCG",
99 "comp_Celegans": "C. elegans",
100 "comp_Dmelanogaster": "D. melanogaster",
101 "comp_Ecoli": "E. coli",
102 "comp_Hsapiens": "H. sapiens",
103 "comp_Mmusculus": "M. musculus",
104 "comp_Scerevisiae": "S. cerevisiae",
105 }
106
107
108 class Field:
109 """A representation of an HTML form field."""
110
111 def __init__(
112 self,
113 name: str,
114 default: Optional[Any] = None,
115 conversion: Optional[Callable] = None,
116 options: Optional[List[Any]] = None,
117 errmsg: str = "Illegal value.",
118 ) -> None:
119 self.name = name
120 self.default = default
121 self.value = default
122 self.conversion = conversion
123 self.options = options
124 self.errmsg = errmsg
125
126 def get_value(self) -> Any:
127 if self.options:
128 if self.value not in self.options:
129 raise ValueError(str((self.name, self.errmsg)))
130
131 if self.conversion:
132 try:
133 return self.conversion(self.value)
134 except ValueError:
135 raise ValueError(str((self.name, self.errmsg)))
136 else:
137 return self.value
138
139
140 def string_or_none(value: Any) -> Optional[str]:
141 if value is None or value == "auto":
142 return None
143 return str(value)
144
145
146 def truth(value: Any) -> bool:
147 if value == "true":
148 return True
149 return bool(value)
150
151
152 def int_or_none(value: Any) -> Optional[int]:
153 if value == "" or value is None or value == "auto":
154 return None
155 return int(value)
156
157
158 def float_or_none(value: Any) -> Optional[float]:
159 if value == "" or value is None or value == "auto":
160 return None
161 return float(value)
162
163
164 def main(htdocs_directory: Optional[str] = None) -> None:
165 logooptions = weblogo.LogoOptions()
166
167 # A list of form fields.
168 # The default for checkbox values must be False (irrespective of
169 # the default in logooptions) since a checked checkbox returns 'true'
170 # but an unchecked checkbox returns nothing.
171 controls = [
172 Field("sequences", ""),
173 Field("sequences_url", ""),
174 Field(
175 "format",
176 "png",
177 weblogo.formatters.get,
178 options=[
179 "png_print",
180 "png",
181 "jpeg",
182 "eps",
183 "pdf",
184 "svg",
185 "logodata",
186 "csv",
187 ],
188 # TODO: Should copy list from __init__.formatters
189 errmsg="Unknown format option.",
190 ),
191 Field(
192 "stacks_per_line",
193 logooptions.stacks_per_line,
194 int,
195 errmsg="Invalid number of stacks per line.",
196 ),
197 Field(
198 "stack_width",
199 "medium",
200 weblogo.std_sizes.get,
201 options=["small", "medium", "large"],
202 errmsg="Invalid logo size.",
203 ),
204 Field(
205 "alphabet",
206 "alphabet_auto",
207 alphabets.get,
208 options=[
209 "alphabet_auto",
210 "alphabet_protein",
211 "alphabet_dna",
212 "alphabet_rna",
213 ],
214 errmsg="Unknown sequence type.",
215 ),
216 Field(
217 "unit_name",
218 "bits",
219 options=["probability", "bits", "nats", "kT", "kJ/mol", "kcal/mol"],
220 ),
221 Field("first_index", 1, int_or_none),
222 Field("logo_start", "", int_or_none),
223 Field("logo_end", "", int_or_none),
224 Field(
225 "composition",
226 "comp_auto",
227 composition.get,
228 options=[
229 "comp_none",
230 "comp_auto",
231 "comp_equiprobable",
232 "comp_CG",
233 "comp_Celegans",
234 "comp_Dmelanogaster",
235 "comp_Ecoli",
236 "comp_Hsapiens",
237 "comp_Mmusculus",
238 "comp_Scerevisiae",
239 ],
240 errmsg="Illegal sequence composition.",
241 ),
242 Field("percentCG", "", float_or_none, errmsg="Invalid CG percentage."),
243 Field("show_errorbars", False, truth),
244 Field("logo_title", logooptions.logo_title),
245 Field("logo_label", logooptions.logo_label),
246 Field("show_xaxis", False, truth),
247 Field("xaxis_label", logooptions.xaxis_label),
248 Field("show_yaxis", False, truth),
249 Field("yaxis_label", logooptions.yaxis_label, string_or_none),
250 Field(
251 "yaxis_scale",
252 logooptions.yaxis_scale,
253 float_or_none,
254 errmsg="The yaxis scale must be a positive number.",
255 ),
256 Field("yaxis_tic_interval", logooptions.yaxis_tic_interval, float_or_none),
257 Field("show_ends", False, truth),
258 Field("show_fineprint", False, truth),
259 Field(
260 "color_scheme",
261 "color_auto",
262 color_schemes.get,
263 options=list(color_schemes.keys()),
264 errmsg="Unknown color scheme",
265 ),
266 Field("color0", ""),
267 Field("symbols0", ""),
268 Field("desc0", ""),
269 Field("color1", ""),
270 Field("symbols1", ""),
271 Field("desc1", ""),
272 Field("color2", ""),
273 Field("symbols2", ""),
274 Field("desc2", ""),
275 Field("color3", ""),
276 Field("symbols3", ""),
277 Field("desc3", ""),
278 Field("color4", ""),
279 Field("symbols4", ""),
280 Field("desc4", ""),
281 Field("ignore_lower_case", False, truth),
282 Field("scale_width", False, truth),
283 ]
284
285 form = {}
286 for c in controls:
287 form[c.name] = c
288
289 form_values = cgilib.FieldStorage() # type: ignore
290
291 # Send default form?
292 if len(form_values) == 0 or "cmd_reset" in form_values:
293 # Load default truth values now.
294 form["show_errorbars"].value = logooptions.show_errorbars
295 form["show_xaxis"].value = logooptions.show_xaxis
296 form["show_yaxis"].value = logooptions.show_yaxis
297 form["show_ends"].value = logooptions.show_ends
298 form["show_fineprint"].value = logooptions.show_fineprint
299 form["scale_width"].value = logooptions.scale_width
300
301 send_form(controls, htdocs_directory=htdocs_directory)
302 return
303
304 # Get form content
305 for c in controls:
306 c.value = form_values.getfirst(c.name, c.default)
307
308 options_from_form = [
309 "format",
310 "stacks_per_line",
311 "stack_width",
312 "alphabet",
313 "unit_name",
314 "first_index",
315 "logo_start",
316 "logo_end",
317 "composition",
318 "show_errorbars",
319 "logo_title",
320 "logo_label",
321 "show_xaxis",
322 "xaxis_label",
323 "show_yaxis",
324 "yaxis_label",
325 "yaxis_scale",
326 "yaxis_tic_interval",
327 "show_ends",
328 "show_fineprint",
329 "scale_width",
330 ]
331
332 errors = []
333 for optname in options_from_form:
334 try:
335 value = form[optname].get_value()
336 if value is not None:
337 setattr(logooptions, optname, value)
338 except ValueError as err:
339 errors.append(err.args)
340
341 # Construct custom color scheme
342 custom = ColorScheme()
343 for i in range(0, 5):
344 color = form["color%d" % i].get_value()
345 symbols = form["symbols%d" % i].get_value()
346 desc = form["desc%d" % i].get_value()
347
348 if color:
349 try:
350 custom.rules.append(SymbolColor(symbols, color, desc))
351 except ValueError:
352 errors.append(("color%d" % i, "Invalid color: %s" % color))
353
354 if form["color_scheme"].value == "color_custom":
355 logooptions.color_scheme = custom
356 else:
357 try:
358 logooptions.color_scheme = form["color_scheme"].get_value()
359 except ValueError as err:
360 errors.append(err.args)
361
362 # FIXME: Ugly fix: Must check that sequence_file key exists
363 # FIXME: Sending malformed or missing form keys should not cause a crash
364 # sequences_file = form["sequences_file"]
365 sequences_from_file = None
366 if "sequences_file" in form_values:
367 sequences_from_file = form_values.getvalue("sequences_file")
368
369 sequences_from_textfield = form["sequences"].get_value()
370 sequences_url = form["sequences_url"].get_value()
371
372 sequences = None
373 seq_file: Union[StringIO, TextIOWrapper, None] = None
374
375 if sequences_from_file:
376 if sequences_from_textfield or sequences_url:
377 errors.append(("sequences_file", "Cannot upload, sequence source conflict"))
378 else:
379 sequences = sequences_from_file
380 seq_file = TextIOWrapper(BytesIO(sequences), encoding="utf-8")
381 elif sequences_from_textfield:
382 if sequences_url:
383 errors.append(("sequences", "Cannot upload, sequence source conflict"))
384 else:
385 # check SEQUENCES_MAXLENGT
386 # If a user tries to paste a very large file into sequence textarea,
387 # then WebLogo runs very slow for no apparently good reason. (Might be client side bug?)
388 # So we limit the maximum sequence size.
389 # Form field also limits size, but not necessarly respected. Also can truncate data
390 # without warning, so we'll set textarea maximum to be larger than MAX_SEQUENCE_SIZE
391 SEQUENCES_MAXLENGTH = 100000
392 if len(sequences_from_textfield) > SEQUENCES_MAXLENGTH:
393 errors.append(
394 (
395 "sequences",
396 "Sequence data too large for text input. Use file upload instead.",
397 )
398 )
399 controls[0] = Field("sequences", "")
400 else:
401 sequences = sequences_from_textfield
402 seq_file = StringIO(sequences)
403
404 elif sequences_url:
405 from .logo import _from_URL_fileopen
406
407 try:
408 seq_file = _from_URL_fileopen(sequences_url)
409 except ValueError:
410 errors.append(("sequences_url", "Cannot parse URL"))
411 except IOError:
412 errors.append(("sequences_url", "Cannot load sequences from URL"))
413
414 else:
415 errors.append(
416 (
417 "sequences",
418 "Please enter a multiple-sequence alignment in the box above, or select a "
419 "file to upload.",
420 )
421 )
422
423 # If we have uncovered errors or we want the chance to edit the logo
424 # ("cmd_edit" command from examples page) then we return the form now.
425 # We do not proceed to the time consuming logo creation step unless
426 # required by a 'create' or 'validate' command, and no errors have been
427 # found yet.
428 if errors or "cmd_edit" in form_values:
429 send_form(controls, errors, htdocs_directory)
430 return
431
432 try:
433 comp = form["composition"].get_value()
434 percentCG = form["percentCG"].get_value()
435 ignore_lower_case = "ignore_lower_case" in form_values
436 if comp == "percentCG":
437 comp = str(percentCG / 100)
438
439 from .matrix import Motif
440
441 try:
442 # Try reading data in transfac format first.
443 # TODO Refactor this code
444 motif = Motif.read_transfac(seq_file, alphabet=logooptions.alphabet) # type: ignore # FIXME
445 prior = weblogo.parse_prior(comp, motif.alphabet)
446 data = weblogo.LogoData.from_counts(motif.alphabet, motif.array, prior)
447 except ValueError:
448 seqs = weblogo.read_seq_data(
449 seq_file,
450 alphabet=logooptions.alphabet,
451 ignore_lower_case=ignore_lower_case,
452 )
453 alpha = seqs.alphabet
454 assert alpha is not None
455 prior = weblogo.parse_prior(comp, alpha)
456 data = weblogo.LogoData.from_seqs(seqs, prior)
457
458 logoformat = weblogo.LogoFormat(data, logooptions)
459 format = str(form["format"].value)
460 logo = weblogo.formatters[format](data, logoformat)
461 except ValueError as err:
462 errors.append(err.args)
463 except IOError as err:
464 errors.append(err.args)
465 except RuntimeError as err:
466 errors.append(err.args)
467
468 if errors or "cmd_validate" in form_values:
469 send_form(controls, errors, htdocs_directory)
470 return
471
472 #
473 # RETURN LOGO OVER HTTP
474 #
475
476 print("Content-Type:", mime_type[format])
477 # Content-Disposition: inline Open logo in browser window
478 # Content-Disposition: attachment Download logo
479 if "download" in form_values:
480 print(
481 "Content-Disposition: attachment; " 'filename="logo.%s"' % extension[format]
482 )
483 else:
484 print("Content-Disposition: inline; " 'filename="logo.%s"' % extension[format])
485 # Separate header from data
486 print()
487 sys.stdout.flush()
488
489 # Finally, and at last, send the logo.
490 sys.stdout.buffer.write(logo)
491
492
493 def send_form(
494 controls: List[Field],
495 errors: Optional[List[tuple]] = None,
496 htdocs_directory: Optional[str] = None,
497 ) -> None:
498 if errors is None:
499 errors = []
500
501 if htdocs_directory is None:
502 htdocs_directory = os.path.join(os.path.dirname(__file__), "htdocs")
503
504 substitutions = {}
505 substitutions["version"] = weblogo.release_description
506 # Bug fix. Not sure why this default substitution isn't added automatically like everything else
507 substitutions["color_custom"] = ""
508 for c in controls:
509 if c.options:
510 for opt in c.options:
511 substitutions[opt.replace("/", "_")] = ""
512 substitutions[str(c.value).replace("/", "_")] = "selected"
513 else:
514 value = c.value
515 if value is None:
516 value = "auto"
517 if value == "true":
518 substitutions[c.name] = "checked"
519 elif type(value) is bool: # noqa: E721
520 if value:
521 substitutions[c.name] = "checked"
522 else:
523 substitutions[c.name] = ""
524 else:
525 substitutions[c.name] = str(value)
526 substitutions[c.name + "_err"] = ""
527 substitutions["logo_range_err"] = ""
528
529 # Disable graphics options if necessary auxiliary programs are not installed.
530 if shutil.which("gs") is None and shutil.which("gswin32c.exe") is None:
531 substitutions["png_print"] = 'disabled="disabled"'
532 substitutions["png"] = 'disabled="disabled"'
533 substitutions["jpeg"] = 'disabled="disabled"'
534 substitutions["pdf"] = 'disabled="disabled"'
535 substitutions["svg"] = 'disabled="disabled"'
536 substitutions["eps"] = 'selected="selected"'
537
538 if shutil.which("pdf2svg") is None:
539 substitutions["svg"] = 'disabled="disabled"'
540
541 if errors:
542 print(errors, file=sys.stderr)
543 error_message: List[str] = []
544 for e in errors:
545 if type(e) is str: # noqa: E721
546 msg = e
547 elif len(e) == 2:
548 substitutions[e[0] + "_err"] = "class='error'"
549 msg = e[1]
550 else:
551 msg = e[0]
552
553 error_message += "ERROR: "
554 error_message += msg
555 error_message += " <br />"
556
557 error_message += (
558 "<input style='float:right; font-size:small' type='submit' "
559 "name='cmd_validate' value='Clear Error' /> "
560 )
561 substitutions["error_message"] = "".join(error_message)
562 else:
563 substitutions["error_message"] = ""
564
565 ref = importlib_resources.files("weblogo.htdocs").joinpath(
566 "create_html_template.html"
567 )
568 template = ref.read_text()
569 html = Template(template).safe_substitute(substitutions) # FIXME
570
571 print("Content-Type: text/html\n\n")
572 print(html)
573
574 # DEBUG
575 # keys = substitutions.keys()
576 # keys.sort()
577 # for k in keys :
578 # print(k, "=", substitutions[k], " <br />")
579
580 # print(" <br />")
581 # print(" <br />")
582 # for k in controls :
583 # print(k.name, "=", k.get_value(), " <br />")
584
585
586 if __name__ == "__main__":
587 from . import _cli
588
589 _cli.main()