]>
git.ipfire.org Git - ipfire.org.git/blob - src/backend/util.py
12 def parse_search_query(query
):
14 for word
in query
.split():
15 # Is this lexeme negated?
16 negated
= word
.startswith("!")
18 # Remove any special characters
19 word
= re
.sub(r
"\W+", "", word
, flags
=re
.UNICODE
)
31 def format_size(s
, max_unit
=None):
32 units
= ("B", "kB", "MB", "GB", "TB")
35 while s
>= 1024 and i
< len(units
) - 1:
39 if max_unit
and units
[i
] == max_unit
:
42 return "%.0f%s" % (s
, units
[i
])
44 def format_time(s
, shorter
=True):
45 #_ = handler.locale.translate
48 hrs
, s
= divmod(s
, 3600)
49 min, s
= divmod(s
, 60)
54 if shorter
and not hrs
:
55 return _("%(min)d min") % { "min" : min }
57 return _("%(hrs)d:%(min)02d hrs") % {"hrs" : hrs
, "min" : min}
59 def random_string(length
=8):
60 input_chars
= string
.ascii_letters
+ string
.digits
62 r
= (random
.choice(input_chars
) for i
in range(length
))
67 # Remove any non-ASCII characters
69 s
= unicodedata
.normalize("NFKD", s
)
73 # Remove excessive whitespace
74 s
= re
.sub(r
"[^\w]+", " ", s
)
76 return "-".join(s
.split())
78 def generate_thumbnail(data
, size
, **args
):
79 assert data
, "No image data received"
81 image
= PIL
.Image
.open(io
.BytesIO(data
))
86 # Remove any alpha-channels
87 if image
.format
== "JPEG" and not image
.mode
== "RGB":
88 # Make a white background
89 background
= PIL
.Image
.new("RGBA", image
.size
, (255,255,255))
91 # Convert image to RGBA if not in RGBA, yet
92 if not image
.mode
== "RGBA":
93 image
= image
.convert("RGBA")
95 # Flatten both images together
96 flattened_image
= PIL
.Image
.alpha_composite(background
, image
)
98 # Remove the alpha channel
99 image
= flattened_image
.convert("RGB")
101 # Resize the image to the desired resolution
102 image
.thumbnail((size
, size
), PIL
.Image
.LANCZOS
)
104 if image
.format
== "JPEG":
105 # Apply a gaussian blur to make compression easier
106 image
= image
.filter(PIL
.ImageFilter
.GaussianBlur(radius
=0.05))
108 # Arguments to optimise the compression
110 "subsampling" : "4:2:0",
114 with io
.BytesIO() as f
:
115 # If writing out the image does not work with optimization,
116 # we try to write it out without any optimization.
118 image
.save(f
, format
, optimize
=True, **args
)
120 image
.save(f
, format
, **args
)