]>
git.ipfire.org Git - ipfire.org.git/blob - src/backend/util.py
13 def parse_search_query(query
):
15 for word
in query
.split():
16 # Is this lexeme negated?
17 negated
= word
.startswith("!")
19 # Remove any special characters
20 word
= re
.sub(r
"\W+", "", word
, flags
=re
.UNICODE
)
32 def format_size(s
, max_unit
=None):
33 units
= ("B", "kB", "MB", "GB", "TB")
36 while s
>= 1024 and i
< len(units
) - 1:
40 if max_unit
and units
[i
] == max_unit
:
43 return "%.0f%s" % (s
, units
[i
])
45 def format_time(s
, shorter
=True):
46 #_ = handler.locale.translate
49 hrs
, s
= divmod(s
, 3600)
50 min, s
= divmod(s
, 60)
55 if shorter
and not hrs
:
56 return _("%(min)d min") % { "min" : min }
58 return _("%(hrs)d:%(min)02d hrs") % {"hrs" : hrs
, "min" : min}
60 def random_string(length
=8):
61 input_chars
= string
.ascii_letters
+ string
.digits
63 r
= (random
.choice(input_chars
) for i
in range(length
))
68 # Remove any non-ASCII characters
70 s
= unicodedata
.normalize("NFKD", s
)
74 # Remove excessive whitespace
75 s
= re
.sub(r
"[^\w]+", " ", s
)
77 return "-".join(s
.split())
79 def generate_thumbnail(data
, size
, square
=False, **args
):
80 assert data
, "No image data received"
82 image
= PIL
.Image
.open(io
.BytesIO(data
))
87 # Remove any alpha-channels
88 if image
.format
== "JPEG" and not image
.mode
== "RGB":
89 # Make a white background
90 background
= PIL
.Image
.new("RGBA", image
.size
, (255,255,255))
92 # Convert image to RGBA if not in RGBA, yet
93 if not image
.mode
== "RGBA":
94 image
= image
.convert("RGBA")
96 # Flatten both images together
97 flattened_image
= PIL
.Image
.alpha_composite(background
, image
)
99 # Remove the alpha channel
100 image
= flattened_image
.convert("RGB")
102 # Resize the image to the desired resolution
104 image
= PIL
.ImageOps
.fit(image
, (size
, size
), PIL
.Image
.LANCZOS
)
106 image
.thumbnail((size
, size
), PIL
.Image
.LANCZOS
)
108 if image
.format
== "JPEG":
109 # Apply a gaussian blur to make compression easier
110 image
= image
.filter(PIL
.ImageFilter
.GaussianBlur(radius
=0.05))
112 # Arguments to optimise the compression
114 "subsampling" : "4:2:0",
118 with io
.BytesIO() as f
:
119 # If writing out the image does not work with optimization,
120 # we try to write it out without any optimization.
122 image
.save(f
, format
, optimize
=True, **args
)
124 image
.save(f
, format
, **args
)