string.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. ########################################################################
  2. # Searx-Qt - Lightweight desktop application for Searx.
  3. # Copyright (C) 2020-2022 CYBERDEViL
  4. #
  5. # This file is part of Searx-Qt.
  6. #
  7. # Searx-Qt is free software: you can redistribute it and/or modify
  8. # it under the terms of the GNU General Public License as published by
  9. # the Free Software Foundation, either version 3 of the License, or
  10. # (at your option) any later version.
  11. #
  12. # Searx-Qt is distributed in the hope that it will be useful,
  13. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. # GNU General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU General Public License
  18. # along with this program. If not, see <https://www.gnu.org/licenses/>.
  19. #
  20. ########################################################################
  21. from searxqt.translations import _
  22. KiB = 1024
  23. MiB = KiB ** 2
  24. GiB = KiB ** 3
  25. TiB = KiB ** 4
  26. def boolToStr(state):
  27. return _("Yes") if state else _("No")
  28. def listToStr(list_):
  29. return ", ".join(list_)
  30. def formatFileSize(fileSize):
  31. """
  32. @param fileSize: File size in bytes to format to string.
  33. @type fileSize: uint
  34. """
  35. sizeStr = ""
  36. if fileSize > TiB: # TiB
  37. sizeStr = f"{fileSize / TiB:.2f} TB"
  38. elif fileSize > GiB: # GiB
  39. sizeStr = f"{fileSize / GiB:.2f} GB"
  40. elif fileSize > MiB: # MiB
  41. sizeStr = f"{fileSize / MiB:.2f} MB"
  42. elif fileSize > KiB: # KiB
  43. sizeStr = f"{fileSize / KiB:.2f} KB"
  44. else:
  45. sizeStr = f"{fileSize} Bytes"
  46. return sizeStr
  47. ## Parse HTML into json
  48. def parseFilesize(filesizeStr):
  49. if " " not in filesizeStr:
  50. return 0
  51. no, unit = filesizeStr.split(" ", 1)
  52. try:
  53. no = float(no)
  54. except ValueError:
  55. return 0
  56. if unit == "KiB":
  57. return int(no * KiB)
  58. if unit == "MiB":
  59. return int(no * MiB)
  60. if unit == "GiB":
  61. return int(no * GiB)
  62. if unit == "TiB":
  63. return int(no * TiB)
  64. return 0
  65. def formatFileCount(fileCount):
  66. """
  67. @param fileCount: File count to format to string.
  68. @type fileCount: uint
  69. """
  70. if fileCount == 1:
  71. return "1 " + _("file")
  72. return f"{fileCount} {_('files')}"