From 7bb4433ea278d631defc2518f9dffe5ac34a3d56 Mon Sep 17 00:00:00 2001 From: Skye Date: Sun, 21 Apr 2024 19:20:29 +0300 Subject: [PATCH 01/21] bug --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 4fa2dff..6455655 100644 --- a/README.md +++ b/README.md @@ -130,7 +130,7 @@ the output file assumes the base name of the input file but the extension confor ## Help in any case you can pass the string help to an option to see its supported operations or inputs nd output formats. ```shell - filemac --conver_doc help + filemac --convert_doc help ``` The above command displays the surported input and output formats for document conversion. ## Contributing From a1e35351dac0aacb5b5ebdddbe601790cccf86cd Mon Sep 17 00:00:00 2001 From: Skye Date: Thu, 25 Apr 2024 17:40:12 +0300 Subject: [PATCH 02/21] improv1 --- filemac/__pycache__/colors.cpython-311.pyc | Bin 1118 -> 1171 bytes filemac/__pycache__/converter.cpython-311.pyc | Bin 57833 -> 66273 bytes filemac/converter.py | 14 ++++- filemac/fmac.py | 17 ++++-- filemac/longImg.py | 56 ++++++++++++++++++ 5 files changed, 82 insertions(+), 5 deletions(-) create mode 100644 filemac/longImg.py diff --git a/filemac/__pycache__/colors.cpython-311.pyc b/filemac/__pycache__/colors.cpython-311.pyc index 995bc0187ec319f2c2d32c561703eb3027642192..53d86bba6f3411be7295bf4d960593b74a05298e 100644 GIT binary patch delta 331 zcmcb|F`1KhIWI340}w=fS4dkukyny2YofXzquj(Y({$k|;S|PThE#?uR*(u1ND;|q z0?|b&smxg-AQlKjv86I)i9*;w9y^f74(D+Id17!LCy>Vp=Wzjf;*}jrdE7uAH=M@<$AYMy+QDS5I!vnXTmWLIVlE@hw= hMj$Tcm|V_0VKNU(fk1<6gX;%r1~$=#_##E16acx#DTn|7 diff --git a/filemac/__pycache__/converter.cpython-311.pyc b/filemac/__pycache__/converter.cpython-311.pyc index cbc7e1ff8d155491120d809b32f62b4cdf8962f1..a45dc02bb6405ae6bc267da10c2b64c41c93bc83 100644 GIT binary patch literal 66273 zcmeFa3v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Yj3^VCukcEz_aUG|{n z6`*e+50fHlNxE7=_9T;`JxPrU4RUUOQfO9BLbH0dL_#DW&aywL z{A?MB%_w*`EqS*udbji5oq~5Kl%Ch_iX4s{hHDm2$*Q8WxU-GPzIO7?U4nC0%(-j1 zu=wJssGBcbBNVQQ=;Js;i#K3Nv`)d<8FO}Gy^6~%KdiaB?po+Cx`gd14?iV`g_6Tq z|HAngi+|wSu2|s#@y9z43eJNu=fSwM=#uS%ZGK=O$UEBwXM4=q&SJ}DW}Dd=X)U(p za^L0t1qWZgMJV3_j{+oSE4XN#-wFNvl#bMGXCIx+o$oxKcQG%LhXcV`$2->w&b2Y; zS_DY=1|4ybPbYj+VAV5@j-ldMT%mJB_ES6SL}Psb z$0FYd5n-Ct*U@1n5qls?)8C%R8HJNTbQuX}GSK`i`UZ%nLtHmyT}2=H2ShA%$Uf~O z2r;h{tz@vm5gg~fK<7;1Gm}V*12o5C6YR_+QX343YhyEJ+M6skktYy=dyHb~(V4OC zff)~R#7j;XPQoLX==|(OiftysIB|J!XEqX?JkuNujD+DzkG|kUjwlxoF|~?B5tiA3 zIn3zbiDoDfG*4ng3&DkAh_g}LeCaAWK$LkZ#1VU(BU?d^F$Ae^OXMH<;-1b!JprX{^FX(nDQ6bG{ls@xMo`{ z+b`R_>eN=8nnJvZ{J5szr5r(1Fu(Tlx>(D>nC1|#IV5NfArQBe%oPcilKCyXrB<-i zzGPZ4jpS${>dsE@u=Br`Uwz6kuG3-`ot@rc=YK7~I%?dhg|s}A+@W*7mM$FBt<{2w enMv-@xnD~cPH1;&(RXB$J9O^XSuU_n<^KhaONy)j diff --git a/filemac/converter.py b/filemac/converter.py index a46a46f..af657e3 100644 --- a/filemac/converter.py +++ b/filemac/converter.py @@ -29,7 +29,7 @@ from pptx import Presentation from pydub import AudioSegment from .colors import (RESET, GREEN, DGREEN, YELLOW, DYELLOW, CYAN, BLUE, DBLUE, - MAGENTA, DMAGENTA, RED, DRED, ICYAN) + DMAGENTA, DRED, ICYAN) from reportlab.lib.pagesizes import letter from reportlab.platypus import Paragraph, SimpleDocTemplate @@ -110,6 +110,7 @@ def word_to_pdf(self): sys.exit(1) subprocess.run(['soffice', '--convert-to', 'pdf', word_file, pdf_file]) + return pdf_file # print(f"{DMAGENTA} Successfully converted {word_file} to {pdf_file}{RESET}") elif os.name == "nt": try: @@ -120,6 +121,7 @@ def word_to_pdf(self): convert(word_file, pdf_file) print( f"{DMAGENTA} Successfully converted {word_file} to {pdf_file}{RESET}") + return pdf_file except Exception as e: print(f"Error converting {word_file} to {pdf_file}: {e}") @@ -645,6 +647,16 @@ def scanAsImgs(self): print(f"{GREEN}Ok{RESET}") return text + def scanAsLongImg(self): + file = self.input_file + from .longImg import pdf_2L_Img + LImg = pdf_2L_Img(file) + from .OCRTextExtractor import ExtractText + text = ExtractText(LImg) + print(text) + print(f"{GREEN}Ok{RESET}") + return text + class FileSynthesis: diff --git a/filemac/fmac.py b/filemac/fmac.py index 91b28ba..5a3c84d 100644 --- a/filemac/fmac.py +++ b/filemac/fmac.py @@ -130,6 +130,10 @@ def main(): "-S", "--scan", help=f"Scan pdf file and extract text\ example {DYELLOW}filemac --scan example.pdf {RESET}") + parser.add_argument( + "-pdf2L", "--doc_long_image", help=f"Convert pdf file to long image\ + example {DYELLOW}filemac --pdf_long_image example.pdf {RESET}") + parser.add_argument( "-SA", "--scanAsImg", help=f"Scan pdf file and extract text\ example {DYELLOW}filemac --scanAsImg example.pdf {RESET}") @@ -151,7 +155,7 @@ def main(): # Call function to handle video conversion inputs before begining conversion elif args.convert_video: - if args.convert_video == 'help' or args.convert_video is None: + if args.convert_video == 'help': print(SUPPORTED_VIDEO_FORMATS_SHOW) sys.exit(1) ev = VideoConverter(args.convert_video, args.target_format) @@ -159,7 +163,7 @@ def main(): # Call function to handle image conversion inputs before begining conversion elif args.convert_image: - if args.convert_image == 'help' or args.convert_image is None: + if args.convert_image == 'help': print(SUPPORTED_IMAGE_FORMATS_SHOW) sys.exit(1) conv = ImageConverter(args.convert_image, args.target_format) @@ -177,7 +181,7 @@ def main(): # Call function to handle audio conversion inputs before begining conversion elif args.convert_audio: - if args.convert_audio == 'help' or args.convert_audio is None: + if args.convert_audio == 'help': print(SUPPORTED_AUDIO_FORMATS_SHOW) sys.exit(1) ev = AudioConverter(args.convert_audio, args.target_format) @@ -197,7 +201,12 @@ def main(): # Call module to scan the input FILE as image object and extract text elif args.scanAsImg: sc = Scanner(args.scanAsImg) - tx = sc.scanAsImgs() + sc.scanAsImgs() + + elif args.doc_2long_image: + from .longImg import LImage + conv = LImage(args.pdf_long_image) + conv.preprocess() # Call module to handle Candidate images for text extraction inputs before begining conversion elif args.OCR: conv = ExtractText(args.OCR) diff --git a/filemac/longImg.py b/filemac/longImg.py new file mode 100644 index 0000000..9797bb8 --- /dev/null +++ b/filemac/longImg.py @@ -0,0 +1,56 @@ +# convert pdf to long image +import os +import subprocess + +from .colors import DGREEN, DMAGENTA, DYELLOW, RESET, YELLOW +from .converter import MakeConversion +from pdf2image import convert_from_path +from PIL import Image # ImageSequence + + +class LImage: + def __init__(self, doc): + self.doc = doc + + def preprocess(self): + doc = self.doc + ext = doc.split('.')[-1].lower() + if ext == "pdf": + LImage.pdf_2L_Img(doc) + if ext == 'doc' or ext == 'docx': + conv = MakeConversion(doc) + pdf = conv.word_to_pdf() + LImage.pdf_2L_Img(pdf) + + elif ext == 'odt': + pdf_file = ext = doc.split('.')[0] + 'docx' + pdf = subprocess.call(['soffice', '--headless', '--convert-to', + 'pdf', '--outdir', os.path.dirname(pdf_file), + os.path.abspath(doc)]) + LImage.pdf_2L_Img(pdf) + else: + print(f"Unsupported format: {ext}") + + @staticmethod + def pdf_2L_Img(pdf_file): + print(f"{YELLOW}Read pdf ..{RESET}") + images = convert_from_path(pdf_file) + out_img = pdf_file[:-4] + '.png' + heights = [img.size[1] for img in images] + total_height = sum(heights) + max_width = max([img.size[0] for img in images]) + + new_im = Image.new('RGB', (max_width, total_height)) + + y_offset = 0 + for img in images: + new_im.paste(img, (0, y_offset)) + y_offset += img.size[1] + print(f"{DYELLOW}Save dest: {DMAGENTA}{out_img}{RESET}") + new_im.save(out_img) + print(f"{DGREEN}Done{RESET}") + return new_im + + +l = LImage('/home/skye/Documents/test.pdf') +l.preprocess() From bec2fb1af56bd192fc850acb339c6a2e27837055 Mon Sep 17 00:00:00 2001 From: Skye Wambua Date: Fri, 14 Nov 2025 15:26:56 +0300 Subject: [PATCH 03/21] UPDATE DEV Signed-off-by: Skye Wambua --- .github/workflows/python-package.yml | 37 + .github/workflows/python-publish.yml | 1 + .gitignore | 38 + .kateproject.notes | 2 + .pyproject.toml | 83 + MANIFEST.in | 30 + README.md | 168 +- audiobot/__init__.py | 50 + audiobot/cli.py | 196 + audiobot/config/__init__.py | 0 audiobot/config/core.py | 8 + audiobot/core/__init__.py | 0 audiobot/core/audio/core.py | 283 + audiobot/core/codec.py | 67 + audiobot/core/effects.py | 115 + audiobot/core/processor.py | 154 + audiobot/utils/logging_utils.py | 40 + audiobot/utils/metadata_utils.py | 57 + audiobot/utils/visualizer.py | 25 + audiobot/version.txt | 1 + filemac/__init__.py | 77 +- filemac/cli/__init__.py | 0 filemac/cli/converter.py | 206 + filemac/cli/main.py | 718 ++ filemac/core/__init__.py | 0 filemac/core/audio/core.py | 262 + filemac/core/audio/m4a_converter.py | 54 + filemac/core/document.py | 878 ++ filemac/core/exceptions.py | 43 + filemac/core/html/__init__.py | 18 + filemac/core/html/core.py | 365 + filemac/core/html/core/__init__.py | 5 + filemac/core/html/core/converter.py | 692 + filemac/core/html/core/html_parser.py | 390 + filemac/core/html/core/style_manager.py | 311 + filemac/core/html/examples/__init__.py | 3 + filemac/core/html/examples/templates.py | 228 + filemac/core/html/styles/__init__.py | 4 + filemac/core/html/styles/css_parser.py | 69 + filemac/core/html/styles/style_applier.py | 83 + filemac/core/html/tests.py | 82 + filemac/core/html/utils/__init__.py | 9 + filemac/core/html/utils/color_utils.py | 121 + filemac/core/html/utils/validation.py | 93 + filemac/core/image/core.py | 783 ++ filemac/core/image/extractor.py | 269 + filemac/core/ocr.py | 199 + filemac/core/pdf/core.py | 415 + filemac/core/recorder.py | 106 + filemac/core/svg/core.py | 47 + filemac/core/text/core.py | 111 + filemac/core/tts/core.py | 0 filemac/core/tts/gtts.py | 562 + filemac/core/validator.py | 19 + filemac/core/video/core.py | 185 + filemac/core/warning.py | 13 + filemac/miscellaneous/VKITPro.py | 135 + filemac/miscellaneous/VRKit.py | 138 + filemac/miscellaneous/video_analyzer.py | 121 + filemac/utils/__init__.py | 0 filemac/utils/colors.py | 271 + filemac/utils/config.py | 11 + filemac/utils/decorators.py | 22 + filemac/utils/file_utils.py | 349 + filemac/utils/formats.py | 168 + filemac/utils/helpmaster.py | 25 + filemac/utils/logging_utils.py | 73 + filemac/utils/screen.py | 19 + filemac/utils/security/vul_mitigate.py | 177 + filemac/utils/simple.py | 8 + fweb/README.md | 26 + fweb/core/__init__.py | 0 fweb/core/admin.py | 30 + fweb/core/apps.py | 6 + fweb/core/config.py | 206 + fweb/core/forms.py | 89 + fweb/core/migrations/0001_initial.py | 48 + fweb/core/migrations/__init__.py | 0 fweb/core/models.py | 41 + fweb/core/static/css/config.css | 127 + fweb/core/static/css/styles.css | 1 + fweb/core/static/js/FileHandler.js | 134 + fweb/core/static/js/ToolsHandler.js | 366 + fweb/core/static/js/UI-X/aos-animate.js | 15 + fweb/core/static/js/UI-X/aos/aos.css | 1 + fweb/core/static/js/UI-X/packed_aosanimate.js | 2 + fweb/core/static/js/apiClient.js | 91 + fweb/core/static/js/main.js | 26 + fweb/core/static/js/processor.js | 50 + fweb/core/static/js/result_utils.js | 21 + fweb/core/static/js/themes.js | 31 + fweb/core/static/js/uiManager.js | 126 + fweb/core/static/js/utils.js | 992 ++ fweb/core/tests.py | 3 + fweb/core/urls.py | 21 + fweb/core/utils.py | 149 + fweb/core/views.py | 280 + fweb/db.sqlite3 | Bin 0 -> 151552 bytes fweb/fweb/__init__.py | 0 fweb/fweb/asgi.py | 16 + fweb/fweb/settings.py | 146 + fweb/fweb/urls.py | 32 + fweb/fweb/wsgi.py | 16 + fweb/manage.py | 22 + fweb/package.json | 43 + fweb/static/admin/css/autocomplete.css | 279 + fweb/static/admin/css/base.css | 1179 ++ fweb/static/admin/css/changelists.css | 343 + fweb/static/admin/css/dark_mode.css | 130 + fweb/static/admin/css/dashboard.css | 29 + fweb/static/admin/css/forms.css | 512 + fweb/static/admin/css/login.css | 61 + fweb/static/admin/css/nav_sidebar.css | 150 + fweb/static/admin/css/responsive.css | 967 ++ fweb/static/admin/css/responsive_rtl.css | 111 + fweb/static/admin/css/rtl.css | 291 + .../admin/css/unusable_password_field.css | 19 + .../css/vendor/select2/LICENSE-SELECT2.md | 21 + .../admin/css/vendor/select2/select2.css | 481 + .../admin/css/vendor/select2/select2.min.css | 1 + fweb/static/admin/css/widgets.css | 593 + fweb/static/admin/img/LICENSE | 20 + fweb/static/admin/img/README.txt | 7 + fweb/static/admin/img/calendar-icons.svg | 63 + fweb/static/admin/img/gis/move_vertex_off.svg | 1 + fweb/static/admin/img/gis/move_vertex_on.svg | 1 + fweb/static/admin/img/icon-addlink.svg | 3 + fweb/static/admin/img/icon-alert.svg | 3 + fweb/static/admin/img/icon-calendar.svg | 9 + fweb/static/admin/img/icon-changelink.svg | 3 + fweb/static/admin/img/icon-clock.svg | 9 + fweb/static/admin/img/icon-deletelink.svg | 3 + fweb/static/admin/img/icon-hidelink.svg | 3 + fweb/static/admin/img/icon-no.svg | 3 + fweb/static/admin/img/icon-unknown-alt.svg | 3 + fweb/static/admin/img/icon-unknown.svg | 3 + fweb/static/admin/img/icon-viewlink.svg | 3 + fweb/static/admin/img/icon-yes.svg | 3 + fweb/static/admin/img/inline-delete.svg | 3 + fweb/static/admin/img/search.svg | 3 + fweb/static/admin/img/selector-icons.svg | 34 + fweb/static/admin/img/sorting-icons.svg | 19 + fweb/static/admin/img/tooltag-add.svg | 3 + fweb/static/admin/img/tooltag-arrowright.svg | 3 + fweb/static/admin/js/SelectBox.js | 116 + fweb/static/admin/js/SelectFilter2.js | 286 + fweb/static/admin/js/actions.js | 204 + .../admin/js/admin/DateTimeShortcuts.js | 408 + .../admin/js/admin/RelatedObjectLookups.js | 240 + fweb/static/admin/js/autocomplete.js | 33 + fweb/static/admin/js/calendar.js | 239 + fweb/static/admin/js/cancel.js | 29 + fweb/static/admin/js/change_form.js | 16 + fweb/static/admin/js/core.js | 184 + fweb/static/admin/js/filters.js | 30 + fweb/static/admin/js/inlines.js | 359 + fweb/static/admin/js/jquery.init.js | 8 + fweb/static/admin/js/nav_sidebar.js | 79 + fweb/static/admin/js/popup_response.js | 15 + fweb/static/admin/js/prepopulate.js | 43 + fweb/static/admin/js/prepopulate_init.js | 15 + fweb/static/admin/js/theme.js | 51 + .../admin/js/unusable_password_field.js | 29 + fweb/static/admin/js/urlify.js | 169 + .../static/admin/js/vendor/jquery/LICENSE.txt | 20 + fweb/static/admin/js/vendor/jquery/jquery.js | 10716 ++++++++++++++++ .../admin/js/vendor/jquery/jquery.min.js | 2 + .../static/admin/js/vendor/select2/LICENSE.md | 21 + .../static/admin/js/vendor/select2/i18n/af.js | 3 + .../static/admin/js/vendor/select2/i18n/ar.js | 3 + .../static/admin/js/vendor/select2/i18n/az.js | 3 + .../static/admin/js/vendor/select2/i18n/bg.js | 3 + .../static/admin/js/vendor/select2/i18n/bn.js | 3 + .../static/admin/js/vendor/select2/i18n/bs.js | 3 + .../static/admin/js/vendor/select2/i18n/ca.js | 3 + .../static/admin/js/vendor/select2/i18n/cs.js | 3 + .../static/admin/js/vendor/select2/i18n/da.js | 3 + .../static/admin/js/vendor/select2/i18n/de.js | 3 + .../admin/js/vendor/select2/i18n/dsb.js | 3 + .../static/admin/js/vendor/select2/i18n/el.js | 3 + .../static/admin/js/vendor/select2/i18n/en.js | 3 + .../static/admin/js/vendor/select2/i18n/es.js | 3 + .../static/admin/js/vendor/select2/i18n/et.js | 3 + .../static/admin/js/vendor/select2/i18n/eu.js | 3 + .../static/admin/js/vendor/select2/i18n/fa.js | 3 + .../static/admin/js/vendor/select2/i18n/fi.js | 3 + .../static/admin/js/vendor/select2/i18n/fr.js | 3 + .../static/admin/js/vendor/select2/i18n/gl.js | 3 + .../static/admin/js/vendor/select2/i18n/he.js | 3 + .../static/admin/js/vendor/select2/i18n/hi.js | 3 + .../static/admin/js/vendor/select2/i18n/hr.js | 3 + .../admin/js/vendor/select2/i18n/hsb.js | 3 + .../static/admin/js/vendor/select2/i18n/hu.js | 3 + .../static/admin/js/vendor/select2/i18n/hy.js | 3 + .../static/admin/js/vendor/select2/i18n/id.js | 3 + .../static/admin/js/vendor/select2/i18n/is.js | 3 + .../static/admin/js/vendor/select2/i18n/it.js | 3 + .../static/admin/js/vendor/select2/i18n/ja.js | 3 + .../static/admin/js/vendor/select2/i18n/ka.js | 3 + .../static/admin/js/vendor/select2/i18n/km.js | 3 + .../static/admin/js/vendor/select2/i18n/ko.js | 3 + .../static/admin/js/vendor/select2/i18n/lt.js | 3 + .../static/admin/js/vendor/select2/i18n/lv.js | 3 + .../static/admin/js/vendor/select2/i18n/mk.js | 3 + .../static/admin/js/vendor/select2/i18n/ms.js | 3 + .../static/admin/js/vendor/select2/i18n/nb.js | 3 + .../static/admin/js/vendor/select2/i18n/ne.js | 3 + .../static/admin/js/vendor/select2/i18n/nl.js | 3 + .../static/admin/js/vendor/select2/i18n/pl.js | 3 + .../static/admin/js/vendor/select2/i18n/ps.js | 3 + .../admin/js/vendor/select2/i18n/pt-BR.js | 3 + .../static/admin/js/vendor/select2/i18n/pt.js | 3 + .../static/admin/js/vendor/select2/i18n/ro.js | 3 + .../static/admin/js/vendor/select2/i18n/ru.js | 3 + .../static/admin/js/vendor/select2/i18n/sk.js | 3 + .../static/admin/js/vendor/select2/i18n/sl.js | 3 + .../static/admin/js/vendor/select2/i18n/sq.js | 3 + .../admin/js/vendor/select2/i18n/sr-Cyrl.js | 3 + .../static/admin/js/vendor/select2/i18n/sr.js | 3 + .../static/admin/js/vendor/select2/i18n/sv.js | 3 + .../static/admin/js/vendor/select2/i18n/th.js | 3 + .../static/admin/js/vendor/select2/i18n/tk.js | 3 + .../static/admin/js/vendor/select2/i18n/tr.js | 3 + .../static/admin/js/vendor/select2/i18n/uk.js | 3 + .../static/admin/js/vendor/select2/i18n/vi.js | 3 + .../admin/js/vendor/select2/i18n/zh-CN.js | 3 + .../admin/js/vendor/select2/i18n/zh-TW.js | 3 + .../admin/js/vendor/select2/select2.full.js | 6820 ++++++++++ .../js/vendor/select2/select2.full.min.js | 2 + .../admin/js/vendor/xregexp/LICENSE.txt | 21 + .../static/admin/js/vendor/xregexp/xregexp.js | 6126 +++++++++ .../admin/js/vendor/xregexp/xregexp.min.js | 17 + fweb/static/css/config.css | 89 + fweb/static/css/styles.css | 1 + .../django-browser-reload/reload-listener.js | 28 + .../django-browser-reload/reload-worker.js | 112 + fweb/static/js/FileHandler.js | 49 + fweb/static/js/UI-X/aos-animate.js | 15 + fweb/static/js/UI-X/aos/aos.css | 1 + fweb/static/js/UI-X/packed_aosanimate.js | 2 + fweb/static/js/themes.js | 31 + fweb/tailwind.config.js | 123 + fweb/templates/core/base.html | 114 + fweb/templates/core/converter.html | 107 + fweb/templates/core/dashboard.html | 147 + fweb/templates/core/results.html | 120 + fweb/templates/core/tools/audio_tools.html | 191 + fweb/templates/core/tools/base_tools.html | 139 + fweb/templates/core/tools/batch_tools.html | 651 + fweb/templates/core/tools/document_tools.html | 645 + fweb/templates/core/tools/image_tools.html | 213 + fweb/templates/core/tools/ocr_tools.html | 554 + fweb/templates/core/tools/video_tools.html | 627 + index.html | 137 + res/audio_effects/chipmunk_demo_v.mp4 | Bin 0 -> 6656796 bytes res/audio_effects/demo.mp3 | Bin 0 -> 211152 bytes res/audio_effects/demo_v.mp4 | Bin 0 -> 4211557 bytes res/audio_effects/high_demo.mp3 | Bin 0 -> 1345244 bytes res/demo.html | 96 + res/init.css | 316 + res/styles.css | 1094 ++ setup.py | 137 +- version.txt | 2 +- voice/VoiceType.py | 153 + voice/__init__.py | 0 265 files changed, 51070 insertions(+), 120 deletions(-) create mode 100644 .github/workflows/python-package.yml create mode 100644 .gitignore create mode 100644 .kateproject.notes create mode 100644 .pyproject.toml create mode 100644 MANIFEST.in create mode 100644 audiobot/__init__.py create mode 100644 audiobot/cli.py create mode 100644 audiobot/config/__init__.py create mode 100644 audiobot/config/core.py create mode 100644 audiobot/core/__init__.py create mode 100644 audiobot/core/audio/core.py create mode 100644 audiobot/core/codec.py create mode 100644 audiobot/core/effects.py create mode 100644 audiobot/core/processor.py create mode 100644 audiobot/utils/logging_utils.py create mode 100644 audiobot/utils/metadata_utils.py create mode 100644 audiobot/utils/visualizer.py create mode 100644 audiobot/version.txt create mode 100644 filemac/cli/__init__.py create mode 100644 filemac/cli/converter.py create mode 100644 filemac/cli/main.py create mode 100644 filemac/core/__init__.py create mode 100644 filemac/core/audio/core.py create mode 100644 filemac/core/audio/m4a_converter.py create mode 100644 filemac/core/document.py create mode 100644 filemac/core/exceptions.py create mode 100644 filemac/core/html/__init__.py create mode 100644 filemac/core/html/core.py create mode 100644 filemac/core/html/core/__init__.py create mode 100644 filemac/core/html/core/converter.py create mode 100644 filemac/core/html/core/html_parser.py create mode 100644 filemac/core/html/core/style_manager.py create mode 100644 filemac/core/html/examples/__init__.py create mode 100644 filemac/core/html/examples/templates.py create mode 100644 filemac/core/html/styles/__init__.py create mode 100644 filemac/core/html/styles/css_parser.py create mode 100644 filemac/core/html/styles/style_applier.py create mode 100644 filemac/core/html/tests.py create mode 100644 filemac/core/html/utils/__init__.py create mode 100644 filemac/core/html/utils/color_utils.py create mode 100644 filemac/core/html/utils/validation.py create mode 100644 filemac/core/image/core.py create mode 100644 filemac/core/image/extractor.py create mode 100644 filemac/core/ocr.py create mode 100644 filemac/core/pdf/core.py create mode 100644 filemac/core/recorder.py create mode 100644 filemac/core/svg/core.py create mode 100644 filemac/core/text/core.py create mode 100644 filemac/core/tts/core.py create mode 100644 filemac/core/tts/gtts.py create mode 100644 filemac/core/validator.py create mode 100644 filemac/core/video/core.py create mode 100644 filemac/core/warning.py create mode 100644 filemac/miscellaneous/VKITPro.py create mode 100644 filemac/miscellaneous/VRKit.py create mode 100644 filemac/miscellaneous/video_analyzer.py create mode 100644 filemac/utils/__init__.py create mode 100644 filemac/utils/colors.py create mode 100644 filemac/utils/config.py create mode 100644 filemac/utils/decorators.py create mode 100644 filemac/utils/file_utils.py create mode 100644 filemac/utils/formats.py create mode 100644 filemac/utils/helpmaster.py create mode 100644 filemac/utils/logging_utils.py create mode 100644 filemac/utils/screen.py create mode 100644 filemac/utils/security/vul_mitigate.py create mode 100644 filemac/utils/simple.py create mode 100644 fweb/README.md create mode 100644 fweb/core/__init__.py create mode 100644 fweb/core/admin.py create mode 100644 fweb/core/apps.py create mode 100644 fweb/core/config.py create mode 100644 fweb/core/forms.py create mode 100644 fweb/core/migrations/0001_initial.py create mode 100644 fweb/core/migrations/__init__.py create mode 100644 fweb/core/models.py create mode 100644 fweb/core/static/css/config.css create mode 100644 fweb/core/static/css/styles.css create mode 100644 fweb/core/static/js/FileHandler.js create mode 100644 fweb/core/static/js/ToolsHandler.js create mode 100644 fweb/core/static/js/UI-X/aos-animate.js create mode 100644 fweb/core/static/js/UI-X/aos/aos.css create mode 100644 fweb/core/static/js/UI-X/packed_aosanimate.js create mode 100644 fweb/core/static/js/apiClient.js create mode 100644 fweb/core/static/js/main.js create mode 100644 fweb/core/static/js/processor.js create mode 100644 fweb/core/static/js/result_utils.js create mode 100644 fweb/core/static/js/themes.js create mode 100644 fweb/core/static/js/uiManager.js create mode 100644 fweb/core/static/js/utils.js create mode 100644 fweb/core/tests.py create mode 100644 fweb/core/urls.py create mode 100644 fweb/core/utils.py create mode 100644 fweb/core/views.py create mode 100644 fweb/db.sqlite3 create mode 100644 fweb/fweb/__init__.py create mode 100644 fweb/fweb/asgi.py create mode 100644 fweb/fweb/settings.py create mode 100644 fweb/fweb/urls.py create mode 100644 fweb/fweb/wsgi.py create mode 100755 fweb/manage.py create mode 100644 fweb/package.json create mode 100644 fweb/static/admin/css/autocomplete.css create mode 100644 fweb/static/admin/css/base.css create mode 100644 fweb/static/admin/css/changelists.css create mode 100644 fweb/static/admin/css/dark_mode.css create mode 100644 fweb/static/admin/css/dashboard.css create mode 100644 fweb/static/admin/css/forms.css create mode 100644 fweb/static/admin/css/login.css create mode 100644 fweb/static/admin/css/nav_sidebar.css create mode 100644 fweb/static/admin/css/responsive.css create mode 100644 fweb/static/admin/css/responsive_rtl.css create mode 100644 fweb/static/admin/css/rtl.css create mode 100644 fweb/static/admin/css/unusable_password_field.css create mode 100644 fweb/static/admin/css/vendor/select2/LICENSE-SELECT2.md create mode 100644 fweb/static/admin/css/vendor/select2/select2.css create mode 100644 fweb/static/admin/css/vendor/select2/select2.min.css create mode 100644 fweb/static/admin/css/widgets.css create mode 100644 fweb/static/admin/img/LICENSE create mode 100644 fweb/static/admin/img/README.txt create mode 100644 fweb/static/admin/img/calendar-icons.svg create mode 100644 fweb/static/admin/img/gis/move_vertex_off.svg create mode 100644 fweb/static/admin/img/gis/move_vertex_on.svg create mode 100644 fweb/static/admin/img/icon-addlink.svg create mode 100644 fweb/static/admin/img/icon-alert.svg create mode 100644 fweb/static/admin/img/icon-calendar.svg create mode 100644 fweb/static/admin/img/icon-changelink.svg create mode 100644 fweb/static/admin/img/icon-clock.svg create mode 100644 fweb/static/admin/img/icon-deletelink.svg create mode 100644 fweb/static/admin/img/icon-hidelink.svg create mode 100644 fweb/static/admin/img/icon-no.svg create mode 100644 fweb/static/admin/img/icon-unknown-alt.svg create mode 100644 fweb/static/admin/img/icon-unknown.svg create mode 100644 fweb/static/admin/img/icon-viewlink.svg create mode 100644 fweb/static/admin/img/icon-yes.svg create mode 100644 fweb/static/admin/img/inline-delete.svg create mode 100644 fweb/static/admin/img/search.svg create mode 100644 fweb/static/admin/img/selector-icons.svg create mode 100644 fweb/static/admin/img/sorting-icons.svg create mode 100644 fweb/static/admin/img/tooltag-add.svg create mode 100644 fweb/static/admin/img/tooltag-arrowright.svg create mode 100644 fweb/static/admin/js/SelectBox.js create mode 100644 fweb/static/admin/js/SelectFilter2.js create mode 100644 fweb/static/admin/js/actions.js create mode 100644 fweb/static/admin/js/admin/DateTimeShortcuts.js create mode 100644 fweb/static/admin/js/admin/RelatedObjectLookups.js create mode 100644 fweb/static/admin/js/autocomplete.js create mode 100644 fweb/static/admin/js/calendar.js create mode 100644 fweb/static/admin/js/cancel.js create mode 100644 fweb/static/admin/js/change_form.js create mode 100644 fweb/static/admin/js/core.js create mode 100644 fweb/static/admin/js/filters.js create mode 100644 fweb/static/admin/js/inlines.js create mode 100644 fweb/static/admin/js/jquery.init.js create mode 100644 fweb/static/admin/js/nav_sidebar.js create mode 100644 fweb/static/admin/js/popup_response.js create mode 100644 fweb/static/admin/js/prepopulate.js create mode 100644 fweb/static/admin/js/prepopulate_init.js create mode 100644 fweb/static/admin/js/theme.js create mode 100644 fweb/static/admin/js/unusable_password_field.js create mode 100644 fweb/static/admin/js/urlify.js create mode 100644 fweb/static/admin/js/vendor/jquery/LICENSE.txt create mode 100644 fweb/static/admin/js/vendor/jquery/jquery.js create mode 100644 fweb/static/admin/js/vendor/jquery/jquery.min.js create mode 100644 fweb/static/admin/js/vendor/select2/LICENSE.md create mode 100644 fweb/static/admin/js/vendor/select2/i18n/af.js create mode 100644 fweb/static/admin/js/vendor/select2/i18n/ar.js create mode 100644 fweb/static/admin/js/vendor/select2/i18n/az.js create mode 100644 fweb/static/admin/js/vendor/select2/i18n/bg.js create mode 100644 fweb/static/admin/js/vendor/select2/i18n/bn.js create mode 100644 fweb/static/admin/js/vendor/select2/i18n/bs.js create mode 100644 fweb/static/admin/js/vendor/select2/i18n/ca.js create mode 100644 fweb/static/admin/js/vendor/select2/i18n/cs.js create mode 100644 fweb/static/admin/js/vendor/select2/i18n/da.js create mode 100644 fweb/static/admin/js/vendor/select2/i18n/de.js create mode 100644 fweb/static/admin/js/vendor/select2/i18n/dsb.js create mode 100644 fweb/static/admin/js/vendor/select2/i18n/el.js create mode 100644 fweb/static/admin/js/vendor/select2/i18n/en.js create mode 100644 fweb/static/admin/js/vendor/select2/i18n/es.js create mode 100644 fweb/static/admin/js/vendor/select2/i18n/et.js create mode 100644 fweb/static/admin/js/vendor/select2/i18n/eu.js create mode 100644 fweb/static/admin/js/vendor/select2/i18n/fa.js create mode 100644 fweb/static/admin/js/vendor/select2/i18n/fi.js create mode 100644 fweb/static/admin/js/vendor/select2/i18n/fr.js create mode 100644 fweb/static/admin/js/vendor/select2/i18n/gl.js create mode 100644 fweb/static/admin/js/vendor/select2/i18n/he.js create mode 100644 fweb/static/admin/js/vendor/select2/i18n/hi.js create mode 100644 fweb/static/admin/js/vendor/select2/i18n/hr.js create mode 100644 fweb/static/admin/js/vendor/select2/i18n/hsb.js create mode 100644 fweb/static/admin/js/vendor/select2/i18n/hu.js create mode 100644 fweb/static/admin/js/vendor/select2/i18n/hy.js create mode 100644 fweb/static/admin/js/vendor/select2/i18n/id.js create mode 100644 fweb/static/admin/js/vendor/select2/i18n/is.js create mode 100644 fweb/static/admin/js/vendor/select2/i18n/it.js create mode 100644 fweb/static/admin/js/vendor/select2/i18n/ja.js create mode 100644 fweb/static/admin/js/vendor/select2/i18n/ka.js create mode 100644 fweb/static/admin/js/vendor/select2/i18n/km.js create mode 100644 fweb/static/admin/js/vendor/select2/i18n/ko.js create mode 100644 fweb/static/admin/js/vendor/select2/i18n/lt.js create mode 100644 fweb/static/admin/js/vendor/select2/i18n/lv.js create mode 100644 fweb/static/admin/js/vendor/select2/i18n/mk.js create mode 100644 fweb/static/admin/js/vendor/select2/i18n/ms.js create mode 100644 fweb/static/admin/js/vendor/select2/i18n/nb.js create mode 100644 fweb/static/admin/js/vendor/select2/i18n/ne.js create mode 100644 fweb/static/admin/js/vendor/select2/i18n/nl.js create mode 100644 fweb/static/admin/js/vendor/select2/i18n/pl.js create mode 100644 fweb/static/admin/js/vendor/select2/i18n/ps.js create mode 100644 fweb/static/admin/js/vendor/select2/i18n/pt-BR.js create mode 100644 fweb/static/admin/js/vendor/select2/i18n/pt.js create mode 100644 fweb/static/admin/js/vendor/select2/i18n/ro.js create mode 100644 fweb/static/admin/js/vendor/select2/i18n/ru.js create mode 100644 fweb/static/admin/js/vendor/select2/i18n/sk.js create mode 100644 fweb/static/admin/js/vendor/select2/i18n/sl.js create mode 100644 fweb/static/admin/js/vendor/select2/i18n/sq.js create mode 100644 fweb/static/admin/js/vendor/select2/i18n/sr-Cyrl.js create mode 100644 fweb/static/admin/js/vendor/select2/i18n/sr.js create mode 100644 fweb/static/admin/js/vendor/select2/i18n/sv.js create mode 100644 fweb/static/admin/js/vendor/select2/i18n/th.js create mode 100644 fweb/static/admin/js/vendor/select2/i18n/tk.js create mode 100644 fweb/static/admin/js/vendor/select2/i18n/tr.js create mode 100644 fweb/static/admin/js/vendor/select2/i18n/uk.js create mode 100644 fweb/static/admin/js/vendor/select2/i18n/vi.js create mode 100644 fweb/static/admin/js/vendor/select2/i18n/zh-CN.js create mode 100644 fweb/static/admin/js/vendor/select2/i18n/zh-TW.js create mode 100644 fweb/static/admin/js/vendor/select2/select2.full.js create mode 100644 fweb/static/admin/js/vendor/select2/select2.full.min.js create mode 100644 fweb/static/admin/js/vendor/xregexp/LICENSE.txt create mode 100644 fweb/static/admin/js/vendor/xregexp/xregexp.js create mode 100644 fweb/static/admin/js/vendor/xregexp/xregexp.min.js create mode 100644 fweb/static/css/config.css create mode 100644 fweb/static/css/styles.css create mode 100644 fweb/static/django-browser-reload/reload-listener.js create mode 100644 fweb/static/django-browser-reload/reload-worker.js create mode 100644 fweb/static/js/FileHandler.js create mode 100644 fweb/static/js/UI-X/aos-animate.js create mode 100644 fweb/static/js/UI-X/aos/aos.css create mode 100644 fweb/static/js/UI-X/packed_aosanimate.js create mode 100644 fweb/static/js/themes.js create mode 100644 fweb/tailwind.config.js create mode 100644 fweb/templates/core/base.html create mode 100644 fweb/templates/core/converter.html create mode 100644 fweb/templates/core/dashboard.html create mode 100644 fweb/templates/core/results.html create mode 100644 fweb/templates/core/tools/audio_tools.html create mode 100644 fweb/templates/core/tools/base_tools.html create mode 100644 fweb/templates/core/tools/batch_tools.html create mode 100644 fweb/templates/core/tools/document_tools.html create mode 100644 fweb/templates/core/tools/image_tools.html create mode 100644 fweb/templates/core/tools/ocr_tools.html create mode 100644 fweb/templates/core/tools/video_tools.html create mode 100644 index.html create mode 100644 res/audio_effects/chipmunk_demo_v.mp4 create mode 100644 res/audio_effects/demo.mp3 create mode 100644 res/audio_effects/demo_v.mp4 create mode 100644 res/audio_effects/high_demo.mp3 create mode 100644 res/demo.html create mode 100644 res/init.css create mode 100644 res/styles.css create mode 100644 voice/VoiceType.py create mode 100644 voice/__init__.py diff --git a/.github/workflows/python-package.yml b/.github/workflows/python-package.yml new file mode 100644 index 0000000..d6786ac --- /dev/null +++ b/.github/workflows/python-package.yml @@ -0,0 +1,37 @@ +# This workflow will install Python dependencies, run tests and lint with a variety of Python versions +# For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-python + +name: Python package + +on: + push: + branches: [ "main" ] + pull_request: + branches: [ "main" ] + +jobs: + build: + + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + python-version: ["3.13"] + + steps: + - uses: actions/checkout@v4 + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@v3 + with: + python-version: ${{ matrix.python-version }} + - name: Install dependencies + run: | + python -m pip install --upgrade pip + python -m pip install flake8 + if [ -f requirements.txt ]; then pip install -r requirements.txt; fi + - name: Lint with flake8 + run: | + # stop the build if there are Python syntax errors or undefined names + flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics + # exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide + flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics diff --git a/.github/workflows/python-publish.yml b/.github/workflows/python-publish.yml index 256ab09..f3a2af1 100644 --- a/.github/workflows/python-publish.yml +++ b/.github/workflows/python-publish.yml @@ -26,6 +26,7 @@ jobs: uses: actions/setup-python@v3 with: python-version: '3.x' + - name: Install dependencies run: | python -m pip install --upgrade pip diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..138fc14 --- /dev/null +++ b/.gitignore @@ -0,0 +1,38 @@ +# Ignore the entire src directory (if not needed) +src/** + +# Ignore this .gitignore file itself (not necessary, but can be included for clarity) +#.gitignore + +# Ignore Python cache directories +__pycache__/ +*.py[cod] + +# Ignore temporary files +*~ +filemac.egg-info/** +# Ignore build directories +**/build/ +**/dist/ + +# Ignore IDE and editor files +.vscode/ +.idea/ +*.vscode/ +*.idea/ + +# Ignore operating system files +.DS_Store +Thumbs.db + +# Ignore log files +*.log + +# Ignore node_modules (if applicable) +node_modules/ + +# Ignore virtual environment directories (if applicable) +env/ +venv/ +*.docx +*.doc diff --git a/.kateproject.notes b/.kateproject.notes new file mode 100644 index 0000000..de71c9a --- /dev/null +++ b/.kateproject.notes @@ -0,0 +1,2 @@ +TODO: +Implement image extractor \ No newline at end of file diff --git a/.pyproject.toml b/.pyproject.toml new file mode 100644 index 0000000..0a045f5 --- /dev/null +++ b/.pyproject.toml @@ -0,0 +1,83 @@ +[build-system] +requires = ["setuptools>=61.0", "wheel"] +build-backend = "setuptools.build_meta" + +[project] +name = "filemac" +version = "2.0.0" # Will be overridden by version.txt in setup.py unless removed from there +description = "Open source Python CLI toolkit for conversion, manipulation, analysis of files (All major file operations)" +readme = "README.md" +requires-python = ">=3.6" +license = { file = "LICENSE" } +authors = [ + { name = "wambua", email = "swskye17@gmail.com" }, +] +keywords = [ + "file-conversion", + "file-analysis", + "file-manipulation", + "ocr", + "image-conversion", + "audio_effects", + "voice_shift", + "pdf", + "docx", +] +classifiers = [ + "Environment :: Console", + "Natural Language :: English", + "Operating System :: OS Independent", + "Programming Language :: Python", + "Programming Language :: Python :: 3 :: Only", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", +] + +dependencies = [ + "argparse", + "pdfminer.six", + "python-docx", + "python-pptx", + "gTTS", + "pypandoc", + "fitz", # Consider replacing with "PyMuPDF" if that's what's actually used + "pydub", + "Pillow", + "pandas", + "opencv-python", + "pytesseract", + "PyPDF2", + "pdf2docx", + "requests", + "moviepy", + "reportlab", + "numpy", + "pdf2image", + "openpyxl", + "rich", + "tqdm", + "ffmpeg-python", + "librosa", + "python-magic", + "matplotlib", + "soundfile", + "SpeechRecognition", + "colorama", + "scipy", + "PyMuPDF", + "pyautogui", + "imageio", + "pynput", + "pyaudio", +] + +[project.urls] +Homepage = "https://pypi.org/project/filemac/" +Source = "https://github.com/skye-cyber/filemac" +Issues = "https://github.com/skye-cyber/filemac/issues" + +[project.scripts] +filemac = "filemac:main" +Filemac = "filemac:main" +FILEMAC = "filemac:main" diff --git a/MANIFEST.in b/MANIFEST.in new file mode 100644 index 0000000..99fb32d --- /dev/null +++ b/MANIFEST.in @@ -0,0 +1,30 @@ +############################# +# MANIFEST.in for “filemac” # +############################# + +# ---------- Top‑level metadata ---------- +include README.md +include LICENSE* +include version.txt + +# ---------- Package‑wide data ---------- +# (Any files your code loads at runtime – templates, models, config files…) +# recursive-include filemac/data * +# recursive-include filemac/templates * +# recursive-include filemac/static * + +# ---------- Documentation (optional) ---------- +# Comment out if you don’t publish docs with the package +# recursive-include docs * + +# ---------- Type information (if you add stubs) ---------- +# include py.typed + +# ---------- Exclude common cruft ---------- +exclude *.py[cod] __pycache__ *.so *.dll *.dylib +prune build +prune dist +prune .git +prune .idea +prune .pytest_cache +prune .~ diff --git a/README.md b/README.md index b5014e0..23f396d 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,14 @@ -# fconverter +# filemac A python file `conversion`, `manipulation`, `Analysis` toolkit `This is a Linux command-line interface (CLI) utility that coverts documents from one format to another, analyzes files, manipulates files. -Your can also convert text file to mp3 formart using google Text to speech library (gTTS). +Your can also convert text file to mp3 format using google Text to speech library (gTTS).` +## Name variations +```shell + filemac -h + Filemac -h + FILEMAC -h + ``` ## Installation 1. using pip @@ -26,14 +32,28 @@ FileMAC [options] stdin format Replace `[options]` with the appropriate command-line options based on the functionality you want to execute. ## Available Options - -- `1`: --convert_doc. -- `2`: --convert_audio. -- `3`: --convert_video. -- `4`: --convert_image. -- `5`: --extract_audio. -- `6`: --Analyze_video -- `7`: --OCR +----------------------- +- `1`: --convert_doc | (doc* inter-conversion + tts) +- `2`: --convert_audio +- `3`: --convert_video +- `4`: --convert_image +- `5`: --extract_audio +- `6`: --Analyze_video +- `8`: --OCR +- `9`: --convert_doc2image +- `10`: --extract_audio +- `11`: --AudioJoin (join audio files to one master file) +- `12`: --resize_image +- `13`: --doc_long_image (convert pdf/doc/docx to long image) +- `14`: --image2pdf (convert image(s) to pdf) +- `15`: --image2word (convert image(s) to word document) +- `16`: --image2gray (convert image(s) to grayscale) +- `17`: --extract_pages (extract pages from pdf selectively) +- `18`: --scanAsImg (convert pdf to images then extract text, number of images=number of pages) +- `19`: --scanAsLong_Image (convert pdf to long image then extract text-good for continuous text extraction) +- `20`: --pdfjoin +- `21`: --audio_effect (manipulate audio/video voice) +- `22`: --voicetype (voice typing) - upcoming ## Examples @@ -42,77 +62,85 @@ Replace `[options]` with the appropriate command-line options based on the funct ```shell filemac --convert_doc example.docx -t pdf ``` - ``Supported formats For document conversion`` - `1`. PDF to DOCX - `2`. PDF to TXT - `3`. PDF to Audio - `4`. DOCX to PDF - `5`. DOCX to pptx - `6`. DOCX to TXT - `7`. DOCX to Audio - `8`. TXT to PDF - `9`. TXT to DOCX - `10`' TXT to Audio - `11`. PPTX to DOCX - `12`. XLSX to Sql - `13`. XLSX to CSV - `14`. XLSX to TXT - `15`. XLSX to DOCX - - This promt parses convert_doc signifying that the inteded operation id document conversion then parses ```example.docx``` as the input file(file path can also be provided) to be converted to format ```pdf```. + **Supported formats For document conversion** + `1`. PDF to (word, txt, audio\[tts\]) + `2`. PDF to TXT + `3`. PDF to Audio(ogg,mp3,wav..*) + `4`. DOCX to (PDF, pptx/ppt, txt, audio, + `5`. TXT to (PDF, word, audio) + `6`. PPTX to DOCX + `7`. XLSX to (Sql, CSV, TXT, word) + + + This promt parses convert_doc signifying that the inteded operation id document conversion then parses ```example.docx``` as the input file(file path can also be provided) to be converted to format ```pdf```. the output file assumes the base name of the input file but the extension conforms to the parsed format```pdf``` 2. converting text mp3 to wav ```shell filemac --convert_audio example.mp3 -t wav ``` - ``Supported formats For audio conversion`` - `1`. wav - `2`. mp3 - `3`. ogg - `4`. flv - `5`. avi - `6`. ogv - `7`. matroska - `8`. mov - `9`. webm + **Supported formats For audio conversion** + - (``wav, mp3, ogg, flv, ogv, avi, mkv, mov, webm``) + 3. Extract text from images ```shell filemac --OCR image.jpg ``` - 2. converting videos +4. converting videos ```shell filemac --convert_video example.mp4 -t wav ``` - ``Supported formats For video conversion`` - `1`. MP4 - `2`. AVI - `3`. OGV - `4`. WEBM - `5`. MOV - `6`. MKV - `7`. FLV - `8`. WMV - -2. converting images + **Supported formats For video conversion** + (``mp4, avi, ogv, webm, mov, mkv, flv, wmv``) + + +5. converting images ```shell filemac --convert_image example.png -t jpg ``` - ``Supported formats For audio conversion`` - `1`.JPEG: `.jpg` - `2`.PNG": `.png` - `3`.GIF": `.gif` - `4`.BM": `.bmp` - `5`.TIFF: `.tiff` - `6`.EXR `.exr` - `7`.PDF: `.pdf` - `8`.WebP: `.webp` - `9`.ICNS: `.icns` - `10`.PSD: `.psd` - `11`.SVG: `.svg` - `12`.EPS: `.eps` +#### Supported formats For audio conversion + `1`.JPEG: `.jpg` + `2`.PNG": `.png` + `3`.GIF": `.gif` + `4`.BM": `.bmp` + `5`.TIFF: `.tiff` + `6`.EXR `.exr` + `7`.PDF: `.pdf` + `8`.WebP: `.webp` + `9`.ICNS: `.icns` + `10`.PSD: `.psd` + `11`.SVG: `.svg` + `12`.EPS: `.eps` + + +### Manipulate audio +--- +#### Audio +```shell +filemac --audio_effect 'demo.mp3' --effect high +``` + +**Original**
+ [Listen to Original Audio](https://skye-cyber.github.io/FileMAC/res/demo.html) + +**Result**
+ [Listen to Modified Audio](https://skye-cyber.github.io/FileMAC/res/demo.html) + +--- + +#### Video +```shell +filemac --audio_effect 'demo.mp4' --effect high +``` +**Original**
+ [Listen to Original Video](https://skye-cyber.github.io/FileMAC/res/demo.html) + +**Result**
+ [Listen to Modified Video](https://skye-cyber.github.io/FileMAC/res/demo.html) + +--- ## Help in any case you can pass the string help to an option to see its supported operations or inputs nd output formats. @@ -125,8 +153,18 @@ The above command displays the surported input and output formats for document c Contributions are welcome! If you encounter any issues or have suggestions for improvements, please open an issue or submit a pull request. ## License - -This project is an open source software. Under GPL-3.0 license +This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . Feel free to modify and customize this template according to your specific project requirements and add any additional sections or information that you think would be helpful for users. diff --git a/audiobot/__init__.py b/audiobot/__init__.py new file mode 100644 index 0000000..3b1561f --- /dev/null +++ b/audiobot/__init__.py @@ -0,0 +1,50 @@ +""" + ///////] /// /// ///////] (O) //////] ///// //////] ///////// + // // /// /// // // /// /// /// // / /// /// /// + ///////// /// /// // / /// /// /// ///// /// /// /// + // // /// /// // / /// // // // / // // /// +// // ////////// /////// / /// /////// /////// /////// /// +Perform audio modifications such as adding voice effect to an audio or video file\n +Operation: +
    +
  • ->Reverb effect
  • +
  • ->Lowpass-reduce noise
  • +
  • ->Hackers voice
  • +
  • ->High voice effect
  • +
  • ->Chpmunk effect
  • +
  • ->Apply deep voice effect
  • +
  • ->Turn voice to whisper
  • +
  • ->distort voice
  • +
  • ->Apply demonic voice
  • +
  • ->Employ robotic voice
  • +
+""" + +from .cli import cli, ArgumentsProcessor +from .utils.logging_utils import LoggingFormatter, colored_logger +from .utils.visualizer import audiowave_visualizer +from .utils.metadata_utils import get_audio_bitrate +from .core.codec import AudioSegmentArrayCodec +from .core.effects import VoiceEffectProcessor +from .core.audio.core import AudioModulator, AudioDenoiser + +__version__ = "0.2.0" +__all__ = [ + "cli", + "ArgumentsProcessor", + "LoggingFormatter", + "colored_logger", + "audiowave_visualizer", + "get_audio_bitrate", + "AudioSegmentArrayCodec", + "VoiceEffectProcessor", + "AudioModulator", + "AudioDenoiser", +] +LOGO = """ + ///////] /// /// ///////] (O) //////] ///// //////] ///////// + // // /// /// // // /// /// /// // / /// /// /// + ///////// /// /// // / /// /// /// ///// /// /// /// + // // /// /// // / /// // // // / // // /// +// // ////////// /////// / /// /////// /////// /////// /// +""" diff --git a/audiobot/cli.py b/audiobot/cli.py new file mode 100644 index 0000000..4b50372 --- /dev/null +++ b/audiobot/cli.py @@ -0,0 +1,196 @@ +#!/usr/bin/python3 + + +""" +CLI Entry point for audiobot.\n +Implements:\n + Argsmain->cmd argument handler either from other packages or directly form cli +""" + +import argparse +import logging + +import os + +import magic +from .utils.metadata_utils import transcribe_audio +from filemac.utils.colors import fg, rs +from .core.processor import VideoProcessor, AudioProcessor +from .utils.logging_utils import colored_logger +from .config.core import Config + +RESET = rs + +Clogger = colored_logger() + + +class ArgumentsProcessor: + def __init__(self, args, parser): + self.args = args + self.parser = parser + self.mime = magic.Magic(mime=True) + self.output_dir = os.getcwd() if not self.args.output else self.args.output + + def process(self): + if not self.args or self.args.audio_effect: + self.parser.print_help() + return + + if self.args.verbose: + logging.getLogger().setLevel(logging.DEBUG) + + if self.args.output and not os.path.exists(self.args.output): + os.makedirs(self.args.output) + if self.args.batch: + self.batch_processor() + else: + self.mono_processor() + + def mono_processor(self): + try: + file_type = self.mime.from_file(self.args.file) + Clogger.info(f"{fg.BLUE}Detected file type: {file_type}{RESET}") + if file_type.startswith("audio"): + if self.args.transcribe: + transcribe_audio(self.args.file) + AudioProcessor().process_audio_file( + self.args.file, + self.args.effect, + self.output_dir, + self.args.verbose, + self.args.visualize, + ) + elif file_type.startswith("video"): + VideoProcessor().process_video_file( + self.args.file, + self.args.effect, + self.output_dir, + self.args.verbose, + self.args.visualize, + ) + else: + Clogger.warning( + f"Unsupported file type: {file_type}. Only audio and video files are supported." + ) + except Exception as e: + Clogger.error(e) + + def batch_processor(self): + try: + for root, _, files in os.walk(self.args.file): + for file in files: + full_path = os.path.join(root, file) + file_type = self.mime.from_file(full_path) + Clogger.info(f"{fg.BLUE}Detected file type: {file_type}{RESET}") + if file_type.startswith("audio"): + if self.args.transcribe: + transcribe_audio(full_path) + AudioProcessor().process_audio_file( + full_path, + self.args.effect, + self.output_dir, + self.args.verbose, + self.args.visualize, + ) + elif file_type.startswith("video"): + VideoProcessor().process_video_file( + full_path, + self.args.effect, + self.output_dir, + self.args.verbose, + self.args.visualize, + ) + else: + Clogger.warning(f"Ignoring unsupported file type: {file}") + except Exception as e: + Clogger.info(e) + + +def cli(argsv=None): + """ + Recieve and process agruments from audio/video audio effects + """ + parser = argparse.ArgumentParser( + description="Audiobot: A tool for audio effects on audio and video files.", + usage="filemac --audio_effect [-h] [--file FILE] \n\ + [-e {robotic,deep,high,echo,reverb,whisper,demonic,chipmunk,hacker,lowpass,distortion}] \n\ + [-o OUTPUT] [-v] [-b] [--visualize] [--transcribe] \n\ + [--audio_effect]", + ) + parser.add_argument( + "file", + help=f"{fg.CYAN}The input audio, video file, or directory.{RESET}", + ) + parser.add_argument( + "-e", + "--effect", + choices=[ + "robotic", + "deep", + "high", + "echo", + "reverb", + "whisper", + "demonic", + "chipmunk", + "hacker", + "lowpass", + "highpass", + "distortion", + "denoise", + ], + help=f"{fg.CYAN}The voice effect to apply.{RESET}", + ) + parser.add_argument( + "--cutoff", + type=int, + help=f"Cutoff frequency for denoise operation, defualt={fg.YELLOW}200{RESET}", + ) + parser.add_argument( + "-N", + "--noise", + choices=["low", "high", "both"], + type=str, + default="low", + help=f"Specifies the type of noise to remove choices:[{fg.BLUE}low, high, both{RESET}] defualt={fg.YELLOW}low{RESET}", + ) + parser.add_argument( + "-o", + "--output", + help=f"{fg.CYAN}Output directory for modified files.{RESET}", + ) + parser.add_argument( + "-v", + "--verbose", + action="store_true", + help=f"{fg.CYAN}Increase output verbosity.{RESET}", + ) + parser.add_argument( + "-b", + "--batch", + action="store_true", + help=f"{fg.CYAN}Batch process all files in a directory.{RESET}", + ) + parser.add_argument( + "--visualize", + action="store_true", + help=f"{fg.CYAN}Visualize the audio waveform before and after modification.{RESET}", + ) + parser.add_argument( + "--transcribe", + action="store_true", + help=f"{fg.CYAN}Transcribe the audio content before applying the effect.{RESET}", + ) + parser.add_argument("--audio_effect", action="store_true", help=argparse.SUPPRESS) + + args = parser.parse_args(argsv) if argsv else parser.parse_args() + if args.cutoff: + config = Config() + config.options["cutoff"] = args.cutoff + config.options["noise"] = args.noise + # Call argument processor + ArgumentsProcessor(args, parser).process() + + +if __name__ == "__main__": + cli() diff --git a/audiobot/config/__init__.py b/audiobot/config/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/audiobot/config/core.py b/audiobot/config/core.py new file mode 100644 index 0000000..5efa61d --- /dev/null +++ b/audiobot/config/core.py @@ -0,0 +1,8 @@ +class Config: + _instance = None + + def __new__(cls): + if cls._instance is None: + cls._instance = super(Config, cls).__new__(cls) + cls._instance.options = {} + return cls._instance diff --git a/audiobot/core/__init__.py b/audiobot/core/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/audiobot/core/audio/core.py b/audiobot/core/audio/core.py new file mode 100644 index 0000000..5274383 --- /dev/null +++ b/audiobot/core/audio/core.py @@ -0,0 +1,283 @@ +import numpy as np +from ...utils.logging_utils import colored_logger +import librosa +from pydub import AudioSegment, effects +from scipy.signal import butter, lfilter, sosfilt +from ...config.core import Config +from filemac.utils.colors import fg, rs + +RESET = rs + +Clogger = colored_logger() +config = Config() + + +class AudioModulator: + def __init__(self): + self._cutoff = config.options.get("cutoff") + + def pitch_shift(self, audio_segment, n_steps): + # Convert the audio samples to a NumPy array in float32 + samples = np.array(audio_segment.get_array_of_samples(), dtype=np.float32) + + # If the audio is stereo, convert it to mono + if audio_segment.channels == 2: + samples = audio_segment.set_channels(1) + + # Convert the samples back to NumPy array and flaoting point + samples = np.array(audio_segment.get_array_of_samples(), dtype=np.float32) + + # Pitch shift (no need to pass sample_rate separately) + shifted_samples = librosa.effects.pitch_shift( + samples, sr=audio_segment.frame_rate, n_steps=n_steps + ) + + # Convert the shifted samples back to int16 + shifted_audio = AudioSegment( + shifted_samples.astype(np.int16).tobytes(), + frame_rate=audio_segment.frame_rate, + sample_width=audio_segment.sample_width, + channels=audio_segment.channels, + ) + + return shifted_audio + + def hacker(self, audio_segment): + """Applies a deep, robotic voice effect used for anonymity.""" + + # Step 1: Pitch shift down (lower the pitch) + Clogger.info("Applying deep pitch shift for hacker voice") + deep_voice = self.pitch_shift(audio_segment, n_steps=-10) + + # Step 2: Speed up for robotic effect + Clogger.info("Speeding up for robotic effect") + robotic_voice = effects.speedup(deep_voice, playback_speed=1.1) + if robotic_voice is None: + Clogger.error("Speedup failed") + return None + + # Step 3: Apply reverb (check for validity) + Clogger.info("Adding subtle echo for distortion") + if isinstance(robotic_voice, AudioSegment): + # Shorter delay for subtle echo + delay = AudioSegment.silent(duration=500) + + Clogger.info("Overlaying echo effect") + + try: + echo_effect = robotic_voice.overlay(delay + robotic_voice - 5000) + except Exception as e: + Clogger.error(f"Error during overlay: {e}") + return None + else: + Clogger.error("Robotic voice generation failed") + return None + + # Step 4: Apply low-pass filter (optional) + hacker_voice_effect = ( + effects.low_pass_filter(echo_effect, cutoff=2500) if echo_effect else None + ) + if hacker_voice_effect is None: + Clogger.error("Low pass filter failed") + return None + + return hacker_voice_effect + + def echo(self, samples, delay=0.2, decay=0.5, sample_rate=44100): + """Apply echo effect with a specified delay and decay.""" + delay_samples = int(sample_rate * delay) + echo_signal = np.zeros(len(samples) + delay_samples) + + echo_signal[: len(samples)] = samples + echo_signal[delay_samples:] += decay * samples # Delayed echo signal + + return echo_signal[: len(samples)] # Truncate to original length + + def reverb(self, samples, decay=0.7, delay=0.05, sample_rate=44100): + try: + """Apply a reverb effect by adding delayed and attenuated copies of the signal.""" + delay_samples = int(sample_rate * delay) + + # Create a delayed version of the samples and attenuate (apply decay) + reverb_samples = np.zeros_like(samples) + + if samples.ndim == 2: # Stereo + for i in range(delay_samples, len(samples)): + reverb_samples[i, 0] = ( + samples[i, 0] + decay * samples[i - delay_samples, 0] + ) + reverb_samples[i, 1] = ( + samples[i, 1] + decay * samples[i - delay_samples, 1] + ) + else: # Mono + for i in range(delay_samples, len(samples)): + reverb_samples[i] = samples[i] + decay * samples[i - delay_samples] + + return reverb_samples + except Exception as e: + Clogger.error(e) + # raise + + def lowpass_filter(self, samples, cutoff=200, sample_rate=44100): + """ + Apply a low-pass filter to remove frequencies higher than the specified cutoff. + + This function uses a 6th-order Butterworth filter to attenuate frequencies above the + cutoff frequency, effectively smoothing the audio signal. + + Args: + samples (numpy.ndarray): The audio samples as a NumPy array. + cutoff (int, optional): The cutoff frequency in Hz. Defaults to 200. + Typical cutoff values: + - Voice: 1000-2000 Hz + - Music: 5000-8000 Hz + - Hiss/noise removal: 200-500 Hz + sample_rate (int, optional): The sample rate of the audio in Hz. Defaults to 44100. + + Returns: + numpy.ndarray: The filtered audio samples as a NumPy array. + """ + + cutoff = self._cutoff if self._cutoff else cutoff + Clogger.debug(f"{fg.BLUE}cutoff: {fg.CYAN}{cutoff}{RESET}") + Clogger.info("Apply a low-pass filter to remove frequencies higher than cutoff") + nyquist = 0.5 * sample_rate + normal_cutoff = cutoff / nyquist + b, a = butter(6, normal_cutoff, btype="low", analog=False) + filtered_samples = lfilter(b, a, samples) + + return filtered_samples + + def distort(self, samples, gain=10, threshold=0.3): + """Apply distortion by clipping the waveform.""" + Clogger.info("Apply distortion by clipping the waveform.") + samples = samples * gain + samples = np.clip(samples, -threshold, threshold) # Clip at threshold + return samples + + def whisper(self, audio_segment): + return effects.low_pass_filter(audio_segment, 70).apply_gain(-10) + + def highpass(self, audio_segment, cutoff: int = 200): + cutoff = self._cutoff if self._cutoff else cutoff + Clogger.info(f"Cutoff: {fg.BBLUE}{cutoff}{RESET}") + return effects.high_pass_filter(audio_segment, cutoff=cutoff) + + def lowpass(self, audio_segment, cutoff: int = 2200): + cutoff = self._cutoff if self._cutoff else cutoff + Clogger.info(f"Cutoff: {fg.BBLUE}{cutoff}{RESET}") + return effects.low_pass_filter(audio_segment, cutoff=cutoff) + + def normalize(self, audio_segment): + return effects.normalize(audio_segment) + + +class AudioDenoiser: + def __init__(self, sample_rate=44100): + self.sample_rate = sample_rate + # Dictionaries to cache filter coefficients by cutoff value + self._sos_low = {} + self._sos_high = {} + self._cutoff = config.options.get("cutoff") + Clogger.debug(f"{fg.BLUE}cutoff: {fg.CYAN}{self._cutoff}{RESET}") + + def lowpass_filter( + self, samples: np.ndarray, cutoff: int = 2200, order: int = 6 + ) -> np.ndarray: + """ + Apply a 6th-order low-pass Butterworth filter to remove frequencies above the cutoff. + + Args: + samples (np.ndarray): The input audio samples. + cutoff (int, optional): Cutoff frequency in Hz. Defaults to 2200. + order (int, optional): Order of the filter. Defaults to 6. + + Returns: + np.ndarray: The low-pass filtered audio samples. + """ + cutoff = self._cutoff if self._cutoff else cutoff + + if not isinstance(samples, np.ndarray): + raise ValueError("Input samples must be a NumPy array") + + nyquist = 0.5 * self.sample_rate + if cutoff >= nyquist: + Clogger.warn(f"Cutoff frequency must be less than Nyquist ({nyquist} Hz)") + cutoff = nyquist - (nyquist * 0.1) + + # Cache coefficients to avoid recomputation for the same cutoff value. + if cutoff not in self._sos_low: + self._sos_low[cutoff] = butter( + order, cutoff / nyquist, btype="low", analog=False, output="sos" + ) + + return sosfilt(self._sos_low[cutoff], samples) + + def highpass_filter( + self, samples: np.ndarray, cutoff: int = 200, order: int = 30 + ) -> np.ndarray: + """ + Apply a 6th-order high-pass Butterworth filter to remove frequencies below the cutoff. + + Args: + samples (np.ndarray): The input audio samples. + cutoff (int, optional): Cutoff frequency in Hz. Defaults to 200. + order (int, optional): Order of the filter. Defaults to 6. + + Returns: + np.ndarray: The high-pass filtered audio samples. + """ + + cutoff = self._cutoff if self._cutoff else cutoff + + if not isinstance(samples, np.ndarray): + raise ValueError("Input samples must be a NumPy array") + + nyquist = 0.5 * self.sample_rate + if cutoff <= 0: + raise ValueError("Cutoff frequency must be positive") + + if cutoff not in self._sos_high: + self._sos_high[cutoff] = butter( + order, cutoff / nyquist, btype="high", analog=False, output="sos" + ) + + return sosfilt(self._sos_high[cutoff], samples) + + def denoise( + self, + samples: np.ndarray, + lowpass_cutoff: int = 2200, + highpass_cutoff: int = 200, + order: int = 6, + ) -> np.ndarray: + """ + Denoise the audio by sequentially applying a low-pass filter and a high-pass filter. + This combination effectively acts as a band-pass filter, + removing both high-frequency noise (hiss) and low-frequency rumble. + + Args: + samples (np.ndarray): The input audio samples. + lowpass_cutoff (int, optional): Cutoff frequency for low-pass filtering. Defaults to 2200 Hz. + highpass_cutoff (int, optional): Cutoff frequency for high-pass filtering. Defaults to 200 Hz. + order (int, optional): Order of the filters. Defaults to 6. + + Returns: + np.ndarray: The denoised audio samples. + """ + noise = config.options.get("noise") if config.options.get("noise") else "low" + + Clogger.info( + f"{fg.BLUE}Noise: {fg.CYAN}{config.options.get('noise')}{RESET}" + ) + if noise == "low": + # Remove high-frequency noise + return self.lowpass_filter(samples, cutoff=lowpass_cutoff, order=order) + if noise == "high": + # Remove low-frequency noise + return self.highpass_filter(samples, cutoff=highpass_cutoff, order=order) + if noise == "both": + # Remove high-frequency noise + filtered = self.lowpass_filter(samples, cutoff=lowpass_cutoff, order=order) + # Remove low-frequency noise + return self.highpass_filter(filtered, cutoff=highpass_cutoff, order=order) diff --git a/audiobot/core/codec.py b/audiobot/core/codec.py new file mode 100644 index 0000000..e107d65 --- /dev/null +++ b/audiobot/core/codec.py @@ -0,0 +1,67 @@ +from pydub import AudioSegment +import numpy as np + + +class AudioSegmentArrayCodec: + """ + This class provides functionality to convert between pydub AudioSegments and NumPy arrays. + + It allows for the following conversions:\n + 1. AudioSegments to NumPy arrays. + 2. NumPy arrays to AudioSegments. + """ + + def __init__(self): + """ + Initializes the AudioSegmentArrayCodec object. + Currently, this constructor does not perform any specific operations. + """ + self = self # Note: This line has no effect and can be removed. + + def numpy_to_audiosegment(self, samples, sample_rate, sample_width, channels): + """ + Converts a NumPy array to a pydub AudioSegment. + + Args: + samples (numpy.ndarray): The NumPy array representing the audio samples. + sample_rate (int): The sample rate of the audio in Hz. + sample_width (int): The sample width in bytes (e.g., 2 for 16-bit audio). + channels (int): The number of audio channels (1 for mono, 2 for stereo). + + Returns: + pydub.AudioSegment: An AudioSegment object created from the NumPy array. + """ + # Flatten the array if it has 2 channels (stereo) + if len(samples.shape) == 2 and channels == 2: + samples = samples.flatten() + + # Convert the NumPy array to raw audio data + raw_data = samples.tobytes() + + # Create a new AudioSegment using the raw audio data + return AudioSegment( + data=raw_data, + sample_width=sample_width, + frame_rate=sample_rate, + channels=channels, + ) + + def audiosegment_to_numpy(self, audio_segment): + """ + Converts a pydub AudioSegment to a NumPy array. + + Args: + audio_segment (pydub.AudioSegment): The AudioSegment object to convert. + + Returns: + tuple: A tuple containing: + - numpy.ndarray: The NumPy array representing the audio samples. + - int: The sample rate of the audio in Hz. + """ + samples = np.array(audio_segment.get_array_of_samples()) + + # If stereo, reshape to (n_samples, 2) + if audio_segment.channels == 2: + samples = samples.reshape((-1, 2)) + + return samples, audio_segment.frame_rate diff --git a/audiobot/core/effects.py b/audiobot/core/effects.py new file mode 100644 index 0000000..36e14da --- /dev/null +++ b/audiobot/core/effects.py @@ -0,0 +1,115 @@ +from pydub import effects +from .codec import AudioSegmentArrayCodec +from .audio.core import AudioModulator +from ..utils.logging_utils import colored_logger +from pydub import AudioSegment + +# logger = colored_logger() + + +class VoiceEffectProcessor: + def __init__(self, audio_segment, effect: str, verbosity: bool = False): + self.effect = effect.lower() + self.audio_segment = audio_segment + self.verbosity = verbosity + self.handler = AudioSegmentArrayCodec() + self.logger = colored_logger() + + def _apply_chipmunk(self): + return AudioModulator().pitch_shift( + effects.speedup(self.audio_segment, 1.01), n_steps=9 + ) + + def _apply_high(self): + return AudioModulator().pitch_shift(self.audio_segment, n_steps=4) + + def _apply_lowpass(self): + return AudioModulator().lowpass(self.audio_segment) + + def _apply_highpass(self): + return AudioModulator().highpass(self.audio_segment) + + def _apply_robotic(self): + return AudioModulator().pitch_shift( + effects.speedup(self.audio_segment, 1.01), n_steps=-10 + ) + + def _apply_demonic(self): + return ( + AudioModulator() + .pitch_shift(effects.speedup(self.audio_segment, 1.01), n_steps=-10) + .overlay( + AudioSegment.silent(duration=700) + self.audio_segment.fade_out(500) + ) + ) + + def _apply_hacker(self): + return AudioModulator().hacker(self.audio_segment) + + def _apply_distortion(self): + samples, sample_rate = self.handler.audiosegment_to_numpy(self.audio_segment) + distorted_samples = AudioModulator().distort(samples) + return self.handler.numpy_to_audiosegment( + distorted_samples, + sample_rate, + self.audio_segment.sample_width, + self.audio_segment.channels, + ) + + def _apply_deep(self): + return AudioModulator().pitch_shift(self.audio_segment, n_steps=-4) + + def _apply_echo(self): + delay = AudioSegment.silent(duration=1000) + return self.audio_segment.overlay(delay + self.audio_segment) + + def _apply_whisper(self): + return AudioModulator().whisper(self.audio_segment) + + def _apply_reverb(self): + samples, sample_rate = self.handler.audiosegment_to_numpy(self.audio_segment) + reverbed_samples = AudioModulator().reverb(samples) + return self.handler.numpy_to_audiosegment( + reverbed_samples, + sample_rate, + self.audio_segment.sample_width, + self.audio_segment.channels, + ) + + def denoise(self): + from .modulator import AudioDenoiser + + sample, sample_rate = self.handler.audiosegment_to_numpy(self.audio_segment) + denoised_sample = AudioDenoiser().denoise(sample) + audio_segment = self.handler.numpy_to_audiosegment( + denoised_sample, + sample_rate, + self.audio_segment.sample_width, + self.audio_segment.channels, + ) + return audio_segment + + def _get_effects(self): + return { + "chipmunk": self._apply_chipmunk, + "high": self._apply_high, + "lowpass": self._apply_lowpass, + "robotic": self._apply_robotic, + "demonic": self._apply_demonic, + "hacker": self._apply_hacker, + "distortion": self._apply_distortion, + "deep": self._apply_deep, + "echo": self._apply_echo, + "whisper": self._apply_whisper, + "reverb": self._apply_reverb, + "denoise": self.denoise, + "highpass": self._apply_highpass, + } + + def apply_effect(self): + effect_handler = self._get_effects().get(self.effect) + if effect_handler: + return effect_handler() + elif self.verbosity: + self.logger.critical(f"Unknown voice effect: {self.effect}") + return self.audio_segment # Return unmodified audio if effect is unknown diff --git a/audiobot/core/processor.py b/audiobot/core/processor.py new file mode 100644 index 0000000..caf08c9 --- /dev/null +++ b/audiobot/core/processor.py @@ -0,0 +1,154 @@ +import os +from .audio.core import AudioModulator +from moviepy import AudioFileClip, VideoFileClip +from ..utils.logging_utils import colored_logger +from pydub import AudioSegment +from ..utils.visualizer import audiowave_visualizer +from ..utils.metadata_utils import get_audio_bitrate +from .effects import VoiceEffectProcessor +from filemac.utils.colors import fg, rs +import sys +# import io + +RESET = rs + +Clogger = colored_logger() + + +class VideoProcessor: + def __init__(self): + pass + + def process_video_file( + self, + input_file, + effect, + output_dir, + verbosity: bool = False, + visualize: bool = False, + ): + """ + Process video file by applying audio effects and retaining original bitrate. + """ + + Clogger.info(f"Set Voice effect : {fg.MAGENTA}{effect}{RESET}") + Clogger.info(f"Processing video file: {input_file}") + + try: + # Get the original video bitrate + original_bitrate = get_audio_bitrate(input_file, verbosity) + if verbosity and original_bitrate: + Clogger.info( + f"Original video bitrate: {fg.YELLOW}{original_bitrate}{RESET}" + ) + + # Capture stdout and stderr + old_stdout = sys.stdout + old_stderr = sys.stderr + # sys.stdout = captured_stdout = io.StringIO() + # sys.stderr = captured_stderr = io.StringIO() + + # Load the video + try: + video = VideoFileClip(input_file) + finally: + sys.stdout = old_stdout # Restore stdout + sys.stderr = old_stderr # Restore stder + audio_file = "temp_audio.wav" + + # Extract audio and save it to a file + if verbosity: + Clogger.info("Extract audio and write it to file") + video.audio.write_audiofile(audio_file) + audio_segment = AudioSegment.from_file(audio_file) + + # Apply the selected voice effect + Clogger.info( + f"Applying the [{fg.BBWHITE}{effect}{RESET}{fg.GREEN}] effect" + ) + modified_audio = VoiceEffectProcessor(audio_segment, effect).apply_effect() + + # Normalize the modified audio + modified_audio = AudioModulator().normalize(modified_audio) + + # Export the modified audio to a WAV file + if verbosity: + Clogger.info("Export the modified audio to a WAV file") + modified_audio.export("modified_audio.wav", format="wav") + + # Load the modified audio file back into an AudioFileClip + new_audio = AudioFileClip("modified_audio.wav") + + # Set the video to use the modified audio + if verbosity: + Clogger.info("Set the video audio to the new modified audio") + final_video = video.with_audio(new_audio) + + # Define the output file path + output_file = os.path.join( + output_dir, f"{effect}_{os.path.basename(input_file)}" + ) + + # Use the original bitrate or default to 5000k if unavailable + if verbosity: + Clogger.info( + f"Set:\n\tCodec = [{fg.fg.MAGENTA}libx264{fg.GREEN}\n" + f"\tCodec type = [{fg.fg.MAGENTA}aac{fg.GREEN}\n" + f"\tBitrate = [{fg.MAGENTA}{original_bitrate or '5000k'}{RESET}]" + ) + + final_video.write_videofile( + output_file, + codec="libx264", + audio_codec="aac", + bitrate=original_bitrate or "5000k", + ) + + Clogger.info(f"Modified video saved as: {output_file}") + Clogger.debug(f"Final bitrate = {get_audio_bitrate(output_file)}") + # Optional: visualize the before and after audio + if visualize: + audiowave_visualizer(audio_file, "modified_audio.wav") + + # Clean up temporary files + if os.path.exists(audio_file): + os.remove(audio_file) + os.remove("modified_audio.wav") + + except KeyboardInterrupt: + Clogger.info("Quit") + sys.exit(1) + except Exception as e: + Clogger.error(f"Error processing video file {input_file}: {e}") + # raise + + +class AudioProcessor: + def __init__(self): + pass + + def process_audio_file( + self, input_file, effect, output_dir, verbosity, visualize=False + ): + Clogger.info(f"Set Voice effect : {fg.MAGENTA}{effect}{RESET}") + + Clogger.info(f"Processing audio file: {fg.MAGENTA}{input_file}{RESET}") + + try: + audio_segment = AudioSegment.from_file(input_file) + if verbosity: + print(f"- INFO - Audio channels: {audio_segment.channels}") + print(f"- INFO - Audio sample width: {audio_segment.sample_width}") + modified_audio = VoiceEffectProcessor(audio_segment, effect).apply_effect() + modified_audio = AudioModulator().normalize(modified_audio) + output_file = os.path.join( + output_dir, f"{effect}_{os.path.basename(input_file)}" + ) + modified_audio.export(output_file, format="wav") + Clogger.info(f"Modified audio saved as: {output_file}") + + if visualize: + audiowave_visualizer(input_file, output_file) + + except Exception as e: + Clogger.error(f"Error processing audio file {input_file}: {e}") diff --git a/audiobot/utils/logging_utils.py b/audiobot/utils/logging_utils.py new file mode 100644 index 0000000..0500ccf --- /dev/null +++ b/audiobot/utils/logging_utils.py @@ -0,0 +1,40 @@ +import logging +from filemac.utils.colors import fg, rs + +RESET = rs + + +class LoggingFormatter(logging.Formatter): + COLORS = { + logging.DEBUG: fg.BBLUE, + logging.INFO: fg.GREEN, + logging.WARNING: fg.YELLOW, + logging.ERROR: fg.RED, + logging.CRITICAL: fg.MAGENTA, + } + + def format(self, record): + log_color = self.COLORS.get(record.levelno, fg.WHITE) + log_message = super().format(record) + return f"{log_color}{log_message}{RESET}" + + +def colored_logger(logger_name="colored_logger") -> logging.Logger: + """ + Sets up a colored logger with a single handler. + + Returns: + logging.Logger: The configured logger. + """ + logger = logging.getLogger(logger_name) + + if not logger.handlers: # Check if handlers already exist + handler = logging.StreamHandler() + handler.setFormatter(LoggingFormatter("- %(levelname)s - %(message)s")) + logger.addHandler(handler) + logger.setLevel(logging.INFO) + + # Prevent log messages from propagating to the root logger. + logger.propagate = False + + return logger diff --git a/audiobot/utils/metadata_utils.py b/audiobot/utils/metadata_utils.py new file mode 100644 index 0000000..cceec73 --- /dev/null +++ b/audiobot/utils/metadata_utils.py @@ -0,0 +1,57 @@ +import speech_recognition as sr +import ffmpeg +from .logging_utils import colored_logger +from filemac.utils.colors import fg, rs + +RESET = rs + +Clogger = colored_logger() + + +def get_audio_bitrate(input_file, verbosity=False): + """ + Probes a media file using ffmpeg and returns its metadata. + + Args: + input_file (str): The path to the media file. + + Returns: + int: bitrate + + Raises: + ffmpeg.Error: If ffmpeg returns a non-zero exit code. + FileNotFoundError: If the input file does not exist. + Exception: For other errors during probing. + """ + if verbosity: + Clogger.info( + f"Fetch the original bitrate of the video file using {fg.YELLOW}ffmpeg{RESET}." + ) + try: + try: + metadata = ffmpeg.probe(input_file) + finally: + bitrate = None + # Iterate over the streams and find the video stream + for stream in metadata["streams"]: + if stream["codec_type"] == "video": + bitrate = stream.get("bit_rate", None) + break + return bitrate + except ffmpeg.Error or Exception as e: + Clogger.error(f"Error fetching bitrate for {input_file}: {e}") + return None + + +def transcribe_audio(input_file): + Clogger.info(f"Transcribing audio: {input_file}") + try: + recognizer = sr.Recognizer() + with sr.AudioFile(input_file) as source: + audio = recognizer.record(source) + transcription = recognizer.recognize_google(audio) + Clogger.info(f"Transcription: {transcription}") + return transcription + except Exception as e: + Clogger.error(f"Error transcribing audio file {input_file}: {e}") + return None diff --git a/audiobot/utils/visualizer.py b/audiobot/utils/visualizer.py new file mode 100644 index 0000000..d4a5baa --- /dev/null +++ b/audiobot/utils/visualizer.py @@ -0,0 +1,25 @@ +import matplotlib.pyplot as plt +import soundfile as sf +from .logging_utils import colored_logger + + +Clogger = colored_logger() + + +def audiowave_visualizer(original_file, modified_file): + Clogger.info(f"Visualizing audio: {original_file} and {modified_file}") + try: + original_data, original_sr = sf.read(original_file) + modified_data, modified_sr = sf.read(modified_file) + + plt.figure(figsize=(14, 5)) + plt.subplot(2, 1, 1) + plt.plot(original_data) + plt.title("Original Audio Waveform") + plt.subplot(2, 1, 2) + plt.plot(modified_data) + plt.title("Modified Audio Waveform") + plt.show() + + except Exception as e: + Clogger.error(f"Error visualizing audio: {e}") diff --git a/audiobot/version.txt b/audiobot/version.txt new file mode 100644 index 0000000..0ea3a94 --- /dev/null +++ b/audiobot/version.txt @@ -0,0 +1 @@ +0.2.0 diff --git a/filemac/__init__.py b/filemac/__init__.py index e32c40a..5a24a59 100644 --- a/filemac/__init__.py +++ b/filemac/__init__.py @@ -1 +1,76 @@ -from .fmac import main +""" +....//////// /// /// ///////// /////// ////// ////// //////// + // /// /// // // // // // // // /// + ///////// /// /// //////// // /// // //----// // + // /// //////// //_____ // // // // ////////// + +Converter document file(s) to different format ie pdf_to_docx. + example filemac --convert_doc example.docx -t pdf + +Convert audio file(s) to and from different format ie mp3 to wav + example filemac --convert_audio example.mp3 -t wav + +Convert video file(s) to and from different format ie mp4 to mkv. + example filemac --convert_video example.mp4 -t mkv + +Convert image file(s) to and from different format ie png to jpg. + example filemac --convert_image example.jpg -t png + +Extract audio from a video. example filemac -xA example.mp4 + +Analyze a given video. + example filemac --analyze_video example.mp4 + +hange size of an image compress/decompress + example filemac --resize_image example.png -t_size 2mb -t png + +Scan pdf file and extract text + example filemac --scan example.pdf + +Convert pdf file to long image + example filemac --doc_long_image example.pdf + +Scan [doc, docx, pdf] + file and extract text,-> very effective + example filemac --scanAsImg example.pdf + +Extract text from an image. + example filemac --OCR image.png +""" + +from audiobot.cli import cli as audiobot + +from .core.image.core import ( + GrayscaleConverter, + ImageCompressor, + ImageConverter, + ImageDocxConverter, + ImagePdfConverter, +) +from .core.pdf.core import PageExtractor, PDF2LongImageConverter, PDFCombine +from .core.recorder import SoundRecorder +from .core.video.core import VideoConverter +from .cli.main import CliInit as main, OperationMapper +from .cli.converter import DocConverter +from voice.VoiceType import VoiceTypeEngine + + +__version__ = "2.1.0" + +__all__ = [ + "audiobot", + "GrayscaleConverter", + "ImageConverter", + "ImageCompressor", + "PDF2LongImageConverter", + "ImagePdfConverter", + "ImageDocxConverter", + "PDFCombine", + "PageExtractor", + "VideoConverter", + "SoundRecorder", + "DocConverter", + "OperationMapper", + "VoiceTypeEngine", + "main", +] diff --git a/filemac/cli/__init__.py b/filemac/cli/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/filemac/cli/converter.py b/filemac/cli/converter.py new file mode 100644 index 0000000..b28e6e3 --- /dev/null +++ b/filemac/cli/converter.py @@ -0,0 +1,206 @@ +import os +import sys +from typing import List, Union +from ..core.warning import default_supressor +from ..utils.simple import logger +from ..utils.colors import fg, rs +from ..core.tts.gtts import GoogleTTS +from ..utils.formats import ( + SUPPORTED_AUDIO_FORMATS_DIRECT, +) +from ..core.document import DocConverter + +RESET = rs +default_supressor() + + +class DirectoryConverter: + """ + If the input file in convert_doc argument is a directory, walk throught the directory and + converter all the surported files to the target format + """ + + def __init__(self, _dir_, _format_, no_resume, threads, _isolate_=None): + self._dir_ = _dir_ + self._format_ = _format_ + self._isolate_ = _isolate_ + self.no_resume = no_resume + self.threads = threads + # Handle isolation and non isolation modes distinctively + self._ls_ = ( + ["pdf", "docx", "doc", "xlsx", "ppt", "pptxxls", "txt"] + if _isolate_ is None + else [_isolate_] + ) + if self._isolate_: + print(f"INFO\t {fg.FMAGENTA}Isolate {fg.DCYAN}{self._isolate_}{RESET}") + + def _unbundle_dir_(self): + if self._format_ in SUPPORTED_AUDIO_FORMATS_DIRECT: + return Batch_Audiofy(self._dir_, self.no_resume, self.threads) + try: + for root, dirs, files in os.walk(self._dir_): + for file in files: + _ext_ = file.split(".")[-1] + + _path_ = os.path.join(root, file) + + if _ext_ in self._ls_ and os.path.exists(_path_): + print(f"INFO\t {fg.FYELLOW}Parse {fg.BLUE}{_path_}{RESET}") + init = MethodMappingEngine(_path_, self._format_) + init.document_eval() + + except FileNotFoundError as e: + print(e) + + except KeyboardInterrupt: + print("\nQuit!") + sys.exit(1) + + except Exception as e: + print(e) + pass + + +class Batch_Audiofy: + def __init__( + self, + obj: Union[ + os.PathLike, + str, + List[Union[os.PathLike, str]], + tuple[str], + ], + no_resume: bool, + threads: int = 3, + ): + self.folder = obj + self.no_resume = no_resume + self.threads = threads + self.worker() + + def worker(self): + conv = GoogleTTS(self.folder, resume=self.no_resume) + inst = conv.THAudio(conv) + inst.audiofy(num_threads=self.threads) + + +class MethodMappingEngine: + """ + Class to handle document conversions based on their extensions and the target + output document format + """ + + def __init__(self, file, outf): + self.file = file + self.outf = outf + + def spreedsheet(self, conv): + if self.outf.lower() == "csv": + conv.convert_xlsx_to_csv() + elif self.outf.lower() in ("txt", "text"): + conv.convert_xls_to_text() + elif self.outf.lower() in list(self.doc_ls): + conv.convert_xls_to_word() + elif self.outf.lower() == "db": + conv.convert_xlsx_to_database() + else: + print(f"{fg.RED}Unsupported output format❌{RESET}") + + def word(self, conv): + if self.outf.lower() in ("txt", "text"): + conv.word_to_txt() + elif self.outf.lower() == "pdf": + conv.word_to_pdf() + elif self.outf.lower() in ("pptx", "ppt"): + conv.word_to_pptx() + elif self.outf.lower() in ("audio", "ogg"): + conv = GoogleTTS(self.file) + conv.audiofy() + else: + print(f"{fg.RED}Unsupported output format❌{RESET}") + + def text(self, conv): + if self.outf.lower() == "pdf": + conv.txt_to_pdf() + elif self.outf.lower() in ("doc", "docx", "word"): + conv.text_to_word() + elif self.outf.lower() in ("audio", "ogg"): + conv = GoogleTTS(self.file) + conv.audiofy() + else: + print(f"{fg.RED}Unsupported output format❌{RESET}") + + def ppt(self, conv): + if self.outf.lower() in ("doc", "docx", "word"): + conv.ppt_to_word() + elif self.outf.lower() in ("text", "txt"): + word = conv.ppt_to_word() + conv = DocConverter(word) + conv.word_to_txt() + elif self.outf.lower() in ("pptx"): + conv.convert_ppt_to_pptx(self.file) + elif self.outf.lower() in ("audio", "ogg", "mp3", "wav"): + conv = GoogleTTS(self.file) + conv.audiofy() + else: + print(f"{fg.RED}Unsupported output format❌{RESET}") + + def pdf(self, conv): + if self.outf.lower() in ("doc", "docx", "word"): + conv.pdf_to_word() + elif self.outf.lower() in ("txt", "text"): + conv.pdf_to_txt() + elif self.outf.lower() in ("audio", "ogg", "mp3", "wav"): + conv = GoogleTTS(self.file) + conv.audiofy() + else: + print(f"{fg.RED}Unsupported output format❌{RESET}") + + def document_eval(self): + self.doc_ls = ["docx", "doc"] + sheetls = ["xlsx", "xls"] + try: + conv = DocConverter(self.file) + if self.file.lower().endswith(tuple(sheetls)): + self.spreedsheet(conv=conv) + + elif self.file.lower().endswith(tuple(self.doc_ls)): + self.word(conv=conv) + + elif self.file.endswith("txt"): + self.text(conv=conv) + + elif self.file.split(".")[-1].lower() in ("ppt", "pptx"): + self.ppt(conv) + + elif self.file.lower().endswith("pdf"): + self.pdf(conv) + + elif self.file.lower().endswith("csv"): + if self.outf.lower() in ("xls", "xlsx", "excel"): + conv.convert_csv_to_xlsx() + + else: + print(f"{fg.fg.BYELLOW}Unsupported Conversion type❌{RESET}") + pass + except Exception as e: + logger.error(e) + + +def _isolate_file(_dir_, target): + try: + isolated_files = [] + for root, dirs, files in os.walk(_dir_): + for file in files: + if file.lower().endswith(target): + _path_ = os.path.join(root, file) + isolated_files.append(_path_) + return isolated_files + except FileNotFoundError as e: + print(e) + except KeyboardInterrupt: + print("\nQuit!") + sys.exit(1) + except Exception as e: + print(e) diff --git a/filemac/cli/main.py b/filemac/cli/main.py new file mode 100644 index 0000000..be5c772 --- /dev/null +++ b/filemac/cli/main.py @@ -0,0 +1,718 @@ +#!/usr/bin/env python3 +import argparse +import os +import sys +from functools import lru_cache +from ..core.document import DocConverter +from ..core.pdf.core import PageExtractor +from ..core.exceptions import FileSystemError, FilemacError +from pathlib import Path +from ..utils.colors import fg, bg, rs + +from ..utils.simple import logger + +try: + from audiobot.cli import cli as audiobot_cli +except ImportError: + pass + +_entry_ = PageExtractor._entry_ + +RESET = rs + + +def CliInit(): + """Define main functions to create commandline arguments for different operations""" + parser = argparse.ArgumentParser( + description="Filemac: A file management tool with audio effects. Supporting wide range of Multimedia Operations", + add_help=False, + epilog=f"{fg.BLUE}When using {fg.MAGENTA}-SALI{fg.BLUE} long images have maximum height that can be processed{RESET}", + ) + + parser.add_argument( + "--convert_doc", + nargs="+", + help=f"Converter document file(s) to different format ie pdf_to_docx.\ + example: {fg.BYELLOW}filemac --convert_doc example.docx -tff pdf{RESET}", + ) + + parser.add_argument( + "--convert_audio", + help=f"Convert audio file(s) to and from different format ie mp3 to wav\ + example: {fg.BYELLOW}filemac --convert_audio example.mp3 -tff wav{RESET}", + ) + + parser.add_argument( + "--convert_video", + help=f"Convert video file(s) to and from different format ie mp4 to mkv.\ + example: {fg.BYELLOW}filemac --convert_video example.mp4 -tf mkv{RESET}", + ) + + parser.add_argument( + "--convert_image", + help=f"Convert image file(s) to and from different format ie png to jpg.\ + example: {fg.BYELLOW}filemac --convert_image example.jpg -tf png{RESET}", + ) + + parser.add_argument( + "--convert_svg", + help=f"Converter svg file(s) to different format ie pdf, png.\ + example: {fg.BYELLOW}filemac --convert_svg example.svg -tff pdf{RESET}", + ) + + parser.add_argument( + "--convert_doc2image", + help=f"Convert documents to images ie png to jpg.\ + example: {fg.BYELLOW}filemac --convert_doc2image example.pdf -tf png{RESET}", + ) + + parser.add_argument( + "--html2word", + help=f"Convert image file(s) to and from different format ie png to jpg.\ + example: {fg.BYELLOW}filemac --html2word index.html{RESET}", + ) + + parser.add_argument( + "-md", + "--markdown2docx", + help=f"Convert Markdown to DOCX with Mermaid rendering.\ + example: {fg.BYELLOW}filemac --markdown2docx example.md{RESET}", + ) + parser.add_argument( + "-xA", + "--extract_audio", + help=f"Extract audio from a video.\ + example: {fg.BYELLOW}filemac -xA example.mp4 {RESET}", + ) + + parser.add_argument( + "-iso", + "--isolate", + help=f"Specify file types to isolate\ + for conversion, only works if directory is provided as input for the {fg.FCYAN}convert_doc{RESET} argument example: {fg.BYELLOW}filemac --convert_doc /home/user/Documents/ --isolate pdf -tf txt{RESET}", + ) + + parser.add_argument( + "-Av", + "--Analyze_video", + help=f"Analyze a given video.\ + example: {fg.BYELLOW}filemac --analyze_video example.mp4 {RESET}", + ) + + parser.add_argument( + "-tf", "--target_format", help="Target format for conversion (optional)" + ) + + parser.add_argument( + "--resize_image", + help=f"change size of an image compress/decompress \ + example: {fg.BYELLOW}filemac --resize_image example.png -tf_size 2mb -tf png {RESET}", + ) + + parser.add_argument( + "-t_size", + help="used in combination with resize_image \ + to specify target image size", + ) + + parser.add_argument( + "-S", + "--scan", + help=f"Scan pdf file and extract text\ + example: {fg.BYELLOW}filemac --scan example.pdf {RESET}", + ) + + parser.add_argument( + "-doc2L", + "--doc_long_image", + help=f"Convert pdf file to long image\ + example: {fg.BYELLOW}filemac --doc_long_image example.pdf {RESET}", + ) + + parser.add_argument( + "-SA", + "--scanAsImg", + help=f"Convert pdf to image then extract text\ + example: {fg.BYELLOW}filemac --scanAsImg example.pdf {RESET}", + ) + + parser.add_argument( + "-SALI", + "--scanAsLong_Image", + help=f"Scan {fg.CYAN}[doc, docx, pdf]\ + {RESET} file and extract text by first converting them to long image,-> very effective\ + example: {fg.BYELLOW}filemac --scanAsImg example.pdf {RESET}", + ) + + parser.add_argument( + "--OCR", + nargs="+", + help=f"Extract text from an image.\ + example: {fg.BYELLOW}filemac --OCR image.png{RESET}", + ) + + """Audio join arguements""" + # Accept 0 or more arguements + parser.add_argument( + "--AudioJoin", + "-AJ", + nargs="*", + help=f"{fg.YELLOW}Join Audio files{RESET} into one master file.\ + Provide a {fg.BLUE}list{RESET} of audio file paths. If no paths are provided, the program will still run.", + metavar="audio_file_path", + ) + + """'arguements for Advanced text to word conversion""" + parser.add_argument( + "-RT2W", + "--Richtext2word", + help=f"Advanced Text to word conversion i.e:{ + fg.BYELLOW + }filemac --Atext2word example.txt --font_size 12 --font_name Arial{RESET}", + ) + + # Add arguments that must accompany the "obj" command + parser.add_argument( + "--font_size", + type=int, + default=12, + help=f"Font size to be used default: {fg.CYAN}12{RESET}", + ) + parser.add_argument( + "--font_name", + type=str, + default="Times New Roman", + help=f"Font name default: {fg.FCYAN}Times New Roman{RESET}", + ) + + """Alternative sequence args, critical redundancy measure""" + parser.add_argument( + "-X", + "--use_extras", + action="store_true", + help=f"Use alternative conversion method: Overides\ + default method i.e: {fg.BYELLOW}filemac --convert_doc example.docx --use_extras -tf pdf{RESET}", + ) + + """Pdf join arguements--> Accepts atleast 1 arguement""" + parser.add_argument("--pdfjoin", "-pj", nargs="+", help="Join Pdf file to one file") + parser.add_argument( + "--order", + type=str, + default="AAB", + help=f"Order of pages when joining the pdf use: {fg.BYELLOW}filemac\ + -pj help for more details{RESET}", + ) + parser.add_argument( + "--extract_pages", + "-p", + nargs="+", + help=f"Extract given pages from pdf: { + fg.BYELLOW + }filemac --extract_pages file.pdf 6 10{RESET} for one page: { + fg.BYELLOW + }filemac --extract_pages file.pdf 5{RESET}", + ) + + parser.add_argument( + "--audio_effect", + "-af", + action="store_true", + help=f"Change audio voice/apply effects/reduce noise {fg.BYELLOW}-MA --help for options{RESET}", + ) + parser.add_argument( + "--audio_help", action="store_true", help="Show help for audiobot" + ) + parser.add_argument( + "--no-resume", + action="store_false", + dest="no_resume", + help=f"Don't Resume previous File operation {fg.BYELLOW}filemac --convert_doc simpledir --no-resume{RESET}", + ) + + parser.add_argument( + "--t", + "-threads", + type=int, + default=3, + help=f"Number of threads for text to speech {fg.BYELLOW}filemac --convert_doc simpledir --no-resume -t 2{RESET}", + ) + parser.add_argument( + "-sep", + "--separator", + choices=["\\n", "\\t", " ", "", "newline", "space", "none", "tab"], + default="\n", + help="Separator to be used in OCR eg.('\\n', ' ', '')", + ) + + parser.add_argument( + "--image2pdf", + nargs="+", + help=f"Convert Images to pdf. {fg.BWHITE}Accepts image list or dir/folder{RESET} e.g `{fg.BYELLOW}filemac --image2pdf image1 image2{RESET}`", + ) + parser.add_argument( + "--image2word", + nargs="+", + help=f"Convert Images to word document. {fg.BWHITE}Accepts image list or dir/folder{RESET} e.g `{fg.BYELLOW}filemac --image2word image1 image2{RESET}`", + ) + parser.add_argument( + "--image2gray", + nargs="+", + help=f"Convert Images to grayscale. {fg.BWHITE}Accepts image list or dir/folder{RESET} e.g `{fg.BYELLOW}filemac --image2gray image1 image2{RESET}`", + ) + parser.add_argument( + "-vt", + "--voicetype", + action="store_true", + help=f"Use your voice to type text. e.g `{fg.BYELLOW}filemac --voicetype{RESET}`", + ) + + parser.add_argument( + "-ex", + "--extract_img", + nargs="+", + help=f"Extract images from pdf. e.g `{fg.BYELLOW}filemac --extract_img input.pdf{RESET}`", + ) + + parser.add_argument( + "-V", + "--version", + action="store_true", + help="Show software version and exit.", + ) + + parser.add_argument( + "--sort", + action="store_true", + help="Order pages by last int before extension.", + ) + parser.add_argument( + "--base", + action="store_true", + help="Base name for image2pdf output", + ) + parser.add_argument( + "--size", + type=str, + help=f"Dimensions for images to be saved by extractor eg {fg.BBLUE}256x82{fg.RESET}", + ) + parser.add_argument( + "--walk", + action="store_true", + help="Do an operation on a dirctory and it's subdirectories.", + ) + parser.add_argument( + "--clean", + action="store_true", + help=f"Clean file/dir after an operation eg after {fg.BMAGENTA}image2pdf clean image dirs{fg.RESET}.", + ) + parser.add_argument("--record", action="store_true", help="Record Audio from mic") + + parser.add_argument( + "-h", "--help", action="store_true", help="Show this help message and exit." + ) + + # Use parse_known_args to allow unknown arguments (for later tunneling) + args, remaining_args = parser.parse_known_args() + mapper = OperationMapper(parser, args, remaining_args) + mapper.run() + + +class OperationMapper: + def __init__(self, parser, args, remaining_args) -> None: + self.parser = parser + self.args = args + self.remaining_args = remaining_args + + def ensure_target_format(self): + print(f"{bg.YELLOW}[Warning]{fg.YELLOW}Please provide target format{RESET}") + return + + def pdfjoin(self): + from ..core.pdf.core import PDFCombine + + if self.args.pdfjoin[0].lower().strip() == "help": + from ..utils.helpmaster import pdf_combine_help + + opts, helper, example = pdf_combine_help() + print(f"{opts}\n {helper}\n {example}") + sys.exit(0) + init = PDFCombine(self.args.pdfjoin, None, None, self.args.order) + init.controller() + + def image_converter(self): + if self.args.convert_image == "help": + from ..utils.formats import SUPPORTED_IMAGE_FORMATS_SHOW + + print(SUPPORTED_IMAGE_FORMATS_SHOW) + return + if self.args.target_format is None: + self.ensure_target_format() + return + if self.args.target_format is None: + print( + f"{fg.RED}Please provide output format specified by{fg.CYAN} '-tf'{RESET}" + ) + return + from ..core.image.core import ImageConverter + + conv = ImageConverter(self.args.convert_image, self.args.target_format) + conv.convert_image() + + def doc_converter(self): + from ..utils.formats import SUPPORTED_AUDIO_FORMATS_DIRECT + from .converter import MethodMappingEngine, DirectoryConverter, Batch_Audiofy + + if self.args.target_format is None: + self.ensure_target_format() + return + if self.args.use_extras: + DocConverter.word2pdf_extra(self.args.convert_doc) + if ( + len(self.args.convert_doc) <= 1 + and not os.path.isdir(self.args.convert_doc[0]) + and isinstance(self.args.convert_doc, list) + and self.args.target_format in SUPPORTED_AUDIO_FORMATS_DIRECT + ): + Batch_Audiofy(self.args.convert_doc, self.args.no_resume, self.args.threads) + elif os.path.isdir(self.args.convert_doc[0]): + conv = DirectoryConverter( + self.args.convert_doc[0], + self.args.target_format, + self.args.no_resume, + self.args.threads, + self.args.isolate, + ) + conv._unbundle_dir_() + elif os.path.isfile(self.args.convert_doc[0]): + ev = MethodMappingEngine(self.args.convert_doc[0], self.args.target_format) + ev.document_eval() + + def handle_help(self): + if not self.args and not self.remaining_args: + self.parser.print_help() + return + + def handle_audio_help(self): + if self.args.audio_help: + audiobot_cli(["--help"]) + return + + def handle_audio_effect(self): + audiobot_cli(self.remaining_args) + return + + def handle_doc_conversion_help(self): + if self.args.convert_doc and self.args.convert_doc[0] == "help": + from ..utils.formats import SUPPORTED_DOC_FORMATS + + print(SUPPORTED_DOC_FORMATS) + return + + def handle_video_conversion_help(self): + if self.args.convert_video and self.args.convert_video == "help": + from ..utils.formats import SUPPORTED_VIDEO_FORMATS_SHOW + + print(SUPPORTED_VIDEO_FORMATS_SHOW) + return + + def handle_video_conversion(self): + if hasattr(self, "agrs") and self.agrs.target_format is None: + self.ensure_target_format() + return + from ..core.video.core import VideoConverter + + ev = VideoConverter(self.args.convert_video, self.args.target_format) + ev.CONVERT_VIDEO() + + def handle_svg(self): + from ..core.svg.core import SVGConverter + + converter = SVGConverter() + _map_ = { + "png": converter.to_png, + "pdf": converter.to_pdf, + "svg": converter.to_svg, + } + target = _map_.get(self.args.target_format, None) + if not target: + raise FilemacError("Target format not valid for svg input.") + from ..utils.file_utils import generate_filename + + output = generate_filename( + ext=self.args.target_format, basedir=Path(self.args.convert_svg) + ) + target( + input_svg=self.args.convert_svg, + output_path=output.as_posix(), + is_string=False, + ) + print(f"Saved To:{output}") + + def handle_image_resize(self): + from ..core.image.core import ImageCompressor + + res = ImageCompressor(self.args.resize_image) + res.resize_image(self.args.t_size) + + def handle_doc_to_image_conversion(self): + conv = DocConverter(self.args.convert_doc2image) + conv.doc2image(self.args.target_format) + + def handle_audio_conversion_help(self): + if self.args.convert_audio == "help": + from ..utils.formats import SUPPORTED_AUDIO_FORMATS_SHOW + + print(SUPPORTED_AUDIO_FORMATS_SHOW) + return + + def handle_audio_conversion(self): + if self.agrs.target_format is None: + self.ensure_target_format() + return + from ..core.audio.core import AudioConverter + + ev = AudioConverter(self.args.convert_audio, self.args.target_format) + ev.pydub_conv() + + def handle_audio_extraction(self): + from ..core.audio.core import AudioExtracter + + vi = AudioExtracter(self.args.extract_audio) + vi.moviepyextract() + + def handle_scan_pdf(self): + sc = PageExtractor(self.args.scan) + sc.scanPDF() + + def handle_scan_images(self): + sc = PageExtractor(self.args.scanAsImg, self.args.no_strip) + sc.scanAsImgs() + + def handle_scan_long_image(self): + sc = PageExtractor(self.args.scanAsLong_Image, self.args.separator) + sc.scanAsLongImg() + + def handle_doc_to_long_image(self): + from ..core.pdf.core import PDF2LongImageConverter + + conv = PDF2LongImageConverter(self.args.doc_long_image) + conv.preprocess() + + def handle_ocr(self): + from ..core.ocr import ExtractText + + ocr = ExtractText(self.args.OCR, self.args.separator) + ocr.run() + + def handle_video_analysis(self): + from ..miscellaneous.video_analyzer import SimpleAnalyzer + + analyzer = SimpleAnalyzer(self.args.Analyze_video) + analyzer.SimpleAnalyzer() + + def handle_audio_join(self): + from ..core.audio.core import AudioJoiner + + joiner = AudioJoiner(self.args.AudioJoin) + joiner.worker() + + def handle_advanced_text_to_word(self): + from ..core.text.core import StyledText + + init = StyledText( + self.args.Richtext2word, None, self.args.font_size, self.args.font_name + ) + init.text_to_word() + + def handle_extract_pages(self): + _entry_(self.args.extract_pages) + + def ImageExtractor(self): + from ..core.image.extractor import process_files + + if self.args.size: + size = tuple([int(x) for x in self.args.size.lower().split("x")]) + process_files(self.args.image_extractor, tsize=size) + else: + process_files(self.args.image_extractor) + + def image2pdf(self): + from ..core.image.core import ImagePdfConverter + + _input = ( + list(self.args.image2pdf) + if not isinstance(self.args.image2pdf, list) + else self.args.image2pdf + ) + if isinstance(_input, list): + if len(_input) > 1 or os.path.isfile(os.path.abspath(_input[0])): + converter = ImagePdfConverter(image_list=_input) + else: + converter = ImagePdfConverter( + input_dir=_input[0], + order=self.args.sort, + base=self.args.base, + walk=self.args.walk, + clean=self.args.clean, + ) + converter.run() + + def image2word(self): + from ..core.image.core import ImageDocxConverter + + _input = self.args.image2word + if isinstance(_input, list): + if len(_input) > 1: + converter = ImageDocxConverter(image_list=_input) + else: + converter = ImageDocxConverter(input_dir=_input[0]) + converter.run() + + def image2grayscale(self): + from ..core.image.core import GrayscaleConverter + + _input = self.args.image2gray + + converter = ( + GrayscaleConverter(_input) + if len(_input) > 1 + else GrayscaleConverter(_input[0]) + ) + converter.run() + + def display_version(self): + version = "2.0.1" + + return print(f"{fg.BLUE}filemac: V-{fg.BGREEN}{version}{RESET}") + + def voicetype(self): + from voice.VoiceType import VoiceTypeEngine + + try: + engine = VoiceTypeEngine() + engine.start() + except KeyboardInterrupt: + print("Quit") + return + except Exception as e: + logger.critical("Critical failure: %s", e) + print(f"{bg.YELLOW}{bg.BRED}Critical error:{RESET} {fg.RED}{str(e)}{RESET}") + return + + def handle_recording(self): + from ..core.recorder import SoundRecorder + + rec = SoundRecorder() + return rec.run() + + def handle_html2word(self): + from ..core.html import HTML2Word + from ..utils.file_utils import generate_filename + + try: + converter = HTML2Word() + if isinstance(self.args.html2word, str): + output = generate_filename( + ext="docx", basedir=Path(self.args.html2word) + ) + converter.convert_file(self.args.html2word, output) + print(f"{fg.DWHITE}Output: {fg.GREEN}{output}{RESET}") + else: + for html_file in self.args.html2word: + output = generate_filename( + ext="docx", basedir=Path(self.args.html2word) + ) + converter.convert_file(self.args.html2word, output) + print(f"{fg.DWHITE}Output: {fg.GREEN}{output}{RESET}") + except KeyboardInterrupt: + sys.exit("\nQUIT") + except Exception as e: + raise + logger.critical("Critical failure: %s", e) + print(f"{bg.YELLOW}{bg.RED}Critical error:{RESET} {fg.RED}{str(e)}{RESET}") + + @lru_cache(maxsize=None) + def get_method(self): + args = self.args + + method_mapper = { + args.audio_effect: self.handle_audio_effect, + (args.help and not args.audio_effect): lambda: ( + self.parser.print_help(), + sys.exit(), + ), + args.version: self.display_version, + tuple(args.convert_doc or ()): self.doc_converter, + args.convert_video: self.handle_video_conversion, + args.convert_image: self.image_converter, + args.resize_image: self.handle_image_resize, + args.convert_doc2image: self.handle_doc_to_image_conversion, + args.convert_audio: self.handle_audio_conversion, + args.extract_audio: self.handle_audio_extraction, + args.scan: self.handle_scan_pdf, + args.scanAsImg: self.handle_scan_images, + args.doc_long_image: self.handle_doc_to_long_image, + args.scanAsLong_Image: self.handle_scan_long_image, + args.convert_svg: self.handle_svg, + args.voicetype: self.voicetype, + tuple(args.OCR or ()): self.handle_ocr, + args.Analyze_video: self.handle_video_analysis, + tuple(args.AudioJoin or ()): self.handle_audio_join, + args.Richtext2word: self.handle_advanced_text_to_word, + args.pdfjoin: self.pdfjoin, + tuple(args.extract_pages or ()): self.handle_extract_pages, + tuple(args.image2pdf or ()): self.image2pdf, + tuple(args.image2word or ()): self.image2word, + tuple(args.image2gray or ()): self.image2grayscale, + args.html2word: self.handle_html2word, + tuple(args.extract_img or ()): self.ImageExtractor, + args.record: self.handle_recording, + } + return next((method_mapper[key] for key in method_mapper if key), None) + + def run(self): + """Check for help argument by calling help method""" + self.handle_help() + + """Check for audio help argument by calling help method""" + self.handle_audio_help() + + """Check for doc conversion help argument by calling help method""" + self.handle_doc_conversion_help() + + """Check for video conversion help argument by calling help method""" + self.handle_video_conversion_help() + + """Check for audio conversion help argument by calling help method""" + self.handle_audio_conversion_help() + + # Find the first non-empty key in method_mapper and execute its corresponding method + try: + """ + audio effects must take precedence due to the nested arguments which + might possibly conflict with the original arguments + """ + method = self.get_method() + if method: + method() + else: + self.parser.print_help() + raise FilemacError("Invalid arguments") + except KeyboardInterrupt: + logger.info("\nQuit") + sys.exit() + except (FilemacError, FileSystemError) as e: + # Handle any exceptions that occur during method execution + logger.error(e) + + except Exception as e: + raise + # Handle any exceptions that occur during method execution + logger.error(f"An error occurred: {e}") + + return + + +if __name__ == "__main__": + CliInit() diff --git a/filemac/core/__init__.py b/filemac/core/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/filemac/core/audio/core.py b/filemac/core/audio/core.py new file mode 100644 index 0000000..c6532b1 --- /dev/null +++ b/filemac/core/audio/core.py @@ -0,0 +1,262 @@ +import os +import re +import sys +from typing import List, Tuple, Union +from moviepy import VideoFileClip +from pydub import AudioSegment +from tqdm.auto import tqdm +from .m4a_converter import m4a +from rich.progress import Progress +from ...utils.colors import fg, rs +from ...utils.formats import SUPPORTED_AUDIO_FORMATS_DIRECT, SUPPORTED_AUDIO_FORMATS + +RESET = rs + + +class AudioConverter: + """Convert Audio file to from one format to another""" + + def __init__(self, input_file, out_format): + self.input_file = input_file + self.out_format = out_format + + def preprocess(self): + files_to_process = [] + + if os.path.isfile(self.input_file): + files_to_process.append(self.input_file) + elif os.path.isdir(self.input_file): + if os.listdir(self.input_file) is None: + print(f"{fg.RED}Cannot work with empty folder{RESET}") + sys.exit(1) + for file in os.listdir(self.input_file): + file_path = os.path.join(self.input_file, file) + if os.path.isfile(file_path): + files_to_process.append(file_path) + + return files_to_process + + def pydub_conv(self): + try: + input_list = self.preprocess() + out_f = self.out_format + input_list = [ + item + for item in input_list + if any(item.lower().endswith(ext) for ext in SUPPORTED_AUDIO_FORMATS) + ] + print(f"{fg.BYELLOW}Initializing conversion..{RESET}") + + def wav_redudancy(): + # Load the mp3 file using Pydub + audio = AudioSegment.from_file(file, fmt) + # Export the audio to a temporary file in wav format (ffmpeg can convert from wav to m4a) + audio.export("temp.wav", format="wav") + + for file in tqdm(input_list): + if out_f.lower() in SUPPORTED_AUDIO_FORMATS_DIRECT: + _, ext = os.path.splitext(file) + output_filename = _ + "." + out_f + fmt = ext[1:] + # print(fmt, out_f) + audio = AudioSegment.from_file(file, fmt) + print(f"{fg.BMAGENTA}Converting to {output_filename}{RESET}") + audio.export(output_filename, format=out_f) + # new_audio = pydub.AudioSegment.from_file('output_audio.') + print(f"{fg.BGREEN}Done{RESET}") + + elif file[-3:].lower() == "m4a" or out_f.lower() == "m4a": + m4a(file, out_f) + + elif ( + out_f.lower() in SUPPORTED_AUDIO_FORMATS + and not SUPPORTED_AUDIO_FORMATS_DIRECT + ): + print("Pending Implemantation For the format") + + else: + print(f"{fg.RED}Unsupported output format{RESET}") + sys.exit(1) + + except KeyboardInterrupt: + print("\nQuit❕") + sys.exit(1) + except Exception as e: + print(f"{fg.RED}{e}{RESET}") + + +class AudioJoiner: + def __init__(self, obj: Union[list, tuple[str]], masterfile=None): + self.obj = obj + self.masterfile = masterfile + self.files = [] + + if isinstance(self.obj, list): + self.isdir = False + for file in self.obj: + self.files.append(file) + + elif os.path.isdir(self.obj): + self.obj = self.obj + self.isdir = True + print(f"Join {fg.BBLUE}{len(os.listdir(self.obj))}{RESET} files") + + for file in list(os.listdir(self.obj)): + path = os.path.join(self.obj, file) + if path.split(".")[-1] in SUPPORTED_AUDIO_FORMATS_DIRECT: + self.files.append(path) + + else: + print("Pass") + pass + + @staticmethod + # Function to extract the number from the filename + def extract_number(filename): + match = re.search(r"_(\d+(\.\d+)?)\.ogg", filename) + if match: + try: + return float(match.group(1)) + except TypeError: + return int(match.group(1)) + else: + return 0 + + def worker(self): + try: + if len(self.files) == 0: + print("No files to work on") + print("\nQuit!") + exit(0) + if self.masterfile is None: + masterfile = os.path.splitext(self.files[0])[0] + "_master.ogg" + print(os.path.splitext(self.files[0])) + else: + masterfile = self.masterfile + print(f"{fg.YELLOW}Master file = {fg.BLUE}{masterfile}{RESET}") + + self.ext = os.path.splitext(masterfile)[-1] + _format = self.ext if self.ext in SUPPORTED_AUDIO_FORMATS_DIRECT else "ogg" + print(f"{fg.BYELLOW}Format = {fg.BBLUE}{_format}{RESET}") + + print(f"{fg.BBLUE}Create a master file{RESET}") + # Create a list to store files + ogg_files = [] + + # Sort the filenames based on the extracted number + _sorted_filenames = sorted(self.files, key=self.extract_number) + + print("." * 20, "Remove Empty files", "." * 20) + sorted_filenames = [] + with Progress() as progress: + task = progress.add_task("[magenta]Preparing..", total=None) + for i, fl in enumerate(_sorted_filenames): + if os.path.getsize(fl) == 0: + print("Empty file, skipping..") + continue + else: + sorted_filenames.append(fl) + progress.update(task, advance=None) + + # loop through the directory while adding the ogg files to the list + with Progress() as progress: + task2 = progress.add_task( + "[cyan]Create list", total=len(sorted_filenames) + ) + for i, filename in enumerate(sorted_filenames): + # print(f"{BWHITE}File {DCYAN}{filename}{RESET}") + ogg_files.append(AudioSegment.from_file(filename)) + progress.update(task2, advance=i) + + # Concatenate the ogg files + combined_ogg = ogg_files[0] + with Progress() as progress: + task3 = progress.add_task( + "[magenta]Joining... ", total=len(sorted_filenames) + ) + for i in range(1, len(sorted_filenames)): + combined_ogg += ogg_files[i] + progress.update(task3, advance=i) + + # Export the combined ogg to new mp3 file or ogg file + combined_ogg.export(masterfile, format=_format) + print(f"{fg.BGREEN}Master file:Ok🤏") + """ + if self.isdir: + query = input(f"{BBLUE}Remove the directory ?(y/n)").lower() in ('y', 'yes') + if query: + shutil.rmtree(self.obj) + """ + except KeyboardInterrupt: + print("\nQuit!") + sys.exit(1) + except Exception as e: + raise + print(f"{fg.RED}{e}{RESET}") + + +class AudioExtracter: + def __init__(self, input_file): + self.input_file = input_file + + def preprocess(self): + try: + files_to_process = [] + + if os.path.isfile(self.input_file): + files_to_process.append(self.input_file) + elif os.path.isdir(self.input_file): + if os.listdir(self.input_file) is None: + print(f"{fg.RED}Cannot work with empty folder{RESET}") + sys.exit(1) + for file in os.listdir(self.input_file): + file_path = os.path.join(self.input_file, file) + ls = ["mp4", "mkv"] + if os.path.isfile(file_path) and any( + file_path.lower().endswith(ext) for ext in ls + ): + files_to_process.append(file_path) + + return files_to_process + except Exception as e: + print(e) + + def moviepyextract(self): + try: + video_list = self.preprocess() + for input_video in video_list: + print(f"{fg.BYELLOW}Extracting..{fg.DCYAN}") + video = VideoFileClip(input_video) + audio = video.audio + basename, _ = os.path.splitext(input_video) + outfile = basename + ".wav" + audio.write_audiofile(outfile) + # print(f"\033[1;32mFile saved as \033[36m{outfile}\033[0m") + except KeyboardInterrupt: + print("\nExiting..") + sys.exit(1) + except Exception as e: + print(e) + + def ffmpeg_extractor(self): + import subprocess + + video_list = self.preprocess() + for input_video in video_list: + # Extract audio + subprocess.run( + ["ffmpeg", "-i", f"{input_video}", f"{input_video.split('.')[0]}.mp3"] + ) + # Merge audio and video + # subprocess.run(["ffmpeg", "-i", f"{input_video}", "-i", "audio.mp3", "-c:v", "copy", "-c:a", "aac", f"{input_video}"]) + + def pydub_extractor(self): + import subprocess + + video_list = self.preprocess() + for input_video in video_list: + # Ensure FFmpeg is installed + subprocess.run(["ffmpeg", "-version"]) + # Extract audio + video = AudioSegment.from_file(f"{input_video}") + video.export(f"{input_video.split('.')[0]}.mp3", format="mp3") diff --git a/filemac/core/audio/m4a_converter.py b/filemac/core/audio/m4a_converter.py new file mode 100644 index 0000000..fd61f13 --- /dev/null +++ b/filemac/core/audio/m4a_converter.py @@ -0,0 +1,54 @@ +import os +import subprocess +from ...utils.formats import SUPPORTED_AUDIO_FORMATS +from ...utils.security.vul_mitigate import SecurePython + + +def convert_m4a_(obj_file, _out_f: str): + try: + out_obj = obj_file.replace(obj_file.split(".")[-1], _out_f) + if obj_file[-3:].lower() == "m4a": + command = [ + "ffmpeg", + "-i", + f"{obj_file}", + "-c:a", + "libmp3lame", + "-b:a", + "320k", + f"{out_obj}", + ] + elif _out_f == "m4a": + command = [ + "ffmpeg", + "-i", + f"{obj_file}", + "-c:a", + "aac", + "-b:a", + "128k", + f"{out_obj}", + ] + subprocess.run(command, check=True, text=True) + return out_obj + except Exception as e: + print(f"\033[91m{e}\033[0m") + + +def m4a(obj, _out_f: str): + try: + secure = SecurePython() + if os.path.isdir(obj): + print("Detected directory input") + for root, dirs, files in os.walk(obj): + for file in files: + if file.endswith(list(SUPPORTED_AUDIO_FORMATS)): + print(f"\033[1;96m{file}\033[0m") + fpath = secure.safe_filepath(root, file) + convert_m4a_(fpath, _out_f) + elif os.path.isfile(obj): + convert_m4a_(obj, _out_f) + except Exception as e: + print(f"\033[91m{e}\033[0m") + finally: + print("\033[1;92mDone") diff --git a/filemac/core/document.py b/filemac/core/document.py new file mode 100644 index 0000000..162d1ea --- /dev/null +++ b/filemac/core/document.py @@ -0,0 +1,878 @@ +"""Handler for dcoument conversion operations requested by the cli entry""" + +import os +import re +import sqlite3 +import subprocess +import sys + +import pandas as pd +import PyPDF2 +from docx import Document +from openpyxl import load_workbook +from pdf2docx import parse +from pdf2image import convert_from_path +from pptx import Presentation +from reportlab.lib.pagesizes import letter +from reportlab.platypus import Paragraph, SimpleDocTemplate +from rich.progress import Progress +from tqdm import tqdm +from ..utils.simple import logger +from ..utils.colors import fg, bg, rs + +RESET = rs + +DEFAULT_SEPARATOR = "\n" + +_ext_word = ["doc", "docx"] +_ext_ppt_ = ["ppt", "pptx"] +_ext_xls = ["xls", "xlsx"] + +PYGAME_DETECT_AVX2 = 1 + + +class DocConverter: + """Implementats all document conversion methods""" + + def __init__(self, input_file): + self.input_file = input_file + + def preprocess(self): + """Check input object whether it`s a file or a directory if a file append + the file to a set and return it otherwise append directory full path + content to the set and return the set file. The returned set will be + evaluated in the next step as required on the basis of requested operation + For every requested operation, the output file if any is automatically + generated on the basis of the input filename and saved in the same + directory as the input file. + Exit if the folder is empty + """ + + try: + files_to_process = [] + + if os.path.isfile(self.input_file): + files_to_process.append(self.input_file) + elif os.path.isdir(self.input_file): + if os.listdir(self.input_file) is None: + print("Cannot work with empty folder") + sys.exit(1) + for file in os.listdir(self.input_file): + file_path = os.path.join(self.input_file, file) + if os.path.isfile(file_path): + files_to_process.append(file_path) + + return files_to_process + except Exception as e: + print(e) + + def word_to_pdf(self): + """Convert word file to pdf document (docx) + ->Check if running on Linux + ->Use subprocess to run the dpkg and grep commands""" + word_list = self.preprocess() + + word_list = [ + item for item in word_list if item.split(".")[-1].lower() in ("doc", "docx") + ] + for word_file in word_list: + pdf_file_dir = os.path.dirname(word_file) + pdf_file = os.path.splitext(word_file)[0] + ".pdf" + + try: + if os.name == "posix": # Check if running on Linux + print( + f"{fg.BLUE}Converting: {RESET}{word_file} {fg.BLUE}to {RESET}{pdf_file}" + ) + # Use subprocess to run the dpkg and grep commands + result = subprocess.run( + ["dpkg", "-l", "libreoffice"], stdout=subprocess.PIPE, text=True + ) + if result.returncode != 0: + logger.exception(f"{fg.RED}Libreoffice not found !{RESET}") + print( + f"{fg.CYAN}Initiating critical redundacy measure !{RESET}" + ) + self.word2pdf_extra(word_file) + subprocess.run( + [ + "soffice", + "--convert-to", + "pdf", + word_file, + "--outdir", + pdf_file_dir, + ] + ) + + print( + f"{fg.BMAGENTA} Successfully converted {word_file} to {pdf_file}{RESET}" + ) + return pdf_file + + elif os.name == "nt": + self.word2pdf_extra(word_file) + return pdf_file + + except Exception as e: + print(f"Error converting {word_file} to {pdf_file}: {e}") + + @staticmethod + def word2pdf_extra(obj, outf=None): + """For window users since it requires Microsoft word to be installed""" + for file in obj: + file = os.path.abspath(file) + if file.split(".")[-1] not in ("doc", "docx"): + logger.error(f"{fg.RED}File is not a word file{RESET}") + sys.exit(1) + pdf_file = os.path.splitext(file)[0] + ".pdf" if outf is None else outf + try: + if not os.path.isfile(file): + print(f"The file {obj} does not exist or is not a valid file.") + sys.exit("Exit!") + logger.info( + f"{fg.BLUE}Converting: {RESET}{file} {fg.BLUE}to {RESET}{pdf_file}" + ) + from docx2pdf import convert + + convert(file, pdf_file) + print(f"{fg.GREEN}Conversion ✅{RESET}") + sys.exit(0) + except ImportError: + logger.warning( + f"{fg.RED}docx2pdf Not found. {fg.CYAN}Run pip install docx2pdf{RESET}" + ) + except Exception as e: + raise + logger.error(e) + + def pdf_to_word(self): + """Convert pdf file to word document (docx)""" + pdf_list = self.preprocess() + pdf_list = [item for item in pdf_list if item.lower().endswith("pdf")] + for pdf_file in pdf_list: + word_file = ( + pdf_file[:-3] + "docx" if pdf_file.lower().endswith("pdf") else None + ) + + try: + command = [ + "lowriter", + "--headless", + '--infilter="writer_pdf_import"', + '--convert-todoc:"MS Word 97"', + pdf_file, + ] + print(f"{fg.BYELLOW}Parse the pdf document..{RESET}") + parse(pdf_file, word_file, start=0, end=None) + + logger.info( + f"{fg.MAGENTA}New file is {fg.CYAN}{word_file}{RESET}" + ) + logger.info(f"{fg.BGREEN}Success👨‍💻✅{RESET}") + except KeyboardInterrupt: + print("\nQuit❕") + sys.exit(1) + except Exception as e: + logger.info( + f"{bg.RED}All conversion attempts have failed: {e}{RESET}" + ) + + def txt_to_pdf(self): + """Convert text file(s) to pdf document (docx) + ->Read the contents of the input .txt file + ->Initialize the PDF document + ->Create a story to hold the elements of the PDF + ->Iterate through each line in the input .txt file and add it to the PDF + ->Build and write the PDF document""" + txt_list = self.preprocess() + _list_ = [item for item in txt_list if item.lower().endswith("txt")] + for _file_ in _list_: + _pdf_ = _file_[:-3] + "pdf" if _file_.lower().endswith("txt") else None + # Read the contents of the input .txt file + with open(_file_, "r", encoding="utf-8") as file: + text_contents = file.readlines() + + # Initialize the PDF document + logger.info(f"{fg.BYELLOW}Initialize the PDF document{RESET}") + doc = SimpleDocTemplate(_pdf_, pagesize=letter) + + # Create a story to hold the elements of the PDF + logger.info( + f"{fg.BYELLOW}Create a story to hold the elements of the PDF{RESET}" + ) + story = [] + + # Iterate through each line in the input .txt file and add it to the PDF + logger.info( + f"{fg.BYELLOW}Iterate through each line in the input .txt file and add it to the PDF{RESET}" + ) + _line_count_ = 0 + try: + for line in text_contents: + _line_count_ += 1 + logger.info( + f"Lines {fg.BBLUE}{_line_count_}{RESET}/{len(text_contents)}" + ) + story.append(Paragraph(line.strip(), style="normalText")) + + except KeyboardInterrupt: + print("\nQuit❕⌨️") + sys.exit(1) + except Exception as e: + logger.error(e) + pass + # Build and write the PDF document + logger.info(f"{fg.BYELLOW}Build and write the PDF document{RESET}") + doc.build(story) + logger.info(f"{fg.MAGENTA}New file is {fg.CYAN}{_pdf_}{RESET}") + print(f"\n{fg.BGREEN}Success👨‍💻✅{RESET}") + + def word_to_pptx(self): + """Convert word file(s) to pptx document (pptx/ppt) + -> Load the Word document + ->Create a new PowerPoint presentation + ->Iterate through each paragraph in the Word document + ->Create a new slide in the PowerPoint presentation + ->Add the paragraph text to the slide + """ + word_list = self.preprocess() + word_list = [ + item for item in word_list if item.split(".")[-1].lower() in ("doc", "docx") + ] + + for word_file in word_list: + if word_list is None: + print("Please provide appropriate file type") + sys.exit(1) + ext = os.path.splitext(word_file)[-1][1:] + + pptx_file = ( + (os.path.splitext(word_file)[0] + ".pptx") + if ext in list(_ext_word) + else None + ) + + try: + # Load the Word document + print(f"{fg.BYELLOW}Load the Word document..{RESET}") + doc = Document(word_file) + + # Create a new PowerPoint presentation + print(f"{fg.BYELLOW}Create a new PowerPoint presentation..{RESET}") + prs = Presentation() + + # Iterate through each paragraph in the Word document + print( + f"{fg.BGREEN}Populating pptx slides with {fg.BYELLOW}{len(doc.paragraphs)}{fg.BGREEN} entries..{RESET}" + ) + count = 0 + for paragraph in doc.paragraphs: + count += 1 + perc = (count / len(doc.paragraphs)) * 100 + print( + f"{fg.BMAGENTA}Progress:: {fg.BCYAN}{perc:.2f}%{RESET}", + end="\r", + ) + # Create a new slide in the PowerPoint presentation + slide = prs.slides.add_slide(prs.slide_layouts[1]) + + # Add the paragraph text to the slide + slide.shapes.title.text = paragraph.text + + # Save the PowerPoint presentation + prs.save(pptx_file) + logger.info( + f"{fg.MAGENTA}New file is {fg.CYAN}{pptx_file}{RESET}" + ) + print(f"\n{fg.BGREEN}Success👨‍💻✅{RESET}") + except KeyboardInterrupt: + print("\nQuit❕⌨️") + sys.exit(1) + except Exception as e: + logger.error(e) + + def word_to_txt(self): + """Convert word file to txt file""" + word_list = self.preprocess() + word_list = [ + item for item in word_list if item.split(".")[-1].lower() in ("dox", "docx") + ] + + for file_path in word_list: + ext = os.path.splitext(file_path)[-1][1:] + txt_file = ( + (os.path.splitext(file_path)[0] + ".txt") + if ext in list(_ext_word) + else "output.txt" + ) + + try: + logger.info(f"{fg.BLUE}Create Doument Tablet{RESET}") + doc = Document(file_path) + + with open(txt_file, "w", encoding="utf-8") as f: + Par = 0 + for paragraph in doc.paragraphs: + f.write(paragraph.text + "\n") + Par += 1 + + print( + f"Par:{fg.BLUE}{Par}/{len(doc.paragraphs)}{RESET}", + end="\r", + ) + logger.info( + f"{fg.MAGENTA}Conversion of file to txt success{RESET}" + ) + + logger.info(f"File: {fg.GREEN}{txt_file}{RESET}") + return txt_file + except KeyboardInterrupt: + print("\nQuit❕⌨️") + sys.exit() + except Exception as e: + logger.error(f"{fg.RED}{e}{RESET}") + with open("conversion.log", "a") as log_file: + log_file.write( + f"Couldn't convert {file_path} to {txt_file}:REASON->{e}" + ) + + def pdf_to_txt(self): + """Convert pdf file to text file""" + + pdf_list = self.preprocess() + pdf_list = [item for item in pdf_list if item.lower().endswith("pdf")] + for file_path in pdf_list: + txt_file = file_path[:-3] + "txt" + try: + print(f"{fg.BYELLOW}Open and read the pdf document..{RESET}") + with open(file_path, "rb") as file: + pdf_reader = PyPDF2.PdfReader(file) + text = "" + _pg_ = 0 + print(f"{fg.YELLOW}Convert pages..{RESET}") + for page_num in range(len(pdf_reader.pages)): + _pg_ += 1 + logger.info( + f"Page {fg.BBLUE}{_pg_}{RESET}/{len(pdf_reader.pages)}" + ) + page = pdf_reader.pages[page_num] + text += page.extract_text() + with open(txt_file, "w", encoding="utf-8") as f: + f.write(text) + logger.info(f"{fg.MAGENTA}New file is {fg.CYAN}{txt_file}{RESET}") + logger.info(f"{fg.BGREEN}Success👨‍💻✅{RESET}") + except Exception as e: + logger.error(f"{fg.RED}{e}{RESET}") + with open("conversion.log", "a") as log_file: + log_file.write(f"Error converting {file_path} to {txt_file}: {e}\n") + + def pptx_to_txt(self, dest=None): + """Convert ppt file to tetx document""" + ppt_list = self.preprocess() + ppt_list = [ + item for item in ppt_list if item.split(".")[-1].lower() in ("ppt", "pptx") + ] + try: + for file_path in ppt_list: + ext = os.path.splitext(file_path)[-1][1:] + + txt_file = (os.path.splitext(file_path)[0]) + ".txt" + + file_path = os.path.abspath(file_path) + + if ext == "ppt": + file_path = self.convert_ppt_to_pptx( + file_path + ) # First convert the ppt to pptx + + presentation = Presentation(file_path) + + logger.info( + f"Slide count ={fg.BMAGENTA} {len(presentation.slides)}{RESET}" + ) + + _slide_count_ = 0 + + with Progress() as progress: + task = progress.add_task( + "[magenta]Preparing..", total=len(presentation.slides) + ) + + for slide in presentation.slides: + _slide_count_ += 1 + # progress.console.print(F"Slide {_slide_count_}/{len(presentation.slides)}", end='\n') + + for shape in slide.shapes: + if shape.has_text_frame: + text_frame = shape.text_frame + + for paragraph in text_frame.paragraphs: + # Create a paragraph in the Word document if it contains text + # Ensure text exists + if any(run.text.strip() for run in paragraph.runs): + for run in paragraph.runs: + text = run.text.strip() + if text and text != " ": + with open(txt_file, "a") as fl: + fl.write(text) + # return txt_file + + progress.update(task, advance=1) + + if dest == "text": + with open(txt_file, "r") as fl: + text_buffer = fl.read() + print(text_buffer) + return text_buffer + + logger.info(f"{fg.MAGENTA}New file is {fg.CYAN}{txt_file}{RESET}") + logger.info(f"{fg.BGREEN}Success👨‍💻✅{RESET}") + except Exception as e: + logger.error(f"\n❌Oops! {bg.RED}{e}{RESET}") + + @staticmethod + def convert_ppt_to_pptx(obj: os.PathLike): + import platform + + try: + if obj.endswith("ppt"): + if platform.system() in ("Linux", "MacOS") or os.name == "posix": + subprocess.run( + ["soffice", "--headless", "--convert-to", "pptx", obj] + ) + return os.path.splitext(obj)[0] + ".pptx" + elif platform.system() in ("Windows") or os.name == "nt": + import win32com.client + + powerpoint = win32com.client.Dispatch("PowerPoint.Application") + powerpoint.Visible = 1 + ppt = powerpoint.Presentations.Open(obj) + pptx_file = os.path.splitext(obj)[0] + ".pptx" + ppt.SaveAs(pptx_file, 24) # 24 is the format for pptx + ppt.Close() + powerpoint.Quit() + return pptx_file + else: + print(f"{fg.RED}Unable to identify the system{RESET}") + except KeyboardInterrupt: + print("\nQuit!") + sys.exit(1) + except Exception as e: + logger.error(f"{fg.RED}{e}{RESET}") + + def ppt_to_word(self): + from docx.enum.text import WD_PARAGRAPH_ALIGNMENT + from docx.shared import Pt + from docx.shared import RGBColor as docxRGBColor + from pptx.dml.color import RGBColor as pptxRGBColor + + """Convert ppt file to word document\n + ->Preserves bold formatting + """ + ppt_list = self.preprocess() + ppt_list = [ + item for item in ppt_list if item.split(".")[-1].lower() in ("ppt", "pptx") + ] + for file_path in ppt_list: + ext = os.path.splitext(file_path)[-1][1:] + word_file = ( + (os.path.splitext(file_path)[0] + ".docx") + if ext in list(_ext_ppt_) + else None + ) + try: + logger.info(f"{fg.BYELLOW}Create Doument Tablet{RESET}") + file_path = os.path.abspath(file_path) + if ext == "ppt": + file_path = self.convert_ppt_to_pptx( + file_path + ) # First convert the ppt to pptx + presentation = Presentation(file_path) + document = Document() + logger.info( + f"Slide count ={fg.BMAGENTA} {len(presentation.slides)}{RESET}" + ) + _slide_count_ = 0 + with Progress() as progress: + task = progress.add_task( + "[magenta]Preparing..", total=len(presentation.slides) + ) + for slide in presentation.slides: + _slide_count_ += 1 + # progress.console.print(F"Slide {_slide_count_}/{len(presentation.slides)}", end='\n') + slide_text = "" + for shape in slide.shapes: + if shape.has_text_frame: + text_frame = shape.text_frame + + for paragraph in text_frame.paragraphs: + # Create a paragraph in the Word document if it contains text + # Ensure text exists + if any(run.text.strip() for run in paragraph.runs): + # print("Has text") + new_paragraph = document.add_paragraph() + + # Set general paragraph properties + new_paragraph.alignment = ( + WD_PARAGRAPH_ALIGNMENT.JUSTIFY + ) # Justify text + new_paragraph.space_after = Pt(6) + new_paragraph.space_before = Pt(6) + new_paragraph.line_spacing = 1.15 + + for run in paragraph.runs: + if run.text.strip(): + slide_text += ( + run.text + ) # Only add non-empty text runs + # print(run.text.strip(), end='\n') + new_run = new_paragraph.add_run( + run.text + ) + + # Preserve bold, italic, underline, font name, and size + new_run.bold = run.font.bold + new_run.italic = run.font.italic + new_run.underline = run.font.underline + new_run.font.name = run.font.name + new_run.font.size = run.font.size + + # Preserve font color + try: + if ( + run.font.color + and run.font.color.rgb + ): + pptx_color = run.font.color.rgb + # If the color is white (255, 255, 255), change it to black (0, 0, 0) + if pptx_color == pptxRGBColor( + 255, 255, 255 + ): + new_run.font.color.rgb = ( + docxRGBColor(0, 0, 0) + ) # Black + else: + # Assign color properly to the Word run + new_run.font.color.rgb = ( + docxRGBColor( + pptx_color[0], + pptx_color[1], + pptx_color[2], + ) + ) + except AttributeError: + pass + + progress.update(task, advance=1) + document.save(word_file) + logger.info( + f"{fg.MAGENTA}New file is {fg.CYAN}{word_file}{RESET}" + ) + logger.info(f"{fg.BGREEN}Success👨‍💻✅{RESET}") + return word_file + except Exception as e: + logger.error(f"\n❌Oops! {bg.RED}{e}{RESET}") + with open("conversion.log", "a") as log_file: + log_file.write(f"\n❌Oops! {e}") + + def text_to_word(self): + """Convert text file to word\n + ->Read the text file\n + ->Filter out non-XML characters\n + ->Create a new Word document\n + ->Add the filtered text content to the document""" + flist = self.preprocess() + flist = [item for item in flist if item.lower().endswith("txt")] + for file_path in flist: + if file_path.lower().endswith("txt"): + word_file = file_path[:-3] + "docx" + + try: + # Read the text file + logger.info(f"{fg.BCYAN}Open and read the text file{RESET}") + with open(file_path, "r", encoding="utf-8", errors="ignore") as file: + text_content = file.read() + + # Filter out non-XML characters + filtered_content = re.sub( + r"[^\x09\x0A\x0D\x20-\uD7FF\uE000-\uFFFD]+", "", text_content + ) + + # Create a new Word document + logger.info(f"{fg.BYELLOW}Create Doument Tablet{RESET}") + doc = Document() + # Add the filtered text content to the document + doc.add_paragraph(filtered_content) + + # Save the document as a Word file + doc.save(word_file) + logger.info( + f"{fg.MAGENTA}New file is {fg.BCYAN}{word_file}{RESET}" + ) + logger.info(f"{fg.BGREEN}Success👨‍💻✅{RESET}") + except FileExistsError as e: + logger.error(f"{str(e)}📁") + except Exception as e: + logger.error(f"\n❌Oops something went awry {fg.RED}{e}{RESET}") + with open("conversion.log", "a") as log_file: + log_file.write( + f"\n❌Oops something went astray{fg.RED}{e}{RESET}" + ) + + def convert_xls_to_word(self): + """Convert xlsx file(s) to word file(s)\n + ->Read the XLS file using pandas\n + ->Create a new Word document\n + ->Iterate over the rows of the dataframe and add them to the Word document""" + xls_list = self.preprocess() + + xls_list = [ + item for item in xls_list if item.split(".")[-1].lower() in ("xls", "xlsx") + ] + + print(f"{fg.BGREEN}Initializing conversion sequence{RESET}") + + for xls_file in xls_list: + ext = os.path.splitext(xls_file)[-1][1:] + word_file = ( + (os.path.splitext(xls_file)[0] + ".docx") + if ext in list(_ext_xls) + else None + ) + try: + """Read the XLS file using pandas""" + + df = pd.read_excel(xls_file) + + """Create a new Word document""" + doc = Document() + + """Iterate over the rows of the dataframe and add them to the + Word document""" + logger.info(f"{fg.ICYAN}Converting {xls_file}..{RESET}") + # time.sleep(2) + total_rows = df.shape[0] + for _, row in df.iterrows(): + current_row = _ + 1 + percentage = (current_row / total_rows) * 100 + for value in row: + doc.add_paragraph(str(value)) + print( + f"Row {fg.BYELLOW}{current_row}/{total_rows} {fg.BBLUE}{percentage:.1f}%{RESET}", + end="\r", + ) + # print(f"\033[1;36m{row}{RESET}") + + # Save the Word document + doc.save(word_file) + print(f"{fg.BGREEN}Conversion successful!{RESET}", end="\n") + except KeyboardInterrupt: + print("\nQuit⌨️") + sys.exit(1) + except Exception as e: + print(f"{bg.RED}Oops Conversion failed:❕{RESET}", str(e)) + + def convert_xls_to_text(self): + """Convert xlsx/xls file/files to text file format + ->Read the XLS file using pandas + ->Convert the dataframe to plain text + ->Write the plain text to the output file""" + xls_list = self.preprocess() + + xls_list = [ + item + for item in xls_list + if any(item.lower().endswith(ext) for ext in _ext_xls) + ] + print(f"{fg.BGREEN}Initializing conversion sequence{RESET}") + for xls_file in tqdm(xls_list): + ext = os.path.splitext(xls_file)[-1][1:] + txt_file = ( + (os.path.splitext(xls_file)[0] + ".txt") + if ext in list(_ext_xls) + else None + ) + try: + # Read the XLS file using pandas + logger.info(f"Converting {xls_file}..") + df = pd.read_excel(xls_file) + + # Convert the dataframe to plain text + text = df.to_string(index=False) + chars = len(text) + words = len(text.split()) + lines = len(text.splitlines()) + + print( + f"Preparing to write: {fg.BYELLOW}{chars} \033[1;30m characters{fg.BYELLOW} {words}\033[1;30m words {fg.BYELLOW}{lines}\033[1;30m lines {RESET}", + end="\n", + ) + # Write the plain text to the output file + with open(txt_file, "w") as file: + file.write(text) + + print(f"{fg.BGREEN}Conversion successful!{RESET}", end="\n") + except KeyboardInterrupt: + print("\nQuit❕") + sys.exit(1) + except Exception as e: + print("Oops Conversion failed:", str(e)) + + def convert_xlsx_to_csv(self): + """Convert xlsx/xls file to csv(comma seperated values) format + ->Load the Excel file + ->Save the DataFrame to CSV""" + xls_list = self.preprocess() + + xls_list = [ + item for item in xls_list if item.split(".")[-1].lower() in ("xls", "xlsx") + ] + for xls_file in tqdm(xls_list): + ext = os.path.splitext(xls_file)[-1][1:] + csv_file = ( + (os.path.splitext(xls_file)[0] + ".csv") + if ext in list(_ext_xls) + else None + ) + try: + """Load the Excel file""" + print(f"{fg.BGREEN}Initializing conversion sequence{RESET}") + df = pd.read_excel(xls_file) + logger.info(f"Converting {xls_file}..") + total_rows = df.shape[0] + print(f"Writing {fg.BYELLOW}{total_rows} rows {RESET}", end="\n") + for i in range(101): + print(f"Progress: {i}%", end="\r") + """Save the DataFrame to CSV""" + df.to_csv(csv_file, index=False) + print(f"{fg.BMAGENTA} Conversion successful{RESET}") + + except KeyboardInterrupt: + print("\nQuit❕") + sys.exit(1) + except Exception as e: + print(e) + + def convert_csv_to_xlsx(self): + csv_list = self.preprocess() + csv_list = [item for item in csv_list if item.split(".")[-1].lower() in ("csv")] + + with Progress() as progress: + task = progress.add_task("[cyan]Coverting", total=len(csv_list)) + for file in csv_list: + file_name = file[:-3] + "xlsx" + df = pd.read_csv(file) + # excel engines ('openpyxl' or 'xlsxwriter') + df.to_excel(file_name, engine="openpyxl", index=False) + + # Load the workbook and the sheet + workbook = load_workbook(file_name) + sheet = workbook.active + + # print("Adjust Columns") + for column in sheet.columns: + max_length = 0 + column_letter = column[0].column_letter + + max_length = max(len(str(cell.value)) for cell in column) + """for cell in column: + try: + if len(str(cell.value)) > max_length: + max_length = len(cell.value) + + except Exception: + pass + """ + + adjusted_width = max_length + 2 + sheet.column_dimensions[column_letter].width = adjusted_width + + # Save the workbook + workbook.save(file_name) + progress.update(task, advance=1) + + def convert_xlsx_to_database(self): + """Convert xlsx file(s) to sqlite + ->Read the Excel file into a pandas DataFrame + ->Create a connection to the SQLite database + ->Insert the DataFrame into a new table in the database + ->Close the database connection""" + xlsx_list = self.preprocess() + xlsx_list = [ + item for item in xlsx_list if item.split(".")[-1].lower() in ("xls", "xlsx") + ] + for xlsx_file in tqdm(xlsx_list): + sqlfile = ( + (os.path.splitext(xlsx_file)[0] + ".sql") + if (xlsx_file.split(".")[0]) in ("xls", "xlsx") + else None + ) + try: + db_file = input( + f"{fg.BBLUE}Please enter desired sql filename: {RESET}" + ) + table_name = input("Please enter desired table name: ") + # res = ["db_file", "table_name"] + if any(db_file) == "": + db_file = sqlfile + table_name = sqlfile[:-4] + if not db_file.endswith(".sql"): + db_file = sqlfile + column = 0 + for i in range(20): + column += 0 + # Read the Excel file into a pandas DataFrame + print(f"Reading {xlsx_file}...") + df = pd.read_excel(xlsx_file) + print(f"{fg.BGREEN}Initializing conversion sequence{RESET}") + print(f"{fg.BGREEN} Connected to sqlite3 database::{RESET}") + # Create a connection to the SQLite database + conn = sqlite3.connect(db_file) + print(f"{fg.BYELLOW} Creating database table::{RESET}") + # Insert the DataFrame into a new table in the database + df.to_sql(table_name, column, conn, if_exists="replace", index=False) + print( + f"Operation successful{RESET} file saved as \033[32{db_file}{RESET}" + ) + # Close the database connection + conn.close() + except KeyboardInterrupt: + print("\nQuit❕") + sys.exit(1) + except Exception as e: + logger.error(f"{e}") + + def doc2image(self, outf="png"): + """Create image objects from given files""" + outf = "png" if outf not in ("png", "jpg") else outf + path_list = self.preprocess() + file_list = [ + item + for item in path_list + if item.split(".")[-1].lower() in ("pdf", "doc", "docx") + ] + imgs = [] + for file in file_list: + if file.lower().endswith("pdf"): + # Convert the PDF to a list of PIL image objects + print(f"{fg.BLUE}Generate image objects ..{RESET}") + images = convert_from_path(file) + + # Save each image to a file + fname = file[:-4] + print(f"{fg.YELLOW}Target images{fg.BLUE} {len(images)}{RESET}") + + with Progress() as progress: + task = progress.add_task( + "[magenta]Generating images ", total=len(images) + ) + for i, image in enumerate(images): + # print(f"{Bfg.BLUE}{i}{RESET}", end="\r") + yd = f"{fname}_{i + 1}.{outf}" + image.save(yd) + imgs.append(yd) + progress.update(task, advance=1) + # print(f"\n{fg.GREEN}Ok{RESET}") + + return imgs diff --git a/filemac/core/exceptions.py b/filemac/core/exceptions.py new file mode 100644 index 0000000..f5a7c9e --- /dev/null +++ b/filemac/core/exceptions.py @@ -0,0 +1,43 @@ +class FilemacError(Exception): + """Custom filemac exception handler""" + + pass + + +class ValidationError(FilemacError): + """Raised when validation fails.""" + + pass + + +class SystemPermissionError(FilemacError): + """ + Raised when user cannot acess to system reasource due to insuficient permissions. + Eg command execusion + """ + + pass + + +class FileSystemError(FilemacError): + """ + Raises when there is file/folder ie FileSystem acess error not related to permissions. + ie write error + """ + + pass + + +class AuthorizationError(FilemacError): + """ + Raised when there is an *Explicit* file/dir/resource access denial. + When priviledge elevelation is required. + """ + + pass + + +class ConfigurationError(FilemacError): + """Raised when invalid configuration.""" + + pass diff --git a/filemac/core/html/__init__.py b/filemac/core/html/__init__.py new file mode 100644 index 0000000..0064a2e --- /dev/null +++ b/filemac/core/html/__init__.py @@ -0,0 +1,18 @@ +""" +Custom HTML to DOCX Converter for CVs and Professional Documents +""" + +from .core.converter import HTML2Word +from .core.html_parser import HTMLParser +from .core.style_manager import StyleManager +from .styles.css_parser import CSSParser +from .styles.style_applier import StyleApplier + +__version__ = "1.0.0" +__all__ = [ + "HTML2Word", + "HTMLParser", + "StyleManager", + "CSSParser", + "StyleApplier", +] diff --git a/filemac/core/html/core.py b/filemac/core/html/core.py new file mode 100644 index 0000000..411ee00 --- /dev/null +++ b/filemac/core/html/core.py @@ -0,0 +1,365 @@ +""" +custom_html_to_docx.py +A reliable HTML to DOCX converter specifically designed for CVs and professional documents +""" + +from docx import Document +from docx.shared import Pt, Inches, RGBColor +from docx.enum.text import WD_ALIGN_PARAGRAPH, WD_BREAK +from docx.oxml.ns import qn +from docx.oxml import parse_xml +import re +from typing import List, Dict, Any +import html as html_parser + + +class CVHTMLConverter: + """A specialized HTML to DOCX converter for CVs and professional documents""" + + def __init__(self): + self.doc = None + self.current_paragraph = None + self.styles = { + "h1": {"size": 16, "bold": True, "alignment": WD_ALIGN_PARAGRAPH.CENTER}, + "h2": {"size": 14, "bold": True, "alignment": WD_ALIGN_PARAGRAPH.LEFT}, + "h3": {"size": 12, "bold": True, "alignment": WD_ALIGN_PARAGRAPH.LEFT}, + "normal": {"size": 11, "bold": False, "alignment": WD_ALIGN_PARAGRAPH.LEFT}, + "bold": {"size": 11, "bold": True, "alignment": WD_ALIGN_PARAGRAPH.LEFT}, + "italic": { + "size": 11, + "italic": True, + "alignment": WD_ALIGN_PARAGRAPH.LEFT, + }, + } + + def convert(self, html_content: str, output_path: str) -> Document: + """ + Convert HTML content to DOCX document + + Args: + html_content: HTML string to convert + output_path: Path for output DOCX file + + Returns: + Document: The created Word document + """ + self.doc = Document() + self._setup_document_styles() + + # Clean and parse HTML + cleaned_html = self._clean_html(html_content) + self._parse_html(cleaned_html) + + self.doc.save(output_path) + return self.doc + + def _setup_document_styles(self): + """Setup document styles and formatting""" + # Set normal style + style = self.doc.styles["Normal"] + font = style.font + font.name = "Calibri" + font.size = Pt(11) + + # Create custom styles for CV + self._create_style("CV Title", 16, True, WD_ALIGN_PARAGRAPH.CENTER) + self._create_style("CV Heading", 14, True, WD_ALIGN_PARAGRAPH.LEFT) + self._create_style("CV Subheading", 12, True, WD_ALIGN_PARAGRAPH.LEFT) + + def _create_style(self, style_name: str, font_size: int, bold: bool, alignment): + """Create a custom style""" + try: + style = self.doc.styles.add_style( + style_name, 1 + ) # 1 = WD_STYLE_TYPE.PARAGRAPH + font = style.font + font.name = "Calibri" + font.size = Pt(font_size) + font.bold = bold + style.paragraph_format.alignment = alignment + except: + # Style might already exist + pass + + def _clean_html(self, html: str) -> str: + """Clean and normalize HTML content""" + # Remove multiple spaces and newlines + html = re.sub(r"\s+", " ", html) + + # Ensure proper tag formatting + html = html.replace("
", "
").replace("
", "
") + + # Decode HTML entities + html = html_parser.unescape(html) + + return html.strip() + + def _parse_html(self, html: str): + """Parse HTML content and convert to DOCX""" + # Split by tags while preserving content + tokens = self._tokenize_html(html) + self._process_tokens(tokens) + + def _tokenize_html(self, html: str) -> List[Dict[str, Any]]: + """Tokenize HTML into manageable chunks""" + tokens = [] + pos = 0 + + while pos < len(html): + # Find next tag + tag_match = re.search(r"]*>", html[pos:]) + + if not tag_match: + # Add remaining text + if pos < len(html): + tokens.append({"type": "text", "content": html[pos:]}) + break + + tag_start = tag_match.start() + pos + tag_end = tag_match.end() + pos + + # Add text before tag + if tag_start > pos: + tokens.append({"type": "text", "content": html[pos:tag_start]}) + + # Add tag + tag_content = html[tag_start:tag_end] + is_closing = tag_content.startswith(""), + } + ) + + pos = tag_end + + return tokens + + def _process_tokens(self, tokens: List[Dict[str, Any]]): + """Process tokens and build document""" + stack = [] # Track open tags + + for token in tokens: + if token["type"] == "text": + self._add_text(token["content"], stack) + elif token["type"] == "tag": + if token["is_closing"]: + # Close tag + if stack and stack[-1]["name"] == token["name"]: + stack.pop() + self._handle_closing_tag(token["name"]) + else: + # Open tag + stack.append(token) + self._handle_opening_tag(token) + + def _handle_opening_tag(self, tag: Dict[str, Any]): + """Handle opening tag""" + tag_name = tag["name"] + + if tag_name in ["h1", "h2", "h3"]: + self._add_heading(tag_name) + elif tag_name == "br": + self._add_line_break() + elif tag_name == "p": + self._start_paragraph() + elif tag_name == "div": + if self.current_paragraph: + self.current_paragraph = None + elif tag_name == "ul": + self.in_list = True + elif tag_name == "li": + self._start_list_item() + + def _handle_closing_tag(self, tag_name: str): + """Handle closing tag""" + if tag_name in ["h1", "h2", "h3", "p"]: + self.current_paragraph = None + elif tag_name == "ul": + self.in_list = False + self.current_paragraph = None + + def _add_heading(self, level: str): + """Add heading based on level""" + self.current_paragraph = self.doc.add_paragraph() + + if level == "h1": + self.current_paragraph.style = "CV Title" + elif level == "h2": + self.current_paragraph.style = "CV Heading" + else: + self.current_paragraph.style = "CV Subheading" + + def _start_paragraph(self): + """Start a new paragraph""" + self.current_paragraph = self.doc.add_paragraph() + + def _start_list_item(self): + """Start a new list item""" + self.current_paragraph = self.doc.add_paragraph(style="List Bullet") + + def _add_line_break(self): + """Add line break""" + if self.current_paragraph: + self.current_paragraph.add_run().add_break(WD_BREAK.LINE) + else: + self.doc.add_paragraph() + + def _add_text(self, text: str, stack: List[Dict[str, Any]]): + """Add text with current formatting""" + if not text.strip(): + return + + # Create paragraph if none exists + if not self.current_paragraph: + self.current_paragraph = self.doc.add_paragraph() + + run = self.current_paragraph.add_run(text) + + # Apply formatting based on stack + self._apply_formatting(run, stack) + + def _apply_formatting(self, run, stack: List[Dict[str, Any]]): + """Apply formatting based on tag stack""" + font = run.font + font.name = "Calibri" + font.size = Pt(11) + + # Check for bold (strong, b) + bold_tags = ["strong", "b", "h1", "h2", "h3"] + if any(tag["name"] in bold_tags for tag in stack): + font.bold = True + + # Check for italic (em, i) + italic_tags = ["em", "i"] + if any(tag["name"] in italic_tags for tag in stack): + font.italic = True + + # Check for underline (u) + underline_tags = ["u"] + if any(tag["name"] in underline_tags for tag in stack): + font.underline = True + + +class AdvancedCVConverter(CVHTMLConverter): + """Enhanced converter with better CSS support and layout management""" + + def __init__(self): + super().__init__() + self.section_spacing = Pt(12) + self.current_style = {} + + def convert_cv_html(self, html_file_path: str, output_path: str) -> Document: + """ + Convert CV HTML file to DOCX with enhanced formatting + + Args: + html_file_path: Path to HTML file + output_path: Output DOCX path + """ + with open(html_file_path, "r", encoding="utf-8") as f: + html_content = f.read() + + return self.convert(html_content, output_path) + + def _extract_css_styles(self, html: str) -> Dict[str, Dict]: + """Extract CSS styles from style tags""" + styles = {} + style_matches = re.findall(r"]*>(.*?)", html, re.DOTALL) + + for style_content in style_matches: + # Parse CSS rules (simplified) + rules = re.findall(r"\.(\w+)\s*\{([^}]+)\}", style_content) + for class_name, properties in rules: + styles[class_name] = self._parse_css_properties(properties) + + return styles + + def _parse_css_properties(self, css: str) -> Dict[str, str]: + """Parse CSS properties into dictionary""" + properties = {} + declarations = css.split(";") + + for declaration in declarations: + if ":" in declaration: + prop, value = declaration.split(":", 1) + properties[prop.strip().lower()] = value.strip() + + return properties + + def _apply_css_style(self, run, style: Dict): + """Apply CSS-style formatting""" + if "font-weight" in style and "bold" in style["font-weight"]: + run.font.bold = True + + if "font-style" in style and "italic" in style["font-style"]: + run.font.italic = True + + if "text-align" in style: + if "center" in style["text-align"]: + run.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER + elif "right" in style["text-align"]: + run.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.RIGHT + + if "color" in style: + color = self._parse_css_color(style["color"]) + if color: + run.font.color.rgb = color + + def _parse_css_color(self, color_str: str) -> RGBColor: + """Parse CSS color string to RGBColor""" + # Handle hex colors + hex_match = re.match( + r"#([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})", color_str + ) + if hex_match: + r, g, b = [int(x, 16) for x in hex_match.groups()] + return RGBColor(r, g, b) + + # Handle rgb() colors + rgb_match = re.match(r"rgb\((\d+),\s*(\d+),\s*(\d+)\)", color_str) + if rgb_match: + r, g, b = [int(x) for x in rgb_match.groups()] + return RGBColor(r, g, b) + + return None + + +# Usage examples and helper functions +def create_cv_from_html_template(): + """Create a CV using our HTML template""" + converter = AdvancedCVConverter() + + # Example usage + with open("/home/skye/Downloads/MWG-CV.html", "r") as f: + html_content = f.read() + + return converter.convert(html_content, "professional_cv.docx") + + +def main(): + """Main demonstration function""" + print("Custom HTML to DOCX Converter for CVs") + print("=====================================") + + # Example 2: Create from our CV template + create_cv_from_html_template() + print("✓ Professional CV created successfully!") + + print("\nLibrary features:") + print("- Custom HTML parsing optimized for CVs") + print("- Professional styling and formatting") + print("- List and bullet point support") + print("- Heading hierarchy") + print("- Basic CSS style support") + print("- Robust error handling") + + +if __name__ == "__main__": + main() diff --git a/filemac/core/html/core/__init__.py b/filemac/core/html/core/__init__.py new file mode 100644 index 0000000..29adda4 --- /dev/null +++ b/filemac/core/html/core/__init__.py @@ -0,0 +1,5 @@ +from .converter import HTML2Word +from .html_parser import HTMLParser +from .style_manager import StyleManager + +__all__ = ["HTML2Word", "HTMLParser", "StyleManager"] diff --git a/filemac/core/html/core/converter.py b/filemac/core/html/core/converter.py new file mode 100644 index 0000000..9da0745 --- /dev/null +++ b/filemac/core/html/core/converter.py @@ -0,0 +1,692 @@ +""" +Main converter class that orchestrates the HTML to DOCX conversion +""" + +import re +from pathlib import Path +from docx import Document +from docx.enum.text import WD_ALIGN_PARAGRAPH +from docx.oxml import parse_xml +from docx.oxml.ns import qn +from docx.shared import Inches +from typing import Dict, List +from docx.oxml import OxmlElement +from .html_parser import HTMLParser +from .style_manager import StyleManager +from ..utils.validation import validate_html, validate_file_path + + +class HTML2Word: + """Main converter class that coordinates HTML parsing and DOCX generation""" + + def __init__(self, default_font: str = "Calibri", default_size: int = 11): + self.doc = None + self.default_font = default_font + self.default_size = default_size + self.html_parser = HTMLParser() + self.style_manager = StyleManager(default_font, default_size) + + # Conversion state + self.current_paragraph = None + self.current_style = {} + self.tag_stack = [] + self.block_element = {} + + def __enter__(self): + self.block_element = self.html_parser.block_elements.copy().add("ol").add("ul") + + def convert(self, html_content: str, output_path: str) -> Document: + """ + Convert HTML content to DOCX document + + Args: + html_content: HTML string to convert + output_path: Path for output DOCX file + + Returns: + Document: The created Word document + """ + # Validate inputs + validate_html(html_content) + + output_path = ( + output_path.as_posix() if isinstance(output_path, Path) else output_path + ) + + validate_file_path(output_path, "output") + + # Initialize document + self.doc = Document() + self.style_manager.setup_document_styles(self.doc) + + # Parse HTML and extract styles + parsed_data = self.html_parser.parse(html_content) + + # Convert to DOCX + self._convert_elements(parsed_data["elements"], parsed_data["styles"]) + + # Save document + self.doc.save(output_path) + return self.doc + + def convert_file(self, html_file_path: str, output_path: str) -> Document: + """ + Convert HTML file to DOCX document + + Args: + html_file_path: Path to HTML file + output_path: Path for output DOCX file + + Returns: + Document: The created Word document + """ + validate_file_path(html_file_path, "input") + + with open(html_file_path, "r", encoding="utf-8") as f: + html_content = f.read() + + return self.convert(html_content, output_path) + + def _convert_elements(self, elements: List[Dict], styles: Dict): + """Convert parsed HTML elements to DOCX format""" + for element in elements: + self._convert_element(element, styles) + + def _convert_element(self, element: Dict, styles: Dict): + """Convert a single HTML element to DOCX""" + element_type = element["type"] + + if element_type == "text": + self._add_text_element(element, styles) + elif element_type == "element": + self._handle_html_element(element, styles) + + def _handle_html_element(self, element: Dict, styles: Dict): + """Handle HTML element based on tag type""" + tag_name = element["tag"].lower() + + # Push to stack for styling + self.tag_stack.append(element) + + is_block_element = tag_name in self.block_element + + try: + # For block elements, ensure we start a new paragraph context + if is_block_element and self.current_paragraph: + # Only start new paragraph if the current one has content + if self.current_paragraph.text.strip(): + self.current_paragraph = None + + # Check for grid/flex containers first + if tag_name in ("div", "section", "container"): + attributes = element.get("attributes", {}) + style_attr = attributes.get("style", "") + is_grid = "display:grid" in style_attr.replace(" ", "") + is_flex = "display:flex" in style_attr.replace(" ", "") + + if is_grid or is_flex: + self._handle_grid_container(element, styles) + else: + self._add_div(element, styles) + + elif tag_name in ["h1", "h2", "h3", "h4", "h5", "h6"]: + self._add_heading(element, styles) + elif tag_name == "p": + self._add_paragraph(element, styles) + elif tag_name == "table": + self._add_table(element, styles) + elif tag_name == "span": + self._add_span(element, styles) + elif tag_name == "br": + self._add_line_break() + elif tag_name == "hr": + self._add_horizontal_rule() + elif tag_name == "ul": + self._start_list(element, styles) + elif tag_name == "ol": + self._start_numbered_list(element, styles) + elif tag_name == "li": + self._add_list_item(element, styles) + elif tag_name == "strong" or tag_name == "b": + self._add_bold_text(element, styles) + elif tag_name == "em" or tag_name == "i": + self._add_italic_text(element, styles) + elif tag_name == "u": + self._add_underline_text(element, styles) + elif tag_name == "pre": + self._add_preformatted_text(element, styles) + elif tag_name == "tr": + self._add_table_row(element, styles) + elif tag_name == "td" or tag_name == "th": + self._add_table_cell(element, styles) + else: + # Process children for unknown tags + self._convert_elements(element.get("children", []), styles) + + finally: + # Always pop from stack + if self.tag_stack and self.tag_stack[-1] == element: + self.tag_stack.pop() + + # For block elements, ensure we clear the paragraph context after processing + if is_block_element: + self.current_paragraph = None + + def _add_preformatted_text(self, element: Dict, styles: Dict): + """Add preformatted text with preserved whitespace""" + if not self.current_paragraph: + self.current_paragraph = self.doc.add_paragraph() + + # Process all text content in pre tag + self._process_preformatted_content(element.get("children", []), styles) + self.current_paragraph = None + + def _process_preformatted_content(self, elements: List[Dict], styles: Dict): + """Process content for pre tags with preserved formatting""" + for element in elements: + if element["type"] == "text": + text = element.get("content", "") + if text: + # Preserve all whitespace in pre tags + run = self.current_paragraph.add_run(text) + self.style_manager.apply_styles_to_run(run, self.tag_stack, styles) + elif element["type"] == "element": + self._handle_html_element(element, styles) + + def _add_text_element(self, element: Dict, styles: Dict): + """Add text element with proper styling and line breaks""" + if not self.current_paragraph: + self.current_paragraph = self.doc.add_paragraph() + + text = element.get("content", "") + + # Handle text with line breaks + if "\n" in text: + lines = text.split("\n") + for i, line in enumerate(lines): + if line.strip(): # Only add non-empty lines + run = self.current_paragraph.add_run(line.strip()) + self.style_manager.apply_styles_to_run(run, self.tag_stack, styles) + + # Add line break except for the last line + if i < len(lines) - 1 and line.strip(): + self._add_line_break() + else: + # Single line of text + if text.strip(): + run = self.current_paragraph.add_run(text.strip()) + self.style_manager.apply_styles_to_run(run, self.tag_stack, styles) + + def _add_heading(self, element: Dict, styles: Dict): + """Add heading with appropriate level""" + level = element["tag"][1] # Extract number from h1, h2, etc. + self.current_paragraph = self.doc.add_paragraph() + + # Apply heading style + self.style_manager.apply_heading_style( + self.current_paragraph, level, element, styles + ) + + # Process children + self._convert_elements(element.get("children", []), styles) + + self.current_paragraph = None + + def _add_paragraph(self, element: Dict, styles: Dict): + """Add paragraph""" + self.current_paragraph = self.doc.add_paragraph() + self.style_manager.apply_paragraph_style( + self.current_paragraph, element, styles + ) + + # Process children + self._convert_elements(element.get("children", []), styles) + + self.current_paragraph = None + + def _add_div(self, element: Dict, styles: Dict): + """Add div element - ensure new paragraph for block-level elements""" + # For divs that contain block-level content, start a new paragraph + attributes = element.get("attributes", {}) + display_style = attributes.get("style", "") + try: + # Check for display: inline in styles + is_inline = "display:inline" in display_style + except AttributeError: + pass + + has_block_content = ( + any( + child.get("tag") in self.block_element + for child in element.get("children", []) + if child["type"] == "element" + ) + or is_inline + ) + + if has_block_content and self.current_paragraph: + self.current_paragraph = None + + self._convert_elements(element.get("children", []), styles) + + def _add_span(self, element: Dict, styles: Dict): + """Add span with inline styling""" + self._convert_elements(element.get("children", []), styles) + + def _add_line_break(self): + """Add a proper line break in Word document""" + if self.current_paragraph: + # Only add break if the paragraph has content + if self.current_paragraph.text.strip(): + self.current_paragraph.add_run().add_break() + else: + # If empty, add a space to maintain the break + self.current_paragraph.add_run(" ") + else: + # Create a new paragraph for the line break + self.current_paragraph = self.doc.add_paragraph() + self.current_paragraph.add_run(" ") + + # def _add_horizontal_rule(self): + """Add horizontal rule""" + # self.doc.add_paragraph().add_run("_" * 50) + + def _add_horizontal_rule(self): + """Add a proper horizontal rule/line""" + try: + # Create a new paragraph for the horizontal rule + hr_paragraph = self.doc.add_paragraph() + + # Add border to the paragraph to create the horizontal line + p_pr = hr_paragraph._p.get_or_add_pPr() + + # Create paragraph borders + p_borders = OxmlElement("w:pBdr") + + # Create bottom border for the horizontal line + bottom_border = OxmlElement("w:bottom") + bottom_border.set(qn("w:val"), "single") + bottom_border.set(qn("w:sz"), "6") # Line thickness (6 = 0.75 pt) + bottom_border.set(qn("w:space"), "1") # Spacing above the line + bottom_border.set(qn("w:color"), "auto") # Automatic color + + # Add the bottom border to the borders element + p_borders.append(bottom_border) + + # Add borders to paragraph properties + p_pr.append(p_borders) + + # Add some spacing after the horizontal rule + p_spacing = OxmlElement("w:spacing") + p_spacing.set(qn("w:after"), "120") # 120 twips = 6 points spacing after + p_pr.append(p_spacing) + + # Clear current paragraph context + self.current_paragraph = None + + except Exception as e: + # Fallback: create a simple horizontal line with underscores + fallback_paragraph = self.doc.add_paragraph() + fallback_paragraph.add_run("_" * 50) # Simple underscore line + self.current_paragraph = None + print(f"Horizontal rule fallback used: {e}") + + def _start_list(self, element: Dict, styles: Dict): + """Start unordered list""" + self._convert_elements(element.get("children", []), styles) + + def _start_numbered_list(self, element: Dict, styles: Dict): + """Start ordered list""" + self._convert_elements(element.get("children", []), styles) + + def _add_list_item(self, element: Dict, styles: Dict): + """Add list item""" + self.current_paragraph = self.doc.add_paragraph(style="List Bullet") + self._convert_elements(element.get("children", []), styles) + self.current_paragraph = None + + def _add_bold_text(self, element: Dict, styles: Dict): + """Add bold text""" + self._convert_elements(element.get("children", []), styles) + + def _add_italic_text(self, element: Dict, styles: Dict): + """Add italic text""" + self._convert_elements(element.get("children", []), styles) + + def _add_underline_text(self, element: Dict, styles: Dict): + """Add underline text""" + self._convert_elements(element.get("children", []), styles) + + # Table handling methods + def _add_table(self, element: Dict, styles: Dict): + """Create a new table""" + # Save current state + saved_paragraph = self.current_paragraph + + attributes = element.get("attributes", {}) + + # Calculate table dimensions + rows = self._count_table_rows(element) + cols = self._count_table_columns(element) + + try: + # Create table with calculated dimensions + if rows > 0 and cols > 0: + # Create table at current position + self.current_table = self.doc.add_table(rows=rows, cols=cols) + self.current_table.autofit = True + self.current_table.allow_autofit = True + + # Apply table styles + self._apply_table_styles(self.current_table, attributes, styles) + + # Reset row and cell counters + self.current_row_index = 0 + self.current_cell_index = 0 + + # Process table content + self._convert_elements(element.get("children", []), styles) + + # Clean up empty rows/cells if needed + self._cleanup_table() + + # Add a paragraph after the table for proper flow + self.current_paragraph = self.doc.add_paragraph() + + except Exception as e: + print(f"Table creation error: {e}") + # Fallback: add a simple paragraph + self.current_paragraph = self.doc.add_paragraph() + self.current_paragraph.add_run("[Table content]") + + finally: + # Restore or clear table context + self.current_table = None + # Restore paragraph context if it was saved + if saved_paragraph: + self.current_paragraph = saved_paragraph + + def _count_table_rows(self, table_element: Dict) -> int: + """Count the number of rows in the table""" + rows = 0 + for child in table_element.get("children", []): + if child.get("type") == "element" and child.get("tag", "").lower() == "tr": + rows += 1 + return max(rows, 1) # At least 1 row + + def _count_table_columns(self, table_element: Dict) -> int: + """Count the maximum number of columns in the table""" + max_cols = 0 + for child in table_element.get("children", []): + if child.get("type") == "element" and child.get("tag", "").lower() == "tr": + col_count = 0 + for cell in child.get("children", []): + if cell.get("type") == "element" and cell.get( + "tag", "" + ).lower() in [ + "td", + "th", + ]: + # Handle colspan + colspan = int(cell.get("attributes", {}).get("colspan", 1)) + col_count += colspan + max_cols = max(max_cols, col_count) + return max(max_cols, 1) # At least 1 column + + def _add_table_row(self, element: Dict, styles: Dict): + """Add a table row""" + if not self.current_table or self.current_row_index >= len( + self.current_table.rows + ): + return + + self.current_row = self.current_table.rows[self.current_row_index] + self.current_cell_index = 0 + + # Process row content + self._convert_elements(element.get("children", []), styles) + + self.current_row_index += 1 + self.current_row = None + + def _add_table_cell(self, element: Dict, styles: Dict): + """Add content to a table cell""" + if not self.current_row or self.current_cell_index >= len( + self.current_row.cells + ): + return + + cell = self.current_row.cells[self.current_cell_index] + tag_name = element.get("tag", "").lower() + attributes = element.get("attributes", {}) + + # Handle colspan and rowspan + colspan = int(attributes.get("colspan", 1)) + # rowspan = int(attributes.get("rowspan", 1)) + + # Apply cell styles + self._apply_cell_styles(cell, attributes, styles, tag_name == "th") + + # Save current paragraph context and switch to cell context + saved_paragraph = self.current_paragraph + self.current_paragraph = ( + cell.paragraphs[0] if cell.paragraphs else cell.add_paragraph() + ) + + # Process cell content + self._convert_elements(element.get("children", []), styles) + + # Restore paragraph context + self.current_paragraph = saved_paragraph + self.current_cell_index += colspan + + def _apply_table_styles(self, table, attributes: Dict, styles: Dict): + """Apply styles to the table""" + # Apply auto-fit by default + table.autofit = True + + # Apply specific width if provided + width_attr = attributes.get("width") or attributes.get("style", "") + if "width" in width_attr: + width_match = re.search(r"width:\s*(\d+)(px|%)", width_attr) + if width_match: + width_value = int(width_match.group(1)) + if width_match.group(2) == "%": + # Convert percentage to approximate width (Word doesn't support % directly) + table_width = Inches(6) # Approximate page width + width_value = int(table_width * width_value / 100) + # table.width = WidthDocx(width_value) # Would need proper width handling + + # Apply border styles + if "border" in attributes.get("style", ""): + self._apply_table_borders(table) + + def _apply_table_borders(self, table): + """Apply borders to table""" + try: + tbl = table._tbl + tblPr = tbl.tblPr + + # Add table borders + tblBorders = OxmlElement("w:tblBorders") + + for border_name in ["top", "left", "bottom", "right", "insideH", "insideV"]: + border = OxmlElement(f"w:{border_name}") + border.set(qn("w:val"), "single") + border.set(qn("w:sz"), "4") + border.set(qn("w:space"), "0") + border.set(qn("w:color"), "auto") + tblBorders.append(border) + + tblPr.append(tblBorders) + except Exception as e: + print(f"Table border styling failed: {e}") + + def _apply_cell_styles( + self, cell, attributes: Dict, styles: Dict, is_header: bool = False + ): + """Apply styles to table cell""" + # Set header styling + if is_header: + for paragraph in cell.paragraphs: + for run in paragraph.runs: + run.font.bold = True + + # Apply background color + bg_color = self._extract_background_color(attributes, styles) + if bg_color: + try: + shading_elm = parse_xml(f'') + cell._tc.get_or_add_tcPr().append(shading_elm) + except Exception: + pass + + # Apply text alignment + align = attributes.get("align") or self._extract_text_align(attributes, styles) + if align: + for paragraph in cell.paragraphs: + if align == "center": + paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER + elif align == "right": + paragraph.alignment = WD_ALIGN_PARAGRAPH.RIGHT + elif align == "justify": + paragraph.alignment = WD_ALIGN_PARAGRAPH.JUSTIFY + + def _extract_background_color(self, attributes: Dict, styles: Dict) -> str: + """Extract background color from attributes and styles""" + # Check inline style + style_attr = attributes.get("style", "") + bg_match = re.search(r"background-color:\s*(#[0-9a-fA-F]+|\w+)", style_attr) + if bg_match: + return bg_match.group(1) + + # Check class styles + class_attr = attributes.get("class", "") + if class_attr: + for class_name in class_attr.split(): + css_selector = f".{class_name}" + if ( + css_selector in styles + and "background-color" in styles[css_selector] + ): + return styles[css_selector]["background-color"] + + return None + + def _extract_text_align(self, attributes: Dict, styles: Dict) -> str: + """Extract text alignment from attributes and styles""" + # Check inline style + style_attr = attributes.get("style", "") + align_match = re.search(r"text-align:\s*(\w+)", style_attr) + if align_match: + return align_match.group(1) + + # Check class styles + class_attr = attributes.get("class", "") + if class_attr: + for class_name in class_attr.split(): + css_selector = f".{class_name}" + if css_selector in styles and "text-align" in styles[css_selector]: + return styles[css_selector]["text-align"] + + return None + + def _cleanup_table(self): + """Clean up empty table rows or cells""" + if not self.current_table: + return + + # Remove completely empty rows + rows_to_remove = [] + for i, row in enumerate(self.current_table.rows): + if all(cell.text.strip() == "" for cell in row.cells): + rows_to_remove.append(i) + + # Remove rows in reverse order to avoid index issues + for i in sorted(rows_to_remove, reverse=True): + try: + self.current_table._tbl.remove(self.current_table.rows[i]._tr) + except Exception: + pass + + def _handle_grid_container(self, element: Dict, styles: Dict): + """Handle grid container (simulate with table)""" + attributes = element.get("attributes", {}) + style_attr = attributes.get("style", "") + + # Check if this is a grid container + is_grid = "display:grid" in style_attr or "display: grid" in style_attr + is_flex = "display:flex" in style_attr or "display: flex" in style_attr + + if is_grid: + self._handle_css_grid(element, styles) + elif is_flex: + self._handle_flex_container(element, styles) + else: + self._convert_elements(element.get("children", []), styles) + + def _handle_css_grid(self, element: Dict, styles: Dict): + """Simulate CSS Grid with a table""" + attributes = element.get("attributes", {}) + style_attr = attributes.get("style", "") + + # Extract grid template columns + grid_cols = 1 + grid_template_match = re.search( + r"grid-template-columns:\s*(repeat\((\d+),\s*1fr\)|[\w\s\(\)]+)", style_attr + ) + if grid_template_match: + if "repeat" in grid_template_match.group(1): + grid_cols = int(grid_template_match.group(2)) + else: + # Count columns by splitting + cols = grid_template_match.group(1).split() + grid_cols = len(cols) + + # Count rows needed + children = [ + child + for child in element.get("children", []) + if child.get("type") == "element" + ] + grid_rows = (len(children) + grid_cols - 1) // grid_cols + + if grid_rows > 0 and grid_cols > 0: + # Create table to simulate grid + table = self.doc.add_table(rows=grid_rows, cols=grid_cols) + table.autofit = True + + # Fill table with grid items + child_index = 0 + for row in table.rows: + for cell in row.cells: + if child_index < len(children): + child = children[child_index] + # Process child element in cell + saved_paragraph = self.current_paragraph + self.current_paragraph = cell.paragraphs[0] + self._convert_element(child, styles) + self.current_paragraph = saved_paragraph + child_index += 1 + + def _handle_flex_container(self, element: Dict, styles: Dict): + """Handle flex container (simulate with table row)""" + attributes = element.get("attributes", {}) + + # Create a single-row table to simulate flex container + children = [ + child + for child in element.get("children", []) + if child.get("type") == "element" + ] + + if children: + table = self.doc.add_table(rows=1, cols=len(children)) + table.autofit = True + + for i, child in enumerate(children): + cell = table.rows[0].cells[i] + saved_paragraph = self.current_paragraph + self.current_paragraph = cell.paragraphs[0] + self._convert_element(child, styles) + self.current_paragraph = saved_paragraph diff --git a/filemac/core/html/core/html_parser.py b/filemac/core/html/core/html_parser.py new file mode 100644 index 0000000..58a6bfb --- /dev/null +++ b/filemac/core/html/core/html_parser.py @@ -0,0 +1,390 @@ +""" +HTML parsing functionality with CSS style extraction +""" + +import re +import html as html_parser +from typing import Dict, List, Any, Tuple +from ..utils.validation import validate_html + + +class HTMLParser: + """Advanced HTML parser with CSS style extraction""" + + def __init__(self): + self.styles = {} + self.prev_element = {} # Store previous element for line breaks + + # Block-level elements that should have automatic line breaks + self.block_elements = { + "div", + "p", + "h1", + "h2", + "h3", + "h4", + "h5", + "h6", + # "ul", + # "ol", + # "li", + "section", + "article", + "header", + "footer", + "nav", + "aside", + "main", + "figure", + "figcaption", + } + + def parse(self, html_content: str) -> Dict[str, Any]: + """ + Parse HTML content and extract structure and styles + + Returns: + Dict with 'elements' and 'styles' keys + """ + validate_html(html_content) + + # Clean HTML + cleaned_html = self._clean_html(html_content) + + # Extract CSS styles + self.styles = self._extract_styles(cleaned_html) + + # Remove style tags from content + content_html = self._remove_style_tags(cleaned_html) + + # Parse HTML structure + elements = self._parse_structure(content_html) + + return {"elements": elements, "styles": self.styles} + + def strip_comments(self, html): + # Remove HTML comments + html = re.sub(r"", "", html, flags=re.DOTALL) + + # Remove JS comments within blocks + html = re.sub( + r"(]*>)(.*?)()", + lambda m: m.group(1) + + re.sub(r"(?m)//.*?$|/\*.*?\*/", "", m.group(2), flags=re.DOTALL) + + m.group(3), + html, + flags=re.DOTALL | re.IGNORECASE, + ) + return html + + def _clean_html(self, html: str) -> str: + """Clean and normalize HTML content""" + # Remove + html = html.replace("", "") + html = html.replace("", "") + + # Remove comments + # html = re.sub(r"", "", html, flags=re.DOTALL) + # Remove js comments + # html = re.sub(r"(?m)//.*?$|/\*.*?\*/", "", html, flags=re.DOTALL) + html = self.strip_comments(html) + + # Preserve line breaks by replacing them with markers + html = re.sub(r"\n+", "", html) + # html = html.replace("-", "—") # Replace - with — + + # Remove title + html = re.sub( + r"]*>.*?", + "", + html, + flags=re.DOTALL | re.IGNORECASE, + ) + + # Remove multiple spaces but preserve single spaces + # html = re.sub(r"[ \t]+", " ", html) + + # Remove multiple spaces and newlines + html = re.sub(r"\s+", " ", html) + + # Ensure proper tag formatting + html = html.replace("
", "
").replace("
", "
") + + # Handle self-closing tags + html = re.sub(r"<(img|br|hr|input)([^>]*)(?", r"<\1\2/>", html) + + # Decode HTML entities + html = html_parser.unescape(html) + return html.strip() + + def _extract_styles(self, html: str) -> Dict[str, Dict]: + """Extract CSS styles from style tags and inline styles""" + styles = {} + + # Extract from style tags + style_matches = re.findall( + r"]*>(.*?)", html, re.DOTALL | re.IGNORECASE + ) + for style_content in style_matches: + styles.update(self._parse_css_rules(style_content)) + + return styles + + def _parse_css_rules(self, css_content: str) -> Dict[str, Dict]: + """Parse CSS rules into a dictionary""" + styles = {} + + # Remove comments + css_content = re.sub(r"/\*.*?\*/", "", css_content, flags=re.DOTALL) + + # Parse rules + rules = re.findall(r"([^{]+)\{([^}]+)\}", css_content) + + for selector, properties in rules: + selector = selector.strip() + style_dict = self._parse_css_properties(properties) + + if selector: + styles[selector] = style_dict + + return styles + + def _parse_css_properties(self, css_properties: str) -> Dict[str, str]: + """Parse CSS properties string into dictionary""" + properties = {} + declarations = [d.strip() for d in css_properties.split(";") if d.strip()] + + for declaration in declarations: + if ":" in declaration: + prop, value = declaration.split(":", 1) + prop = prop.strip().lower() + value = value.strip() + properties[prop] = value + + return properties + + def _remove_style_tags(self, html: str) -> str: + """Remove style tags from HTML""" + return re.sub( + r"]*>.*?", "", html, flags=re.DOTALL | re.IGNORECASE + ) + + def _parse_structure(self, html: str) -> List[Dict]: + """Parse HTML structure into a tree of elements and with automatic line breaks for block elements""" + tokens = self._tokenize_html(html) + elements, _ = self._build_element_tree(tokens) + return elements + + def _tokenize_html(self, html: str) -> List[Dict]: + """Tokenize HTML into tags and text while preserving line breaks""" + tokens = [] + pos = 0 + + # First, normalize line breaks and preserve them with markers + html = self._preserve_line_breaks(html) + + while pos < len(html): + # Find next tag + tag_match = re.search(r"]*)>", html[pos:]) + + if not tag_match: + # Add remaining text + if pos < len(html): + text_content = html[pos:] + text_content = self._restore_line_breaks(text_content) + if text_content.strip(): + tokens.append({"type": "text", "content": text_content}) + break + + tag_start = tag_match.start() + pos + tag_end = tag_match.end() + pos + + # Add text before tag + if tag_start > pos: + text_content = html[pos:tag_start] + text_content = self._restore_line_breaks(text_content) + if text_content.strip(): + tokens.append({"type": "text", "content": text_content}) + + # Extract tag information + full_tag = html[tag_start:tag_end] + tag_name = tag_match.group(1).lower() + attributes = self._parse_attributes(tag_match.group(2)) + is_closing = full_tag.startswith("") + + current_element = { + "type": "tag", + "name": tag_name, + "full_tag": full_tag, + "attributes": attributes, + "is_closing": is_closing, + "is_self_closing": is_self_closing, + } + + # Add automatic line break logic + self._add_auto_line_break(tokens, current_element) + + tokens.append(current_element) + self.prev_element = current_element + pos = tag_end + + return tokens + + def _add_auto_line_break(self, tokens: List[Dict], current_element: Dict): + """Automatically add line breaks between block elements when needed""" + if not self.prev_element: + return + + prev_name = self.prev_element.get("name", "") + current_name = current_element.get("name", "") + prev_is_closing = self.prev_element.get("is_closing", False) + current_is_closing = current_element.get("is_closing", False) + + # Case 1: Closing block element followed by another block element + if ( + prev_is_closing + and prev_name in self.block_elements + and not current_is_closing + and current_name in self.block_elements + ): + # Add line break between block elements + line_break = { + "type": "tag", + "name": "br", + "full_tag": "
", + "attributes": {}, + "is_closing": False, + "is_self_closing": True, + } + tokens.append(line_break) + self.prev_element = line_break + + # Case 2: Closing block element followed by text (content within same block) + elif ( + prev_is_closing + and prev_name in self.block_elements + and current_element["type"] == "text" + and current_element.get("content", "").strip() + ): + # This handles content that should be on new lines within the same block + line_break = { + "type": "tag", + "name": "br", + "full_tag": "
", + "attributes": {}, + "is_closing": False, + "is_self_closing": True, + } + tokens.append(line_break) + self.prev_element = line_break + + # Case 3: Text followed by opening block element + elif ( + self.prev_element["type"] == "text" + and not current_is_closing + and current_name in self.block_elements + ): + # Add line break before new block element + line_break = { + "type": "tag", + "name": "br", + "full_tag": "
", + "attributes": {}, + "is_closing": False, + "is_self_closing": True, + } + tokens.append(line_break) + self.prev_element = line_break + + def _preserve_line_breaks(self, html: str) -> str: + """Preserve line breaks by converting them to markers""" + # Replace line breaks with a unique marker that won't interfere with HTML parsing + html = html.replace("\r\n", "\n") # Normalize Windows line endings + html = html.replace("\r", "\n") # Normalize Mac line endings + + # Use a unique marker that won't appear in normal text + html = html.replace("\n", "⏎") # Using a special character as marker + return html + + def _restore_line_breaks(self, text: str) -> str: + """Restore line breaks from markers""" + return text.replace("⏎", "\n") + + def _parse_attributes(self, attribute_string: str) -> Dict[str, str]: + """Parse HTML attributes string into dictionary""" + attributes = {} + + # Find all attribute=value pairs + pattern = r'(\w+)\s*=\s*["\']([^"\']*)["\']' + matches = re.findall(pattern, attribute_string) + + for key, value in matches: + attributes[key.lower()] = value + + # Also look for boolean attributes + boolean_attrs = re.findall(r"(\w+)(?=\s+|>)", attribute_string) + for attr in boolean_attrs: + if attr.lower() not in attributes: + attributes[attr.lower()] = "true" + + return attributes + + def _add_multiple_line_breaks(self, count: int): + """Add multiple line breaks""" + if count <= 0: + return + + for i in range(count): + self._add_line_break() + + def _build_element_tree( + self, tokens: List[Dict], start_index: int = 0 + ) -> Tuple[List[Dict], int]: + """Build a tree structure from tokens""" + elements = [] + i = start_index + + while i < len(tokens): + token = tokens[i] + + if token["type"] == "text": + elements.append({"type": "text", "content": token["content"]}) + i += 1 + + elif token["type"] == "tag": + if token["is_closing"]: + # Return when we hit a closing tag + return elements, i + 1 + + elif token["is_self_closing"]: + # Self-closing tag - add as element with no children + elements.append( + { + "type": "element", + "tag": token["name"], + "attributes": token["attributes"], + "children": [], + } + ) + i += 1 + + else: + # Opening tag - recursively process children + child_elements, next_index = self._build_element_tree(tokens, i + 1) + + elements.append( + { + "type": "element", + "tag": token["name"], + "attributes": token["attributes"], + "children": child_elements, + } + ) + + i = next_index + + else: + i += 1 + + return elements, i diff --git a/filemac/core/html/core/style_manager.py b/filemac/core/html/core/style_manager.py new file mode 100644 index 0000000..3c476dc --- /dev/null +++ b/filemac/core/html/core/style_manager.py @@ -0,0 +1,311 @@ +""" +Style management and application for DOCX elements +""" + +from docx import Document +from docx.shared import Pt, Inches, RGBColor +from docx.enum.text import WD_ALIGN_PARAGRAPH, WD_LINE_SPACING +from docx.oxml.ns import qn +from typing import Dict, List, Any +import re + +from ..utils.color_utils import ColorConverter + + +class StyleManager: + """Manages styles and applies them to DOCX elements""" + + def __init__(self, default_font: str = "Calibri", default_size: int = 11): + self.default_font = default_font + self.default_size = default_size + self.color_converter = ColorConverter() + + # Style mappings + self.heading_styles = { + "1": {"size": 16, "bold": True, "alignment": WD_ALIGN_PARAGRAPH.CENTER}, + "2": {"size": 14, "bold": True, "alignment": WD_ALIGN_PARAGRAPH.LEFT}, + "3": {"size": 12, "bold": True, "alignment": WD_ALIGN_PARAGRAPH.LEFT}, + "4": {"size": 11, "bold": True, "alignment": WD_ALIGN_PARAGRAPH.LEFT}, + "5": {"size": 11, "bold": True, "alignment": WD_ALIGN_PARAGRAPH.LEFT}, + "6": {"size": 11, "bold": True, "alignment": WD_ALIGN_PARAGRAPH.LEFT}, + } + + def setup_document_styles(self, doc: Document): + """Setup default document styles""" + # Set normal style + style = doc.styles["Normal"] + font = style.font + font.name = self.default_font + font.size = Pt(self.default_size) + + # Create custom styles + self._create_cv_styles(doc) + + def _create_cv_styles(self, doc: Document): + """Create custom styles for CV""" + styles_config = { + "Title": { + "size": 16, + "bold": True, + "alignment": WD_ALIGN_PARAGRAPH.CENTER, + }, + "Heading": { + "size": 14, + "bold": True, + "alignment": WD_ALIGN_PARAGRAPH.LEFT, + }, + "Subheading": { + "size": 12, + "bold": True, + "alignment": WD_ALIGN_PARAGRAPH.LEFT, + }, + "Contact": { + "size": 10, + "bold": False, + "alignment": WD_ALIGN_PARAGRAPH.CENTER, + }, + } + + for style_name, config in styles_config.items(): + try: + style = doc.styles.add_style(style_name, 1) # WD_STYLE_TYPE.PARAGRAPH + font = style.font + font.name = self.default_font + font.size = Pt(config["size"]) + font.bold = config["bold"] + style.paragraph_format.alignment = config["alignment"] + except ValueError: + # Style might already exist + pass + + def apply_styles_to_run(self, run, tag_stack: List[Dict], styles: Dict): + """Apply styles to a text run based on tag stack and CSS styles""" + # Apply basic font + run.font.name = self.default_font + run.font.size = Pt(self.default_size) + + # Apply styles from tag stack and CSS + self._apply_inline_styles(run, tag_stack, styles) + self._apply_css_styles(run, tag_stack, styles) + + def _apply_inline_styles(self, run, tag_stack: List[Dict], styles: Dict): + """Apply inline styles from HTML attributes""" + for element in tag_stack: + if element.get("type") == "element": + attributes = element.get("attributes", {}) + style_attr = attributes.get("style", "") + + if style_attr: + self._apply_style_attribute(run, style_attr) + + def _apply_css_styles(self, run, tag_stack: List[Dict], styles: Dict): + """Apply CSS styles from style definitions""" + for element in tag_stack: + if element.get("type") == "element": + tag_name = element.get("tag", "") + attributes = element.get("attributes", {}) + + # Check for class-based styles + class_attr = attributes.get("class", "") + if class_attr: + for class_name in class_attr.split(): + css_selector = f".{class_name}" + if css_selector in styles: + self._apply_css_properties(run, styles[css_selector]) + + # Check for tag-based styles + tag_selector = tag_name + if tag_selector in styles: + self._apply_css_properties(run, styles[tag_selector]) + + def _apply_style_attribute(self, run, style_attr: str): + """Apply style attribute to run""" + properties = self._parse_style_attribute(style_attr) + self._apply_css_properties(run, properties) + + def _parse_style_attribute(self, style_attr: str) -> Dict[str, str]: + """Parse style attribute string into properties dictionary""" + properties = {} + declarations = [d.strip() for d in style_attr.split(";") if d.strip()] + + for declaration in declarations: + if ":" in declaration: + prop, value = declaration.split(":", 1) + properties[prop.strip().lower()] = value.strip() + + return properties + + def _apply_css_properties(self, run, properties: Dict[str, str]): + """Apply CSS properties to a run""" + for prop, value in properties.items(): + try: + if prop == "font-weight": + if value in ["bold", "bolder", "700", "800", "900"]: + run.font.bold = True + + elif prop == "font-style": + if value == "italic": + run.font.italic = True + + elif prop == "text-decoration": + if "underline" in value: + run.font.underline = True + + elif prop == "color": + color = self.color_converter.parse_color(value) + if color: + run.font.color.rgb = color + + elif prop == "font-size": + size = self._parse_font_size(value) + if size: + run.font.size = Pt(size) + + elif prop == "font-family": + run.font.name = value.split(",")[0].strip().strip("\"'") + + elif prop == "background-color": + # Word doesn't directly support background color for text runs + # This would require more complex handling with shading + pass + + except Exception: + # Continue with other properties if one fails + continue + + def _parse_font_size(self, size_str: str) -> float: + """Parse font size string to points""" + try: + # Handle pixel values (approximate conversion: 1px ≈ 0.75pt) + if "px" in size_str: + return float(size_str.replace("px", "").strip()) * 0.75 + + # Handle point values + elif "pt" in size_str: + return float(size_str.replace("pt", "").strip()) + + # Handle em values (approximate) + elif "em" in size_str: + return float(size_str.replace("em", "").strip()) * self.default_size + + # Handle percentage + elif "%" in size_str: + return ( + float(size_str.replace("%", "").strip()) / 100 + ) * self.default_size + + # Handle named sizes + elif size_str in ["xx-small", "x-small", "small", "medium"]: + return self.default_size + elif size_str == "large": + return self.default_size * 1.2 + elif size_str == "x-large": + return self.default_size * 1.5 + elif size_str == "xx-large": + return self.default_size * 2 + + # Assume points if no unit + else: + return float(size_str) + + except (ValueError, TypeError): + return None + + def apply_heading_style(self, paragraph, level: str, element: Dict, styles: Dict): + """Apply heading style to paragraph""" + # Apply basic heading style + if level in self.heading_styles: + config = self.heading_styles[level] + paragraph.style = self._get_heading_style_name(level) + + # Apply additional CSS styles + self._apply_paragraph_css_styles(paragraph, element, styles) + + def apply_paragraph_style(self, paragraph, element: Dict, styles: Dict): + """Apply styles to paragraph""" + self._apply_paragraph_css_styles(paragraph, element, styles) + + def _apply_paragraph_css_styles(self, paragraph, element: Dict, styles: Dict): + """Apply CSS styles to paragraph""" + attributes = element.get("attributes", {}) + + # Check for inline styles + style_attr = attributes.get("style", "") + if style_attr: + properties = self._parse_style_attribute(style_attr) + self._apply_paragraph_css_properties(paragraph, properties) + + # Check for class-based styles + class_attr = attributes.get("class", "") + if class_attr: + for class_name in class_attr.split(): + css_selector = f".{class_name}" + if css_selector in styles: + self._apply_paragraph_css_properties( + paragraph, styles[css_selector] + ) + + def _apply_paragraph_css_properties(self, paragraph, properties: Dict[str, str]): + """Apply CSS properties to paragraph""" + for prop, value in properties.items(): + try: + if prop == "text-align": + if value == "center": + paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER + elif value == "right": + paragraph.alignment = WD_ALIGN_PARAGRAPH.RIGHT + elif value == "justify": + paragraph.alignment = WD_ALIGN_PARAGRAPH.JUSTIFY + else: + paragraph.alignment = WD_ALIGN_PARAGRAPH.LEFT + + elif prop == "margin" or prop == "margin-top": + # Convert margin to spacing + margin = self._parse_size_value(value) + if margin: + paragraph.paragraph_format.space_after = Pt(margin) + + elif prop == "margin-bottom": + margin = self._parse_size_value(value) + if margin: + paragraph.paragraph_format.space_after = Pt(margin) + + elif prop == "line-height": + if value == "normal": + paragraph.paragraph_format.line_spacing_rule = ( + WD_LINE_SPACING.SINGLE + ) + else: + try: + line_height = float(value) + paragraph.paragraph_format.line_spacing = line_height + except ValueError: + pass + + except Exception: + continue + + def _parse_size_value(self, size_str: str) -> float: + """Parse size value to points""" + try: + if "px" in size_str: + return float(size_str.replace("px", "").strip()) * 0.75 + elif "pt" in size_str: + return float(size_str.replace("pt", "").strip()) + elif "em" in size_str: + return float(size_str.replace("em", "").strip()) * self.default_size + else: + return float(size_str) + except (ValueError, TypeError): + return None + + def _get_heading_style_name(self, level: str) -> str: + """Get appropriate style name for heading level""" + if level == "1": + return "Title" + elif level == "2": + return "Heading" + elif level == "3": + return "Subheading" + else: + return "Normal" diff --git a/filemac/core/html/examples/__init__.py b/filemac/core/html/examples/__init__.py new file mode 100644 index 0000000..5c612b4 --- /dev/null +++ b/filemac/core/html/examples/__init__.py @@ -0,0 +1,3 @@ +from .cv_templates import CVTemplates + +__all__ = ["CVTemplates"] diff --git a/filemac/core/html/examples/templates.py b/filemac/core/html/examples/templates.py new file mode 100644 index 0000000..d4e3261 --- /dev/null +++ b/filemac/core/html/examples/templates.py @@ -0,0 +1,228 @@ +""" +Example CV templates for testing and demonstration +""" + + +class Templates: + """Collection of CV HTML templates""" + + @staticmethod + def get_basic_cv(): + """Get basic CV template""" + return """ + + + + + + +
+

MWANGANGI KALOVWE

+
+ Phone: 0769330481 | Email: kalovwemwangangi18@gmail.com
+ Address: Kabati, Mutonguni Ward, Kitui County | Postal: 9-90203, Tulia +
+
+ +
+
PROFESSIONAL SUMMARY
+

Detail-oriented Electrical and Electronics Technician with specialized training in power systems and hands-on experience in geothermal power plant operations. Skilled in electrical system maintenance, troubleshooting, and circuit analysis.

+
+ +
+
EDUCATION
+

+ 2021 - 2024
+ Ikutha Technical and Vocational College
+ Diploma in Electrical and Electronics (Power Option)
+ Completed: April 3, 2024 +

+
+ +
+
PROFESSIONAL EXPERIENCE
+

+ May 2023 - July 2023
+ KenGen - Olkaria Geothermal Power Plants
+ Electrical Maintenance Intern +

+
    +
  • Performed maintenance of electrical systems and power distribution equipment
  • +
  • Maintained turbine generators and auxiliary systems
  • +
  • Conducted battery maintenance and testing
  • +
+
+ + + """ + + @staticmethod + def get_advanced_template(): + """Get advanced template with more styling""" + return """ + + + + + + +
+
MWANGANGI KALOVWE
+
+ 📞 0769330481 | ✉️ kalovwemwangangi18@gmail.com
+ 📍 Kabati, Mutonguni Ward, Kitui County | 📮 9-90203, Tulia +
+
+ +
+
Professional Summary
+

+ Detail-oriented Electrical and Electronics Technician with specialized training in power systems + and hands-on experience in geothermal power plant operations. Skilled in electrical system maintenance, + troubleshooting, and circuit analysis. Seeking to leverage technical expertise and problem-solving + abilities in a challenging electrical engineering role. +

+
+ +
+
Education
+ +
+
2021 - 2024
+
Ikutha Technical and Vocational College
+
Diploma in Electrical and Electronics (Power Option)
+
Completed: April 3, 2024
+
+ +
+
January 2016 - November 2019
+
Kea Secondary School
+
Kenya Certificate of Secondary Education (KCSE)
+
Mean Grade: C- (Minus)
+
+
+ +
+
Technical Skills
+
+
Electrical System Maintenance
+
Power System Operations
+
Circuit Analysis
+
PLC Programming
+
Solar Installation
+
Transformer Maintenance
+
Battery Systems
+
Technical Reporting
+
+
+ + + """ diff --git a/filemac/core/html/styles/__init__.py b/filemac/core/html/styles/__init__.py new file mode 100644 index 0000000..208878b --- /dev/null +++ b/filemac/core/html/styles/__init__.py @@ -0,0 +1,4 @@ +from .css_parser import CSSParser +from .style_applier import StyleApplier + +__all__ = ["CSSParser", "StyleApplier"] diff --git a/filemac/core/html/styles/css_parser.py b/filemac/core/html/styles/css_parser.py new file mode 100644 index 0000000..cbbffda --- /dev/null +++ b/filemac/core/html/styles/css_parser.py @@ -0,0 +1,69 @@ +""" +Advanced CSS parsing functionality +""" + +import re +from typing import Dict, List + + +class CSSParser: + """Advanced CSS parser with support for various CSS features""" + + def __init__(self): + self.styles = {} + + def parse_css(self, css_content: str) -> Dict[str, Dict]: + """Parse CSS content into style dictionary""" + # Remove comments + css_content = re.sub(r"/\*.*?\*/", "", css_content, flags=re.DOTALL) + + # Parse rules + rules = re.findall(r"([^{]+)\{([^}]+)\}", css_content) + + for selector, properties in rules: + selector = selector.strip() + style_dict = self._parse_properties(properties) + + if selector: + self.styles[selector] = style_dict + + return self.styles + + def _parse_properties(self, properties: str) -> Dict[str, str]: + """Parse CSS properties string""" + style_dict = {} + declarations = [d.strip() for d in properties.split(";") if d.strip()] + + for declaration in declarations: + if ":" in declaration: + prop, value = declaration.split(":", 1) + prop = prop.strip().lower() + value = value.strip() + style_dict[prop] = value + + return style_dict + + def get_styles_for_element( + self, tag: str, classes: List[str] = None, element_id: str = None + ) -> Dict[str, str]: + """Get combined styles for an element based on tag, classes, and ID""" + combined_styles = {} + + # Tag styles + if tag in self.styles: + combined_styles.update(self.styles[tag]) + + # Class styles + if classes: + for class_name in classes: + class_selector = f".{class_name}" + if class_selector in self.styles: + combined_styles.update(self.styles[class_selector]) + + # ID styles + if element_id: + id_selector = f"#{element_id}" + if id_selector in self.styles: + combined_styles.update(self.styles[id_selector]) + + return combined_styles diff --git a/filemac/core/html/styles/style_applier.py b/filemac/core/html/styles/style_applier.py new file mode 100644 index 0000000..feb7bb6 --- /dev/null +++ b/filemac/core/html/styles/style_applier.py @@ -0,0 +1,83 @@ +""" +Style application logic for different CSS properties +""" + +from docx.shared import Pt, RGBColor +from docx.enum.text import WD_ALIGN_PARAGRAPH +from typing import Dict +import re + +from ..utils.color_utils import ColorConverter + + +class StyleApplier: + """Applies CSS styles to DOCX elements""" + + def __init__(self): + self.color_converter = ColorConverter() + + def apply_text_styles(self, run, styles: Dict[str, str]): + """Apply text-related styles to a run""" + for prop, value in styles.items(): + self._apply_text_style(run, prop, value) + + def _apply_text_style(self, run, prop: str, value: str): + """Apply a single text style property""" + try: + if prop == "color": + color = self.color_converter.parse_color(value) + if color: + run.font.color.rgb = color + + elif prop == "font-size": + size = self._parse_font_size(value) + if size: + run.font.size = Pt(size) + + elif prop == "font-family": + run.font.name = value.split(",")[0].strip().strip("\"'") + + elif prop == "font-weight": + if value in ["bold", "bolder", "700", "800", "900"]: + run.font.bold = True + elif value in ["normal", "lighter", "400"]: + run.font.bold = False + + elif prop == "font-style": + if value == "italic": + run.font.italic = True + elif value == "normal": + run.font.italic = False + + elif prop == "text-decoration": + if "underline" in value: + run.font.underline = True + if "line-through" in value: + run.font.strike = True + + elif prop == "text-transform": + if value == "uppercase": + run.text = run.text.upper() + elif value == "lowercase": + run.text = run.text.lower() + elif value == "capitalize": + run.text = run.text.title() + + except Exception: + pass + + def _parse_font_size(self, size_str: str) -> float: + """Parse font size to points""" + try: + if "px" in size_str: + return float(size_str.replace("px", "").strip()) * 0.75 + elif "pt" in size_str: + return float(size_str.replace("pt", "").strip()) + elif "em" in size_str: + return float(size_str.replace("em", "").strip()) * 11 # Default size + elif "%" in size_str: + return (float(size_str.replace("%", "").strip()) / 100) * 11 + else: + return float(size_str) + except (ValueError, TypeError): + return None diff --git a/filemac/core/html/tests.py b/filemac/core/html/tests.py new file mode 100644 index 0000000..92b4488 --- /dev/null +++ b/filemac/core/html/tests.py @@ -0,0 +1,82 @@ +#!/usr/bin/env python3 +""" +Test script for the CV Converter library +""" + +import os +import sys + +# Add the library to path +sys.path.insert(0, os.path.join(os.path.dirname(__file__), "cv_converter")) + +from filemac.core.html import HTML2Word +from filemac.core.html.examples.templates import Templates + + +def test_basic_conversion(): + """Test basic conversion""" + print("Testing basic CV conversion...") + + converter = HTML2Word() + html_content = Templates.get_basic_template() + + converter.convert(html_content, "test_basic_cv.docx") + print("✓ Basic CV created: test_basic_cv.docx") + + +def test_advanced_conversion(): + """Test advanced conversion with styling""" + print("Testing advanced CV conversion...") + + converter = HTML2Word() + html_content = Templates.get_advanced_cv() + + converter.convert(html_content, "test_advanced_cv.docx") + print("✓ Advanced CV created: test_advanced_cv.docx") + + +def test_file_conversion(): + """Test conversion from HTML file""" + print("Testing file-based conversion...") + + # Create test HTML file + with open("test_cv.html", "w", encoding="utf-8") as f: + f.write(Templates.get_basic_template()) + + converter = HTML2Word() + converter.convert_file("test_cv.html", "test_file_cv.docx") + print("✓ File-based CV created: test_file_cv.docx") + + +def main(): + """Run all tests""" + print("CV Converter Library Test Suite") + print("=" * 40) + + try: + test_basic_conversion() + test_advanced_conversion() + test_file_conversion() + + print("\n" + "=" * 40) + print("All tests completed successfully! 🎉") + print("\nGenerated files:") + for file in [ + "test_basic_cv.docx", + "test_advanced_cv.docx", + "test_file_cv.docx", + ]: + if os.path.exists(file): + print(f" - {file}") + + except Exception as e: + print(f"\n❌ Error during testing: {e}") + import traceback + + traceback.print_exc() + + +if __name__ == "__main__": + # main() + converter = HTML2Word() + converter.convert_file("/home/skye/Downloads/MWG-CV.html", "test.docx") diff --git a/filemac/core/html/utils/__init__.py b/filemac/core/html/utils/__init__.py new file mode 100644 index 0000000..d779482 --- /dev/null +++ b/filemac/core/html/utils/__init__.py @@ -0,0 +1,9 @@ +from .color_utils import ColorConverter +from .validation import validate_css, validate_html, validate_file_path + +__all__ = [ + "ColorConverter", + "validate_css", + "validate_html", + "validate_file_path", +] diff --git a/filemac/core/html/utils/color_utils.py b/filemac/core/html/utils/color_utils.py new file mode 100644 index 0000000..a13d09c --- /dev/null +++ b/filemac/core/html/utils/color_utils.py @@ -0,0 +1,121 @@ +""" +Color conversion and parsing utilities +""" + +import re +from docx.shared import RGBColor +from typing import Optional + + +class ColorConverter: + """Converts various color formats to RGBColor""" + + def __init__(self): + self.named_colors = { + "black": RGBColor(0, 0, 0), + "white": RGBColor(255, 255, 255), + "red": RGBColor(255, 0, 0), + "green": RGBColor(0, 128, 0), + "blue": RGBColor(0, 0, 255), + "yellow": RGBColor(255, 255, 0), + "cyan": RGBColor(0, 255, 255), + "magenta": RGBColor(255, 0, 255), + "gray": RGBColor(128, 128, 128), + "grey": RGBColor(128, 128, 128), + "orange": RGBColor(255, 165, 0), + "purple": RGBColor(128, 0, 128), + "brown": RGBColor(165, 42, 42), + "pink": RGBColor(255, 192, 203), + "navy": RGBColor(0, 0, 128), + "teal": RGBColor(0, 128, 128), + "olive": RGBColor(128, 128, 0), + "maroon": RGBColor(128, 0, 0), + "silver": RGBColor(192, 192, 192), + "lime": RGBColor(0, 255, 0), + "aqua": RGBColor(0, 255, 255), + "fuchsia": RGBColor(255, 0, 255), + } + + def parse_color(self, color_str: str) -> Optional[RGBColor]: + """ + Parse color string and return RGBColor + + Supports: + - Hex: #RRGGBB, #RGB + - RGB: rgb(r, g, b) + - RGBA: rgba(r, g, b, a) - alpha ignored + - Named colors: red, blue, etc. + """ + if not color_str: + return None + + color_str = color_str.strip().lower() + + # Named colors + if color_str in self.named_colors: + return self.named_colors[color_str] + + # Hex colors + hex_match = re.match(r"#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})", color_str) + if hex_match: + r, g, b = [int(x, 16) for x in hex_match.groups()] + return RGBColor(r, g, b) + + # Short hex colors + short_hex_match = re.match(r"#([0-9a-f])([0-9a-f])([0-9a-f])", color_str) + if short_hex_match: + r, g, b = [int(x * 2, 16) for x in short_hex_match.groups()] + return RGBColor(r, g, b) + + # RGB colors + rgb_match = re.match(r"rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)", color_str) + if rgb_match: + r, g, b = [int(x) for x in rgb_match.groups()] + return RGBColor(r, g, b) + + # RGBA colors (ignore alpha) + rgba_match = re.match( + r"rgba\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*[\d.]+\s*\)", color_str + ) + if rgba_match: + r, g, b = [int(x) for x in rgba_match.groups()[:3]] + return RGBColor(r, g, b) + + # HSL colors (basic conversion) + hsl_match = re.match(r"hsl\(\s*(\d+)\s*,\s*(\d+)%\s*,\s*(\d+)%\s*\)", color_str) + if hsl_match: + h, s, l = [int(x) for x in hsl_match.groups()] + return self._hsl_to_rgb(h, s, l) + + return None + + def _hsl_to_rgb(self, h: int, s: int, l: int) -> RGBColor: + """Convert HSL color to RGB (simplified)""" + # Normalize values + h = h % 360 + s = max(0, min(100, s)) / 100 + l = max(0, min(100, l)) / 100 + + # Simplified conversion + c = (1 - abs(2 * l - 1)) * s + x = c * (1 - abs((h / 60) % 2 - 1)) + m = l - c / 2 + + if 0 <= h < 60: + r, g, b = c, x, 0 + elif 60 <= h < 120: + r, g, b = x, c, 0 + elif 120 <= h < 180: + r, g, b = 0, c, x + elif 180 <= h < 240: + r, g, b = 0, x, c + elif 240 <= h < 300: + r, g, b = x, 0, c + else: + r, g, b = c, 0, x + + r = int((r + m) * 255) + g = int((g + m) * 255) + b = int((b + m) * 255) + + return RGBColor(r, g, b) diff --git a/filemac/core/html/utils/validation.py b/filemac/core/html/utils/validation.py new file mode 100644 index 0000000..4a0d2d6 --- /dev/null +++ b/filemac/core/html/utils/validation.py @@ -0,0 +1,93 @@ +""" +Validation utilities for the converter +""" + +import os +import re +from pathlib import Path + + +def validate_html(html_content: str) -> bool: + """ + Validate HTML content + + Args: + html_content: HTML string to validate + + Returns: + bool: True if valid + + Raises: + ValueError: If HTML content is invalid + """ + if not html_content or not isinstance(html_content, str): + raise ValueError("HTML content must be a non-empty string") + + if len(html_content.strip()) == 0: + raise ValueError("HTML content cannot be empty or whitespace only") + + # Basic check for HTML tags + if not re.search(r"<[^>]+>", html_content): + raise ValueError("HTML content must contain valid HTML tags") + + return True + + +def validate_file_path(file_path: str, file_type: str = "input") -> bool: + """ + Validate file path + + Args: + file_path: Path to validate + file_type: Type of file ('input' or 'output') + + Returns: + bool: True if valid + + Raises: + ValueError: If file path is invalid + FileNotFoundError: If input file doesn't exist + """ + if ( + not file_path + or not isinstance(file_path, str) + and not isinstance(file_path, Path) + ): + raise ValueError(f"{file_type} file path must be a non-empty string") + + if file_type == "input": + if not os.path.exists(file_path): + raise FileNotFoundError(f"Input file not found: {file_path}") + + if not os.path.isfile(file_path): + raise ValueError(f"Input path is not a file: {file_path}") + + elif file_type == "output": + output_dir = os.path.dirname(file_path) + if output_dir and not os.path.exists(output_dir): + try: + os.makedirs(output_dir) + except OSError as e: + raise ValueError(f"Cannot create output directory: {e}") + + # Check file extension + if not file_path.lower().endswith((".html", ".htm", ".docx")): + raise ValueError(f"File must have .html, .htm, or .docx extension: {file_path}") + + return True + + +def validate_css(css_content: str) -> bool: + """ + Validate CSS content + + Args: + css_content: CSS string to validate + + Returns: + bool: True if valid + """ + if not css_content or not isinstance(css_content, str): + raise ValueError("CSS content must be a non-empty string") + + return True diff --git a/filemac/core/image/core.py b/filemac/core/image/core.py new file mode 100644 index 0000000..fdb5ce5 --- /dev/null +++ b/filemac/core/image/core.py @@ -0,0 +1,783 @@ +import shutil +from reportlab.pdfgen import canvas +from reportlab.lib.pagesizes import letter +import re +from pathlib import Path +from docx.shared import Inches, Mm +from docx import Document +import os +import sys +from tqdm import tqdm +from PIL import Image +import cv2 +from typing import List, Tuple, Union, Optional +from ...utils.simple import logger +from ...utils.decorators import Decorators +from ...utils.formats import SUPPORTED_IMAGE_FORMATS +from ...utils.file_utils import modify_filename_if_exists, DirectoryScanner +from ...utils.colors import fg, rs + +RESET = rs + + +class ImageCompressor: + def __init__(self, input_image_path): + self.input_image_path = input_image_path + + def resize_image(self, target_size): + try: + input_image_path = self.input_image_path + ext = input_image_path[-3:] + output_image_path = ( + os.path.splitext(input_image_path)[0] + f"_resized.{ext}" + ) + + original_image = Image.open(input_image_path) + original_size = original_image.size + size = os.path.getsize(input_image_path) + print(f"Original image size {fg.YELLOW}{size / 1000_000:.2f}MiB{RESET}") + + # Calculate the aspect ratio of the original image + aspect_ratio = original_size[0] / original_size[1] + + # Convert the target sixze to bytes + tz = int(target_size[:-2]) + if target_size[-2:].lower() == "mb": + target_size_bytes = tz * 1024 * 1024 + elif target_size[-2:].lower() == "kb": + target_size_bytes = tz * 1024 + else: + logger.warning( + f"Invalid units. Please use either {fg.BMAGENTA}'MB'{RESET}\ + or {fg.BMAGENTA}'KB'{RESET}" + ) + + # Calculate the new dimensions based on the target size + new_width, new_height = ImageCompressor.calculate_new_dimensions( + original_size, aspect_ratio, target_size_bytes + ) + print(f"{fg.BLUE}Processing ..{RESET}") + resized_image = original_image.resize((new_width, new_height)) + resized_image.save(output_image_path, optimize=True, format="png") + t_size = os.path.getsize(output_image_path) / 1000_000 + print(f"{fg.BGREEN}Ok{RESET}") + print( + f"Image resized to {fg.BYELLOW}{t_size:.2f}{RESET} and saved to {fg.BYELLOW}{output_image_path}" + ) + except KeyboardInterrupt: + print("\nQuit⏹️") + sys.exit(1) + except KeyError: + print("KeyError") + except Exception as e: + print(f"{fg.RED}{e}{RESET}") + + def calculate_new_dimensions(original_size, aspect_ratio, target_size_bytes): + try: + # Calculate the new dimensions based on the target size in bytes + original_size_bytes = ( + original_size[0] * original_size[1] * 3 + ) # Assuming 24-bit color depth + scale_factor = (target_size_bytes / original_size_bytes) ** 0.5 + + new_width = int(original_size[0] * scale_factor) + new_height = int(original_size[1] * scale_factor) + + return new_width, new_height + except KeyboardInterrupt: + print("\nQuit⏹️") + sys.exit(1) + except KeyError: + print("KeyError") + except Exception as e: + print(f"{fg.RED}{e}{RESET}") + + +class ImageConverter: + """Convert images file to from one format to another""" + + def __init__(self, input_file, out_format): + self.input_file = input_file + self.out_format = out_format + + def preprocess(self) -> list: + try: + files_to_process = [] + + if os.path.isfile(self.input_file): + files_to_process.append(self.input_file) + elif os.path.isdir(self.input_file): + if os.listdir(self.input_file) is None: + print("Cannot work with empty folder") + sys.exit(1) + for file in os.listdir(self.input_file): + file_path = os.path.join(self.input_file, file) + if os.path.isfile(file_path): + files_to_process.append(file_path) + + return files_to_process + except FileNotFoundError: + print("File not found❕") + sys.exit(1) + + def convert_image(self) -> os.PathLike: + try: + input_list = self.preprocess() + out_f = self.out_format.upper() + out_f = "JPEG" if out_f == "JPG" else out_f + input_list = [ + item + for item in input_list + if any( + item.lower().endswith(ext) + for ext in SUPPORTED_IMAGE_FORMATS.values() + ) + ] + for file in tqdm(input_list): + if out_f.upper() in SUPPORTED_IMAGE_FORMATS: + _ = os.path.splitext(file)[0] + output_filename = _ + SUPPORTED_IMAGE_FORMATS[out_f].lower() + else: + print("Unsupported output format") + sys.exit(1) + """Load the image using OpenCV: """ + img = cv2.imread(file) + """Convert the OpenCV image to a PIL image: """ + pil_img = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB)) + + pil_img.save(output_filename, out_f) + + print(f"Saved image as: {fg.DCYAN}{output_filename}{RESET}") + + return output_filename + except KeyboardInterrupt: + print("\nQuit❕") + sys.exit(1) + except AssertionError: + print("Assertion failed.") + except KeyError: + print( + f"{fg.RED}ERROR:\tPending Implementation for{fg.ICYAN} {out_f} {fg.BWHITE}format{RESET}" + ) + except Exception as e: + print(f"{fg.RED}{e}{RESET}") + + +class GrayscaleConverter: + """ + Class for converting images to grayscale and saving the processed output. + + Attributes: + input_obj (Optional[Union[list[str], str, os.PathLike]]): Input file(s) or directory. + output_file (Optional[Union[list[str], str, os.PathLike]]): Output file path or directory. + """ + + def __init__( + self, + input_obj: Union[List[str], Tuple[str], str, os.PathLike], + output_file: Optional[Union[list[str], str, os.PathLike]] = None, + ): + """ + Initializes the GrayscaleConverter object. + + Args: + input_obj: Input file(s) or directory. + output_file: Output file path or directory. + """ + self.input_obj = input_obj + self.output_file = output_file + + def get_output_file( + self, image_path: Optional[Union[str, os.PathLike]] = None + ) -> Union[str, os.PathLike]: + """ + Computes the correct output file path for a given input file. + + Args: + image_path: Path to the input file. + + Returns: + The computed output file path. + """ + logger.info(f"{fg.BWHITE}Obtaining output file name{RESET}") + if self.output_file and self.output_file.endswith( + tuple(SUPPORTED_IMAGE_FORMATS.values()) + ): + return os.path.abspath(self.output_file) + if self.output_file: + return os.path.abspath(os.path.splitext(self.output_file)[0] + ".png") + if image_path: + return os.path.abspath( + os.path.splitext(os.path.basename(image_path))[0] + ".png" + ) + return "default_output.txt" + + def run(self): + """ + Runs the image to grayscale conversion operation on the input files. + + Applies the for_loop_decorator to process each image in the input list. + """ + file_list = DirectoryScanner(self.input_obj).run() + + @Decorators().for_loop_decorator(file_list) + def process_image(self, image_path): + """Processes a single image, converting it to grayscale and saving.""" + try: + logger.info(f"{fg.YELLOW}Processing {fg.CYAN}{image_path}{RESET}") + img = cv2.imread(image_path) + if img is None: + raise FileNotFoundError(f"Could not read image: {image_path}") + gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) + _, thresh = cv2.threshold( + gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU + ) + self.save_pil_image(thresh, image_path) + except FileNotFoundError as e: + logger.error(f"{fg.RED}{e}{RESET}") + except Exception as e: + raise + logger.error(f"An unexpected error occurred: {fg.RED}{e}{RESET}") + + process_image(self) + + def save_pil_image(self, thresh, image_path): + """ + Saves a NumPy array representing a grayscale image as a PIL Image. + + Args: + thresh: The NumPy array representing the grayscale image. + image_path: The path of the original image, used to derive the output filename. + """ + try: + img_pil = Image.fromarray(thresh) + filename = self.get_output_file(image_path) + filename = modify_filename_if_exists(filename) + img_pil.save(filename) + logger.info(f"{fg.GREEN}Image saved as {fg.BLUE}{filename}{RESET}") + except Exception as e: + raise + logger.error(f"Unable to save the image: {fg.RED}{e}{RESET}") + + +class ImageDocxConverter: + """ + A class for converting images to DOCX documents. + """ + + def __init__( + self, + image_list: Union[Tuple[str], List[str]] = None, + input_dir: Union[str, os.PathLike] = None, + output_path: Union[str, os.PathLike] = None, + image_size: Tuple[float, float] = (6, 8), # Default to 6x8 inches + margin_mm: float = 25, # Default margin of 25mm (approx 1 inch) + ) -> None: + """ + Initializes the ImageToDocxConverter object. + + Args: + output_path: Path to save the output DOCX file + the file name e.g ~/Document/output.docx. + filename: Name of the output DOCX file. + image_size: Tuple (width, height) in inches. + margin_mm: Margin in millimeters. + """ + self.image_list = image_list + self.input_dir = input_dir + self.output_path = output_path if output_path else self.ensure_output_file() + self.image_size = image_size + self.margin_mm = margin_mm + self.document = Document() # Create a new document object filename + + # Set document margins in the constructor + sections = self.document.sections + for section in sections: + section.top_margin = Mm(self.margin_mm) + section.bottom_margin = Mm(self.margin_mm) + section.left_margin = Mm(self.margin_mm) + section.right_margin = Mm(self.margin_mm) + self.create_output_directory() # Create output directory in constructor + + def ensure_output_file(self) -> os.PathLike: + file_name = "filemac_image2docx.docx" + if self.input_dir: + base_dir = self.input_dir + else: + base_dir = Path(self.image_list[0]).parent + + file_path = os.path.join(base_dir, file_name) + + return file_path + + def create_output_directory(self) -> None: + """ + Creates the output directory if it does not exist. + """ + Path(self.output_path).parent.mkdir(parents=True, exist_ok=True) + + def get_valid_images(self, image_paths: List[str]) -> List[str]: + """ + Filters the list of image paths, returning only those with supported formats. + + Args: + image_paths: A list of file paths to images. + + Returns: + A list of file paths to valid images. + """ + valid_images = [] + for image_path in image_paths: + try: + if Image.open(image_path).format.lower() in [ + _formats[1:] for _formats in SUPPORTED_IMAGE_FORMATS.values() + ]: + valid_images.append(image_path) + else: + print( + f"{fg.MAGENTA}Skipping unsupported image format: {fg.CYAN}{image_path}{RESET}" + ) + except Exception as e: + print( + f"{fg.RED}Error processing image {fg.YELLOW}{image_path} - {fg.RED} {e}{RESET}" + ) + return valid_images + + def convert_images_to_docx(self, image_paths: List[str]) -> os.PathLike: + """ + Converts a list of images to a single DOCX document. + + Args: + image_paths: List of image file paths. + """ + + valid_images = self.get_valid_images(image_paths) + if not valid_images: + print("No valid images to convert.") + return + + for image_path in valid_images: + try: + # Add a paragraph for each image + paragraph = self.document.add_paragraph() + run = paragraph.add_run() + run.add_picture( + image_path, + width=Inches(self.image_size[0]), + height=Inches(self.image_size[1]), + ) + # Add a page break after each image, except the last one + if image_path != valid_images[-1]: + self.document.add_page_break() + except Exception as e: + print( + f"{fg.RED}Error processing image {fg.YELLOW}{image_path}:{fg.RED} {e}{RESET}" + ) + + docx_file_path = ( + self.output_path + if self.output_path.endswith(("docx", "doc")) + else f"{self.output_path}.docx" + ) + self.document.save(docx_file_path) + return docx_file_path + + def convert_images_in_directory(self, input_dir, output_path) -> os.PathLike: + """ + Converts all images in a directory to a PDF. + + Args: + input_dir (str): The directory containing the images. + output_path (str): The path to save the generated Word File. + file_extensions (tuple, optional): Tuple of image file extensions to include. + """ + + if not os.path.exists(input_dir): + raise FileNotFoundError(f"Directory not found: {input_dir}") + + image_paths = sorted( + [os.path.join(input_dir, f) for f in os.listdir(input_dir)] + ) + + image_paths = self.get_valid_images(image_paths) + + if not image_paths: + raise ValueError(f"No images found in directory: {input_dir}") + + self.create_pdf_from_images(image_paths, output_path) + return output_path + + def run(self) -> os.PathLike: + """ + Runs the conversion process. + + Args: + image_paths: List of image file paths to convert. + """ + if not any((self.image_list, self.input_dir)): + print("No image paths provided.") + sys.exit() + + if self.image_list and self.output_path: + if all(os.path.exists(img) for img in self.image_list): + docx_file_path = self.convert_images_to_docx(self.image_list) + elif self.input_dir and self.output_path: + if os.path.exists(self.input_dir): + docx_file_path = self.convert_images_in_directory( + self.input_dir, self.output_path + ) + + if docx_file_path: + print( + f"{fg.GREEN_RG}Successfully created DOCX: {fg.BLUE}{docx_file_path}{RESET}" + ) + + return docx_file_path + + def cli(self, args: List[str]) -> None: + """ + Main function to parse command line arguments and perform the conversion. + + Args: + args: List of command line arguments. + """ + if not args or "-h" in args or "--help" in args: + print( + """ + Usage: python image_to_docx.py [options] image1 image2 ... imageN + + Options: + -h, --help show this help message and exit + -o, --output PATH path to save the output DOCX file (default: current directory) + -n, --name FILENAME name of the output DOCX file (default: output_document) + -s, --size WIDTHxHEIGHT size of images in inches (e.g., 6x8) (default: 6x8) + -m, --margin MARGIN_MM margin in millimeters (default: 25) + """ + ) + sys.exit() + + image_paths = [] + output_path = "." # Current directory + filename = "output_document" + image_size = (6, 8) # Default 6x8 inches + margin_mm = 25 + + i = 1 + while i < len(args): + if args[i] in ("-o", "--output"): + output_path = args[i + 1] + i += 2 + elif args[i] in ("-n", "--name"): + filename = args[i + 1] + i += 2 + elif args[i] in ("-s", "--size"): + try: + size_str = args[i + 1] + width, height = map(float, size_str.split("x")) + image_size = (width, height) + except ValueError: + print("Invalid size format. Please use WIDTHxHEIGHT (e.g., 6x8).") + sys.exit(1) + i += 2 + elif args[i] in ("-m", "--margin"): + try: + margin_mm = float(args[i + 1]) + except ValueError: + print("Invalid margin format. Please provide a numeric value.") + sys.exit(1) + i += 2 + else: + if not args[i].startswith("-"): + image_paths.append(args[i]) + i += 1 + else: + print(f"Unknown argument: {args[i]}") + sys.exit(1) + + converter = ImageDocxConverter(output_path, filename, image_size, margin_mm) + converter.run(image_paths) + + +class ImagePdfConverter: + """ + A class for converting images to PDF. + """ + + def __init__( + self, + image_list: Union[List[str], Tuple[str]] = None, + input_dir=None, + output_pdf_path=None, + page_size=letter, + order: bool = False, + base: bool = False, + walk: bool = False, + clean: bool = False, + ): + self.image_list = image_list + self.input_dir = input_dir + self.page_size = page_size + self.order = order + self.base = base + self.walk = walk + self.clean = clean + self.output_pdf_path = ( + output_pdf_path if output_pdf_path else self.ensure_output_file() + ) + + def ensure_output_file(self) -> os.PathLike: + file_name = "filemac_image2pdf.pdf" + if self.input_dir: + base_dir = self.input_dir + if self.base: + one_file = os.listdir(self.input_dir)[0] + base_name, ext = os.path.splitext(one_file) + if "_img_" in base_name: + base_name = base_name.split("_img_")[0] + file_name = base_name + ".pdf" + else: + file_name = self.input_dir.split("_imgs")[0] + ".pdf" + else: + base_dir = Path(self.image_list[0]).parent + + file_path = os.path.join(base_dir, file_name) + + return file_path + + def _clean(self, dirs: list): + print(f"{fg.UWHITE}{fg.BWHITE}Clean Images Host dir{fg.RESET}") + for d in dirs: + abspath = os.path.abspath(d) + print(f"{fg.BWHITE}Nuke: {fg.BYELLOW}{abspath}{fg.RESET}") + # print(Path(d).is_relative_to(os.path.expanduser("~"))) + if ( + os.path.exists(d) and os.path.isdir(d) + # and Path(d).is_relative_to(os.path.expanduser("~")) + ): + shutil.rmtree(abspath) + + def create_pdf_from_images( + self, image_paths, output_pdf_path, resize_to_fit=True + ) -> os.PathLike: + """ + Creates a PDF from a list of image paths. + + Args: + image_paths (list): A list of image file paths. + output_pdf_path (str): The path to save the generated PDF. + resize_to_fit (bool, optional): Whether to resize images to fit the page. Defaults to True. + + Raises: + FileNotFoundError: If any image path is invalid. + ValueError: If image_paths is empty or contains non-image files. + Exception: for pillow image opening errors, or reportlab canvas errors. + """ + + if not image_paths: + raise ValueError("Image paths list is empty.") + + for image_path in image_paths: + if not os.path.exists(image_path): + raise FileNotFoundError(f"Image not found: {image_path}") + try: + Image.open(image_path) + except Exception as e: + raise ValueError(f"Error opening image {image_path}: {e}") + + try: + c = canvas.Canvas(output_pdf_path, pagesize=self.page_size) + width, height = self.page_size + + for image_path in image_paths: + img = Image.open(image_path) + img_width, img_height = img.size + + if resize_to_fit: + ratio = min(width / img_width, height / img_height) + new_width = img_width * ratio + new_height = img_height * ratio + x = (width - new_width) / 2 + y = (height - new_height) / 2 + else: + x = (width - img_width) / 2 + y = (height - img_height) / 2 + new_width = img_width + new_height = img_height + + c.drawImage( + image_path, + x, + y, + width=new_width, + height=new_height, + preserveAspectRatio=True, + ) + c.showPage() + + c.save() + + return output_pdf_path + except Exception as e: + raise Exception(f"Error creating PDF: {e}") + + @staticmethod + def ensure_format(input_image) -> os.PathLike: + from ..imagepy.converter import ImageConverter + + converter = ImageConverter(input_image, "png") + output_image = converter.convert_image() + return output_image + + def extract_img_number(self, filename): + match = re.search(r"_img_(\d+)", filename) + return int(match.group(1)) if match else float("inf") + + def _sort(self, obj, ext): + if self.order: + if isinstance(obj, list): + return sorted( + obj, + key=lambda f: self.extract_img_number(f), + ) + return sorted( + [ + os.path.join(obj, f) + for f in os.listdir(obj) + if f.lower().endswith(ext) + ], + key=lambda f: self.extract_img_number(f), + ) + else: + return sorted( + [ + os.path.join(obj, f) + for f in os.listdir(obj) + if f.lower().endswith(ext) + ] + ) + + def convert_images_in_directory_recursive( + self, input_dir, output_pdf_path, file_extensions=(".jpg", ".jpeg", ".png") + ): + """ + Recursively walks through a directory and its subdirectories, + converting images in each folder into a separate PDF. + + Args: + input_dir (str): Root directory containing images. + output_root (str): Directory to save the generated PDFs. + file_extensions (tuple): Supported image extensions. + """ + try: + if not os.path.exists(input_dir): + raise FileNotFoundError(f"Directory not found: {input_dir}") + + # if not os.path.exists(output_root): + # os.makedirs(output_root) + dclean = [] + for root, _, files in os.walk(input_dir): + image_paths = [ + os.path.join(root, f) + for f in files + if f.lower().endswith(file_extensions) + ] + + if not image_paths: + continue # No valid images in this directory + + # Optional: sort images with your custom logic + image_paths = self._sort(image_paths, file_extensions) + + # Ensure formats are valid + for index, image in enumerate(image_paths): + if not image.lower().endswith(file_extensions): + image_paths[index] = self.ensure_format(image) + + # Create a relative PDF name based on the subdir structure + fname = os.path.split(root)[-1].split("_imgs")[0] + ".pdf" + relative_path = os.path.join( + os.path.dirname((os.path.relpath(root, input_dir))), fname + ) + # Host dir for images to be cleaned is clean is on + dname = os.path.relpath(root, input_dir) + dclean.append(dname) + + # pdf_name = relative_path.replace(os.sep, "_") + ".pdf" + # pdf_output_path = os.path.join(output_root, pdf_name) + + # Create the PDF for this folder + self.create_pdf_from_images(image_paths, relative_path) + print(f"{fg.BWHITE}Created PDF{RESET}: {relative_path}") + if self.clean: + self._clean(dclean) + except Exception as e: + print(f"\033[31m{e}\033[0m") + sys.exit(1) + + def convert_images_in_directory( + self, input_dir, output_pdf_path, file_extensions=(".jpg", ".jpeg", ".png") + ) -> os.PathLike: + try: + """ + Converts all images in a directory to a PDF. + + Args: + input_dir (str): The directory containing the images. + output_pdf_path (str): The path to save the generated PDF. + file_extensions (tuple, optional): Tuple of image file extensions to include. + """ + + if not os.path.exists(input_dir): + raise FileNotFoundError(f"Directory not found: {input_dir}") + + image_paths = self._sort(input_dir, ext=file_extensions) + + for index, image in enumerate(image_paths): + if not image.endswith(file_extensions): + image_paths[index] = self.ensure_format(image) + + if not image_paths: + raise ValueError( + f"\033[31mNo images found in directory:\033[1m {input_dir}\033[0m" + ) + + self.create_pdf_from_images(image_paths, output_pdf_path) + return output_pdf_path + except ValueError as e: + print(e) + sys.exit(1) + + def run(self) -> os.PathLike: + """ + Runs the PDF creation based on the object's initialization parameters. + """ + if self.image_list and self.output_pdf_path: + if all(os.path.exists(img) for img in self.image_list): + output_pdf_path = self.create_pdf_from_images( + self.image_list, self.output_pdf_path + ) + print(f"{fg.GREEN}PDF created successfully from directory!{RESET}") + print(f"{fg.GREEN}Output:{RESET} {fg.BLUE}{output_pdf_path}{RESET}") + else: + print(f"{fg.RED}One or more images in the list do not exist.{RESET}") + elif self.input_dir and self.output_pdf_path: + if os.path.exists(self.input_dir): + if self.walk: + output_pdf_path = self.convert_images_in_directory_recursive( + self.input_dir, self.output_pdf_path + ) + else: + output_pdf_path = self.convert_images_in_directory( + self.input_dir, self.output_pdf_path + ) + print(f"{fg.GREEN}PDF created successfully from directory!{RESET}") + print( + f"{fg.BWHITE}Output:{RESET} {fg.BLUE}{output_pdf_path}{RESET}" + ) + else: + print(f"Directory {fg.YELLOW}{self.input_dir}{RESET} does not exist.") + else: + print( + "Please provide either image_list and output_pdf_path or input_dir and output_pdf_path during object instantiation." + ) + return + return output_pdf_path diff --git a/filemac/core/image/extractor.py b/filemac/core/image/extractor.py new file mode 100644 index 0000000..c12872c --- /dev/null +++ b/filemac/core/image/extractor.py @@ -0,0 +1,269 @@ +import sys +import fitz # PyMuPDF for PDF +from docx import Document +from PIL import Image +from io import BytesIO +from typing import List, Union, Tuple +from pathlib import Path +import os +from ...utils.colors import fg, rs +from ...utils.file_utils import dirbuster + +RESET = rs + + +class ImageExtractor: + """ + Base class for extracting images from document files. + """ + + def __init__(self, output_path: str = None, tsize: tuple = (20, 20)) -> None: + """ + Initializes the ImageExtractor object. + + Args: + output_path: Path to save the extracted images. + """ + base_path = ( + os.path.join(output_path, "FilemacExctracts") + if output_path + else os.path.join(os.path.abspath(os.getcwd()), "FilemacExctracts") + ) + self.output_path = base_path + self.tsize = tsize + self.output_base = None + + def _extract_images(self, file_path: str) -> List[Image.Image]: + """ + Extracts images from the given file. This is a placeholder + for the actual extraction logic, to be implemented by + subclasses. + + Args: + file_path: Path to the document file. + + Returns: + A list of PIL Image objects. Returns an empty list if no images + are found or if there is an error. + """ + raise NotImplementedError("Subclasses must implement this method") + + def extract_and_save_images(self, file_path: str) -> None: + """ + Extracts and saves images from the given file. + + Args: + file_path: Path to the document file. + """ + images = self._extract_images(file_path) + self.output_base = os.path.split(file_path)[0] + if not images: + print(f"No images found in {file_path}") + return + + base_filename = Path(file_path).stem + self._save_images(images, base_filename) + + def is_page_sized_image(self, img, target_size=(595, 842), tolerance=1): + """Check if image is approximately page-sized (default: A4 at 72 DPI).""" + img_width, img_height = img.size + target_width, target_height = self.tsize if self.tsize else target_size + + within_width = ( + img_width > target_width + ) # abs(img_width - target_width) >= target_width * tolerance + within_height = ( + img_height > target_height + # abs(img_height - target_height) >= target_height * tolerance + ) + + return within_width and within_height + + def _save_images(self, images: List[Image.Image], base_filename: str) -> None: + """ + Saves the extracted images to the output directory. + + Args: + images: A list of PIL Image objects. + base_filename: The base filename to use when saving images (e.g., 'page_1'). + """ + self.output_path = os.path.join(self.output_base, f"{base_filename}_imgs") + os.makedirs(self.output_path, exist_ok=True) # Ensure directory exists + + for i, img in enumerate(images): + try: + if self.tsize and not self.is_page_sized_image(img): + print( + f"Skipping image {i + 1}: ({fg.CYAN}{img.size}{RESET}) <= {fg.BLUE}{self.tsize}{RESET}" + ) + continue + + # Generate a unique filename for each image + img_format = img.format or "PNG" # Default to PNG if format is None + safe_filename = f"{base_filename}_img_{i + 1}.{img_format.lower()}" + + img_path = Path(self.output_path) / safe_filename + img.save(img_path) + print(f"Saved image: {fg.GREEN}{img_path}{RESET}") + except Exception as e: + raise + print(f"Error saving image {i + 1} from {base_filename}: {e}") + + +class PdfImageExtractor(ImageExtractor): + """ + Extracts images from PDF files. + """ + + def __init__(self, output_path, size): + super().__init__( + output_path, size or (20, 20) + ) # Call Parent.__init__ with value + + def _extract_images(self, file_path: str) -> List[Image.Image]: + """ + Extracts images from a PDF file using PyMuPDF. + + Args: + file_path: Path to the PDF file. + + Returns: + A list of PIL Image objects. + """ + print(f"{fg.BWHITE}File: {fg.BLUE}{file_path}{RESET}") + images: List[Image.Image] = [] + try: + pdf_document = fitz.open(file_path) + for page_index in range(len(pdf_document)): + page = pdf_document.load_page(page_index) + image_list = page.get_images(full=True) # Get detailed image info + for img_index, img_info in enumerate(image_list): + xref = img_info[0] # Get the XREF of the image + base_image = pdf_document.extract_image(xref) + image_bytes = base_image["image"] + try: + pil_image = Image.open(BytesIO(image_bytes)) + images.append(pil_image) + except Exception as e: + print( + f"Error processing image {img_index + 1} from PDF page {page_index + 1}: {e}" + ) + pdf_document.close() + except Exception as e: + print(f"Error processing PDF file: {file_path} - {e}") + return images + + +class DocxImageExtractor(ImageExtractor): + """ + Extracts images from DOCX files. + """ + + def __init__(self, output_path, size): + super().__init__( + output_path, size or (20, 20) + ) # Call Parent.__init__ with value + + def _extract_images(self, file_path: str) -> List[Image.Image]: + """ + Extracts images from a DOCX file. + + Args: + file_path: Path to the DOCX file. + + Returns: + A list of PIL Image objects. + """ + images: List[Image.Image] = [] + try: + docx_document = Document(file_path) + for part in docx_document.part.rels.values(): + if "image" in part.target_ref: + image_bytes = part.target_part.blob + try: + pil_image = Image.open(BytesIO(image_bytes)) + images.append(pil_image) + except Exception as e: + print(f"Error processing image from DOCX: {e}") + except Exception as e: + print(f"Error processing DOCX file: {file_path} - {e}") + return images + + +def process_files( + file_paths: Union[Tuple[str], List[str]], + output_path: str = os.getcwd(), + tsize: tuple = None, +) -> None: + """ + Processes the given files and extracts images from them. + + Args: + file_paths: List of paths to the files to process. + output_path: Path to save the extracted images. + """ + try: + for file_path in file_paths: + if os.path.isdir(file_path): + files = dirbuster(file_path) + process_files(files, tsize=tsize) + if file_path.lower().endswith(".pdf"): + extractor = PdfImageExtractor(output_path, tsize) + extractor.extract_and_save_images(file_path) + elif file_path.lower().endswith((".docx")): + extractor = DocxImageExtractor(output_path, tsize) + extractor.extract_and_save_images(file_path) + else: + print(f"Skipping unsupported file format: {file_path}") + except KeyboardInterrupt: + print("\nQuit") + sys.exit() + + +def main(args: List[str]) -> None: + """ + Main function to parse command line arguments and perform image extraction. + + Args: + args: List of command line arguments. + """ + if not args or "-h" in args or "--help" in args: + print( + """ + Usage: python extract_images.py [options] file1 file2 ... fileN + + Options: + -h, --help show this help message and exit + -o, --output PATH path to save the extracted images (default: extracted_images) + """ + ) + sys.exit() + + file_paths = [] + output_path = "extracted_images" # Default output path + + i = 1 + while i < len(args): + if args[i] in ("-o", "--output"): + output_path = args[i + 1] + i += 2 + else: + if not args[i].startswith("-"): + file_paths.append(args[i]) + i += 1 + else: + print(f"Unknown argument: {args[i]}") + sys.exit(1) + + file_paths.append( + "/home/skye/Downloads/KDEConnect/SPE 2304 Server Side Programming Year III Semester II.pdf" + ) + if not file_paths: + print("No files provided for image extraction.") + sys.exit(1) + + process_files(file_paths, output_path) + + +if __name__ == "__main__": + main(sys.argv[1:]) diff --git a/filemac/core/ocr.py b/filemac/core/ocr.py new file mode 100644 index 0000000..4fbe426 --- /dev/null +++ b/filemac/core/ocr.py @@ -0,0 +1,199 @@ +import logging +import os +import sys +from typing import Union, List, Optional + +import cv2 +import pytesseract +from PIL import Image +from rich.progress import Progress +from ..utils.colors import fg, bg, rs +from ..utils.file_utils import modify_filename_if_exists, DirectoryScanner + + +RESET = rs + +# Define constants for better readability and maintainability +SUPPORTED_IMAGE_FORMATS = {"png", "jpg", "jpeg"} +DEFAULT_CONFIG = "-l eng --oem 3 --psm 6" +DEFAULT_SEPARATOR = "\n" + +# Configure logging at the module level +logging.basicConfig(level=logging.INFO, format="%(levelname)-8s %(message)s") +logger = logging.getLogger(__name__) + + +class ExtractText: + """ + Extracts text from images using OCR, with options for file/directory input, + output file naming, and text separation. + """ + + def __init__( + self, + input_obj: Optional[Union[list[str], tuple[str], str, os.PathLike]], + sep: str = DEFAULT_SEPARATOR, + ): + """ + Initializes the ExtractText object. + + Args: + input_obj: Path to the image file or directory containing images. + sep: Separator to use when joining extracted text. Defaults to newline. + """ + if not isinstance(input_obj, (str, list, os.PathLike)): + raise TypeError( + f"input_obj must be a string or os.PathLike, not {type(input_obj)}" + ) + self.input_obj = input_obj + self.sep = sep + self.sep = ( + "\n" + if self.sep == "newline" + else ( + "\t" + if self.sep == "tab" + else ( + " " + if self.sep == "space" + else ("" if self.sep == "none" else self.sep) + ) + ) + ) + + """ + separator_map = { + "newline": "\n", + "tab": "\t", + "space": " ", + "none": "", + } + + self.sep = separator_map.get(self.sep, self.sep) + """ + + def _process_image(self, image_path: str, output_file: str) -> str: + """ + Extracts text from a single image and saves it to a file. + + Args: + image_path: Path to the image file. + output_file: Path to the output text file. + + Returns: + The extracted text. Returns an empty string on error. + """ + try: + # Load image using OpenCV + img = cv2.imread(image_path) + if img is None: + raise ValueError(f"Could not read image: {image_path}") + + # Preprocess image for better OCR results + gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) + _, thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) + img_pil = Image.fromarray(thresh) + + # Perform OCR using pytesseract + self.sep = ( + self.sep.replace("\r\n", "\n") + .replace("\\n", "\n") + .replace("\r", "\n") + .replace("\r\t", "\t") + .replace("\\t", "\t") + ) + + text = pytesseract.image_to_string(img_pil, config=DEFAULT_CONFIG) + text = self.sep.join(text.splitlines()) # handle empty lines + logger.info("") + logger.info(f"Extracted text from {image_path}") + print(f"{fg.YELLOW}{text}{RESET}") + + # Save text to file + with open(output_file, "w", encoding="utf-8") as file: # Specify encoding + file.write(text) + return text + + except FileNotFoundError as e: + logger.error(f"File not found: {e}") + except IOError as e: + logger.error(f"IOError: {e}") + except pytesseract.TesseractError as e: + logger.error(f"Tesseract error: {e}") + except cv2.error as e: + logger.error(f"OpenCV error processing {image_path}: {e}") + except Exception as e: + logger.error( + f"An unexpected error occurred while processing {image_path}: {e}" + ) + + return "" # Return empty string on error + + def run( + self, output_file: Optional[Union[list[str], str, os.PathLike]] = None + ) -> Optional[List[str]]: + """ + Runs the OCR extraction process on the input file(s) or directory. + + Args: + output_file: Optional path to a single output file. If provided, all + extracted text will be written to this file. If None, output + files will be generated based on input image names. + + Returns: + A list of extracted texts, or None if no images were processed. + If output_file is provided, returns a list with a single string. + """ + + image_list = DirectoryScanner(self.input_obj).run() + num_images = len(image_list) + extracted_texts = [] + + if num_images == 0: + logger.warning("No images found to process.") + return None + + try: + if output_file: + # Process all images and concatenate text into one output file + all_text = "" + with Progress() as progress: + task = progress.add_task( + "[yellow]Extracting text...", total=num_images + ) + for image_path in image_list: + all_text += ( + self._process_image( + image_path, os.path.splitext(output_file)[0] + ".txt" + ) + + self.sep + ) + progress.update(task, advance=1) + with open(output_file, "w", encoding="utf-8") as f: + f.write(all_text) + return [all_text] # Return a list containing the combined text + + else: + # Process each image individually, creating separate output files + with Progress() as progress: + task = progress.add_task( + "[yellow]Extracting text...", total=num_images + ) + for image_path in image_list: + _output_file = ( + os.path.splitext(os.path.basename(image_path))[0] + ".txt" + ) + _output_file = modify_filename_if_exists(_output_file) + text = self._process_image(image_path, _output_file) + extracted_texts.append(text) + progress.update(task, advance=1) + return extracted_texts + + except KeyboardInterrupt: + print( + f"\n[{bg.YELLOW}X{RESET}]Operation interrupted by {fg.UBLUE}user{RESET}.[/]" + ) + sys.exit(0) + except Exception as e: + logger.error(f"An unexpected error occurred: {bg.RED}{e}{RESET}") + return None # Ensure None is returned on error diff --git a/filemac/core/pdf/core.py b/filemac/core/pdf/core.py new file mode 100644 index 0000000..e9f3197 --- /dev/null +++ b/filemac/core/pdf/core.py @@ -0,0 +1,415 @@ +import os +import subprocess +import sys + +import PyPDF2 +from pdf2image import convert_from_path +from PIL import Image # ImageSequence +from tqdm.auto import tqdm +from ...utils.simple import logger +from ..document import DocConverter +from ..exceptions import FilemacError, FileSystemError +from ...utils.colors import fg, bg, rs +from ..ocr import ExtractText + + +RESET = rs +DEFAULT_SEPARATOR = "\n" + + +class PDF2LongImageConverter: + def __init__(self, doc): + self.document = doc + + def preprocess(self): + ext = self.doc.split(".")[-1].lower() + if ext == "pdf": + long_image = self.convert(self.doc) + return long_image + if ext == "doc" or ext == "docx": + conv = DocConverter(self.doc) + + path = conv.word_to_pdf() + long_image = self.convert(path) + return long_image + elif ext == "odt": + return self.subprocess_executor() + + def subprocess_executor(self): + # pdf_file = ext = doc.split('.')[0] + 'docx' + logger.info(f"{fg.DCYAN}Invoked soffice ..{RESET}") + subprocess.call( + [ + "soffice", + "--convert-to", + "pdf", + self.document, + "--outdir", + os.path.dirname(self.document), + ] + ) + pdf_file = os.path.abspath( + os.path.dirname(self.document) + + "/" + + (self.document.split("/")[-1].split(".")[0]) + + ".pdf" + ) + long_image = self.convert(pdf_file) + return long_image + + @staticmethod + def convert(pdf_file): + try: + logger.info(f"{fg.BYELLOW}Read pdf{RESET}") + images = convert_from_path(pdf_file) + out_img = pdf_file[:-4] + ".png" + heights = [img.size[1] for img in images] + total_height = sum(heights) + max_width = max([img.size[0] for img in images]) + + logger.info(f"{fg.DCYAN}Draw image ..{RESET}") + new_im = Image.new("RGB", (max_width, total_height)) + + y_offset = 0 + for i, img in enumerate(images): + logger.info(f"{fg.BBLUE}{i}{RESET}", end="\r") + new_im.paste(img, (0, y_offset)) + y_offset += img.size[1] + logger.info(f"{fg.BYELLOW}Save dest: {fg.BMAGENTA}{out_img}{RESET}") + new_im.save(out_img) + logger.info(f"{fg.BGREEN}Success😇✅{RESET}") + return out_img + except FileNotFoundError: + raise FileSystemError(f"{fg.RED}File not found!{RESET}") + except KeyboardInterrupt: + logger.DEBUG("\nQuit❕") + sys.exit() + except Exception as e: + raise FilemacError(f"{fg.RED}{e}{RESET}") + + +class PageExtractor: + """ + Extract pages specified by pange range from a pdf file and save them as a new file + Args: + Pdf -> pdf file to be operated on. + Llimit -> lower limit, the start page for extraction + Ulimit -> upper limit, the end of extraction. Only one page (Llimit) is extracted ifnoUlimit is specified + Range of pages to be extracted is given by Llimit and Ulimit inclusive + Returns: + outf-> the output file contsining the extracted pages + """ + + def __init__( + self, + pdf, + Llimits: int, + Ulimit: int = None, + ): + limits = [Llimits, Ulimit] + self.pdf = pdf + self.start = limits[0] - 1 + self.stop = limits[-1] + + self.outf = f"{pdf.split('.')[0]}_{self.start}_{self.stop}_extract.pdf" + + if self.stop is None: + self.start = self.start + self.stop = self.start + 1 + self.outf = f"{pdf.split('.')[0]}_{self.start + 1}_extract.pdf" + + def getPages(self): + """ + Extract the the page range. Write the pages to new pdf file + if self.stop (Ulimit) == -1 all pages are extracted from the Llimit to the last Page + """ + try: + reader = PyPDF2.PdfReader(self.pdf) + + if self.stop == -1: + self.stop = len(reader.pages) + + pdf_writer = PyPDF2.PdfWriter() + print(f"{fg.BBLUE}[🤖]{fg.BBLUE} Extracting:{RESET}") + for page_num in range(self.start, self.stop): + print( + f"{fg.BBLUE}[📄]{RESET}{fg.DCYAN}Page {page_num + 1}{RESET}" + ) + page = reader.pages[page_num] + pdf_writer.add_page(page) + + # Write the merged PDF to the output file + with open(self.outf, "wb") as out_file: + pdf_writer.write(out_file) + print( + f"{fg.BBLUE}[+]{RESET} {fg.BWHITE}File {fg.BMAGENTA}{self.outf}{RESET}" + ) + return self.outf + except KeyboardInterrupt: + print("\n [!] Quit") + exit(2) + except FileNotFoundError as e: + print(f"[{bg.BRED}-{RESET}] {fg.RED}{e}{RESET}") + except Exception as e: + print(e) + # raise + + @staticmethod + def _entry_(kwargs): + """ + Args: + kwargs type: list - Contains Upper and lower limit (first and last page) + Returns: + None + """ + if len(kwargs) > 2: + arg1, arg2, arg3 = kwargs + init = PageExtractor(arg1, int(arg2), int(arg3)) + init.getPages() + elif len(kwargs) == 2: + ( + arg1, + arg2, + ) = kwargs + init = PageExtractor(arg1, int(arg2)) + init.getPages() + else: + pass + + +class PDFCombine: + def __init__(self, obj1, obj2=None, outf=None, order="AA"): + self.obj1 = obj1 + self.obj2 = obj2 + self.outf = outf + self.order = order + + if self.outf is None: + try: + self.outf = os.path.join( + os.path.join( + os.path.split(self.obj1[0])[0], + f"{os.path.split(self.obj1[0])[1].split('.')[0]}_{os.path.split(self.obj1[1])[1].split('.')[0]}_filemac.pdf", + ) + ) + except Exception: + self.outf = "Filemac_pdfjoin.pdf" + + def controller(self): + if self.order in {"AB", "BA", "ABA", "BAB"}: + self.combine_pdfs_ABA_interleave() + elif self.order in {"AA", "BB", "AAB", "BBA"}: + if type(self.obj1) is list: + self.merge_All_AAB() + else: + self.combine_pdfs_AAB_order() + + def combine_pdfs_ABA_interleave(self): + try: + pdf_writer = PyPDF2.PdfWriter() + # Create PdfReader objects for each input PDF file + pdf_readers = [PyPDF2.PdfReader(file) for file in self.obj1] + + max_pages = max(len(reader.pages) for reader in pdf_readers) + # pdf_readers = [PyPDF2.PdfReader(pdf) for pdf in pdf_files] + + for page_num in range(max_pages): + for reader in pdf_readers: + if page_num < len(reader.pages): + print( + f"{fg.CYAN}Page {fg.BBLUE}{page_num + 1}/{len(reader.pages)}{RESET}", + end="\r", + ) + # Order pages in terms of page1-pd1, page2-pd2 + page = reader.pages[page_num] + pdf_writer.add_page(page) + + with open(self.outf, "wb") as self.outf: + pdf_writer.write(self.outf) + print( + f"\n{fg.FCYAN}PDFs combined with specified page order into{RESET}{fg.BBLUE} {self.outf.name}{RESET}" + ) + except KeyboardInterrupt: + print("\nQuit!") + sys.exit(1) + except Exception as e: + print(f"{fg.RED}{e}{RESET}") + + def combine_pdfs_AAB_order(self): + try: + pdf_writer = PyPDF2.PdfWriter() + reader1 = PyPDF2.PdfReader(self.obj1) + reader2 = PyPDF2.PdfReader(self.obj2) + # pdf_readers = [PyPDF2.PdfReader(pdf) for pdf in pdf_files] + + print(f"{fg.CYAN}File A{RESET}") + for p1_num in range(len(reader1.pages)): + print(f"Page {p1_num + 1}/{len(reader1.pages)}", end="\r") + p1 = reader1.pages[p1_num] + # Order pages in terms of page1-pd1, page2-pd2 + pdf_writer.add_page(p1) + + print(f"\n{fg.CYAN}File B{RESET}") + for p2_num in range(len(reader2.pages)): + print(f"Page {p2_num + 1}/{len(reader2.pages)}", end="\r") + p2 = reader2.pages[p2_num] + pdf_writer.add_page(p2) + + with open(self.outf, "wb") as self.outf: + pdf_writer.write(self.outf) + print( + f"\n{fg.FCYAN}PDFs combined with specified page order into{RESET}{fg.BBLUE} {self.outf.name}{RESET}" + ) + except KeyboardInterrupt: + print("\nQuit!") + sys.exit(1) + except Exception as e: + print(f"{fg.RED}{e}{RESET}") + + def merge_All_AAB(self): + try: + pdf_writer = PyPDF2.PdfWriter() + + # List to store the reader objects + pdf_readers = [PyPDF2.PdfReader(file) for file in self.obj1] + + # max_pages = max(len(reader.pages) for reader in pdf_readers) + + for reader in pdf_readers: + for page_num in range(len(reader.pages)): + print( + f"{fg.BWHITE}Page {fg.CYAN}{page_num + 1}/{len(reader.pages)}{RESET}", + end="\r", + ) + page = reader.pages[page_num] + pdf_writer.add_page(page) + + # Write the merged PDF to the output file + with open(self.outf, "wb") as out_file: + pdf_writer.write(out_file) + print( + f"\n{fg.FCYAN}PDFs combined with specified page order into{RESET}{fg.BBLUE} {self.outf}{RESET}" + ) + except KeyboardInterrupt: + print("\nQuit!") + sys.exit(1) + except Exception as e: + print(f"{fg.RED}{e}{RESET}") + + +class Scanner: + """Implementation of scanning to extract data from pdf files and images + input_file -> file to be scanned pdf,image + Args: + input_file->file to be scanned + no_strip-> Preserves text formating once set to True, default: False + Returns: + None""" + + def __init__(self, input_file, sep: str = DEFAULT_SEPARATOR): + self.input_file = input_file + self.sep = sep + + def preprocess(self): + files_to_process = [] + + if os.path.isfile(self.input_file): + files_to_process.append(self.input_file) + elif os.path.isdir(self.input_file): + for file in os.listdir(self.input_file): + file_path = os.path.join(self.input_file, file) + if os.path.isfile(file_path): + files_to_process.append(file_path) + + return files_to_process + + def scanPDF(self, obj=None): + """Obj - object for scanning where the object is not a list""" + pdf_list = self.preprocess() + pdf_list = [item for item in pdf_list if item.lower().endswith("pdf")] + if obj: + pdf_list = [obj] + + for pdf in pdf_list: + out_f = pdf[:-3] + "txt" + print(f"{fg.YELLOW}Read pdf ..{RESET}") + + with open(pdf, "rb") as f: + reader = PyPDF2.PdfReader(f) + text = "" + + pg = 0 + for page_num in range(len(reader.pages)): + pg += 1 + + print(f"{fg.BYELLOW}Progress:{RESET}", end="") + print(f"{fg.CYAN}{pg}/{len(reader.pages)}{RESET}", end="\r") + page = reader.pages[page_num] + text += page.extract_text() + + print(f"\n{text}") + print(f"\n{fg.YELLOW}Write text to {fg.GREEN}{out_f}{RESET}") + with open(out_f, "w") as f: + f.write(text) + + print(f"\n{fg.BGREEN}Ok{RESET}") + + def scanAsImgs(self): + file = self.input_file + mc = DocConverter(file) + img_objs = mc.doc2image() + + text = "" + + for i in tqdm(img_objs, desc="Extracting", leave=False): + extract = ExtractText(i, self.sep) + _text = extract.OCR() + + if _text is not None: + text += _text + with open(f"{self.input_file[:-4]}_filemac.txt", "a") as _writer: + _writer.write(text) + + def _cleaner_(): + print(f"{fg.FMAGENTA}Clean") + for obj in img_objs: + if os.path.exists(obj): + print(obj, end="\r") + os.remove(obj) + txt_file = f"{obj[:-4]}.txt" + if os.path.exists(txt_file): + print(f"{bg.CYAN_BG}{txt_file}{RESET}", end="\r") + os.remove(txt_file) + + _cleaner_() + from ...utils.screen import clear_screen + + clear_screen() + print(f"{bg.GREEN}Full Text{RESET}") + print(text) + print( + f"{fg.BWHITE}Text File ={fg.IGREEN}{self.input_file[:-4]}_filemac.txt{RESET}" + ) + print(f"{fg.GREEN}Ok✅{RESET}") + return text + + def scanAsLongImg(self) -> bool: + """Convert the pdf to long image for scanning - text extraction""" + + try: + pdf_list = self.preprocess() + pdf_list = [item for item in pdf_list if item.lower().endswith("pdf")] + from ..pdf.core import PDF2LongImageConverter + + for file in pdf_list: + converter = PDF2LongImageConverter(file) + file = converter.preprocess() + + tx = ExtractText(file, self.sep) + text = tx.OCR() + if text is not None: + # print(text) + print(f"{fg.GREEN}Ok{RESET}") + return True + except Exception as e: + print(e) diff --git a/filemac/core/recorder.py b/filemac/core/recorder.py new file mode 100644 index 0000000..a8843db --- /dev/null +++ b/filemac/core/recorder.py @@ -0,0 +1,106 @@ +#!/usr/bin/python3 +import numpy as np +import sounddevice as sd +import wavio +import time +from pynput import keyboard +import sys + + +class SoundRecorder: + def __init__(self, frequency=44100, channels=2, dtype=np.int16): + self.fs = frequency # Sample rate (samples per second) + self.channels = 2 # Number of audio channels + self.dtype = dtype # Data type for the recording + + self.paused = False # Global flag for pause + self.recording = [] # Buffer for recorded chunks + self.start_time = 0 # Start time for elapsed time tracking + self.elapsed_time = 0 # Track elapsed time + self.running = True # Track recording status + self.filename = self.filename_prober() + + def format_time(self, seconds): + hours = int(seconds // 3600) + minutes = int((seconds % 3600) // 60) + sec = int(seconds % 60) + return f"\033[34m{hours:02d}\033[35m:{minutes:02d}\033[32m:{sec:02d} \033[0m" + + def on_press(self, key): + # global paused, running + try: + if key == keyboard.Key.space: + self.paused = not self.paused # Toggle pause/resume + if self.paused: + print("\nPaused... Press SPACE to resume.") + else: + print("\nRecording resumed... Press SPACE to pause.") + elif key == keyboard.Key.enter: + self.running = False # Stop recording + print("\nRecording finished.") + return False # Stop listener + except Exception as e: + print(f"Error: {e}") + + def record_audio(self): + # global paused, recording, start_time, elapsed_time, running + print("Press SPACE to pause/resume, ENTER to stop and save.") + start_time = time.time() + + def callback(indata, frames, callback_time, status): + if not self.paused: + self.recording.append(indata.copy()) + self.elapsed_time = time.time() - start_time + print(f"Elapsed Time: {self.format_time(self.elapsed_time)}", end="\r") + + with sd.InputStream( + samplerate=self.fs, + channels=self.channels, + dtype=self.dtype, + callback=callback, + ): + with keyboard.Listener(on_press=self.on_press) as listener: + while self.running: + time.sleep(0.1) # Prevents high CPU usage + listener.stop() + + return ( + np.concatenate(self.recording, axis=0) + if self.recording + else np.array([], dtype=self.dtype) + ) + + def run(self): + try: + r_data = self.record_audio() + self.save_audio(r_data) + return self.filename + except KeyboardInterrupt: + sys.exit() + + def save_audio(self, recording): + if recording.size == 0: + print("No audio recorded.") + else: + wavio.write(self.filename, recording, self.fs, sampwidth=2) + print(f"Recording saved as {self.filename}") + + @staticmethod + def filename_prober(): + _filename = None + + while not _filename: + _filename = input("\033[94mEnter Desired File Name\033[0;1;89m:") + + filename = f"{_filename}.wav" if len(_filename.split(".")) < 2 else _filename + return filename + + +if __name__ == "__main__": + try: + filename = input("\033[94mEnter Desired File Name\033[0;1;89m:") + ".wav" + recorder = SoundRecorder() + file = recorder.run() + except KeyboardInterrupt: + print("\nQuit!") + exit(1) diff --git a/filemac/core/svg/core.py b/filemac/core/svg/core.py new file mode 100644 index 0000000..fcbede0 --- /dev/null +++ b/filemac/core/svg/core.py @@ -0,0 +1,47 @@ +import cairosvg + + +class SVGConverter: + """ + A utility class for converting SVG files to various formats using CairoSVG. + Supported formats: PNG, PDF, SVG (optimized). + """ + + @staticmethod + def to_png(input_svg: str, output_path: str, is_string: bool = False): + """ + Convert SVG to PNG. + :param input_svg: Path to SVG file or raw SVG string. + :param output_path: Output PNG file path. + :param is_string: Set True if input_svg is raw SVG data. + """ + if is_string: + cairosvg.svg2png(bytestring=input_svg.encode(), write_to=output_path) + else: + cairosvg.svg2png(url=input_svg, write_to=output_path) + + @staticmethod + def to_pdf(input_svg: str, output_path: str, is_string: bool = False): + """ + Convert SVG to PDF. + :param input_svg: Path to SVG file or raw SVG string. + :param output_path: Output PDF file path. + :param is_string: Set True if input_svg is raw SVG data. + """ + if is_string: + cairosvg.svg2pdf(bytestring=input_svg.encode(), write_to=output_path) + else: + cairosvg.svg2pdf(url=input_svg, write_to=output_path) + + @staticmethod + def to_svg(input_svg: str, output_path: str, is_string: bool = False): + """ + Convert/Optimize SVG to SVG. + :param input_svg: Path to SVG file or raw SVG string. + :param output_path: Output SVG file path. + :param is_string: Set True if input_svg is raw SVG data. + """ + if is_string: + cairosvg.svg2svg(bytestring=input_svg.encode(), write_to=output_path) + else: + cairosvg.svg2svg(url=input_svg, write_to=output_path) diff --git a/filemac/core/text/core.py b/filemac/core/text/core.py new file mode 100644 index 0000000..b09aa2e --- /dev/null +++ b/filemac/core/text/core.py @@ -0,0 +1,111 @@ +"""Create a word document directly from a text file.""" + +from docx import Document +from docx.shared import Pt, RGBColor + +from ...utils.colors import fg, rs + +RESET = rs + + +class StyledText: + """ + Args: + obj-> input object (normally a formated text file) + fsize ->font-size default = 12: int + fstyle -> font-name default = Times New Roman: str + out_obj -> output object(file) name: str + Returns: + None + + Given obj -> Text file where: + '#' is used to specify formarting + Only three heading leavels are supported. + '#' Heading1, + '##' -> Heading2, + '###' -> Heading3 + """ + + def __init__( + self, obj, out_obj=None, fsize: int = 12, fstyle: str = "Times New Roman" + ): + self.obj = obj + self.out_obj = out_obj + self.fsize = fsize + self.fstyle = fstyle + if self.out_obj is None: + self.out_obj = f"{self.obj.split('.')[0]}_filemac.docx" + + def text_to_word(self): + """ + Create new document, + heading_styles -> define formating + Open the text file and read it line by line. + For every line check whether it starts with '#' format specify , ommit the specifier and formart the line. + Strip empty spaces from every line. + Set body font to fstyle and font size to fsize. + """ + + print(f"{fg.BWHITE}Set Font: {fg.CYAN}{self.fsize}{RESET}") + print(f"{fg.BWHITE}Set Style: {fg.CYAN}{self.fstyle}{RESET}") + # Create a new Document + doc = Document() + + # Define formatting for headings and body text + head_font_name = self.fstyle + heading_styles = { + # Heading 1 + 1: {"font_size": Pt(18), "font_color": RGBColor(126, 153, 184)}, + # Heading 2 + 2: {"font_size": Pt(16), "font_color": RGBColor(0, 120, 212)}, + # Heading 3 + 3: {"font_size": Pt(14), "font_color": RGBColor(0, 120, 212)}, + # Heading 4 + 4: {"font_size": Pt(13), "font_color": RGBColor(0, 120, 212)}, + } + + body_font_name = "Times New Roman" + body_font_size = Pt(self.fsize) + body_font_color = RGBColor(0, 0, 0) # Black color + + # Open the text file and read content + with open(self.obj, "r") as file: + lines = file.readlines() + + for i, line in enumerate(lines): + print( + f"{fg.BWHITE}Line: {fg.DCYAN}{i}{fg.YELLOW} of {fg.BLUE}{len(lines)}{RESET}", + end="\r", + ) + # Determine heading level or body text + if line.startswith("#"): + level = line.count("#") + level = min(level, 3) # Support up to 3 levels of headings + style = heading_styles.get(level, heading_styles[1]) + p = doc.add_paragraph() + # Remove '#' and extra space + run = p.add_run(line[level + 1 :].strip()) + run.font.size = style["font_size"] + run.font.name = head_font_name + run.font.color.rgb = style["font_color"] + p.style = f"Heading{level}" + else: + p = doc.add_paragraph() + run = p.add_run(line.strip()) + run.font.name = body_font_name + run.font.size = body_font_size + run.font.color.rgb = body_font_color + + # Save the document + print("\n") + doc.save(self.out_obj) + print( + f"{fg.BWHITE}Text file converted to Word document: {fg.MAGENTA}{self.out_obj}{RESET}" + ) + + +if __name__ == "__main__": + init = StyledText("/home/skye/Documents/FMAC/file2.txt") + + # Call the function + init.text_to_word() diff --git a/filemac/core/tts/core.py b/filemac/core/tts/core.py new file mode 100644 index 0000000..e69de29 diff --git a/filemac/core/tts/gtts.py b/filemac/core/tts/gtts.py new file mode 100644 index 0000000..efa38a4 --- /dev/null +++ b/filemac/core/tts/gtts.py @@ -0,0 +1,562 @@ +import json +import math +import os +import PyPDF2 +import shutil +import sys +from docx import Document +from threading import Lock, Thread +from typing import List, Union +import requests +from gtts import gTTS +from pydub import AudioSegment +from rich.errors import MarkupError +from ..document import DocConverter +from ...utils.colors import fg, rs +from ...utils.simple import logger + +RESET = rs + +_ext_word = ["doc", "docx"] + + +class GoogleTTS: + """Definition of audiofying class""" + + def __init__( + self, + obj: Union[os.PathLike, str, List[Union[os.PathLike, str]]], + resume: bool = True, + ): + self.obj = obj + self.resume = resume + + @staticmethod + def join_audios(files, output_file): + masterfile = output_file + "_master.mp3" + print( + f"{fg.BBLUE}Create a master file {fg.BMAGENTA}{masterfile}{RESET}", + end="\r", + ) + # Create a list to store files + ogg_files = [] + # loop through the directory while adding the ogg files to the list + for filename in files: + print(f"Join {fg.BBLUE}{len(files)}{RESET} files") + # if filename.endswith('.ogg'): + # ogg_file = os.path.join(path, filename) + ogg_files.append(AudioSegment.from_file(filename)) + + # Concatenate the ogg files + combined_ogg = ogg_files[0] + for i in range(1, len(files)): + combined_ogg += ogg_files[i] + + # Export the combined ogg to new mp3 file or ogg file + combined_ogg.export(output_file + "_master.ogg", format="ogg") + print( + f"{fg.BGREEN}Master file:Ok {RESET}" + ) + + def Synthesise( + self, + text: str, + output_file: str, + CHUNK_SIZE: int = 1_000, + _tmp_folder_: str = "tmp_dir", + thread_name: str = None, + max_retries: int = 30, + ) -> None: + """Converts given text to speech using Google Text-to-Speech API.""" + # from rich.progress import (BarColumn, Progress, SpinnerColumn,TextColumn) + + config = ConfigManager() + # Define directories and other useful variables for genrating output_file and checkpoint_file + out_dir = os.path.split(output_file)[0] + + thread_name = f"thread_{os.path.split(output_file.split('.')[0])[-1]}" + _file_ = os.path.split(output_file)[1] + + _tmp_folder_ = os.path.join(out_dir, _tmp_folder_) + + # Remove temporary dir if it exists, rare-cases since file names are mostly unique + if os.path.exists(_tmp_folder_) and self.resume is False: + # query = input(f"{fg.BBLUE}Remove the {os.path.join(out_dir, _tmp_folder_)} directory (y/n)?{RESET} ").lower() in ('y', 'yes') + shutil.rmtree(_tmp_folder_) + + # Create temporary folder to house chunks + if not os.path.exists(_tmp_folder_): + logger.info( + f"{fg.BYELLOW}Create temporary directory = {fg.BBLUE}{_tmp_folder_}{RESET}" + ) + os.mkdir(_tmp_folder_) + + _full_output_path_ = os.path.join(_tmp_folder_, _file_) + + # Read reume chunk from the configuration file + start_chunk = int(config.read_config_file(thread_name)) * 1_000 + start_chunk = 0 if start_chunk is None else start_chunk + + """ If chunk is not 0 multiply the chunk by the highest decimal value of the chunk size + else set it to 0 meaning file is being operated on for the first time + """ + resume_chunk_pos = start_chunk * 1_000 if start_chunk != 0 else start_chunk + + try: + print(f"{fg.BYELLOW}Start thread:: {thread_name}{RESET}") + + total_chunks = math.ceil(len(text) / CHUNK_SIZE) + + counter = ( + math.ceil(resume_chunk_pos / CHUNK_SIZE) if resume_chunk_pos != 0 else 0 + ) + + attempt = 0 + + while attempt <= max_retries: + try: + # Initialize progress bar for the overall process + + for i in range(resume_chunk_pos, len(text), CHUNK_SIZE): + print( + f"Processing: chunk {fg.BMAGENTA}{counter}/{total_chunks} {fg.DCYAN}{counter / total_chunks * 100:.2f}%{RESET}\n", + end="\r", + ) + chunk = text[i : i + CHUNK_SIZE] + # print(chunk) + if os.path.exists(f"{_full_output_path_}_{counter}.ogg"): + if counter == start_chunk: + print( + f"{fg.CYAN}Chunk vs file confict: {fg.BLUE}Resolving{RESET}" + ) + os.remove(f"{_full_output_path_}_{counter}.ogg") + output_filename = f"{_full_output_path_}_{counter}.ogg" + + # Remove empty file + elif ( + os.path.getsize(f"{_full_output_path_}_{counter}.ogg") + != 0 + ): + os.remove(f"{_full_output_path_}_{counter}.ogg") + output_filename = f"{_full_output_path_}_{counter}.ogg" + + else: + output_filename = ( + f"{_full_output_path_}_{counter + 1}.ogg" + ) + + else: + output_filename = f"{_full_output_path_}_{counter}.ogg" + + tts = gTTS(text=chunk, lang="en", slow=False) + + tts.save(output_filename) + + # Update current_chunk in the configuration + config.update_config_entry(thread_name, current_chunk=counter) + + counter += 1 + + except FileNotFoundError as e: + logger.error(f"{fg.RED}{e}{RESET}") + + except ( + requests.exceptions.ConnectionError + ): # Handle connectivity/network error + logger.error(f"{fg.RED}ConnectionError{RESET}") + + # Exponential backoff for retries + for _sec_ in range(2**attempt, 0, -1): + print( + # Increament the attempts + f"{fg.BWHITE}Resume in {fg.BBLUE}{_sec_}{RESET}", + end="\r", + ) + + attempt += 1 + + # Read chunk from configuration + resume_chunk_pos = int(config.read_config_file(thread_name)) * 1_000 + + except ( + requests.exceptions.HTTPError + ) as e: # Exponential backoff for retries + logger.error(f"HTTP error: {e.status_code} - {e.reason}") + for _sec_ in range(2**attempt, 0, -1): + print( + f"{fg.BWHITE}Resume in {fg.BBLUE}{_sec_}{RESET}", + end="\r", + ) + + attempt += 1 + + resume_chunk_pos = int(config.read_config_file(thread_name)) * 1_000 + + except requests.exceptions.RequestException as e: + logger.error(f"{fg.RED}{e}{RESET}") + + for _sec_ in range(2**attempt, 0, -1): + print( + f"{fg.BWHITE}Resume in {fg.BBLUE}{_sec_}{RESET}", + end="\r", + ) + attempt += 1 + + resume_chunk_pos = int(config.read_config_file(thread_name)) * 1_000 + + except ( + ConnectionError, + ConnectionAbortedError, + ConnectionRefusedError, + ConnectionResetError, + ): + logger.error(f"{fg.RED}Connection at attempt{RESET}") + + for _sec_ in range(2**attempt, 0, -1): + print( + f"{fg.BWHITE}Resume in {fg.BLUE}{_sec_}{RESET}", + end="\r", + ) + + attempt += 1 + + resume_chunk_pos = int(config.read_config_file(thread_name)) * 1_000 + + except MarkupError as e: + logger.error(f"{fg.RED}{e}{RESET}") + except Exception as e: # Handle all other types of exceptions + logger.error( + f"{fg.BMAGENTA}{attempt + 1}/{max_retries}:{fg.RED}{e}{RESET}" + ) + + for _sec_ in range(2**attempt, 0, -1): + pass + + attempt += 1 + + resume_chunk_pos = int(config.read_config_file(thread_name)) * 1_000 + + else: + print( + f"{fg.BMAGENTA}Conversion success✅. \n {fg.CYAN}INFO\t Create masterfile{RESET}" + ) + + if ( + len(os.listdir(_tmp_folder_)) > 2 + ): # Combine generated gTTS objects + from .JoinAudios import JoinAudios + + joiner = JoinAudios(_tmp_folder_, masterfile=output_file) + joiner.worker() + # Remove temporary files + shutil.rmtree(_tmp_folder_) + + break # Exit the retry loop if successfull + + else: + print( + f"{fg.RED}Maximum retries reached. Unable to complete the operation after {fg.BMAGENTA} {max_retries} attempts.{RESET}" + ) + sys.exit(2) + + finally: + pass + + @staticmethod + def pdf_to_text(pdf_path): + logger.info(f"{fg.GREEN} Initializing pdf to text conversion{RESET}") + try: + with open(pdf_path, "rb") as file: + pdf_reader = PyPDF2.PdfReader(file) + text = "" + _pg_ = 0 + print(f"{fg.YELLOW}Convert pages..{RESET}") + for page_num in range(len(pdf_reader.pages)): + _pg_ += 1 + logger.info( + f"Page {fg.BBLUE}{_pg_}{RESET}/{len(pdf_reader.pages)}" + ) + page = pdf_reader.pages[page_num] + text += page.extract_text() + print(f"{fg.BGREEN}Ok{RESET}\n") + return text + except Exception as e: + logger.error( + f"{fg.RED}Failed to extract text from '{fg.YELLOW}{pdf_path}'{RESET}:\n {e}" + ) + + @staticmethod + def text_file(input_file): + try: + with open(input_file, "r", errors="ignore") as file: + text = file.read().replace("\n", " ") + return text + except FileNotFoundError: + logger.error("File '{}' was not found.📁".format(input_file)) + except Exception as e: + logger.error(f"{fg.RED}{str(e)}{RESET}") + + @staticmethod + def docx_to_text(docx_path): + try: + logger.info(f"{fg.BLUE} Converting {docx_path} to text{RESET}") + doc = Document(docx_path) + paragraphs = [paragraph.text for paragraph in doc.paragraphs] + return "\n".join(paragraphs) + except FileNotFoundError: + logger.error(f"File '{docx_path}' was not found.📁") + except Exception as e: + logger.error( + f"{fg.RED}Error converting {docx_path} to text: {e} {RESET}" + ) + + class ThreadClient: + def __init__(self, instance): + self.instance = instance + self.lock = Lock() + self.config = ConfigManager() + + def audiofy(self, num_threads=3): + ls = ("pdf", "docx", "doc", "txt", "ppt", "pptx") + + def create_thread(item, thread_name): + # Create a unique temp dir for each file + temp_dir = f"tmp_dir_{os.path.split(item.split('.')[0])[-1]}" + + # Ensure proper locking when adding config entry + with self.lock: + # Record config entry for each item + self.config.add_config_entry( + thread_name, f"{item.split('.')[0]}", temp_dir, 0 + ) + + # Create and return the thread + return Thread( + target=self.worker, + args=(item, temp_dir, thread_name), + name=thread_name, + ) + + threads = [] + processed_items = 0 + + # Process a list of files + def process_batch(): + for thread in threads: + thread.start() + for thread in threads: + thread.join() + threads.clear() # Clear thread list after batch is done + + # Handle files provided as a list + if isinstance(self.instance.obj, list): + for item in self.instance.obj: + item = os.path.abspath(item) + if os.path.isfile(item) and item.endswith(ls): + thread_name = f"thread_{os.path.split(item.split('.')[0])[-1]}" + thread = create_thread(item, thread_name) + threads.append(thread) + processed_items += 1 + + # Process threads in batches of 'num_threads' + if processed_items % num_threads == 0: + process_batch() + + # Process remaining threads in case the list isn't a perfect multiple of num_threads + if threads: + process_batch() + + # Handle a single file + elif os.path.isfile(self.instance.obj): + item = os.path.abspath(self.instance.obj) + if item.endswith(ls): + thread_name = f"thread_{os.path.split(item.split('.')[0])[-1]}" + thread = create_thread(item, thread_name) + threads.append(thread) + process_batch() # Process immediately for single file + + # Handle a directory of files + elif os.path.isdir(self.instance.obj): + for item in os.listdir(self.instance.obj): + item = os.path.abspath(item) + if os.path.isfile(item) and item.endswith(ls): + thread_name = f"thread_{os.path.split(item.split('.')[0])[-1]}" + thread = create_thread(item, thread_name) + threads.append(thread) + processed_items += 1 + + # Process threads in batches + if processed_items % num_threads == 0: + process_batch() + + # Process remaining threads + if threads: + process_batch() + + def worker(self, input_file, _temp_dir_, thread_name): + output_file = os.path.split(input_file)[-1].split(".")[0] + ".ogg" + print(f"Thread {thread_name} processing file: {input_file}") + + try: + # Extract text based on file type + if input_file.endswith(".pdf"): + text = GoogleTTS.pdf_to_text(input_file) + elif input_file.lower().endswith(tuple(_ext_word)): + text = GoogleTTS.docx_to_text(input_file) + elif input_file.endswith(".txt"): + text = GoogleTTS.text_file(input_file) + elif input_file.split(".")[-1] in ("ppt", "pptx"): + conv = DocConverter(input_file) + word = conv.ppt_to_word() + conv = DocConverter(word) + text = GoogleTTS.text_file(conv.word_to_txt()) + else: + raise ValueError( + "Unsupported file format. Please provide a PDF, txt, or Word document." + ) + + # Synthesize audio using the extracted text + self.instance.Synthesise( + text, output_file, _tmp_folder_=_temp_dir_, thread_name=thread_name + ) + print(f"Thread {thread_name} completed processing {input_file}") + + except Exception as e: + print(f"Error in thread {thread_name}: {e}") + except KeyboardInterrupt: + print(f"Thread {thread_name} interrupted.") + sys.exit(1) + + +class ConfigManager: + def __init__(self, config_path="filemac_config.json"): + self.config_path = config_path + + def create_config_file(self, config_data): + """ + Create or overwrite a configuration file to record thread names, associated file names, and current chunks. + + Args: + config_data(list): A list of dictionaries containing thread name, associated file name, temp dir, and current chunk. + """ + try: + # Ensure the output directory exists + output_dir = os.path.dirname(self.config_path) + if output_dir and not os.path.exists(output_dir): + os.makedirs(output_dir) + + # Write the configuration data to a JSON file + with open(self.config_path, "w") as config_file: + json.dump(config_data, config_file, indent=4) + + print(f"Configuration file '{self.config_path}' created successfully.") + except Exception as e: + print(f"Error creating configuration file: {e}") + + def read_config_file(self, thread=None): + """ + Read the configuration file and return the data or a specific thread's current chunk. + + Args: + thread (str): The thread name to search for in the config. If None, returns the full config. + + Returns: + dict/list: Returns a specific entry for the thread or the full configuration data. + None: If the file doesn't exist or thread is not found. + """ + try: + if not os.path.exists(self.config_path): + print(f"Configuration file '{self.config_path}' not found.") + return None + + with open(self.config_path, "r") as config_file: + config = json.load(config_file) + + if thread is None: + return config # Return entire configuration + + # Search for specific thread's current chunk + for entry in config: + if entry["thread_name"] == thread: + return entry.get("current_chunk", None) + + print(f"Entry for thread '{thread}' not found.") + return None + + except Exception as e: + print(f"Error reading configuration file: {e}") + return None + + def add_config_entry(self, thread_name, associated_file, tmp_dir, current_chunk): + """ + Add a new entry to the configuration file. + + Args: + thread_name (str): The name of the thread to be added. + associated_file (str): The associated file name for the thread. + tmp_dir (str): Temporary directory for the thread. + current_chunk (int): The current chunk number for the thread. + """ + try: + # Read existing config data or create a new list if the file doesn't exist + config_data = self.read_config_file() or [] + + # Check if the thread already exists in the configuration + for entry in config_data: + if entry["thread_name"] == thread_name: + print( + f"Thread '{thread_name}' already exists. Use 'update_config_entry' to update it." + ) + return + + # Add the new entry + config_data.append( + { + "thread_name": thread_name, + "associated_file": associated_file, + "tmp_dir": tmp_dir, + "current_chunk": current_chunk, + } + ) + + # Save the updated configuration + self.create_config_file(config_data) + + except Exception as e: + print(f"Error adding config entry: {e}") + + def update_config_entry( + self, thread_name, associated_file=None, tmp_dir=None, current_chunk=None + ): + """ + Update an existing entry in the configuration file. + + Args: + thread_name (str): The name of the thread to update. + associated_file (str, optional): The updated associated file name. Defaults to None. + tmp_dir (str, optional): The updated temporary directory. Defaults to None. + current_chunk (int, optional): The updated current chunk number. Defaults to None. + """ + try: + # Read existing config data + config_data = self.read_config_file() or [] + + # Find the entry to update + for entry in config_data: + if entry["thread_name"] == thread_name: + if associated_file: + entry["associated_file"] = associated_file + if tmp_dir: + entry["tmp_dir"] = tmp_dir + if current_chunk is not None: + entry["current_chunk"] = current_chunk + + # Save the updated configuration + self.create_config_file(config_data) + print(f"Thread '{thread_name}' updated successfully.") + return True + + print(f"Thread '{thread_name}' not found in the configuration.") + + except Exception as e: + print(f"Error updating config entry: {e}") diff --git a/filemac/core/validator.py b/filemac/core/validator.py new file mode 100644 index 0000000..51b70be --- /dev/null +++ b/filemac/core/validator.py @@ -0,0 +1,19 @@ +from typing import Tuple +from pathlib import Path + + +class SystemValidator: + """Validates system requirements and dependencies.""" + + @staticmethod + def validate_file_permissions(temp_dir: Path) -> Tuple[bool, str]: + """Validate write permissions in temporary directory.""" + try: + if temp_dir.is_file(): + temp_dir = temp_dir.parent + test_file = temp_dir / "permission_test.txt" + test_file.write_text("test") + test_file.unlink() + return True, "Write permissions verified" + except (OSError, IOError) as e: + return False, f"Insufficient permissions: {str(e)}" diff --git a/filemac/core/video/core.py b/filemac/core/video/core.py new file mode 100644 index 0000000..977a0bb --- /dev/null +++ b/filemac/core/video/core.py @@ -0,0 +1,185 @@ +""" +Convert video file to from one format to another +""" + +import os +import subprocess +import sys + +import cv2 +from moviepy import VideoFileClip +from pydub import AudioSegment +from tqdm import tqdm + +from ...utils.colors import fg, bg, rs +from ...utils.formats import SUPPORTED_VIDEO_FORMATS, Video_codecs + + +RESET = rs + + +class VideoConverter: + def __init__(self, input_file, out_format=None): + self.input_file = input_file + self.out_format = out_format + + def preprocess(self): + if self.out_format is None: + return None + files_to_process = [] + + if os.path.isfile(self.input_file): + files_to_process.append(self.input_file) + elif os.path.isdir(self.input_file): + if os.listdir(self.input_file) is None: + print(f"{bg.RED}Cannot work with empty folder{RESET}") + sys.exit(1) + for file in os.listdir(self.input_file): + file_path = os.path.join(self.input_file, file) + if os.path.isfile(file_path): + files_to_process.append(file_path) + + return files_to_process + + def ffmpeg_merger(self, obj: list = None): + video_list = self.preprocess(), obj + for input_video in video_list: + base, ext = input_video.split(".", 1) + output_file = f"{base}_new_.{ext}" + + # keep the original video quality by using -c:v copy, which avoids re-encoding. + subprocess.run( + [ + "ffmpeg", + "-i", + input_video, + "-i", + "audio.mp3", + "-c:v", + "copy", + "-c:a", + "aac", + "-strict", + "experimental", + output_file, + ] + ) + + def pydub_merger(self, obj: list = None): + video_list = self.preprocess() or obj + for input_video in video_list: + output_file = [f"{_}_new_.{ext}" for _, ext in [input_video.split(".", 1)]][ + 0 + ] + # Process or manipulate audio with Pydub (e.g., adjust volume) + audio = AudioSegment.from_file("audio.mp3") + audio = audio + 6 # Increase volume by 6 dB + audio.export("processed_audio.mp3", format="mp3") + + # Merge processed audio with video using FFmpeg + subprocess.run( + [ + "ffmpeg", + "-i", + input_video, + "-i", + "processed_audio.mp3", + "-c:v", + "copy", + "-c:a", + "aac", + output_file, + ] + ) + + def cv2_merger(self, obj: list = None): + video_list = self.preprocess(), obj + for input_video in video_list: + # Read video and save frames (without audio) + cap = cv2.VideoCapture(input_video) + + # Retrieve width and height from the video + width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) + height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) + fps = int(cap.get(cv2.CAP_PROP_FPS)) + + # _, ext = input_video.split('.')[0] + # output_file = f"{_}_new{ext}" + output_file = [f"{_}_new_.{ext}" for _, ext in [input_video.split(".", 1)]][ + 0 + ] + # Define the VideoWriter with the video dimensions + out = cv2.VideoWriter( + output_file, cv2.VideoWriter_fourcc(*"mp4v"), fps, (width, height) + ) + + # Read frames from the original video and write them to the output + while cap.isOpened(): + ret, frame = cap.read() + if not ret: + break + out.write(frame) + + # Release resources + cap.release() + out.release() + + # Merge with audio using FFmpeg + subprocess.run( + [ + "ffmpeg", + "-i", + "video_no_audio.mp4", + "-i", + "audio.mp3", + "-c:v", + "copy", + "-c:a", + "aac", + output_file, + ] + ) + + def CONVERT_VIDEO(self): + try: + input_list = self.preprocess() + out_f = self.out_format.upper() + input_list = [ + item + for item in input_list + if any(item.upper().endswith(ext) for ext in SUPPORTED_VIDEO_FORMATS) + ] + print(f"{fg.BYELLOW}Initializing conversion..{RESET}") + + for file in tqdm(input_list): + if out_f.upper() in Video_codecs.keys(): + _, ext = os.path.splitext(file) + output_filename = _ + "." + out_f.lower() + # print(output_filename) + elif ( + out_f.upper() in SUPPORTED_VIDEO_FORMATS + and out_f.upper() not in Video_codecs.keys() + ): + print( + f"{fg.RED}Unsupported output format --> Pending Implementation{RESET}" + ) + sys.exit(1) + else: + print(f"{fg.RED}Unsupported output format{RESET}") + sys.exit(1) + + """Load the video file""" + video = VideoFileClip(file) + + """Export the video to a different format""" + print(f"Converting file to: {fg.BMAGENTA}{output_filename}{RESET}") + video.write_videofile(output_filename, codec=Video_codecs[out_f]) + + """Close the video file""" + print(f"{fg.BGREEN}Done{RESET}") + video.close() + except KeyboardInterrupt: + print("\nQuit❕") + sys.exit(1) + except Exception as e: + print(e) diff --git a/filemac/core/warning.py b/filemac/core/warning.py new file mode 100644 index 0000000..eece477 --- /dev/null +++ b/filemac/core/warning.py @@ -0,0 +1,13 @@ +import warnings + + +def default_supressor(): + # warnings.filterwarnings(action="ignore", category=warnings.defaultaction, module="numexpr") + warnings.simplefilter("ignore", RuntimeWarning) + with warnings.catch_warnings(): + warnings.filterwarnings( + "ignore", + message="Your system is avx2 capable but pygame was not built with support for it.", + category=RuntimeWarning, + ) + return True diff --git a/filemac/miscellaneous/VKITPro.py b/filemac/miscellaneous/VKITPro.py new file mode 100644 index 0000000..77b7c9c --- /dev/null +++ b/filemac/miscellaneous/VKITPro.py @@ -0,0 +1,135 @@ +#!/usr/bin/python3 +import logging +import os + +import cv2 +from colorama import Fore, Style, init +from moviepy import AudioFileClip, VideoFileClip + +# import numpy as np +from tqdm import tqdm + +# Initialize colorama +init(autoreset=True) + +# Custom formatter class to add colors + + +class CustomFormatter(logging.Formatter): + COLORS = { + logging.DEBUG: Fore.BLUE, + logging.INFO: Fore.GREEN, + logging.WARNING: Fore.YELLOW, + logging.ERROR: Fore.RED, + logging.CRITICAL: Fore.MAGENTA, + } + + def format(self, record): + log_color = self.COLORS.get(record.levelno, Fore.WHITE) + log_message = super().format(record) + return f"{log_color}{log_message}{Style.RESET_ALL}" + + +# Set up logging +logger = logging.getLogger("colored_logger") +handler = logging.StreamHandler() +handler.setFormatter(CustomFormatter("- %(levelname)s - %(message)s")) + +logger.addHandler(handler) +logger.setLevel(logging.INFO) + + +class AudioMan: + def __init__(self, obj): + self.obj = obj + # Load the video file + self.video = VideoFileClip(self.obj) + basename, _ = os.path.splitext(self.obj) + self.outfile = basename + ".wav" + + def Extract_audio(self): + # audio = video.audio + self.video.audio.write_audiofile(self.outfile) + + def Write_audio(self, outfile): + # Load the audio file + audio = AudioFileClip(outfile) + new = self.video.set_audio(audio) + # Export the final video + return new.write_videofile( + "output_@vkitpro.mp4", codec="libx264", audio_codec="aac", bitrate="125.4k" + ) + + +class VideoRepair: + def __init__(self, obj): + self.obj = obj + + logger.info("Open the file") + self.cap = cv2.VideoCapture(obj) + if not self.cap.isOpened(): + logger.error("Could not open video file.") + return + + # Collect file metadata + self.frame_count = int(self.cap.get(cv2.CAP_PROP_FRAME_COUNT)) + width = int(self.cap.get(cv2.CAP_PROP_FRAME_WIDTH)) + height = int(self.cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) + fps = self.cap.get(cv2.CAP_PROP_FPS) + + logger.info( + "File info:\n" + f"\tFrames: \033[95m{self.frame_count}\033[0;32m\n" + f"\tFrame Width: \033[0;95m{width}\033[0;32m\n" + f"\tFrame Height: \033[0;95m{height}\033[0;32m\n" + f"\tFPS: \033[0;95m{fps}\033[0m" + ) + + def get_frame_size_in_bytes(frame): + return frame.nbytes # Get the size of the frame in bytes + + def Repair(self, batch: int = 2): + logger.info("Find missing frames and index them") + """batch_size = batch * 1024 * 1024 + l_frame = None + r_frame = None + current_batch_size = 0 + frames_batch = []""" + + for _ in tqdm(range(self.frame_count), desc="Progress"): + ret, frame = self.cap.read() + if not ret: + # If no frame is captured, break the loop + self.frames.append(None) + else: + self.frames.append(frame) + + self.cap.release() + + +class cv2Repair: + def __init__(self): + self = self + + def preprocessor(input_video_path): + cap = cv2.VideoCapture(input_video_path) + + while cap.isOpened(): + ret, frame = cap.read() + if not ret: + pass + else: + yield frame # Yield frame one by one (lazy loading) + + cap.release() + + def repair(self): + # Process the frames using the generator + for frame in tqdm(self.preprocessor("/home/skye/Videos/FixedSupercar.mp4")): + run = AudioMan() + run.Write_audio() + + +if __name__ == "__main__": + run = AudioMan("/home/skye/Videos/FixedSupercar.mp4") + run.Write_audio("/home/skye/Videos/supercar.wav") diff --git a/filemac/miscellaneous/VRKit.py b/filemac/miscellaneous/VRKit.py new file mode 100644 index 0000000..07e511f --- /dev/null +++ b/filemac/miscellaneous/VRKit.py @@ -0,0 +1,138 @@ +#!/usr/bin/python3 +import logging +import cv2 +from colorama import Fore, Style, init + +# import numpy as np +from tqdm import tqdm + +# Initialize colorama +init(autoreset=True) + +# Custom formatter class to add colors + + +class CustomFormatter(logging.Formatter): + COLORS = { + logging.DEBUG: Fore.BLUE, + logging.INFO: Fore.GREEN, + logging.WARNING: Fore.YELLOW, + logging.ERROR: Fore.RED, + logging.CRITICAL: Fore.MAGENTA, + } + + def format(self, record): + log_color = self.COLORS.get(record.levelno, Fore.WHITE) + log_message = super().format(record) + return f"{log_color}{log_message}{Style.RESET_ALL}" + + +# Set up logging +logger = logging.getLogger("colored_logger") +handler = logging.StreamHandler() +handler.setFormatter(CustomFormatter("- %(levelname)s - %(message)s")) + +logger.addHandler(handler) +logger.setLevel(logging.INFO) + + +def detect_missing_frames(frames): + """Implementation for missing frame detection and index them, append index + of missing frames to a list""" + missing_frames = [] + logger.info("Index missing frames") + for i in tqdm(range(1, len(frames) - 1), desc="Progress"): + if frames[i] is None: + missing_frames.append(i) + + # Exit when no missing frames are found + if not missing_frames: + exit(0) + return missing_frames + + +def interpolate_frame(prev_frame, next_frame): + """Based on number and size of missing frames use this logic to create a + dummy frame by interpolating. + combine the frame before and after the missing frame and find the missing + frame by calculating middle weight.""" + logger.info("Interpolating") + return cv2.addWeighted(prev_frame, 0.5, next_frame, 0.5, 0) + + +def repair_video(input_path, output_path): + logger.info("Open the file") + cap = cv2.VideoCapture(input_path) + if not cap.isOpened(): + logger.error("Could not open video file.") + return + + # Collect file metadata + frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) + width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) + height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) + fps = cap.get(cv2.CAP_PROP_FPS) + + logger.info( + "File info:\n" + f"\tFrames: \033[95m{frame_count}\033[0;32m\n" + f"\tFrame Width: \033[0;95m{width}\033[0;32m\n" + f"\tFPS: \033[0;95m{fps}\033[0m" + ) + + frames = [] + # Remove missing frames + logger.info("Find missing frames and index them") + for _ in tqdm(range(frame_count), desc="Progress"): + ret, frame = cap.read() + if not ret: + frames.append(None) + else: + frames.append(frame) + + cap.release() + + """ Call function to detect missing frames and decide on the method to apply + depending on number of missing frames. If number is larger than frame_count * 0.1 +remove the missing frames else interpolate.""" + + missing_frames = detect_missing_frames(frames) + if ( + len(missing_frames) > frame_count * 0.1 + ): # Arbitrary threshold for many missing frames + frames = [f for f in frames if f is not None] + else: + for i in missing_frames: + """ Based on missing frame `i` find previous frame `frames[i-1]` and preceeding frame `frames[i+1]` wher both previous and preceeding are not missing. Use them to create the middle frame.""" + if ( + i > 0 + and i < frame_count - 1 + and frames[i - 1] is not None + and frames[i + 1] is not None + ): + frames[i] = interpolate_frame(frames[i - 1], frames[i + 1]) + else: + """Where ...""" + frames[i] = ( + frames[i - 1] if frames[i - 1] is not None else frames[i + 1] + ) + + # Create writer objectfor the frames + out = cv2.VideoWriter( + output_path, cv2.VideoWriter_fourcc(*"mp4v"), fps, (width, height) + ) + + # Write the new video to file + for frame in frames: + "Don't write empty frames" + if frame is not None: + out.write(frame) + + out.release() + print("Video repair complete and saved to:", output_path) + + +# Usage +input_video_path = "/home/skye/Videos/supercar.mp4" +output_video_path = "output_video.mp4" +repair_video(input_video_path, output_video_path) diff --git a/filemac/miscellaneous/video_analyzer.py b/filemac/miscellaneous/video_analyzer.py new file mode 100644 index 0000000..49561c6 --- /dev/null +++ b/filemac/miscellaneous/video_analyzer.py @@ -0,0 +1,121 @@ +"""A basic/simple file analyzer""" + +import sys +import cv2 +import numpy as np +from ..utils.colors import fg, rs +import ffmpeg + +RESET = rs + + +class SimpleAnalyzer: + """Video - video object subject for analysis + return video`s: duration, total_area and frame_count""" + + def __init__(self, video): + self.video = video + + @staticmethod + def get_metadata(input_file): + """Fetch the original bitrate of the video file using ffmpeg.""" + try: + probe = ffmpeg.probe(input_file) + print(probe.get("streams")[1]) + bitrate = None + # Iterate over the streams and find the video stream + for stream in probe["streams"]: + bitrate = ( + stream.get("bit_rate", None) + if stream["codec_type"] == "video" + else None + ) + aspect_ratio = ( + stream.get("sample_aspect_ratio") + if stream["sample_aspect_ratio"] + else None + ) + codec_name = stream.get("codec_name") if stream["codec_name"] else None + channels = stream.get("channels") + + encoder = stream.get("encoder") if stream.get("encoder") else None + break + return bitrate, aspect_ratio, codec_name, channels, encoder + except ffmpeg.Error as e: + raise + print(f"Error: {e}") + except Exception as e: + raise + print(f"Error: {e}") + + def analyze(self): + """Read the video file/obj + Increase frame count and accumulate area + Calculate current frame duration + Display the resulting frame""" + + try: + # Read the video file + cap = cv2.VideoCapture(self.video) + print(f"{fg.BYELLOW}Initializing..{RESET}") + # Initialize variables + # Frame rate (fps) + bitrate, aspect_ratio, codec_name, channels, encoder = self.get_metadata( + self.video + ) + frame_count = 0 + total_area = 0 + duration = 0 + + print(f"{fg.DCYAN}Working on it{RESET}") + while True: + ret, frame = cap.read() + + if not ret: + break + # Increase frame count and accumulate area + frame_count += 1 + total_area += np.prod(frame.shape[:2]) + + # Calculate current frame duration + fps = cap.get(cv2.CAP_PROP_FPS) + duration += 1 / fps + + # Display the resulting frame + cv2.imshow("Frame", frame) + + # Break the loop after pressing 'q' + if cv2.waitKey(1) == ord("q"): + break + + # Release the video capture object and close all windows + cap.release() + cv2.destroyAllWindows() + + # Print results + # print(f"Size {fg.BGREEN}{size}{RESET}Kb") + print(f"Channels: {fg.BGREEN}{channels}{RESET}") + print(f"Encoder {fg.BGREEN}{encoder}{RESET}") + print(f"Bitrate {fg.BGREEN}{bitrate}{RESET}") + print(f"Aspect ratio{fg.BGREEN}{aspect_ratio}{RESET}") + print(f"Codec name {fg.BGREEN}{codec_name}{RESET}") + print(f"Total Frames: {fg.BGREEN}{frame_count}{RESET}") + print( + f"Average Frame Area: {fg.BGREEN}{total_area / frame_count}{RESET}" + ) + print(f"Duration: {fg.BGREEN}{duration:.2f}{RESET} seconds") + return frame_count, total_area, duration + except KeyboardInterrupt: + print("\nExiting") + sys.exit(1) + except TypeError: + pass + except Exception as e: + print(e) + sys.exit(1) + + +if __name__ == "__main__": + vi = SimpleAnalyzer("/home/skye/Videos/demo.mkv") + # SimpleAnalyzer.get_metadata("/home/skye/Videos/demo.mkv") + vi.analyze() diff --git a/filemac/utils/__init__.py b/filemac/utils/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/filemac/utils/colors.py b/filemac/utils/colors.py new file mode 100644 index 0000000..def6fc7 --- /dev/null +++ b/filemac/utils/colors.py @@ -0,0 +1,271 @@ +import os + +from colorama import Fore, Style, init + +init(autoreset=True) + + +class ForegroundColor: + if os.name == "posix": + RESET = "\033[0m" # Reset to default text color + + # Red Variants + RED = "\033[91m" # Normal RED + BRED = "\033[1;91m" # Deep RED + FRED = "\033[2;91m" # Faint red + IRED = "\033[3;91m" # Indented RED + LRED = "\033[4;91m" # Underlined RED + URED = "\033[5;91m" # Blinking RED + + # Green Variants + GREEN = "\033[92m" # Normal green + BGREEN = "\033[1;92m" # Deep green + FGREEN = "\033[2;92m" # Faint green + IGREEN = "\033[3;92m" # Indented GREEN + LGREEN = "\033[4;92m" # Underlined GREEN + UGREEN = "\033[5;92m" # Blinking GREEN + + # Yellow Variants + YELLOW = "\033[93m" # Normal yellow + BYELLOW = "\033[1;93m" # Deep YELLOW + FYELLOW = "\033[2;93m" # Faint YELLOW + IYELLOW = "\033[3;93m" # Indented YELLOW + LYELLOW = "\033[4;93m" # Underlined YELLOW + UYELLOW = "\033[5;93m" # Blinking YELLOW + + # Blue Variants + BLUE = "\033[94m" # Normal BLUE + BBLUE = "\033[1;94m" # Deep BLUE + FBLUE = "\033[2;94m" # Faint Blue + IBLUE = "\033[3;94m" # Indented BLUE + LBLUE = "\033[4;94m" # Underlined BLUE + UBLUE = "\033[5;94m" # Blinking BLUE + + # Magenta Variants + MAGENTA = "\033[95m" # Normal MAGENTA + BMAGENTA = "\033[1;95m" # Deep MAGENTA + FMAGENTA = "\033[2;95m" # Faint MAGENTA + IMAGENTA = "\033[3;95m" # Indented MAGENTA + LMAGENTA = "\033[4;95m" # Underlined MAGENTA + UMAGENTA = "\033[5;95m" # Blinking MAGENTA + + # Cyan Variants + CYAN = "\033[96m" # Normal cyan + DCYAN = "\033[1;96m" # Deep CYAN + FCYAN = "\033[2;96m" # Faint cyan + ICYAN = "\033[3;96m" # Indented CYAN + LCYAN = "\033[4;96m" # Underlined CYAN + UCYAN = "\033[5;96m" # Blinking CYAN + + # White Variants + BWHITE = "\033[1m" # Bold white + BBWHITE = "\033[5;97;1m" # Bold Blinking white + WHITE = "\033[97m" # Normal white + DWHITE = "\033[1;97m" # Deep white + FWHITE = "\033[2;97m" # Faint white + IWHITE = "\033[3;97m" # Indented white + LWHITE = "\033[4;97m" # Underlined white + UWHITE = "\033[5;97m" # Blinking white + + if os.name == "nt": + RESET = Style.RESET_ALL + + # Red Variants + RED = Fore.LIGHTRED_EX + BRED = Fore.RED + FRED = Fore.RED + IRED = Fore.RED + LRED = Fore.LIGHTRED_EX # Underlined RED + URED = Fore.RED # Blinking not directly supported, using RED + + # Green Variants + GREEN = Fore.LIGHTGREEN_EX + BGREEN = Fore.GREEN + FGREEN = Fore.GREEN + IGREEN = Fore.GREEN + LGREEN = Fore.LIGHTGREEN_EX # Underlined GREEN + UGREEN = Fore.GREEN # Blinking not directly supported, using GREEN + + # Yellow Variants + YELLOW = Fore.LIGHTYELLOW_EX + BYELLOW = Fore.YELLOW + FYELLOW = Fore.YELLOW + IYELLOW = Fore.YELLOW + LYELLOW = Fore.LIGHTYELLOW_EX # Underlined YELLOW + UYELLOW = Fore.YELLOW # Blinking not directly supported, using YELLOW + + # Blue Variants + BLUE = Fore.LIGHTBLUE_EX + BBLUE = Fore.BLUE + FBLUE = Fore.BLUE + IBLUE = Fore.BLUE + LBLUE = Fore.LIGHTBLUE_EX # Underlined BLUE + UBLUE = Fore.BLUE # Blinking not directly supported, using BLUE + + # Magenta Variants + MAGENTA = Fore.LIGHTMAGENTA_EX + BMAGENTA = Fore.MAGENTA + FMAGENTA = Fore.MAGENTA + IMAGENTA = Fore.LIGHTMAGENTA_EX + LMAGENTA = Fore.LIGHTMAGENTA_EX # Underlined MAGENTA + UMAGENTA = Fore.MAGENTA # Blinking not directly supported, using MAGENTA + + # Cyan Variants + CYAN = Fore.LIGHTCYAN_EX + DCYAN = Fore.CYAN + ICYAN = Fore.WHITE # Indented CYAN + FCYAN = Fore.CYAN + LCYAN = Fore.LIGHTCYAN_EX # Underlined CYAN + UCYAN = Fore.CYAN # Blinking not directly supported, using CYAN + + # White Variants + BWHITE = Fore.WHITE + BBWHITE = Fore.WHITE # Blinking not directly supported, using WHITE + WHITE = Fore.WHITE + DWHITE = Fore.WHITE # Deep white (not distinct in colorama) + FWHITE = Fore.WHITE # Faint white (not distinct in colorama) + IWHITE = Fore.WHITE # Indented white (not distinct in colorama) + LWHITE = Fore.WHITE # Underlined white (not distinct in colorama) + UWHITE = Fore.WHITE # Blinking not directly supported, using WHITE + + +class BackgroundColor: + if os.name == "posix": + RESET = "\033[0m" # Reset to default text color + + # Red Variants + RED = "\033[91m" # Normal RED + BRED = "\033[1;41m" # Deep RED + FRED = "\033[2;41m" # Faint red + IRED = "\033[3;41m" # Indented RED + LRED = "\033[4;41m" # Underlined RED + URED = "\033[5;41m" # Blinking RED + + # Green Variants + GREEN = "\033[42m" # Normal green + BGREEN = "\033[1;42m" # Deep green + FGREEN = "\033[2;42m" # Faint green + IGREEN = "\033[3;42m" # Indented GREEN + LGREEN = "\033[4;42m" # Underlined GREEN + UGREEN = "\033[5;42m" # Blinking GREEN + + # Yellow Variants + YELLOW = "\033[43m" # Normal yellow + BYELLOW = "\033[1;43m" # Deep YELLOW + FYELLOW = "\033[2;43m" # Faint YELLOW + IYELLOW = "\033[3;43m" # Indented YELLOW + LYELLOW = "\033[4;43m" # Underlined YELLOW + UYELLOW = "\033[5;43m" # Blinking YELLOW + + # Blue Variants + BLUE = "\033[44m" # Normal BLUE + BBLUE = "\033[1;44m" # Deep BLUE + FBLUE = "\033[2;44m" # Faint Blue + IBLUE = "\033[3;44m" # Indented BLUE + LBLUE = "\033[4;44m" # Underlined BLUE + UBLUE = "\033[5;44m" # Blinking BLUE + + # Magenta Variants + MAGENTA = "\033[45m" # Normal MAGENTA + BMAGENTA = "\033[1;45m" # Deep MAGENTA + FMAGENTA = "\033[2;45m" # Faint MAGENTA + IMAGENTA = "\033[3;45m" # Indented MAGENTA + LMAGENTA = "\033[4;45m" # Underlined MAGENTA + UMAGENTA = "\033[5;45m" # Blinking MAGENTA + + # Cyan Variants + CYAN = "\033[46m" # Normal cyan + DCYAN = "\033[1;46m" # Deep CYAN + FCYAN = "\033[2;46m" # Faint cyan + ICYAN = "\033[3;46m" # Indented CYAN + LCYAN = "\033[4;46m" # Underlined CYAN + UCYAN = "\033[5;46m" # Blinking CYAN + + # White Variants + BWHITE = "\033[1m" # Bold white + BBWHITE = "\033[5;47;1m" # Bold Blinking white + WHITE = "\033[47m" # Normal white + DWHITE = "\033[1;47m" # Deep white + FWHITE = "\033[2;47m" # Faint white + IWHITE = "\033[3;47m" # Indented white + LWHITE = "\033[4;47m" # Underlined white + UWHITE = "\033[5;47m" # Blinking white + + BLACK = "\033[40m" # Black Background + + if os.name == "nt": + RESET = Style.RESET_ALL + + # Red Variants + RED = Fore.LIGHTRED_EX + BRED = Fore.RED + FRED = Fore.RED + IRED = Fore.RED + LRED = Fore.LIGHTRED_EX # Underlined RED + URED = Fore.RED # Blinking not directly supported, using RED + + # Green Variants + GREEN = Fore.LIGHTGREEN_EX + BGREEN = Fore.GREEN + FGREEN = Fore.GREEN + IGREEN = Fore.GREEN + LGREEN = Fore.LIGHTGREEN_EX # Underlined GREEN + UGREEN = Fore.GREEN # Blinking not directly supported, using GREEN + + # Yellow Variants + YELLOW = Fore.LIGHTYELLOW_EX + BYELLOW = Fore.YELLOW + FYELLOW = Fore.YELLOW + IYELLOW = Fore.YELLOW + LYELLOW = Fore.LIGHTYELLOW_EX # Underlined YELLOW + UYELLOW = Fore.YELLOW # Blinking not directly supported, using YELLOW + + # Blue Variants + BLUE = Fore.LIGHTBLUE_EX + BBLUE = Fore.BLUE + FBLUE = Fore.BLUE + IBLUE = Fore.BLUE + LBLUE = Fore.LIGHTBLUE_EX # Underlined BLUE + UBLUE = Fore.BLUE # Blinking not directly supported, using BLUE + + # Magenta Variants + MAGENTA = Fore.LIGHTMAGENTA_EX + BMAGENTA = Fore.MAGENTA + FMAGENTA = Fore.MAGENTA + IMAGENTA = Fore.LIGHTMAGENTA_EX + LMAGENTA = Fore.LIGHTMAGENTA_EX # Underlined MAGENTA + UMAGENTA = Fore.MAGENTA # Blinking not directly supported, using MAGE + + # Cyan Variants + CYAN = Fore.LIGHTCYAN_EX + DCYAN = Fore.CYAN + ICYAN = Fore.WHITE # Indented CYAN + FCYAN = Fore.CYAN + LCYAN = Fore.LIGHTCYAN_EX # Underlined CYAN + UCYAN = Fore.CYAN # Blinking not directly supported, using CYAN + + # White Variants + BWHITE = Fore.WHITE + BBWHITE = Fore.WHITE # Blinking not directly supported, using WHITE + WHITE = Fore.WHITE + DWHITE = Fore.WHITE # Deep white (not distinct in colorama) + FWHITE = Fore.WHITE # Faint white (not distinct in colorama) + IWHITE = Fore.WHITE # Indented white (not distinct in colorama) + LWHITE = Fore.WHITE # Underlined white (not distinct in colorama) + UWHITE = Fore.WHITE # Blinking not directly supported, using WHITE + + +fg = ForegroundColor() +bg = BackgroundColor() +rs = fg.RESET + + +class OutputFormater: + """ANSI styles for output display""" + + INFO = f"{fg.BLUE}[i]{rs}" + WARN = f"{fg.YELLOW}[!]{rs}" + ERR = f"{fg.RED}[x]{rs}" + EXP = f"{fg.MAGENTA}[⁉️]{rs}" # For exceptios + OK = f"{fg.GREEN}[✓]{rs}" + RESET = rs diff --git a/filemac/utils/config.py b/filemac/utils/config.py new file mode 100644 index 0000000..f5d7bd5 --- /dev/null +++ b/filemac/utils/config.py @@ -0,0 +1,11 @@ +from pathlib import Path +import os + +BASE_DIR = Path(__file__).resolve().home() + +OUTPUT_DIR = BASE_DIR / "Documents" + +CACHE_DIR = BASE_DIR / "tmp/filemac" + +# Ensure cache dir exists +os.makedirs(CACHE_DIR, exist_ok=True) diff --git a/filemac/utils/decorators.py b/filemac/utils/decorators.py new file mode 100644 index 0000000..0a6a9df --- /dev/null +++ b/filemac/utils/decorators.py @@ -0,0 +1,22 @@ +class Decorators: + def __init__(self): + pass + + @staticmethod + def for_loop_decorator(data_list): + """ + A decorator that calls the decorated function with each element + from the provided list or tuple. + + Args: + data_list: A list or tuple of data to iterate over. + """ + + def decorator(func): + def wrapper(self, *args, **kwargs): + for item in data_list: + func(self, item, *args, **kwargs) + + return wrapper + + return decorator diff --git a/filemac/utils/file_utils.py b/filemac/utils/file_utils.py new file mode 100644 index 0000000..770642a --- /dev/null +++ b/filemac/utils/file_utils.py @@ -0,0 +1,349 @@ +""" +File utility functions for filemac. +""" + +import fnmatch +import os +import shutil +import tempfile +import uuid +from pathlib import Path +from typing import Iterator, List, Optional, Union + +from tqdm.auto import tqdm + +# from .colors import fg, rs +from ..core.exceptions import FileSystemError +from .colors import OutputFormater as OF +from .config import OUTPUT_DIR +from .formats import SUPPORTED_IMAGE_FORMATS +from .simple import logger + + +def dirbuster(_dir_): + try: + target = [] + for root, dirs, files in os.walk(_dir_): + for file in files: + ext = file.split(".")[-1] + + _path_ = os.path.join(root, file) + if os.path.exists(_path_) and ext.lower() in ("pdf", "doc", "docx"): + target.append(_path_) + return target + except FileNotFoundError as e: + print(e) + + except KeyboardInterrupt: + print("\nQuit!") + return + + +def generate_filename(ext, basedir=OUTPUT_DIR, postfix="filemac") -> Path: + """ + Generate Filename given its extension + Args: + ext-> str + basedir-> Path + postfix = str + Returns: + path + """ + + filename = OUTPUT_DIR / f"{uuid.uuid4().hex}-{postfix}.{ext}" + + return filename + + +class FileSystemHandler: + """ + Encapsulates file handling utilities required by cleaner + """ + + def __init__(self, ignore: list | tuple = None): + self.ignore = ignore + + def find_files(self, paths, patterns, recursive=True) -> list: + try: + candidates = [] + for path in paths: + path_obj = Path(path).expanduser().resolve() + if not path_obj.exists(): + continue + if recursive: + for file in tqdm( + path_obj.rglob("*"), desc="Searching", leave=False + ): + if file.is_file() and any( + fnmatch.fnmatch(file.name, pat) for pat in patterns + ): + candidates.append(file) + else: + for file in tqdm(path_obj.glob("*"), desc="Searching", leave=False): + if file.is_file() and any( + fnmatch.fnmatch(file.name, pat) for pat in patterns + ): + candidates.append(file) + return self.ignore_pattern(candidates) + except Exception as e: + raise FileSystemError(e) + + def find_directories(self, paths, patterns, recursive=True, empty=True) -> list: + try: + candidates = [] + for path in paths: + path_obj = Path(path).expanduser().resolve() + if not path_obj.exists(): + continue + if recursive: + for root, dirs, files in tqdm( + os.walk(path_obj, followlinks=True), + desc="Searching", + leave=False, + ): + for dir in dirs: + if len(os.listdir(os.path.join(root, dir))) == 0: + candidates.append(Path(root) / dir) + + else: + for item in tqdm( + os.listdir(path_obj), desc="Searching", leave=False + ): + if os.path.isdir(item) and len(os.listdir(item)) == 0: + candidates.append(path_obj / item) + + return self.ignore_pattern(candidates) + except Exception as e: + raise FileSystemError(e) + + def ignore_pattern(self, items: list | tuple, ignore: list | tuple = None) -> list: + ignore = self.ignore if not ignore else ignore + candidates = [] + for item in items: + for ig in ignore: + _ig = ig.lower() + if _ig in item.as_uri().lower().split( + "/" + ) + item.as_uri().lower().split("\\"): + continue + + candidates.append(item) + + return candidates + + @staticmethod + def _find_files(pattern: str, recursive: bool = True) -> Iterator[Path]: + """Find files matching pattern.""" + path = Path(pattern) + + if path.exists() and path.is_file(): + yield path + return + + # Handle glob patterns + if recursive: + yield from Path(".").rglob(pattern) + else: + yield from Path(".").glob(pattern) + + @staticmethod + def delete_files(files) -> bool: + try: + for f in files: + if f.exists(): + f.unlink() + print(f"{OF.OK} Deleted: {f}") + return True + except (PermissionError, OSError) as e: + raise FileSystemError(e) + except Exception as e: + print(f"{OF.ERR} Failed to delete {f}: {e}") + return False + + @staticmethod + def delete_folders(files) -> bool: + try: + for f in files: + if f.exists(): + f.rmdir() + print(f"{OF.OK} Deleted: {f}") + return True + except (PermissionError, OSError) as e: + raise FileSystemError(e) + except Exception as e: + print(f"{OF.ERR} Failed to delete {f}: {e}") + return False + + @staticmethod + def ensure_directory(path: Path) -> Path: + """Ensure directory exists, create if necessary.""" + try: + path.mkdir(parents=True, exist_ok=True) + return path + except OSError as e: + raise FileSystemError(f"Failed to create directory {path}: {str(e)}") + + @staticmethod + def safe_filename(name: str, max_length: int = 255) -> str: + """Convert string to safe filename.""" + # Replace unsafe characters + safe_name = "".join(c if c.isalnum() or c in "._- " else "_" for c in name) + + # Remove extra spaces and underscores + safe_name = "_".join(filter(None, safe_name.split())) + + # Trim to max length + if len(safe_name) > max_length: + name_hash = str(hash(safe_name))[-8:] + safe_name = safe_name[: max_length - 9] + "_" + name_hash + + return safe_name + + +class TemporaryFileManager: + """Manages temporary files with proper cleanup.""" + + def __init__(self, prefix: str = "kcleaner_"): + self.temp_files = [] + self.temp_dirs = [] + self.prefix = prefix + + def create_temp_file(self, suffix: str, content: str = "") -> Path: + """Create a temporary file with the given suffix and content.""" + try: + with tempfile.NamedTemporaryFile( + mode="w", + suffix=suffix, + prefix=self.prefix, + encoding="utf-8", + delete=False, + ) as f: + if content: + f.write(content) + temp_path = Path(f.name) + + self.temp_files.append(temp_path) + return temp_path + + except (OSError, IOError) as e: + raise FileSystemError(f"Failed to create temporary file: {str(e)}") + + def create_temp_dir(self) -> Path: + """Create a temporary directory.""" + try: + temp_dir = Path(tempfile.mkdtemp(prefix=self.prefix)) + self.temp_dirs.append(temp_dir) + return temp_dir + except OSError as e: + raise FileSystemError(f"Failed to create temporary directory: {str(e)}") + + def cleanup(self): + """Clean up all temporary files and directories.""" + for temp_file in self.temp_files: + try: + if temp_file.exists(): + temp_file.unlink() + except OSError as e: + logger.warning(f"Failed to delete temporary file {temp_file}: {e}") + + for temp_dir in self.temp_dirs: + try: + if temp_dir.exists(): + shutil.rmtree(temp_dir) + except OSError as e: + logger.warning(f"Failed to delete temporary directory {temp_dir}: {e}") + + self.temp_files.clear() + self.temp_dirs.clear() + + +class DirectoryScanner: + def __init__(self, input_obj: Optional[Union[str, list[str], os.PathLike]]): + self.input_obj = input_obj + + def get_dir_files(self): + """ + Get file path list given dir/folder + + ------- + Args: + path: path to the directory/folder + Returns: + ------- + list + """ + files = [ + os.path.join(self.input_obj, f) + for f in os.listdir(self.input_obj) + if os.path.isfile(os.path.join(self.input_obj, f)) + and self._is_supported_image(f) + ] + if not files: # Check for empty directory *after* filtering + raise FileNotFoundError( + f"No supported image files found in: {self.input_obj}" + ) + return files + + def _is_supported_image(self, filename: str) -> bool: + """Checks if a file has a supported image extension.""" + return filename.lower().endswith(tuple(SUPPORTED_IMAGE_FORMATS.values())) + + def _get_image_files(self, files: list = None) -> List[str]: + """ + Identifies image files to process, handling both single files and directories. + + Returns: + A list of paths to image files. Raises FileNotFoundError if no + valid image files are found. + """ + files = self.input_obj if not files else files + + if isinstance(files, (str, os.PathLike)): + if os.path.isfile(files): + return [files] + else: + return self.get_dir_files(files) + + files_to_process = [] + for obj in files: + if os.path.isfile(obj): + if self._is_supported_image(obj): + files_to_process.append(obj) + else: + logger.warning(f"Skipping unsupported file: {obj}") + + elif os.path.isdir(obj): + files = self.get_dir_files(obj) + if not files: # Check for empty directory *after* filtering + raise FileNotFoundError(f"No supported image files found in: {obj}") + files_to_process.extend(files) + else: + raise FileNotFoundError( + f"Input is not a valid file or directory: {obj}" + ) + return files_to_process + + def run(self): + supported_files = self._get_image_files(self.input_obj) + return supported_files + + +def modify_filename_if_exists(filename): + """ + Modifies the filename by adding "_filemac" before the extension if the original filename exists. + + Args: + filename (str): The filename to modify. + + Returns: + str: The modified filename, or the original filename if it doesn't exist or has no extension. + """ + if os.path.exists(filename): + parts = filename.rsplit(".", 1) # Split from the right, at most once + if len(parts) == 2: + base, ext = parts + return f"{base}_filemac.{ext}" + else: + return f"{filename}_filemac" # handle files with no extension. + else: + return filename diff --git a/filemac/utils/formats.py b/filemac/utils/formats.py new file mode 100644 index 0000000..9ab7aac --- /dev/null +++ b/filemac/utils/formats.py @@ -0,0 +1,168 @@ +# multimedia_cli/formats +from .colors import fg, bg, rs + + +RESET = rs + +SUPPORTED_DOC_FORMATS = f""" +|--------------------------------------------------------------------------- +|{bg.BBLUE}Input format{RESET} |{bg.BBLUE}Output format{RESET} | +|________________________________|__________________________________________| +| xlsx {fg.BYELLOW}-------------------->{RESET}|csv txt doc/docx db(sql) | +| | | +| doc/docx{fg.BYELLOW}-------------------->{RESET}|txt pdf ppt/pptx audio(ogg) | +| | | +| txt {fg.BYELLOW}-------------------->{RESET}|pdf docx/doc audio(ogg) | +| | | +| pdf {fg.BYELLOW}-------------------->{RESET}|doc/docx txt audio(ogg) | +| | | +| pptx/ppt{fg.BYELLOW}-------------------->{RESET}|doc/docx | +| | +|___________________________________________________________________________| +""" + + +# Add supported input and output formats for each media type +SUPPORTED_AUDIO_FORMATS = [ + "wav", # Waveform Audio File Format + "mp3", # MPEG Audio Layer III + "ogg", + "flv", + "ogv", + "webm", + "aiff", + "flac", + "m4a", + "raw", + "bpf", + "aac", +] # Advanced Audio Codec] (Free Lossless Audio Codec) + +SUPPORTED_AUDIO_FORMATS_DIRECT = [ + "mp3", + "wav", + "raw", + "ogg", + "aiff", + "flac", + "flv", # Flash Video + "webm", + "ogv", +] # Video +SUPPORTED_AUDIO_FORMATS_SHOW = f""" +|==============================| +| {bg.BBLUE}Supported I/O formats {RESET} | +|==============================| +| {fg.CYAN} wav {fg.BYELLOW} | +| {fg.CYAN} mp3 {fg.BYELLOW} | +| {fg.CYAN} ogg {fg.BYELLOW} | +| {fg.CYAN} flv {fg.BYELLOW} | +| {fg.CYAN} ogv {fg.BYELLOW} | +| {fg.CYAN} mov {fg.BYELLOW} | +| {fg.CYAN} webm {fg.BYELLOW} | +| {fg.CYAN} aac {fg.BYELLOW}-------------->|{bg.IMAGENTA}Pending Implementation{RESET}{fg.BYELLOW} +| {fg.CYAN} bpf {fg.BYELLOW}-------------->|{bg.IMAGENTA}Pending Implementation{RESET}{fg.BYELLOW} +| {fg.CYAN} m4a {fg.BYELLOW} | +| {fg.CYAN} raw {fg.BYELLOW} | +| {fg.CYAN} aiff {fg.BYELLOW} | +-------------------------------- + +""" + +SUPPORTED_VIDEO_FORMATS = [ + "MP4", # MPEG-4 part 14 Bitrate - 860kb/s + "AVI", # Audio Video Interleave + "OGV", + "WEBM", + "MOV", # QuickTime video Bitrate - 1.01mb/s + "MKV", # Matroska video - MKV is known for its support of high-quality content. Bitrate-1.01mb/s + "FLV", # Flash video Bitrate + "WMV", +] + + +Video_codecs = { + "MP4": "mpeg4", + "AVI": "rawvideo", + # "OGV": "avc", + "WEBM": "libvpx", + "MOV": "mpeg4", # QuickTime video + "MKV": "mpeg4", # Matroska video + "FLV": "flv", + # "WMV": "WMV" +} +SUPPORTED_VIDEO_FORMATS_SHOW = f""" +,_______________________________________, +|x| {bg.BBLUE}Supported I/O formats{RESET} |x| +|x|-----------------------------------{fg.BYELLOW}|x| +|x| {fg.BMAGENTA} MP4 {fg.BYELLOW} |x| +|x| {fg.BMAGENTA} AVI {fg.BYELLOW} |x| +|x| {fg.BMAGENTA} OGV {fg.BYELLOW}-------------->|x|{fg.IMAGENTA}Pending Implementation{RESET}{fg.BYELLOW} +|x| {fg.BMAGENTA} WEBM{fg.BYELLOW} |x| +|x| {fg.BMAGENTA} MOV {fg.BYELLOW} |x| +|x| {fg.BMAGENTA} MKV {fg.BYELLOW} |x| +|x| {fg.BMAGENTA} FLV {fg.BYELLOW} |x| +|x| {fg.BMAGENTA} WMV {fg.BYELLOW}-------------->|x|{fg.IMAGENTA}Pending Implementation{RESET}{fg.BYELLOW} +|,|___________________.BMAGENTA________________|,|{fg.BYELLOW} +""" + +SUPPORTED_IMAGE_FORMATS = { + "JPEG": ".jpeg", # Joint Photographic Experts Group -Lossy compression + "JPG": ".jpg", # Joint Photographic Experts Group - not lossy + "PNG": ".png", + "GIF": ".gif", # Graphics Interchange Format + "BMP": ".bmp", # Windows BMP image + "DIB": ".dib", # Windows BMP image + "TIFF": ".tiff", # Tagged Image File Format A flexible and high-quality image format that supports lossless compression + "PIC": ".pic", + "PDF": ".pdf", + "WEBP": ".webp", + "EPS": ".eps", + "ICNS": ".icns", # MacOS X icon + # Waiting Implementation 👇 + "PSD": ".psd", + "SVG": ".svg", # Scalable vector Graphics + "EXR": ".exr", + "DXF": ".dxf", # Autocad format 2D + "PICT": ".pct", + "PS": ".ps", # PostSciript + "POSTSCRIPT": ".ps", +} + +SUPPORTED_IMAGE_FORMATS_SHOW = f""" +__________________________________________ +|x|{bg.BBLUE}Supported I/O formats{RESET} |x| +|x|_____________________________________{fg.BYELLOW}|x| +|x| {fg.BMAGENTA} JPEG {fg.BYELLOW} |x| +|x| {fg.BMAGENTA} PNG {fg.BYELLOW} |x| +|x| {fg.BMAGENTA} GIF {fg.BYELLOW} |x| +|x| {fg.BMAGENTA} BMP {fg.BYELLOW} |x| +|x| {fg.BMAGENTA} DIB {fg.BYELLOW} |x| +|x| {fg.BMAGENTA} TIFF {fg.BYELLOW} |x| +|x| {fg.BMAGENTA} PIC {fg.BYELLOW} |x| +|x| {fg.BMAGENTA} EXR {fg.FMAGENTA}---------------->|x|{fg.FCYAN} Pending Implementation{RESET}{fg.BYELLOW} +|x| {fg.BMAGENTA} PDF {fg.BYELLOW} |x| +|x| {fg.BMAGENTA} WebP {fg.BYELLOW} |x| +|x| {fg.BMAGENTA} ICNS {fg.BYELLOW} |x| +|x| {fg.BMAGENTA} PSD {fg.FMAGENTA}---------------->|x|{fg.FCYAN} Pending Implementation{RESET}{fg.BYELLOW} +|x| {fg.BMAGENTA} SVG {fg.FMAGENTA}---------------->|x|{fg.FCYAN} Pending Implementation{RESET}{fg.BYELLOW} +|x| {fg.BMAGENTA} EPS {fg.BYELLOW} |x| +|x| {fg.BMAGENTA} Postscript {fg.FMAGENTA}---------->|x|{fg.FCYAN} Pending Implementation{RESET}{fg.BYELLOW} +|x| {fg.BMAGENTA} PICT {fg.FMAGENTA}---------------->|x|{fg.FCYAN} Pending Implementation{RESET}{fg.BYELLOW} +|_|_____________________________________|x| +""" + +SUPPORTED_DOCUMENT_FORMATS = [ + "pdf", + "doc", + "docx", + "csv", + "xlsx", + "xls", + "ppt", + "pptx", + "txt", + "ogg", + "mp3", + "audio", +] diff --git a/filemac/utils/helpmaster.py b/filemac/utils/helpmaster.py new file mode 100644 index 0000000..4b17d4a --- /dev/null +++ b/filemac/utils/helpmaster.py @@ -0,0 +1,25 @@ +from .utils.colors import fg, rs + + +RESET = rs + + +def pdf_combine_help(): + options = f""" + _________________________ + {fg.BWHITE}|Linear: {fg.YELLOW}AA/BB/AAB/BBA{RESET} | + {fg.BWHITE}|Shifted: {fg.YELLOW}AB/BA/ABA/BAB{RESET} | + _________________________""" + + helper = f"""\n\t--------------------------------------------------------------------------------------------- + {fg.BWHITE}|Currently There are 2 supported methods: {fg.FCYAN}Linear and Alternating/shifting.{RESET}\t\t | + |-------------------------------------------------------------------------------------------| + {fg.BWHITE}|->Linear pages are ordered in form of: {fg.CYAN}File1Page1,...Fil1Pagen{RESET} then {fg.CYAN}File2Page1,...Fil2Pagen{RESET}|\n\t{fg.BWHITE}|File2 is joined at the end of the file1.\t\t\t\t\t\t | + |-------------------------------------------------------------------------------------------| + {fg.BWHITE}|->Shifting method Picks: {fg.CYAN}File1Page1, File2Page1...File1pagen,File2Pagen{RESET}\t\t | + |--------------------------------------------------------------------------------------------""" + + ex = f"""\t_____________________________________________________ + \t|->{fg.BBLUE}filemac --pdfjoin file1.pdf file2.pdf --order AAB{RESET}| + \t-----------------------------------------------------""" + return options, helper, ex diff --git a/filemac/utils/logging_utils.py b/filemac/utils/logging_utils.py new file mode 100644 index 0000000..b7162f6 --- /dev/null +++ b/filemac/utils/logging_utils.py @@ -0,0 +1,73 @@ +""" +Logging configuration for Filemac. +""" + +import logging +import sys +from typing import Optional + + +def setup_logging( + level: int = logging.INFO, + format_string: Optional[str] = None, + log_file: Optional[str] = None, +) -> logging.Logger: + """ + Setup logging configuration for kcleaner. + + Args: + level: Logging level + format_string: Custom format string + log_file: Optional log file path + + Returns: + Configured logger + """ + if format_string is None: + format_string = "%(asctime)s - %(name)s - %(levelname)s - %(message)s" + + formatter = logging.Formatter(format_string) + + # Root logger + logger = logging.getLogger("filemac") + logger.setLevel(level) + + # Clear existing handlers + for handler in logger.handlers[:]: + logger.removeHandler(handler) + + # Console handler + console_handler = logging.StreamHandler(sys.stdout) + console_handler.setFormatter(formatter) + logger.addHandler(console_handler) + + # File handler if specified + if log_file: + file_handler = logging.FileHandler(log_file, encoding="utf-8") + file_handler.setFormatter(formatter) + logger.addHandler(file_handler) + + # Prevent propagation to root logger + logger.propagate = False + + return logger + + +class LoggingContext: + """Context manager for temporary logging configuration.""" + + def __init__(self, level: int = logging.INFO, log_file: Optional[str] = None): + self.level = level + self.log_file = log_file + self.original_level = None + self.file_handler = None + + def __enter__(self): + self.original_level = logging.getLogger("filemac").level + setup_logging(level=self.level, log_file=self.log_file) + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + setup_logging(level=self.original_level) + if self.file_handler: + logging.getLogger("filemac").removeHandler(self.file_handler) diff --git a/filemac/utils/screen.py b/filemac/utils/screen.py new file mode 100644 index 0000000..3c6d4de --- /dev/null +++ b/filemac/utils/screen.py @@ -0,0 +1,19 @@ +"""Provides screen actions like clearing screen etc.""" + +import os +import ctypes + + +def clear_screen(): + """ + Clear the screen using ctypes in windows and os.system('clear') in unix systems + """ + if os.name == "nt": # Windows system + ctypes.windll.kernel32.SetConsoleCursorPosition( + ctypes.windll.kernel32.GetStdHandle(-11), (0, 0) + ) + ctypes.windll.kernel32.FillConsoleOutputCharacter( + ctypes.windll.kernel32.GetStdHandle(-11), b"\x00", 80 * 10, (0, 0) + ) + else: # Unix/Linux/MacOS systems + os.system("clear") diff --git a/filemac/utils/security/vul_mitigate.py b/filemac/utils/security/vul_mitigate.py new file mode 100644 index 0000000..398fb6e --- /dev/null +++ b/filemac/utils/security/vul_mitigate.py @@ -0,0 +1,177 @@ +import os +import subprocess +import sqlite3 + +# import shlex +import json +import tempfile +import logging +import html +import requests +from dotenv import load_dotenv +from ...core.exceptions import ValidationError + +# from importlib import resources +from ..colors import fg, rs + +RESET = rs + +pkg_resources = [] + + +class SecurePython: + def __init__(self): + """Initialize security mitigations.""" + load_dotenv() # Load environment variables for secret management + logging.basicConfig(level=logging.INFO) + + # ✅ 1. Prevent Command Injection + def secure_subprocess(self, command_list): + """Runs a secure subprocess command using a list format to prevent command injection.""" + if not isinstance(command_list, list): + raise ValidationError("Command must be a list") + try: + result = subprocess.run( + command_list, check=True, capture_output=True, text=True + ) + return result.stdout + except subprocess.CalledProcessError as e: + logging.error(f"Command failed: {e}") + return None + + # ✅ 2. Prevent Path Traversal + def safe_filepath(self, base_dir, user_input_path): + """Prevents path traversal by restricting access to a safe base directory.""" + full_path = os.path.abspath(os.path.join(base_dir, user_input_path)) + + if not full_path.startswith(os.path.abspath(base_dir)): + raise ValueError("Invalid file path: Path traversal attempt detected") + print(f"{fg.BBLUE}Return safe path: {fg.BGREEN}{full_path}{RESET}") + return full_path + + # ✅ 3. Prevent SQL Injection + def safe_sql_query(self, db_path, query, params): + """Executes a parameterized SQL query to prevent SQL injection.""" + conn = sqlite3.connect(db_path) + cursor = conn.cursor() + try: + cursor.execute(query, params) + result = cursor.fetchall() + conn.commit() + return result + except sqlite3.Error as e: + logging.error(f"SQL error: {e}") + return None + finally: + conn.close() + + # ✅ 4. Secure File Handling + def secure_temp_file(self, content): + """Creates a secure temporary file to prevent race conditions.""" + with tempfile.NamedTemporaryFile(delete=True) as temp_file: + temp_file.write(content.encode()) + temp_file.flush() + return temp_file.name # Return temp file path for safe use + + # ✅ 5. Secure Secret Management + def get_secret(self, key): + """Fetches secrets from environment variables.""" + secret = os.getenv(key) + if not secret: + logging.warning(f"Secret {key} is missing!") + return secret + + # ✅ 6. Prevent Insecure Deserialization + def safe_json_load(self, json_string): + """Safely loads JSON instead of using pickle to avoid remote code execution.""" + try: + return json.loads(json_string) + except json.JSONDecodeError as e: + logging.error(f"Invalid JSON: {e}") + return None + + # ✅ 7. Prevent XSS Attacks + def sanitize_html(self, user_input): + """Escapes HTML to prevent XSS attacks.""" + return html.escape(user_input) + + # ✅ 8. Check Dependency Vulnerabilities + def check_dependencies(self): + """Checks installed dependencies for known vulnerabilities.""" + try: + installed_packages = { + pkg.key: pkg.version for pkg in pkg_resources.working_set + } + response = requests.get("https://pyup.io/api/v1/safety/") + if response.status_code == 200: + vulnerable_packages = [] + for package, version in installed_packages.items(): + if package in response.json(): + vulnerable_packages.append(package) + if vulnerable_packages: + logging.warning( + f"Vulnerable dependencies found: {vulnerable_packages}" + ) + else: + logging.info("No known vulnerable dependencies detected.") + else: + logging.warning("Failed to fetch vulnerability database.") + except Exception as e: + logging.error(f"Error checking dependencies: {e}") + + # ✅ 9. Secure Logging + def secure_logging(self, message): + """Logs messages securely without sensitive data exposure.""" + sanitized_message = message.replace("password", "*****").replace( + "API_KEY", "*****" + ) + logging.info(sanitized_message) + + # ✅ 10. Run All Security Mitigations + def entry_run(self): + """Runs all security mitigations where applicable.""" + logging.info("🔒 Running security mitigations...") + + # Example secure execution + self.secure_subprocess(["echo", "Secure Execution"]) + + # Example secure file path usage + try: + safe_path = self.safe_filepath("/safe/directory", "../etc/passwd") + logging.info(f"Safe path resolved: {safe_path}") + except ValueError as e: + logging.error(e) + + # Example secure SQL execution + self.safe_sql_query(":memory:", "CREATE TABLE test (id INTEGER, name TEXT)", ()) + self.safe_sql_query( + ":memory:", "INSERT INTO test (id, name) VALUES (?, ?)", (1, "John Doe") + ) + + # Example secure file handling + temp_file = self.secure_temp_file("Secure data") + logging.info(f"Created secure temp file at {temp_file}") + + # Example secret fetching + self.get_secret("API_KEY") + + # Example safe JSON parsing + self.safe_json_load('{"key": "value"}') + + # Example HTML sanitization + sanitized_html = self.sanitize_html("") + logging.info(f"Sanitized HTML: {sanitized_html}") + + # Example dependency check + self.check_dependencies() + + # Example secure logging + self.secure_logging("User attempted login with password: mypassword") + + logging.info("✅ All security mitigations executed successfully!") + + +# === Run SecurePython Class === +if __name__ == "__main__": + sp = SecurePython() + sp.entry_run() diff --git a/filemac/utils/simple.py b/filemac/utils/simple.py new file mode 100644 index 0000000..e40164c --- /dev/null +++ b/filemac/utils/simple.py @@ -0,0 +1,8 @@ +import logging + +# Configure logging +logging.basicConfig( + level=logging.INFO, + format="%(levelname)s - %(message)s", +) +logger = logging.getLogger("filemac") diff --git a/fweb/README.md b/fweb/README.md new file mode 100644 index 0000000..7757011 --- /dev/null +++ b/fweb/README.md @@ -0,0 +1,26 @@ +## Architecture Overview +### Project Structure +```text +filemac_web/ +├── filemac_web/ # Django project +│ ├── settings.py +│ ├── urls.py +│ └── wsgi.py +├── filemac_app/ # Main application +│ ├── models.py +│ ├── views.py +│ ├── urls.py +│ ├── forms.py +│ └── utils.py +├── templates/ +│ ├── base.html +│ ├── index.html +│ ├── dashboard.html +│ ├── converters/ +│ └── results/ +├── static/ +│ ├── css/ +│ ├── js/ +│ └── images/ +└── media/ # Uploaded files +``` diff --git a/fweb/core/__init__.py b/fweb/core/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/fweb/core/admin.py b/fweb/core/admin.py new file mode 100644 index 0000000..cc64292 --- /dev/null +++ b/fweb/core/admin.py @@ -0,0 +1,30 @@ +from django.contrib import admin +from .models import ProcessingJob, ProcessedFile + + +@admin.register(ProcessingJob) +class ProcessingJobAdmin(admin.ModelAdmin): + list_display = ("job_id", "tool_id", "user", "status", "progress", "created_at") + list_filter = ("status", "tool_id", "created_at") + search_fields = ("job_id", "tool_id", "user__username") + readonly_fields = ("created_at", "updated_at") + fieldsets = ( + (None, {"fields": ("job_id", "user", "tool_id", "status", "progress")}), + ("Files", {"fields": ("input_files", "output_files")}), + ("Timestamps", {"fields": ("created_at", "updated_at")}), + ("Error", {"fields": ("error_message",), "classes": ("collapse",)}), + ) + + +@admin.register(ProcessedFile) +class ProcessedFileAdmin(admin.ModelAdmin): + list_display = ( + "original_name", + "processed_name", + "job", + "file_size", + "processed_at", + ) + list_filter = ("job__tool_id", "processed_at") + search_fields = ("original_name", "processed_name", "job__job_id") + readonly_fields = ("processed_at",) diff --git a/fweb/core/apps.py b/fweb/core/apps.py new file mode 100644 index 0000000..bde16cf --- /dev/null +++ b/fweb/core/apps.py @@ -0,0 +1,6 @@ +from django.apps import AppConfig + + +class FilemacAppConfig(AppConfig): + default_auto_field = "django.db.models.BigAutoField" + name = "core" diff --git a/fweb/core/config.py b/fweb/core/config.py new file mode 100644 index 0000000..fb6f9e5 --- /dev/null +++ b/fweb/core/config.py @@ -0,0 +1,206 @@ +# Tool configurations +TOOL_CONFIGS = { + "document": { + "icon": "file-pdf", + "color": "blue", + "description": "Document conversion and processing tools", + "tools": [ + { + "id": "convert_doc", + "name": "Document Conversion", + "icon": """M566.6 214.6L470.6 310.6C461.4 319.8 447.7 322.5 435.7 317.5C423.7 312.5 416 300.9 416 288L416 224L96 224C78.3 224 64 209.7 64 192C64 174.3 78.3 160 96 160L416 160L416 96C416 83.1 423.8 71.4 435.8 66.4C447.8 61.4 461.5 64.2 470.7 73.3L566.7 169.3C579.2 181.8 579.2 202.1 566.7 214.6zM169.3 566.6L73.3 470.6C60.8 458.1 60.8 437.8 73.3 425.3L169.3 329.3C178.5 320.1 192.2 317.4 204.2 322.4C216.2 327.4 224 339.1 224 352L224 416L544 416C561.7 416 576 430.3 576 448C576 465.7 561.7 480 544 480L224 480L224 544C224 556.9 216.2 568.6 204.2 573.6C192.2 578.6 178.5 575.8 169.3 566.7z""", + "color": "blue", + "description": "Convert between PDF, DOCX, TXT, and other document formats", + }, + { + "id": "pdf_join", + "name": "PDF Joining", + "icon": """M288 64C252.7 64 224 92.7 224 128L224 384C224 419.3 252.7 448 288 448L480 448C515.3 448 544 419.3 544 384L544 183.4C544 166 536.9 149.3 524.3 137.2L466.6 81.8C454.7 70.4 438.8 64 422.3 64L288 64zM160 192C124.7 192 96 220.7 96 256L96 512C96 547.3 124.7 576 160 576L352 576C387.3 576 416 547.3 416 512L416 496L352 496L352 512L160 512L160 256L176 256L176 192L160 192z""", + "color": "red", + "description": "Merge multiple PDF files into a single document", + }, + { + "id": "scan_pdf", + "name": "PDF Text Extraction", + "icon": """M480 272C480 317.9 465.1 360.3 440 394.7L566.6 521.4C579.1 533.9 579.1 554.2 566.6 566.7C554.1 579.2 533.8 579.2 521.3 566.7L394.7 440C360.3 465.1 317.9 480 272 480C157.1 480 64 386.9 64 272C64 157.1 157.1 64 272 64C386.9 64 480 157.1 480 272zM272 416C351.5 416 416 351.5 416 272C416 192.5 351.5 128 272 128C192.5 128 128 192.5 128 272C128 351.5 192.5 416 272 416z""", + "color": "green", + "description": "Extract text from PDF documents using OCR", + }, + { + "id": "doc_long_image", + "name": "Document to Long Image", + "icon": """M160 96C124.7 96 96 124.7 96 160L96 480C96 515.3 124.7 544 160 544L480 544C515.3 544 544 515.3 544 480L544 160C544 124.7 515.3 96 480 96L160 96zM224 176C250.5 176 272 197.5 272 224C272 250.5 250.5 272 224 272C197.5 272 176 250.5 176 224C176 197.5 197.5 176 224 176zM368 288C376.4 288 384.1 292.4 388.5 299.5L476.5 443.5C481 450.9 481.2 460.2 477 467.8C472.8 475.4 464.7 480 456 480L184 480C175.1 480 166.8 475 162.7 467.1C158.6 459.2 159.2 449.6 164.3 442.3L220.3 362.3C224.8 355.9 232.1 352.1 240 352.1C247.9 352.1 255.2 355.9 259.7 362.3L286.1 400.1L347.5 299.6C351.9 292.5 359.6 288.1 368 288.1z""", + "color": "purple", + "description": "Convert documents to long continuous images", + }, + { + "id": "extract_pages", + "name": "Extract PDF Pages", + "icon": """M128.5 64C93.2 64 64.5 92.7 64.5 128L64.5 512C64.5 547.3 93.2 576 128.5 576L384.5 576C419.8 576 448.5 547.3 448.5 512L448.5 416L526.6 416L495.6 447C486.2 456.4 486.2 471.6 495.6 480.9C505 490.2 520.2 490.3 529.5 480.9L601.5 408.9C610.9 399.5 610.9 384.3 601.5 375L529.5 303C520.1 293.6 504.9 293.6 495.6 303C486.3 312.4 486.2 327.6 495.6 336.9L526.6 367.9L448.5 367.9L448.5 234.4C448.5 217.4 441.8 201.1 429.8 189.1L323.2 82.7C311.2 70.7 295 64 278 64L128.5 64zM390 240L296.5 240C283.2 240 272.5 229.3 272.5 216L272.5 122.5L390 240zM256.5 392C256.5 378.7 267.2 368 280.5 368L384.5 368L384.5 416L280.5 416C267.2 416 256.5 405.3 256.5 392z""", + "color": "orange", + "description": "Extract specific pages from PDF documents", + }, + # { no-longer viable + # "id": "Atext2word", + # "name": "Advanced Text to Word", + # "icon": """M72 96C49.9 96 32 113.9 32 136L32 192C32 209.7 46.3 224 64 224C81.7 224 96 209.7 96 192L96 160L160 160L160 480L128 480C110.3 480 96 494.3 96 512C96 529.7 110.3 544 128 544L256 544C273.7 544 288 529.7 288 512C288 494.3 273.7 480 256 480L224 480L224 160L288 160L288 192C288 209.7 302.3 224 320 224C337.7 224 352 209.7 352 192L352 136C352 113.9 334.1 96 312 96L72 96zM470.6 425.4C458.1 412.9 437.8 412.9 425.3 425.4C412.8 437.9 412.8 458.2 425.3 470.7L489.3 534.7C501.8 547.2 522.1 547.2 534.6 534.7L598.6 470.7C611.1 458.2 611.1 437.9 598.6 425.4C586.1 412.9 565.8 412.9 553.3 425.4L543.9 434.8L543.9 205.3L553.3 214.7C565.8 227.2 586.1 227.2 598.6 214.7C611.1 202.2 611.1 181.9 598.6 169.4L534.6 105.4C528.6 99.4 520.5 96 512 96C503.5 96 495.4 99.4 489.4 105.4L425.4 169.4C412.9 181.9 412.9 202.2 425.4 214.7C437.9 227.2 458.2 227.2 470.7 214.7L480.1 205.3L480.1 434.8L470.7 425.4z""", + # "color": "indigo", + # "description": "Convert text files to Word documents with formatting", + # }, + { + "id": "doc2image", + "name": "Document to Images", + "icon": """M128 128C128 92.7 156.7 64 192 64L341.5 64C358.5 64 374.8 70.7 386.8 82.7L493.3 189.3C505.3 201.3 512 217.6 512 234.6L512 512C512 547.3 483.3 576 448 576L192 576C156.7 576 128 547.3 128 512L128 128zM336 122.5L336 216C336 229.3 346.7 240 360 240L453.5 240L336 122.5zM256 320C256 302.3 241.7 288 224 288C206.3 288 192 302.3 192 320C192 337.7 206.3 352 224 352C241.7 352 256 337.7 256 320zM220.6 512L419.4 512C435.2 512 448 499.2 448 483.4C448 476.1 445.2 469 440.1 463.7L343.3 361.9C337.3 355.6 328.9 352 320.1 352L319.8 352C311 352 302.7 355.6 296.6 361.9L199.9 463.7C194.8 469 192 476.1 192 483.4C192 499.2 204.8 512 220.6 512z""", + "color": "pink", + "description": "Convert documents to image formats", + }, + ], + }, + "image": { + "icon": "image", + "color": "red", + "description": "Image processing and conversion tools", + "tools": [ + { + "id": "convert_image", + "name": "Image Conversion", + "icon": """M544.1 256L552 256C565.3 256 576 245.3 576 232L576 88C576 78.3 570.2 69.5 561.2 65.8C552.2 62.1 541.9 64.2 535 71L483.3 122.8C439 86.1 382 64 320 64C191 64 84.3 159.4 66.6 283.5C64.1 301 76.2 317.2 93.7 319.7C111.2 322.2 127.4 310 129.9 292.6C143.2 199.5 223.3 128 320 128C364.4 128 405.2 143 437.7 168.3L391 215C384.1 221.9 382.1 232.2 385.8 241.2C389.5 250.2 398.3 256 408 256L544.1 256zM573.5 356.5C576 339 563.8 322.8 546.4 320.3C529 317.8 512.7 330 510.2 347.4C496.9 440.4 416.8 511.9 320.1 511.9C275.7 511.9 234.9 496.9 202.4 471.6L249 425C255.9 418.1 257.9 407.8 254.2 398.8C250.5 389.8 241.7 384 232 384L88 384C74.7 384 64 394.7 64 408L64 552C64 561.7 69.8 570.5 78.8 574.2C87.8 577.9 98.1 575.8 105 569L156.8 517.2C201 553.9 258 576 320 576C449 576 555.7 480.6 573.4 356.5z""", + "color": "red", + "description": "Convert between PNG, JPG, WEBP, and other image formats", + }, + { + "id": "resize_image", + "name": "Image Resize", + "icon": """M264 96L120 96C106.7 96 96 106.7 96 120L96 264C96 273.7 101.8 282.5 110.8 286.2C119.8 289.9 130.1 287.8 137 281L177 241L256 320L177 399L137 359C130.1 352.1 119.8 350.1 110.8 353.8C101.8 357.5 96 366.3 96 376L96 520C96 533.3 106.7 544 120 544L264 544C273.7 544 282.5 538.2 286.2 529.2C289.9 520.2 287.9 509.9 281 503L241 463L320 384L399 463L359 503C352.1 509.9 350.1 520.2 353.8 529.2C357.5 538.2 366.3 544 376 544L520 544C533.3 544 544 533.3 544 520L544 376C544 366.3 538.2 357.5 529.2 353.8C520.2 350.1 509.9 352.1 503 359L463 399L384 320L463 241L503 281C509.9 287.9 520.2 289.9 529.2 286.2C538.2 282.5 544 273.7 544 264L544 120C544 106.7 533.3 96 520 96L376 96C366.3 96 357.5 101.8 353.8 110.8C350.1 119.8 352.2 130.1 359 137L399 177L320 256L241 177L281 137C287.9 130.1 289.9 119.8 286.2 110.8C282.5 101.8 273.7 96 264 96z""", + "color": "blue", + "description": "Resize and compress images", + }, + { + "id": "image2pdf", + "name": "Image to PDF", + "icon": """M128 64C92.7 64 64 92.7 64 128L64 512C64 547.3 92.7 576 128 576L208 576L208 464C208 428.7 236.7 400 272 400L448 400L448 234.5C448 217.5 441.3 201.2 429.3 189.2L322.7 82.7C310.7 70.7 294.5 64 277.5 64L128 64zM389.5 240L296 240C282.7 240 272 229.3 272 216L272 122.5L389.5 240zM272 444C261 444 252 453 252 464L252 592C252 603 261 612 272 612C283 612 292 603 292 592L292 564L304 564C337.1 564 364 537.1 364 504C364 470.9 337.1 444 304 444L272 444zM304 524L292 524L292 484L304 484C315 484 324 493 324 504C324 515 315 524 304 524zM400 444C389 444 380 453 380 464L380 592C380 603 389 612 400 612L432 612C460.7 612 484 588.7 484 560L484 496C484 467.3 460.7 444 432 444L400 444zM420 572L420 484L432 484C438.6 484 444 489.4 444 496L444 560C444 566.6 438.6 572 432 572L420 572zM508 464L508 592C508 603 517 612 528 612C539 612 548 603 548 592L548 548L576 548C587 548 596 539 596 528C596 517 587 508 576 508L548 508L548 484L576 484C587 484 596 475 596 464C596 453 587 444 576 444L528 444C517 444 508 453 508 464z""", + "color": "green", + "description": "Convert images to PDF documents", + }, + { + "id": "image2word", + "name": "Image to Word", + "icon": """M128 128C128 92.7 156.7 64 192 64L341.5 64C358.5 64 374.8 70.7 386.8 82.7L493.3 189.3C505.3 201.3 512 217.6 512 234.6L512 512C512 547.3 483.3 576 448 576L192 576C156.7 576 128 547.3 128 512L128 128zM336 122.5L336 216C336 229.3 346.7 240 360 240L453.5 240L336 122.5zM263.4 338.8C260.5 325.9 247.7 317.7 234.8 320.6C221.9 323.5 213.7 336.3 216.6 349.2L248.6 493.2C250.9 503.7 260 511.4 270.8 512C281.6 512.6 291.4 505.9 294.8 495.6L320 419.9L345.2 495.6C348.6 505.8 358.4 512.5 369.2 512C380 511.5 389.1 503.8 391.4 493.2L423.4 349.2C426.3 336.3 418.1 323.4 405.2 320.6C392.3 317.8 379.4 325.9 376.6 338.8L363.4 398.2L342.8 336.4C339.5 326.6 330.4 320 320 320C309.6 320 300.5 326.6 297.2 336.4L276.6 398.2L263.4 338.8z""", + "color": "purple", + "description": "Convert images to Word documents", + }, + { + "id": "image2gray", + "name": "Grayscale Conversion", + "icon": """M320 64C178.6 64 64 178.6 64 320C64 461.4 178.6 576 320 576C388.8 576 451.3 548.8 497.3 504.6C504.6 497.6 506.7 486.7 502.6 477.5C498.5 468.3 488.9 462.6 478.8 463.4C473.9 463.8 469 464 464 464C362.4 464 280 381.6 280 280C280 207.9 321.5 145.4 382.1 115.2C391.2 110.7 396.4 100.9 395.2 90.8C394 80.7 386.6 72.5 376.7 70.3C358.4 66.2 339.4 64 320 64z""", + "color": "gray", + "description": "Convert images to grayscale", + }, + { + "id": "ocr", + "name": "OCR Text Extraction", + "icon": """M72 96C49.9 96 32 113.9 32 136L32 192C32 209.7 46.3 224 64 224C81.7 224 96 209.7 96 192L96 160L160 160L160 480L128 480C110.3 480 96 494.3 96 512C96 529.7 110.3 544 128 544L256 544C273.7 544 288 529.7 288 512C288 494.3 273.7 480 256 480L224 480L224 160L288 160L288 192C288 209.7 302.3 224 320 224C337.7 224 352 209.7 352 192L352 136C352 113.9 334.1 96 312 96L72 96zM470.6 425.4C458.1 412.9 437.8 412.9 425.3 425.4C412.8 437.9 412.8 458.2 425.3 470.7L489.3 534.7C501.8 547.2 522.1 547.2 534.6 534.7L598.6 470.7C611.1 458.2 611.1 437.9 598.6 425.4C586.1 412.9 565.8 412.9 553.3 425.4L543.9 434.8L543.9 205.3L553.3 214.7C565.8 227.2 586.1 227.2 598.6 214.7C611.1 202.2 611.1 181.9 598.6 169.4L534.6 105.4C528.6 99.4 520.5 96 512 96C503.5 96 495.4 99.4 489.4 105.4L425.4 169.4C412.9 181.9 412.9 202.2 425.4 214.7C437.9 227.2 458.2 227.2 470.7 214.7L480.1 205.3L480.1 434.8L470.7 425.4z""", + "color": "indigo", + "description": "Extract text from images using OCR", + }, + ], + }, + "audio": { + "icon": "music", + "color": "green", + "description": "Audio conversion and processing tools", + "tools": [ + { + "id": "convert_audio", + "name": "Audio Conversion", + "icon": """M566.6 214.6L470.6 310.6C461.4 319.8 447.7 322.5 435.7 317.5C423.7 312.5 416 300.9 416 288L416 224L96 224C78.3 224 64 209.7 64 192C64 174.3 78.3 160 96 160L416 160L416 96C416 83.1 423.8 71.4 435.8 66.4C447.8 61.4 461.5 64.2 470.7 73.3L566.7 169.3C579.2 181.8 579.2 202.1 566.7 214.6zM169.3 566.6L73.3 470.6C60.8 458.1 60.8 437.8 73.3 425.3L169.3 329.3C178.5 320.1 192.2 317.4 204.2 322.4C216.2 327.4 224 339.1 224 352L224 416L544 416C561.7 416 576 430.3 576 448C576 465.7 561.7 480 544 480L224 480L224 544C224 556.9 216.2 568.6 204.2 573.6C192.2 578.6 178.5 575.8 169.3 566.7z""", + "color": "green", + "description": "Convert between MP3, WAV, FLAC, and other audio formats", + }, + { + "id": "audio_join", + "name": "Audio Joining", + "icon": """M296.5 69.2C311.4 62.3 328.6 62.3 343.5 69.2L562.1 170.2C570.6 174.1 576 182.6 576 192C576 201.4 570.6 209.9 562.1 213.8L343.5 314.8C328.6 321.7 311.4 321.7 296.5 314.8L77.9 213.8C69.4 209.8 64 201.3 64 192C64 182.7 69.4 174.1 77.9 170.2L296.5 69.2zM112.1 282.4L276.4 358.3C304.1 371.1 336 371.1 363.7 358.3L528 282.4L562.1 298.2C570.6 302.1 576 310.6 576 320C576 329.4 570.6 337.9 562.1 341.8L343.5 442.8C328.6 449.7 311.4 449.7 296.5 442.8L77.9 341.8C69.4 337.8 64 329.3 64 320C64 310.7 69.4 302.1 77.9 298.2L112 282.4zM77.9 426.2L112 410.4L276.3 486.3C304 499.1 335.9 499.1 363.6 486.3L527.9 410.4L562 426.2C570.5 430.1 575.9 438.6 575.9 448C575.9 457.4 570.5 465.9 562 469.8L343.4 570.8C328.5 577.7 311.3 577.7 296.4 570.8L77.9 469.8C69.4 465.8 64 457.3 64 448C64 438.7 69.4 430.1 77.9 426.2z""", + "color": "blue", + "description": "Merge multiple audio files into one", + }, + { + "id": "extract_audio", + "name": "Extract Audio from Video", + "icon": """M96 240L96 352C96 475.7 196.3 576 320 576C443.7 576 544 475.7 544 352L544 240L416 240L416 352C416 405 373 448 320 448C267 448 224 405 224 352L224 240L96 240zM96 192L224 192L224 128C224 110.3 209.7 96 192 96L128 96C110.3 96 96 110.3 96 128L96 192zM416 192L544 192L544 128C544 110.3 529.7 96 512 96L448 96C430.3 96 416 110.3 416 128L416 192z""", + "color": "purple", + "description": "Extract audio tracks from video files", + }, + { + "id": "audio_effect", + "name": "Audio Effects", + "icon": """M128 160C128 142.3 142.3 128 160 128L320 128C337.7 128 352 142.3 352 160L352 448L448 448L448 320C448 302.3 462.3 288 480 288L544 288C561.7 288 576 302.3 576 320C576 337.7 561.7 352 544 352L512 352L512 480C512 497.7 497.7 512 480 512L320 512C302.3 512 288 497.7 288 480L288 192L192 192L192 320C192 337.7 177.7 352 160 352L96 352C78.3 352 64 337.7 64 320C64 302.3 78.3 288 96 288L128 288L128 160""", + "color": "yellow", + "description": "Apply effects and process audio files", + }, + ], + }, + "video": { + "icon": "video", + "color": "purple", + "description": "Video conversion and analysis tools", + "tools": [ + { + "id": "convert_video", + "name": "Video Conversion", + "icon": """M544.1 256L552 256C565.3 256 576 245.3 576 232L576 88C576 78.3 570.2 69.5 561.2 65.8C552.2 62.1 541.9 64.2 535 71L483.3 122.8C439 86.1 382 64 320 64C191 64 84.3 159.4 66.6 283.5C64.1 301 76.2 317.2 93.7 319.7C111.2 322.2 127.4 310 129.9 292.6C143.2 199.5 223.3 128 320 128C364.4 128 405.2 143 437.7 168.3L391 215C384.1 221.9 382.1 232.2 385.8 241.2C389.5 250.2 398.3 256 408 256L544.1 256zM573.5 356.5C576 339 563.8 322.8 546.4 320.3C529 317.8 512.7 330 510.2 347.4C496.9 440.4 416.8 511.9 320.1 511.9C275.7 511.9 234.9 496.9 202.4 471.6L249 425C255.9 418.1 257.9 407.8 254.2 398.8C250.5 389.8 241.7 384 232 384L88 384C74.7 384 64 394.7 64 408L64 552C64 561.7 69.8 570.5 78.8 574.2C87.8 577.9 98.1 575.8 105 569L156.8 517.2C201 553.9 258 576 320 576C449 576 555.7 480.6 573.4 356.5z""", + "color": "purple", + "description": "Convert between MP4, MKV, AVI, and other video formats", + }, + { + "id": "analyze_video", + "name": "Video Analysis", + "icon": """M96 96C113.7 96 128 110.3 128 128L128 464C128 472.8 135.2 480 144 480L544 480C561.7 480 576 494.3 576 512C576 529.7 561.7 544 544 544L144 544C99.8 544 64 508.2 64 464L64 128C64 110.3 78.3 96 96 96zM192 160C192 142.3 206.3 128 224 128L416 128C433.7 128 448 142.3 448 160C448 177.7 433.7 192 416 192L224 192C206.3 192 192 177.7 192 160zM224 240L352 240C369.7 240 384 254.3 384 272C384 289.7 369.7 304 352 304L224 304C206.3 304 192 289.7 192 272C192 254.3 206.3 240 224 240zM224 352L480 352C497.7 352 512 366.3 512 384C512 401.7 497.7 416 480 416L224 416C206.3 416 192 401.7 192 384C192 366.3 206.3 352 224 352z""", + "color": "green", + "description": "Analyze video files and extract metadata", + }, + { + "id": "extract_audio", + "name": "Extract Audio from Video", + "icon": """M532 71C539.6 77.1 544 86.3 544 96L544 400C544 444.2 501 480 448 480C395 480 352 444.2 352 400C352 355.8 395 320 448 320C459.2 320 470 321.6 480 324.6L480 207.9L256 257.7L256 464C256 508.2 213 544 160 544C107 544 64 508.2 64 464C64 419.8 107 384 160 384C171.2 384 182 385.6 192 388.6L192 160C192 145 202.4 132 217.1 128.8L505.1 64.8C514.6 62.7 524.5 65 532.1 71.1z""", + "color": "blue", + "description": "Extract audio tracks from video files", + }, + ], + }, + "batch": { + "icon": "layer-group", + "color": "purple", + "description": "Batch processing and workflow tools", + "tools": [ + { + "id": "batch_dashboard", + "name": "Batch Processing Dashboard", + "icon": """M64 320C64 178.6 178.6 64 320 64C461.4 64 576 178.6 576 320C576 461.4 461.4 576 320 576C178.6 576 64 461.4 64 320zM352 160C352 142.3 337.7 128 320 128C302.3 128 288 142.3 288 160C288 177.7 302.3 192 320 192C337.7 192 352 177.7 352 160zM320 480C355.3 480 384 451.3 384 416C384 399.8 378 384.9 368 373.7L437.5 234.8C443.4 222.9 438.6 208.5 426.8 202.6C415 196.7 400.5 201.5 394.6 213.3L325.1 352.2C323.4 352.1 321.7 352 320 352C284.7 352 256 380.7 256 416C256 451.3 284.7 480 320 480zM240 208C240 190.3 225.7 176 208 176C190.3 176 176 190.3 176 208C176 225.7 190.3 240 208 240C225.7 240 240 225.7 240 208zM160 352C177.7 352 192 337.7 192 320C192 302.3 177.7 288 160 288C142.3 288 128 302.3 128 320C128 337.7 142.3 352 160 352zM512 320C512 302.3 497.7 288 480 288C462.3 288 448 302.3 448 320C448 337.7 462.3 352 480 352C497.7 352 512 337.7 512 320z""", + "color": "purple", + "description": "Manage batch processing operations", + }, + { + "id": "batch_doc_convert", + "name": "Batch Document Conversion", + "icon": """M288 64C252.7 64 224 92.7 224 128L224 384C224 419.3 252.7 448 288 448L480 448C515.3 448 544 419.3 544 384L544 183.4C544 166 536.9 149.3 524.3 137.2L466.6 81.8C454.7 70.4 438.8 64 422.3 64L288 64zM160 192C124.7 192 96 220.7 96 256L96 512C96 547.3 124.7 576 160 576L352 576C387.3 576 416 547.3 416 512L416 496L352 496L352 512L160 512L160 256L176 256L176 192L160 192z""", + "color": "blue", + "description": "Convert multiple documents in batch", + }, + { + "id": "folder_operations", + "name": "Folder Operations", + "icon": """M80 88C80 74.7 69.3 64 56 64C42.7 64 32 74.7 32 88L32 456C32 486.9 57.1 512 88 512L272 512L272 464L88 464C83.6 464 80 460.4 80 456L80 224L272 224L272 176L80 176L80 88zM368 288L560 288C586.5 288 608 266.5 608 240L608 144C608 117.5 586.5 96 560 96L477.3 96C468.8 96 460.7 92.6 454.7 86.6L446.1 78C437.1 69 424.9 63.9 412.2 63.9L368 64C341.5 64 320 85.5 320 112L320 240C320 266.5 341.5 288 368 288zM368 576L560 576C586.5 576 608 554.5 608 528L608 432C608 405.5 586.5 384 560 384L477.3 384C468.8 384 460.7 380.6 454.7 374.6L446.1 366C437.1 357 424.9 351.9 412.2 351.9L368 352C341.5 352 320 373.5 320 400L320 528C320 554.5 341.5 576 368 576z""", + "color": "yellow", + "description": "Process entire folders recursively", + }, + { + "id": "bulk_ocr", + "name": "Bulk OCR Processing", + "icon": """M72 96C49.9 96 32 113.9 32 136L32 192C32 209.7 46.3 224 64 224C81.7 224 96 209.7 96 192L96 160L160 160L160 480L128 480C110.3 480 96 494.3 96 512C96 529.7 110.3 544 128 544L256 544C273.7 544 288 529.7 288 512C288 494.3 273.7 480 256 480L224 480L224 160L288 160L288 192C288 209.7 302.3 224 320 224C337.7 224 352 209.7 352 192L352 136C352 113.9 334.1 96 312 96L72 96zM470.6 425.4C458.1 412.9 437.8 412.9 425.3 425.4C412.8 437.9 412.8 458.2 425.3 470.7L489.3 534.7C501.8 547.2 522.1 547.2 534.6 534.7L598.6 470.7C611.1 458.2 611.1 437.9 598.6 425.4C586.1 412.9 565.8 412.9 553.3 425.4L543.9 434.8L543.9 205.3L553.3 214.7C565.8 227.2 586.1 227.2 598.6 214.7C611.1 202.2 611.1 181.9 598.6 169.4L534.6 105.4C528.6 99.4 520.5 96 512 96C503.5 96 495.4 99.4 489.4 105.4L425.4 169.4C412.9 181.9 412.9 202.2 425.4 214.7C437.9 227.2 458.2 227.2 470.7 214.7L480.1 205.3L480.1 434.8L470.7 425.4z""", + "color": "indigo", + "description": "Extract text from multiple files", + }, + ], + }, +} diff --git a/fweb/core/forms.py b/fweb/core/forms.py new file mode 100644 index 0000000..e1bc796 --- /dev/null +++ b/fweb/core/forms.py @@ -0,0 +1,89 @@ +from django import forms + + +class FileUploadForm(forms.Form): + files = forms.FileField( + widget=forms.ClearableFileInput(attrs={"multiple": True}), required=True + ) + target_format = forms.ChoiceField(required=False) + use_extras = forms.BooleanField(required=False) + + def __init__(self, *args, **kwargs): + tool_config = kwargs.pop("tool_config", {}) + super().__init__(*args, **kwargs) + + # Dynamically set choices based on tool + if "format_choices" in tool_config: + self.fields["target_format"].choices = tool_config["format_choices"] + + +class DocumentConversionForm(FileUploadForm): + isolate = forms.CharField(required=False, max_length=50) + threads = forms.IntegerField(required=False, min_value=1, max_value=10, initial=3) + preserve_quality = forms.BooleanField(required=False, initial=True) + + +class ImageConversionForm(FileUploadForm): + quality = forms.IntegerField(required=False, min_value=1, max_value=100, initial=85) + width = forms.IntegerField(required=False, min_value=1) + height = forms.IntegerField(required=False, min_value=1) + size_limit = forms.CharField(required=False, max_length=20) + + +class AudioConversionForm(FileUploadForm): + bitrate = forms.ChoiceField( + choices=[ + ("128", "128 kbps"), + ("192", "192 kbps"), + ("256", "256 kbps"), + ("320", "320 kbps"), + ], + initial="192", + ) + sample_rate = forms.ChoiceField( + choices=[("44100", "44.1 kHz"), ("48000", "48 kHz"), ("96000", "96 kHz")], + initial="44100", + ) + + +class VideoConversionForm(FileUploadForm): + quality = forms.ChoiceField( + choices=[ + ("high", "High Quality"), + ("medium", "Medium Quality"), + ("low", "Low Quality"), + ("original", "Original Quality"), + ], + initial="medium", + ) + resolution = forms.ChoiceField( + choices=[ + ("original", "Original"), + ("4k", "4K (3840x2160)"), + ("1080p", "1080p (1920x1080)"), + ("720p", "720p (1280x720)"), + ], + initial="original", + ) + + +class OCRForm(FileUploadForm): + language = forms.ChoiceField( + choices=[ + ("eng", "English"), + ("spa", "Spanish"), + ("fra", "French"), + ("deu", "German"), + ("multi", "Multiple Languages"), + ], + initial="eng", + ) + output_format = forms.ChoiceField( + choices=[ + ("txt", "Plain Text"), + ("docx", "Word Document"), + ("pdf", "PDF Document"), + ], + initial="txt", + ) + preserve_layout = forms.BooleanField(required=False, initial=True) diff --git a/fweb/core/migrations/0001_initial.py b/fweb/core/migrations/0001_initial.py new file mode 100644 index 0000000..e6a71d5 --- /dev/null +++ b/fweb/core/migrations/0001_initial.py @@ -0,0 +1,48 @@ +# Generated by Django 5.1.6 on 2025-09-26 16:15 + +import django.db.models.deletion +from django.conf import settings +from django.db import migrations, models + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ] + + operations = [ + migrations.CreateModel( + name='ProcessingJob', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('job_id', models.CharField(max_length=100, unique=True)), + ('tool_id', models.CharField(max_length=50)), + ('input_files', models.JSONField()), + ('output_files', models.JSONField(default=list)), + ('status', models.CharField(choices=[('pending', 'Pending'), ('processing', 'Processing'), ('completed', 'Completed'), ('failed', 'Failed'), ('cancelled', 'Cancelled')], default='pending', max_length=20)), + ('progress', models.IntegerField(default=0)), + ('created_at', models.DateTimeField(auto_now_add=True)), + ('updated_at', models.DateTimeField(auto_now=True)), + ('error_message', models.TextField(blank=True)), + ('user', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), + ], + options={ + 'ordering': ['-created_at'], + }, + ), + migrations.CreateModel( + name='ProcessedFile', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('original_name', models.CharField(max_length=255)), + ('processed_name', models.CharField(max_length=255)), + ('file_path', models.CharField(max_length=500)), + ('file_size', models.BigIntegerField()), + ('processed_at', models.DateTimeField(auto_now_add=True)), + ('job', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='core.processingjob')), + ], + ), + ] diff --git a/fweb/core/migrations/__init__.py b/fweb/core/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/fweb/core/models.py b/fweb/core/models.py new file mode 100644 index 0000000..8ed85ef --- /dev/null +++ b/fweb/core/models.py @@ -0,0 +1,41 @@ +from django.db import models +from django.contrib.auth.models import User + + +class ProcessingJob(models.Model): + JOB_STATUS = [ + ("pending", "Pending"), + ("processing", "Processing"), + ("completed", "Completed"), + ("failed", "Failed"), + ("cancelled", "Cancelled"), + ] + + job_id = models.CharField(max_length=100, unique=True) + user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) + tool_id = models.CharField(max_length=50) + input_files = models.JSONField() # List of input file paths + output_files = models.JSONField(default=list) # List of output file paths + status = models.CharField(max_length=20, choices=JOB_STATUS, default="pending") + progress = models.IntegerField(default=0) # 0-100 + created_at = models.DateTimeField(auto_now_add=True) + updated_at = models.DateTimeField(auto_now=True) + error_message = models.TextField(blank=True) + + class Meta: + ordering = ["-created_at"] + + def __str__(self): + return f"{self.job_id} - {self.tool_id} - {self.status}" + + +class ProcessedFile(models.Model): + job = models.ForeignKey(ProcessingJob, on_delete=models.CASCADE) + original_name = models.CharField(max_length=255) + processed_name = models.CharField(max_length=255) + file_path = models.CharField(max_length=500) + file_size = models.BigIntegerField() + processed_at = models.DateTimeField(auto_now_add=True) + + def __str__(self): + return f"{self.original_name} -> {self.processed_name}" diff --git a/fweb/core/static/css/config.css b/fweb/core/static/css/config.css new file mode 100644 index 0000000..fe30e5a --- /dev/null +++ b/fweb/core/static/css/config.css @@ -0,0 +1,127 @@ +@tailwind base; +@tailwind components; +@tailwind utilities; +.scrollbar-hide { + /* Hide scrollbar for Chrome, Safari, and Edge */ + -ms-overflow-style: none; /* Internet Explorer 10+ */ + scrollbar-width: none; /* Firefox */ + overflow: -moz-scrollbars-none; /* Older Firefox */ + overflow-y: scroll; /* Add this to ensure the content is scrollable */ + &::-webkit-scrollbar { + display: none; /* Hide scrollbar for Chrome, Safari, and Edge */ + } +} + +@import url("https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap"); + +body { + font-family: "Inter", sans-serif; +} + +.fade-in { + animation: fadeIn 0.5s ease-in-out; +} + +@keyframes fadeIn { + from { + opacity: 0; + } + to { + opacity: 1; + } +} + +.gradient-bg { + background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); +} +.card-hover { + transition: all 0.3s ease; +} +.card-hover:hover { + transform: translateY(-5px); + box-shadow: + 0 20px 25px -5px rgba(0, 0, 0, 0.1), + 0 10px 10px -5px rgba(0, 0, 0, 0.04); +} +.file-drop-zone { + border: 2px dashed #d1d5db; + transition: all 0.3s ease; +} +.file-drop-zone.dragover { + border-color: #3b82f6; + background-color: #eff6ff; +} +.nav-link { + @apply px-3 py-2 rounded-md text-sm font-medium text-gray-700 dark:text-gray-300 hover:text-gray-900 dark:hover:text-white hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors; +} +.nav-link.active { + @apply bg-blue-100 dark:bg-blue-900 text-blue-700 dark:text-blue-300; +} +.tool-active { + @apply bg-blue-50 dark:bg-blue-900 border-blue-500 border-r-4; +} + +.nav-svg { + @apply w-[1.1rem] h-[1.1rem] text-2xl text-blue-600 fill-gray-700 dark:fill-gray-300; +} + +.nav-svg.active { + @apply fill-blue-700 dark:fill-blue-300; +} + +.waveform { + display: flex; + align-items: center; + height: 40px; + width: 100%; + justify-content: space-between; +} + +.bar { + width: 3px; + height: 10px; + background-color: #3b82f6; + border-radius: 3px; + animation: wave 1.2s infinite ease-in-out; +} + +@keyframes wave { + 0%, + 100% { + transform: scaleY(0.5); + } + 50% { + transform: scaleY(1.8); + } +} + +.bar:nth-child(1) { + animation-delay: 0s; +} +.bar:nth-child(2) { + animation-delay: 0.1s; +} +.bar:nth-child(3) { + animation-delay: 0.2s; +} +.bar:nth-child(4) { + animation-delay: 0.3s; +} +.bar:nth-child(5) { + animation-delay: 0.4s; +} +.bar:nth-child(6) { + animation-delay: 0.5s; +} +.bar:nth-child(7) { + animation-delay: 0.6s; +} +.bar:nth-child(8) { + animation-delay: 0.7s; +} +.bar:nth-child(9) { + animation-delay: 0.8s; +} +.bar:nth-child(10) { + animation-delay: 0.9s; +} diff --git a/fweb/core/static/css/styles.css b/fweb/core/static/css/styles.css new file mode 100644 index 0000000..d882f01 --- /dev/null +++ b/fweb/core/static/css/styles.css @@ -0,0 +1 @@ +*,::backdrop,:after,:before{--tw-border-spacing-x:0;--tw-border-spacing-y:0;--tw-translate-x:0;--tw-translate-y:0;--tw-rotate:0;--tw-skew-x:0;--tw-skew-y:0;--tw-scale-x:1;--tw-scale-y:1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness:proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-color:#3b82f680;--tw-ring-offset-shadow:0 0 #0000;--tw-ring-shadow:0 0 #0000;--tw-shadow:0 0 #0000;--tw-shadow-colored:0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }/*! tailwindcss v3.4.17 | MIT License | https://tailwindcss.com*/*,:after,:before{box-sizing:border-box;border:0 solid #e5e7eb}:after,:before{--tw-content:""}:host,html{line-height:1.5;-webkit-text-size-adjust:100%;tab-size:4;font-family:ui-sans-serif,system-ui,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;font-feature-settings:normal;font-variation-settings:normal;-webkit-tap-highlight-color:transparent}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,pre,samp{font-family:JetBrains Mono,monospace;font-feature-settings:normal;font-variation-settings:normal;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:initial}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-feature-settings:inherit;font-variation-settings:inherit;font-size:100%;font-weight:inherit;line-height:inherit;letter-spacing:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}button,input:where([type=button]),input:where([type=reset]),input:where([type=submit]){-webkit-appearance:button;background-color:initial;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:initial}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dd,dl,figure,h1,h2,h3,h4,h5,h6,hr,p,pre{margin:0}fieldset{margin:0}fieldset,legend{padding:0}menu,ol,ul{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::placeholder,textarea::placeholder{opacity:1;color:#9ca3af}[role=button],button{cursor:pointer}:disabled{cursor:default}audio,canvas,embed,iframe,img,object,svg,video{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}[hidden]:where(:not([hidden=until-found])){display:none}.\!container{width:100%!important}.container{width:100%}@media (min-width:640px){.\!container{max-width:640px!important}.container{max-width:640px}}@media (min-width:768px){.\!container{max-width:768px!important}.container{max-width:768px}}@media (min-width:1024px){.\!container{max-width:1024px!important}.container{max-width:1024px}}@media (min-width:1280px){.\!container{max-width:1280px!important}.container{max-width:1280px}}@media (min-width:1536px){.\!container{max-width:1536px!important}.container{max-width:1536px}}.pointer-events-none{pointer-events:none}.visible{visibility:visible}.collapse{visibility:collapse}.static{position:static}.\!fixed{position:fixed!important}.fixed{position:fixed}.absolute{position:absolute}.relative{position:relative}.sticky{position:-webkit-sticky;position:sticky}.inset-0{inset:0}.left-3{left:.75rem}.top-0{top:0}.top-1\/2{top:50%}.top-24{top:6rem}.top-6{top:1.5rem}.isolate{isolation:isolate}.z-50{z-index:50}.mx-2{margin-left:.5rem;margin-right:.5rem}.mx-4{margin-left:1rem;margin-right:1rem}.mx-auto{margin-left:auto;margin-right:auto}.mb-1{margin-bottom:.25rem}.mb-2{margin-bottom:.5rem}.mb-3{margin-bottom:.75rem}.mb-4{margin-bottom:1rem}.mb-6{margin-bottom:1.5rem}.mb-8{margin-bottom:2rem}.ml-2{margin-left:.5rem}.ml-6{margin-left:1.5rem}.mr-1{margin-right:.25rem}.mr-2{margin-right:.5rem}.mr-3{margin-right:.75rem}.mr-4{margin-right:1rem}.mt-1{margin-top:.25rem}.mt-12{margin-top:3rem}.mt-2{margin-top:.5rem}.mt-3{margin-top:.75rem}.mt-4{margin-top:1rem}.mt-6{margin-top:1.5rem}.mt-8{margin-top:2rem}.block{display:block}.inline-block{display:inline-block}.inline{display:inline}.flex{display:flex}.table{display:table}.table-caption{display:table-caption}.table-cell{display:table-cell}.grid{display:grid}.contents{display:contents}.\!hidden{display:none!important}.hidden{display:none}.h-10{height:2.5rem}.h-12{height:3rem}.h-16{height:4rem}.h-2{height:.5rem}.h-3{height:.75rem}.h-48{height:12rem}.h-5{height:1.25rem}.h-6{height:1.5rem}.h-7{height:1.75rem}.h-8{height:2rem}.h-full{height:100%}.max-h-40{max-height:10rem}.max-h-96{max-height:24rem}.max-h-\[90vh\]{max-height:90vh}.min-h-\[600px\]{min-height:600px}.w-10{width:2.5rem}.w-12{width:3rem}.w-5{width:1.25rem}.w-6{width:1.5rem}.w-7{width:1.75rem}.w-8{width:2rem}.w-full{width:100%}.max-w-3xl{max-width:48rem}.max-w-4xl{max-width:56rem}.max-w-6xl{max-width:72rem}.max-w-7xl{max-width:80rem}.max-w-md{max-width:28rem}.flex-1{flex:1 1 0%}.flex-shrink-0{flex-shrink:0}.-translate-y-1\/2{--tw-translate-y:-50%}.-translate-y-1\/2,.transform{transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.cursor-pointer{cursor:pointer}.resize{resize:both}.grid-cols-1{grid-template-columns:repeat(1,minmax(0,1fr))}.grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}.flex-col{flex-direction:column}.flex-wrap{flex-wrap:wrap}.items-center{align-items:center}.justify-center{justify-content:center}.justify-between{justify-content:space-between}.gap-1{gap:.25rem}.gap-2{gap:.5rem}.gap-3{gap:.75rem}.gap-4{gap:1rem}.gap-6{gap:1.5rem}.gap-8{gap:2rem}.space-x-2>:not([hidden])~:not([hidden]){--tw-space-x-reverse:0;margin-right:calc(.5rem*var(--tw-space-x-reverse));margin-left:calc(.5rem*(1 - var(--tw-space-x-reverse)))}.space-x-3>:not([hidden])~:not([hidden]){--tw-space-x-reverse:0;margin-right:calc(.75rem*var(--tw-space-x-reverse));margin-left:calc(.75rem*(1 - var(--tw-space-x-reverse)))}.space-x-4>:not([hidden])~:not([hidden]){--tw-space-x-reverse:0;margin-right:calc(1rem*var(--tw-space-x-reverse));margin-left:calc(1rem*(1 - var(--tw-space-x-reverse)))}.space-y-1>:not([hidden])~:not([hidden]){--tw-space-y-reverse:0;margin-top:calc(.25rem*(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.25rem*var(--tw-space-y-reverse))}.space-y-2>:not([hidden])~:not([hidden]){--tw-space-y-reverse:0;margin-top:calc(.5rem*(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.5rem*var(--tw-space-y-reverse))}.space-y-3>:not([hidden])~:not([hidden]){--tw-space-y-reverse:0;margin-top:calc(.75rem*(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.75rem*var(--tw-space-y-reverse))}.space-y-4>:not([hidden])~:not([hidden]){--tw-space-y-reverse:0;margin-top:calc(1rem*(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1rem*var(--tw-space-y-reverse))}.space-y-6>:not([hidden])~:not([hidden]){--tw-space-y-reverse:0;margin-top:calc(1.5rem*(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1.5rem*var(--tw-space-y-reverse))}.overflow-auto{overflow:auto}.overflow-hidden{overflow:hidden}.overflow-y-auto{overflow-y:auto}.truncate{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.whitespace-pre-wrap{white-space:pre-wrap}.rounded{border-radius:.25rem}.rounded-2xl{border-radius:1rem}.rounded-full{border-radius:9999px}.rounded-lg{border-radius:.5rem}.rounded-xl{border-radius:.75rem}.border{border-width:1px}.border-2{border-width:2px}.border-b{border-bottom-width:1px}.border-r-4{border-right-width:4px}.border-t{border-top-width:1px}.border-dashed{border-style:dashed}.border-blue-500{--tw-border-opacity:1;border-color:rgb(59 130 246/var(--tw-border-opacity,1))}.border-gray-200{--tw-border-opacity:1;border-color:rgb(229 231 235/var(--tw-border-opacity,1))}.border-gray-300{--tw-border-opacity:1;border-color:rgb(209 213 219/var(--tw-border-opacity,1))}.bg-black{--tw-bg-opacity:1;background-color:rgb(0 0 0/var(--tw-bg-opacity,1))}.bg-blue-100{--tw-bg-opacity:1;background-color:rgb(219 234 254/var(--tw-bg-opacity,1))}.bg-blue-50{--tw-bg-opacity:1;background-color:rgb(239 246 255/var(--tw-bg-opacity,1))}.bg-blue-600{--tw-bg-opacity:1;background-color:rgb(37 99 235/var(--tw-bg-opacity,1))}.bg-gray-200{--tw-bg-opacity:1;background-color:rgb(229 231 235/var(--tw-bg-opacity,1))}.bg-gray-50{--tw-bg-opacity:1;background-color:rgb(249 250 251/var(--tw-bg-opacity,1))}.bg-green-100{--tw-bg-opacity:1;background-color:rgb(220 252 231/var(--tw-bg-opacity,1))}.bg-green-600{--tw-bg-opacity:1;background-color:rgb(22 163 74/var(--tw-bg-opacity,1))}.bg-indigo-100{--tw-bg-opacity:1;background-color:rgb(224 231 255/var(--tw-bg-opacity,1))}.bg-indigo-600{--tw-bg-opacity:1;background-color:rgb(79 70 229/var(--tw-bg-opacity,1))}.bg-pink-100{--tw-bg-opacity:1;background-color:rgb(252 231 243/var(--tw-bg-opacity,1))}.bg-pink-600{--tw-bg-opacity:1;background-color:rgb(219 39 119/var(--tw-bg-opacity,1))}.bg-purple-100{--tw-bg-opacity:1;background-color:rgb(243 232 255/var(--tw-bg-opacity,1))}.bg-purple-600{--tw-bg-opacity:1;background-color:rgb(147 51 234/var(--tw-bg-opacity,1))}.bg-red-100{--tw-bg-opacity:1;background-color:rgb(254 226 226/var(--tw-bg-opacity,1))}.bg-red-300{--tw-bg-opacity:1;background-color:rgb(252 165 165/var(--tw-bg-opacity,1))}.bg-red-600{--tw-bg-opacity:1;background-color:rgb(220 38 38/var(--tw-bg-opacity,1))}.bg-white{--tw-bg-opacity:1;background-color:rgb(255 255 255/var(--tw-bg-opacity,1))}.bg-yellow-100{--tw-bg-opacity:1;background-color:rgb(254 249 195/var(--tw-bg-opacity,1))}.bg-yellow-600{--tw-bg-opacity:1;background-color:rgb(202 138 4/var(--tw-bg-opacity,1))}.bg-opacity-50{--tw-bg-opacity:0.5}.bg-gradient-to-br{background-image:linear-gradient(to bottom right,var(--tw-gradient-stops))}.from-blue-50{--tw-gradient-from:#eff6ff var(--tw-gradient-from-position);--tw-gradient-to:#eff6ff00 var(--tw-gradient-to-position);--tw-gradient-stops:var(--tw-gradient-from),var(--tw-gradient-to)}.from-green-50{--tw-gradient-from:#f0fdf4 var(--tw-gradient-from-position);--tw-gradient-to:#f0fdf400 var(--tw-gradient-to-position);--tw-gradient-stops:var(--tw-gradient-from),var(--tw-gradient-to)}.from-indigo-50{--tw-gradient-from:#eef2ff var(--tw-gradient-from-position);--tw-gradient-to:#eef2ff00 var(--tw-gradient-to-position);--tw-gradient-stops:var(--tw-gradient-from),var(--tw-gradient-to)}.from-pink-50{--tw-gradient-from:#fdf2f8 var(--tw-gradient-from-position);--tw-gradient-to:#fdf2f800 var(--tw-gradient-to-position);--tw-gradient-stops:var(--tw-gradient-from),var(--tw-gradient-to)}.from-red-50{--tw-gradient-from:#fef2f2 var(--tw-gradient-from-position);--tw-gradient-to:#fef2f200 var(--tw-gradient-to-position);--tw-gradient-stops:var(--tw-gradient-from),var(--tw-gradient-to)}.from-yellow-50{--tw-gradient-from:#fefce8 var(--tw-gradient-from-position);--tw-gradient-to:#fefce800 var(--tw-gradient-to-position);--tw-gradient-stops:var(--tw-gradient-from),var(--tw-gradient-to)}.to-blue-100{--tw-gradient-to:#dbeafe var(--tw-gradient-to-position)}.to-green-100{--tw-gradient-to:#dcfce7 var(--tw-gradient-to-position)}.to-indigo-100{--tw-gradient-to:#e0e7ff var(--tw-gradient-to-position)}.to-pink-100{--tw-gradient-to:#fce7f3 var(--tw-gradient-to-position)}.to-red-100{--tw-gradient-to:#fee2e2 var(--tw-gradient-to-position)}.to-yellow-100{--tw-gradient-to:#fef9c3 var(--tw-gradient-to-position)}.fill-blue-500{fill:#3b82f6}.fill-blue-600{fill:#2563eb}.fill-gray-400{fill:#9ca3af}.fill-gray-500{fill:#6b7280}.fill-gray-700{fill:#374151}.fill-green-500{fill:#22c55e}.fill-green-600{fill:#16a34a}.fill-indigo-500{fill:#6366f1}.fill-indigo-600{fill:#4f46e5}.fill-pink-600{fill:#db2777}.fill-purple-500{fill:#a855f7}.fill-purple-600{fill:#9333ea}.fill-red-500{fill:#ef4444}.fill-red-600{fill:#dc2626}.fill-sky-500{fill:#0ea5e9}.fill-slate-800{fill:#1e293b}.fill-white{fill:#fff}.fill-yellow-500{fill:#eab308}.fill-yellow-600{fill:#ca8a04}.fill-orange-500{fill:#f97316}.fill-pink-500{fill:#ec4899}.stroke-white{stroke:#fff}.p-2{padding:.5rem}.p-3{padding:.75rem}.p-4{padding:1rem}.p-6{padding:1.5rem}.p-8{padding:2rem}.px-2{padding-left:.5rem;padding-right:.5rem}.px-3{padding-left:.75rem;padding-right:.75rem}.px-4{padding-left:1rem;padding-right:1rem}.px-6{padding-left:1.5rem;padding-right:1.5rem}.py-1{padding-top:.25rem;padding-bottom:.25rem}.py-12{padding-top:3rem;padding-bottom:3rem}.py-2{padding-top:.5rem;padding-bottom:.5rem}.py-3{padding-top:.75rem;padding-bottom:.75rem}.py-6{padding-top:1.5rem;padding-bottom:1.5rem}.py-8{padding-top:2rem;padding-bottom:2rem}.pl-10{padding-left:2.5rem}.pr-4{padding-right:1rem}.pt-6{padding-top:1.5rem}.text-left{text-align:left}.text-center{text-align:center}.font-mono{font-family:JetBrains Mono,monospace}.text-2xl{font-size:1.5rem;line-height:2rem}.text-3xl{font-size:1.875rem;line-height:2.25rem}.text-4xl{font-size:2.25rem;line-height:2.5rem}.text-lg{font-size:1.125rem;line-height:1.75rem}.text-sm{font-size:.875rem;line-height:1.25rem}.text-xl{font-size:1.25rem;line-height:1.75rem}.text-xs{font-size:.75rem;line-height:1rem}.font-bold{font-weight:700}.font-medium{font-weight:500}.font-normal{font-weight:400}.font-semibold{font-weight:600}.uppercase{text-transform:uppercase}.lowercase{text-transform:lowercase}.text-blue-500{--tw-text-opacity:1;color:rgb(59 130 246/var(--tw-text-opacity,1))}.text-blue-600{--tw-text-opacity:1;color:rgb(37 99 235/var(--tw-text-opacity,1))}.text-blue-800{--tw-text-opacity:1;color:rgb(30 64 175/var(--tw-text-opacity,1))}.text-gray-300{--tw-text-opacity:1;color:rgb(209 213 219/var(--tw-text-opacity,1))}.text-gray-400{--tw-text-opacity:1;color:rgb(156 163 175/var(--tw-text-opacity,1))}.text-gray-500{--tw-text-opacity:1;color:rgb(107 114 128/var(--tw-text-opacity,1))}.text-gray-600{--tw-text-opacity:1;color:rgb(75 85 99/var(--tw-text-opacity,1))}.text-gray-700{--tw-text-opacity:1;color:rgb(55 65 81/var(--tw-text-opacity,1))}.text-gray-800{--tw-text-opacity:1;color:rgb(31 41 55/var(--tw-text-opacity,1))}.text-gray-900{--tw-text-opacity:1;color:rgb(17 24 39/var(--tw-text-opacity,1))}.text-green-600{--tw-text-opacity:1;color:rgb(22 163 74/var(--tw-text-opacity,1))}.text-green-800{--tw-text-opacity:1;color:rgb(22 101 52/var(--tw-text-opacity,1))}.text-indigo-600{--tw-text-opacity:1;color:rgb(79 70 229/var(--tw-text-opacity,1))}.text-indigo-800{--tw-text-opacity:1;color:rgb(55 48 163/var(--tw-text-opacity,1))}.text-purple-600{--tw-text-opacity:1;color:rgb(147 51 234/var(--tw-text-opacity,1))}.text-purple-800{--tw-text-opacity:1;color:rgb(107 33 168/var(--tw-text-opacity,1))}.text-red-600{--tw-text-opacity:1;color:rgb(220 38 38/var(--tw-text-opacity,1))}.text-red-800{--tw-text-opacity:1;color:rgb(153 27 27/var(--tw-text-opacity,1))}.text-slate-700{--tw-text-opacity:1;color:rgb(51 65 85/var(--tw-text-opacity,1))}.text-white{--tw-text-opacity:1;color:rgb(255 255 255/var(--tw-text-opacity,1))}.text-yellow-800{--tw-text-opacity:1;color:rgb(133 77 14/var(--tw-text-opacity,1))}.opacity-90{opacity:.9}.shadow{--tw-shadow:0 1px 3px 0 #0000001a,0 1px 2px -1px #0000001a;--tw-shadow-colored:0 1px 3px 0 var(--tw-shadow-color),0 1px 2px -1px var(--tw-shadow-color)}.shadow,.shadow-lg{box-shadow:var(--tw-ring-offset-shadow,0 0 #0000),var(--tw-ring-shadow,0 0 #0000),var(--tw-shadow)}.shadow-lg{--tw-shadow:0 10px 15px -3px #0000001a,0 4px 6px -4px #0000001a;--tw-shadow-colored:0 10px 15px -3px var(--tw-shadow-color),0 4px 6px -4px var(--tw-shadow-color)}.shadow-md{--tw-shadow:0 4px 6px -1px #0000001a,0 2px 4px -2px #0000001a;--tw-shadow-colored:0 4px 6px -1px var(--tw-shadow-color),0 2px 4px -2px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow,0 0 #0000),var(--tw-ring-shadow,0 0 #0000),var(--tw-shadow)}.blur{--tw-blur:blur(8px)}.blur,.grayscale{filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.grayscale{--tw-grayscale:grayscale(100%)}.\!invert{--tw-invert:invert(100%)!important;filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)!important}.invert{--tw-invert:invert(100%);filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.\!filter{filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)!important}.filter{filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.transition-all{transition-property:all;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-colors{transition-property:color,background-color,border-color,fill,stroke,-webkit-text-decoration-color;transition-property:color,background-color,border-color,text-decoration-color,fill,stroke;transition-property:color,background-color,border-color,text-decoration-color,fill,stroke,-webkit-text-decoration-color;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.duration-300{transition-duration:.3s}.ease-in{transition-timing-function:cubic-bezier(.4,0,1,1)}.ease-in-out{transition-timing-function:cubic-bezier(.4,0,.2,1)}.ease-out{transition-timing-function:cubic-bezier(0,0,.2,1)}.scrollbar-hide{-ms-overflow-style:none;scrollbar-width:none;overflow:-moz-scrollbars-none;overflow-y:scroll;&::-webkit-scrollbar{display:none}}body{font-family:Inter,sans-serif}.fade-in{animation:fadeIn .5s ease-in-out}@keyframes fadeIn{0%{opacity:0}to{opacity:1}}.gradient-bg{background:linear-gradient(135deg,#667eea,#764ba2)}.card-hover{transition:all .3s ease}.card-hover:hover{transform:translateY(-5px);box-shadow:0 20px 25px -5px #0000001a,0 10px 10px -5px #0000000a}.file-drop-zone{border:2px dashed #d1d5db;transition:all .3s ease}.file-drop-zone.dragover{border-color:#3b82f6;background-color:#eff6ff}.nav-link{border-radius:.375rem;padding:.5rem .75rem;font-size:.875rem;line-height:1.25rem;font-weight:500;--tw-text-opacity:1;color:rgb(55 65 81/var(--tw-text-opacity,1));transition-property:color,background-color,border-color,fill,stroke,-webkit-text-decoration-color;transition-property:color,background-color,border-color,text-decoration-color,fill,stroke;transition-property:color,background-color,border-color,text-decoration-color,fill,stroke,-webkit-text-decoration-color;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.nav-link:hover{--tw-bg-opacity:1;background-color:rgb(243 244 246/var(--tw-bg-opacity,1));--tw-text-opacity:1;color:rgb(17 24 39/var(--tw-text-opacity,1))}.nav-link:is(.dark *){--tw-text-opacity:1;color:rgb(209 213 219/var(--tw-text-opacity,1))}.nav-link:hover:is(.dark *){--tw-bg-opacity:1;background-color:rgb(55 65 81/var(--tw-bg-opacity,1));--tw-text-opacity:1;color:rgb(255 255 255/var(--tw-text-opacity,1))}.nav-link.active{--tw-bg-opacity:1;background-color:rgb(219 234 254/var(--tw-bg-opacity,1));--tw-text-opacity:1;color:rgb(29 78 216/var(--tw-text-opacity,1))}.nav-link.active:is(.dark *){--tw-bg-opacity:1;background-color:rgb(30 58 138/var(--tw-bg-opacity,1));--tw-text-opacity:1;color:rgb(147 197 253/var(--tw-text-opacity,1))}.tool-active{border-right-width:4px;--tw-border-opacity:1;border-color:rgb(59 130 246/var(--tw-border-opacity,1));--tw-bg-opacity:1;background-color:rgb(239 246 255/var(--tw-bg-opacity,1))}.tool-active:is(.dark *){--tw-bg-opacity:1;background-color:rgb(30 58 138/var(--tw-bg-opacity,1))}.nav-svg{height:1.1rem;width:1.1rem;fill:#374151;font-size:1.5rem;line-height:2rem;--tw-text-opacity:1;color:rgb(37 99 235/var(--tw-text-opacity,1))}.nav-svg:is(.dark *){fill:#d1d5db}.nav-svg.active{fill:#1d4ed8}.nav-svg.active:is(.dark *){fill:#93c5fd}.waveform{display:flex;align-items:center;height:40px;width:100%;justify-content:space-between}.bar{width:3px;height:10px;background-color:#3b82f6;border-radius:3px;animation:wave 1.2s ease-in-out infinite}@keyframes wave{0%,to{transform:scaleY(.5)}50%{transform:scaleY(1.8)}}.bar:first-child{animation-delay:0s}.bar:nth-child(2){animation-delay:.1s}.bar:nth-child(3){animation-delay:.2s}.bar:nth-child(4){animation-delay:.3s}.bar:nth-child(5){animation-delay:.4s}.bar:nth-child(6){animation-delay:.5s}.bar:nth-child(7){animation-delay:.6s}.bar:nth-child(8){animation-delay:.7s}.bar:nth-child(9){animation-delay:.8s}.bar:nth-child(10){animation-delay:.9s}.hover\:bg-blue-50:hover{--tw-bg-opacity:1;background-color:rgb(239 246 255/var(--tw-bg-opacity,1))}.hover\:bg-blue-700:hover{--tw-bg-opacity:1;background-color:rgb(29 78 216/var(--tw-bg-opacity,1))}.hover\:bg-gray-300:hover{--tw-bg-opacity:1;background-color:rgb(209 213 219/var(--tw-bg-opacity,1))}.hover\:bg-gray-50:hover{--tw-bg-opacity:1;background-color:rgb(249 250 251/var(--tw-bg-opacity,1))}.hover\:bg-green-50:hover{--tw-bg-opacity:1;background-color:rgb(240 253 244/var(--tw-bg-opacity,1))}.hover\:bg-green-700:hover{--tw-bg-opacity:1;background-color:rgb(21 128 61/var(--tw-bg-opacity,1))}.hover\:bg-indigo-700:hover{--tw-bg-opacity:1;background-color:rgb(67 56 202/var(--tw-bg-opacity,1))}.hover\:bg-pink-700:hover{--tw-bg-opacity:1;background-color:rgb(190 24 93/var(--tw-bg-opacity,1))}.hover\:bg-primary-100:hover{--tw-bg-opacity:1;background-color:rgb(219 234 254/var(--tw-bg-opacity,1))}.hover\:bg-purple-50:hover{--tw-bg-opacity:1;background-color:rgb(250 245 255/var(--tw-bg-opacity,1))}.hover\:bg-purple-700:hover{--tw-bg-opacity:1;background-color:rgb(126 34 206/var(--tw-bg-opacity,1))}.hover\:bg-red-50:hover{--tw-bg-opacity:1;background-color:rgb(254 242 242/var(--tw-bg-opacity,1))}.hover\:bg-red-700:hover{--tw-bg-opacity:1;background-color:rgb(185 28 28/var(--tw-bg-opacity,1))}.hover\:bg-yellow-700:hover{--tw-bg-opacity:1;background-color:rgb(161 98 7/var(--tw-bg-opacity,1))}.hover\:text-blue-600:hover{--tw-text-opacity:1;color:rgb(37 99 235/var(--tw-text-opacity,1))}.hover\:text-blue-800:hover{--tw-text-opacity:1;color:rgb(30 64 175/var(--tw-text-opacity,1))}.hover\:text-gray-700:hover{--tw-text-opacity:1;color:rgb(55 65 81/var(--tw-text-opacity,1))}.hover\:text-green-800:hover{--tw-text-opacity:1;color:rgb(22 101 52/var(--tw-text-opacity,1))}.focus\:border-transparent:focus{border-color:#0000}.focus\:ring-2:focus{--tw-ring-offset-shadow:var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow:var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow,0 0 #0000)}.focus\:ring-blue-500:focus{--tw-ring-opacity:1;--tw-ring-color:rgb(59 130 246/var(--tw-ring-opacity,1))}.focus\:ring-green-500:focus{--tw-ring-opacity:1;--tw-ring-color:rgb(34 197 94/var(--tw-ring-opacity,1))}.dark\:block:is(.dark *){display:block}.dark\:hidden:is(.dark *){display:none}.dark\:border-gray-600:is(.dark *){--tw-border-opacity:1;border-color:rgb(75 85 99/var(--tw-border-opacity,1))}.dark\:border-gray-700:is(.dark *){--tw-border-opacity:1;border-color:rgb(55 65 81/var(--tw-border-opacity,1))}.dark\:bg-\[\#004754\]:is(.dark *){--tw-bg-opacity:1;background-color:rgb(0 71 84/var(--tw-bg-opacity,1))}.dark\:bg-blue-700:is(.dark *){--tw-bg-opacity:1;background-color:rgb(29 78 216/var(--tw-bg-opacity,1))}.dark\:bg-blue-900:is(.dark *){--tw-bg-opacity:1;background-color:rgb(30 58 138/var(--tw-bg-opacity,1))}.dark\:bg-gray-600:is(.dark *){--tw-bg-opacity:1;background-color:rgb(75 85 99/var(--tw-bg-opacity,1))}.dark\:bg-gray-700:is(.dark *){--tw-bg-opacity:1;background-color:rgb(55 65 81/var(--tw-bg-opacity,1))}.dark\:bg-gray-800:is(.dark *){--tw-bg-opacity:1;background-color:rgb(31 41 55/var(--tw-bg-opacity,1))}.dark\:bg-gray-900:is(.dark *){--tw-bg-opacity:1;background-color:rgb(17 24 39/var(--tw-bg-opacity,1))}.dark\:bg-green-700:is(.dark *){--tw-bg-opacity:1;background-color:rgb(21 128 61/var(--tw-bg-opacity,1))}.dark\:bg-green-900:is(.dark *){--tw-bg-opacity:1;background-color:rgb(20 83 45/var(--tw-bg-opacity,1))}.dark\:bg-indigo-700:is(.dark *){--tw-bg-opacity:1;background-color:rgb(67 56 202/var(--tw-bg-opacity,1))}.dark\:bg-indigo-900:is(.dark *){--tw-bg-opacity:1;background-color:rgb(49 46 129/var(--tw-bg-opacity,1))}.dark\:bg-pink-700:is(.dark *){--tw-bg-opacity:1;background-color:rgb(190 24 93/var(--tw-bg-opacity,1))}.dark\:bg-purple-900:is(.dark *){--tw-bg-opacity:1;background-color:rgb(88 28 135/var(--tw-bg-opacity,1))}.dark\:bg-red-700:is(.dark *){--tw-bg-opacity:1;background-color:rgb(185 28 28/var(--tw-bg-opacity,1))}.dark\:bg-red-900:is(.dark *){--tw-bg-opacity:1;background-color:rgb(127 29 29/var(--tw-bg-opacity,1))}.dark\:bg-yellow-700:is(.dark *){--tw-bg-opacity:1;background-color:rgb(161 98 7/var(--tw-bg-opacity,1))}.dark\:bg-yellow-900:is(.dark *){--tw-bg-opacity:1;background-color:rgb(113 63 18/var(--tw-bg-opacity,1))}.dark\:from-blue-900:is(.dark *){--tw-gradient-from:#1e3a8a var(--tw-gradient-from-position);--tw-gradient-to:#1e3a8a00 var(--tw-gradient-to-position);--tw-gradient-stops:var(--tw-gradient-from),var(--tw-gradient-to)}.dark\:from-green-900:is(.dark *){--tw-gradient-from:#14532d var(--tw-gradient-from-position);--tw-gradient-to:#14532d00 var(--tw-gradient-to-position);--tw-gradient-stops:var(--tw-gradient-from),var(--tw-gradient-to)}.dark\:from-indigo-900:is(.dark *){--tw-gradient-from:#312e81 var(--tw-gradient-from-position);--tw-gradient-to:#312e8100 var(--tw-gradient-to-position);--tw-gradient-stops:var(--tw-gradient-from),var(--tw-gradient-to)}.dark\:from-pink-900:is(.dark *){--tw-gradient-from:#831843 var(--tw-gradient-from-position);--tw-gradient-to:#83184300 var(--tw-gradient-to-position);--tw-gradient-stops:var(--tw-gradient-from),var(--tw-gradient-to)}.dark\:from-red-900:is(.dark *){--tw-gradient-from:#7f1d1d var(--tw-gradient-from-position);--tw-gradient-to:#7f1d1d00 var(--tw-gradient-to-position);--tw-gradient-stops:var(--tw-gradient-from),var(--tw-gradient-to)}.dark\:from-yellow-900:is(.dark *){--tw-gradient-from:#713f12 var(--tw-gradient-from-position);--tw-gradient-to:#713f1200 var(--tw-gradient-to-position);--tw-gradient-stops:var(--tw-gradient-from),var(--tw-gradient-to)}.dark\:to-blue-800:is(.dark *){--tw-gradient-to:#1e40af var(--tw-gradient-to-position)}.dark\:to-green-800:is(.dark *){--tw-gradient-to:#166534 var(--tw-gradient-to-position)}.dark\:to-indigo-800:is(.dark *){--tw-gradient-to:#3730a3 var(--tw-gradient-to-position)}.dark\:to-pink-800:is(.dark *){--tw-gradient-to:#9d174d var(--tw-gradient-to-position)}.dark\:to-red-800:is(.dark *){--tw-gradient-to:#991b1b var(--tw-gradient-to-position)}.dark\:to-yellow-800:is(.dark *){--tw-gradient-to:#854d0e var(--tw-gradient-to-position)}.dark\:fill-gray-200:is(.dark *){fill:#e5e7eb}.dark\:fill-gray-300:is(.dark *){fill:#d1d5db}.dark\:fill-gray-400:is(.dark *){fill:#9ca3af}.dark\:fill-indigo-300:is(.dark *){fill:#a5b4fc}.dark\:fill-pink-300:is(.dark *){fill:#f9a8d4}.dark\:fill-purple-300:is(.dark *){fill:#d8b4fe}.dark\:fill-white:is(.dark *){fill:#fff}.dark\:text-blue-200:is(.dark *){--tw-text-opacity:1;color:rgb(191 219 254/var(--tw-text-opacity,1))}.dark\:text-blue-400:is(.dark *){--tw-text-opacity:1;color:rgb(96 165 250/var(--tw-text-opacity,1))}.dark\:text-gray-200:is(.dark *){--tw-text-opacity:1;color:rgb(229 231 235/var(--tw-text-opacity,1))}.dark\:text-gray-300:is(.dark *){--tw-text-opacity:1;color:rgb(209 213 219/var(--tw-text-opacity,1))}.dark\:text-gray-400:is(.dark *){--tw-text-opacity:1;color:rgb(156 163 175/var(--tw-text-opacity,1))}.dark\:text-gray-500:is(.dark *){--tw-text-opacity:1;color:rgb(107 114 128/var(--tw-text-opacity,1))}.dark\:text-green-200:is(.dark *){--tw-text-opacity:1;color:rgb(187 247 208/var(--tw-text-opacity,1))}.dark\:text-green-400:is(.dark *){--tw-text-opacity:1;color:rgb(74 222 128/var(--tw-text-opacity,1))}.dark\:text-indigo-200:is(.dark *){--tw-text-opacity:1;color:rgb(199 210 254/var(--tw-text-opacity,1))}.dark\:text-indigo-400:is(.dark *){--tw-text-opacity:1;color:rgb(129 140 248/var(--tw-text-opacity,1))}.dark\:text-purple-200:is(.dark *){--tw-text-opacity:1;color:rgb(233 213 255/var(--tw-text-opacity,1))}.dark\:text-purple-400:is(.dark *){--tw-text-opacity:1;color:rgb(192 132 252/var(--tw-text-opacity,1))}.dark\:text-red-200:is(.dark *){--tw-text-opacity:1;color:rgb(254 202 202/var(--tw-text-opacity,1))}.dark\:text-red-400:is(.dark *){--tw-text-opacity:1;color:rgb(248 113 113/var(--tw-text-opacity,1))}.dark\:text-slate-300:is(.dark *){--tw-text-opacity:1;color:rgb(203 213 225/var(--tw-text-opacity,1))}.dark\:text-white:is(.dark *){--tw-text-opacity:1;color:rgb(255 255 255/var(--tw-text-opacity,1))}.dark\:text-yellow-200:is(.dark *){--tw-text-opacity:1;color:rgb(254 240 138/var(--tw-text-opacity,1))}.dark\:hover\:bg-\[\#002d34\]:hover:is(.dark *){--tw-bg-opacity:1;background-color:rgb(0 45 52/var(--tw-bg-opacity,1))}.dark\:hover\:bg-gray-500:hover:is(.dark *){--tw-bg-opacity:1;background-color:rgb(107 114 128/var(--tw-bg-opacity,1))}.dark\:hover\:bg-gray-600:hover:is(.dark *){--tw-bg-opacity:1;background-color:rgb(75 85 99/var(--tw-bg-opacity,1))}.dark\:hover\:bg-gray-700:hover:is(.dark *){--tw-bg-opacity:1;background-color:rgb(55 65 81/var(--tw-bg-opacity,1))}.dark\:hover\:text-blue-400:hover:is(.dark *){--tw-text-opacity:1;color:rgb(96 165 250/var(--tw-text-opacity,1))}@media (min-width:640px){.sm\:px-6{padding-left:1.5rem;padding-right:1.5rem}}@media (min-width:768px){.md\:col-span-2{grid-column:span 2/span 2}.md\:ml-6{margin-left:1.5rem}.md\:flex{display:flex}.md\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.md\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.md\:grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}.md\:space-x-8>:not([hidden])~:not([hidden]){--tw-space-x-reverse:0;margin-right:calc(2rem*var(--tw-space-x-reverse));margin-left:calc(2rem*(1 - var(--tw-space-x-reverse)))}}@media (min-width:1024px){.lg\:col-span-1{grid-column:span 1/span 1}.lg\:col-span-2{grid-column:span 2/span 2}.lg\:col-span-3{grid-column:span 3/span 3}.lg\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.lg\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.lg\:grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}.lg\:px-8{padding-left:2rem;padding-right:2rem}} \ No newline at end of file diff --git a/fweb/core/static/js/FileHandler.js b/fweb/core/static/js/FileHandler.js new file mode 100644 index 0000000..6e7ae2b --- /dev/null +++ b/fweb/core/static/js/FileHandler.js @@ -0,0 +1,134 @@ +class FileHandler { + constructor() { + this.setupGlobalFileHandlers(); + } + + setupFileDropZone(dropZoneId, inputId, multiple = true) { + const dropZone = document.getElementById(dropZoneId); + const fileInput = document.getElementById(inputId); + + if (!dropZone || !fileInput) return; + + fileInput.multiple = multiple; + + // Click to select files + dropZone.addEventListener("click", () => fileInput.click()); + + // Drag and drop handlers + this.setupDragAndDrop(dropZone, fileInput, multiple); + + // File input change handler + fileInput.addEventListener("change", () => { + this.updateFileList(dropZoneId, fileInput.files); + }); + } + + openFileSelector(dropZoneId) { + const inputElement = document.getElementById(`${dropZoneId}-input`); + inputElement?.click(); + } + + setupDragAndDrop(dropZone, fileInput, multiple) { + dropZone.addEventListener("dragover", (e) => { + e.preventDefault(); + dropZone.classList.add("dragover"); + }); + + dropZone.addEventListener("dragleave", () => { + dropZone.classList.remove("dragover"); + }); + + dropZone.addEventListener("drop", (e) => { + e.preventDefault(); + dropZone.classList.remove("dragover"); + + if (multiple) { + fileInput.files = e.dataTransfer.files; + } else { + fileInput.files = + e.dataTransfer.files.length > 0 + ? [e.dataTransfer.files[0]] + : new DataTransfer().files; + } + this.updateFileList(dropZone.id, fileInput.files); + }); + } + + updateFileList(dropZoneId, files) { + const dropZone = document.getElementById(dropZoneId); + const fileList = dropZone.querySelector(".file-list"); + const placeholder = dropZone.querySelector(".drop-placeholder"); + + if (files.length > 0) { + if (placeholder) placeholder.classList.add("hidden"); + fileList.innerHTML = ""; + + Array.from(files).forEach((file, index) => { + const fileItem = this.createFileItem(file, dropZoneId, index); + fileList.appendChild(fileItem); + }); + } else { + if (placeholder) placeholder.classList.remove("hidden"); + fileList.innerHTML = ""; + } + } + + createFileItem(file, dropZoneId, index) { + const fileItem = document.createElement("div"); + fileItem.className = + "flex items-center justify-between p-3 bg-gray-50 dark:bg-gray-700 rounded-lg mb-2"; + fileItem.innerHTML = ` +
+ + ${file.name} +
+
+ ${(file.size / 1024 / 1024).toFixed(2)} MB + +
+ `; + return fileItem; + } + + removeFile(dropZoneId, index) { + const fileInput = document.querySelector( + `#${dropZoneId.replace("-drop-zone", "-file-input")}`, + ); + const dt = new DataTransfer(); + + Array.from(fileInput.files).forEach((file, i) => { + if (i !== index) dt.items.add(file); + }); + + fileInput.files = dt.files; + this.updateFileList(dropZoneId, fileInput.files); + } + + setupGlobalFileHandlers() { + // Add any global file-related event listeners here + } + + validateFiles(files, allowedTypes = []) { + if (files.length === 0) return { valid: false, error: "No files selected" }; + + if (allowedTypes.length > 0) { + for (let file of files) { + const extension = file.name.split(".").pop().toLowerCase(); + if (!allowedTypes.includes(extension)) { + return { + valid: false, + error: `File type .${extension} is not allowed`, + }; + } + } + } + + return { valid: true }; + } +} + +// Initialize global file handler +window.fileHandler = new FileHandler(); diff --git a/fweb/core/static/js/ToolsHandler.js b/fweb/core/static/js/ToolsHandler.js new file mode 100644 index 0000000..1361636 --- /dev/null +++ b/fweb/core/static/js/ToolsHandler.js @@ -0,0 +1,366 @@ +class ToolHandler { + constructor() { + this.currentTool = null; + this.category = document.body.dataset.category || "document"; + this.init(); + } + + init() { + this.setupToolNavigation(); + this.initializeFromURL(); + } + + setupToolNavigation() { + // Add click handlers to all tool navigation items + document.addEventListener("click", (e) => { + const toolNav = e.target.closest(".tool-nav"); + if (toolNav) { + const toolId = this.getToolIdFromElement(toolNav); + if (toolId) { + this.showTool(toolId); + e.preventDefault(); + } + } + }); + } + + getToolIdFromElement(element) { + // Find the tool ID from element's classes (class="tool-nav tool-{id}") + for (let className of element.classList) { + if (className.startsWith("tool-") && className !== "tool-nav") { + return className.replace("tool-", ""); + } + } + return null; + } + + showTool(toolId, category) { + this.category = category; + // Hide all tool interfaces + this.hideAllToolInterfaces(); + + // Show selected tool + const selectedTool = document.getElementById(`tool-${toolId}`); + if (selectedTool) { + selectedTool.classList.remove("hidden"); + this.currentTool = toolId; + } + + // Update active navigation + this.updateActiveNav(toolId); + + // Update URL + this.updateURL(toolId); + + // Initialize tool-specific functionality + this.initializeTool(toolId); + } + + hideAllToolInterfaces() { + document.querySelectorAll(".tool-interface").forEach((_interface) => { + _interface.classList.add("hidden"); + }); + } + + updateActiveNav(toolId) { + document.querySelectorAll(".tool-nav").forEach((nav) => { + nav.classList.remove("tool-active"); + }); + + const activeNav = document.querySelector(`.tool-${toolId}`); + if (activeNav) { + activeNav.classList.add("tool-active"); + } + } + + updateURL(toolId) { + const newUrl = `${window.location.pathname}?tool=${toolId}`; + window.history.replaceState({ tool: toolId }, "", newUrl); + } + + initializeTool(toolId) { + const toolConfigs = { + // Document Tools + convert_doc: () => this.initDocumentConversion(), + pdf_join: () => this.initPDFJoining(), + scan_pdf: () => this.initPDFScanning(), + doc_long_image: () => this.initLongImageConversion(), + extract_pages: () => this.initPageExtraction(), + //Atext2word: () => this.initTextToWord(), + doc2image: () => this.initDocToImages(), + + // Image Tools + convert_image: () => this.initImageConversion(), + resize_image: () => this.initImageResize(), + image2pdf: () => this.initImageToPDF(), + image2word: () => this.initImageToWord(), + image2gray: () => this.initGrayscaleConversion(), + ocr: () => this.initOCR(), + + // Audio Tools + convert_audio: () => this.initAudioConversion(), + audio_join: () => this.initAudioJoining(), + extract_audio: () => this.initAudioExtraction(), + audio_effect: () => this.initAudioEffects(), + + // Video Tools + convert_video: () => this.initVideoConversion(), + analyze_video: () => this.initVideoAnalysis(), + + // Batch Tools + batch_dashboard: () => this.initBatchDashboard(), + batch_doc_convert: () => this.initBatchDocConversion(), + folder_operations: () => this.initFolderOperations(), + bulk_ocr: () => this.initBulkOCR(), + }; + + if (toolConfigs[toolId]) { + toolConfigs[toolId](); + } else { + console.warn(`No initialization found for tool: ${toolId}`); + } + } + + // Tool-specific initialization methods + ///=====Doc Operation==// + initDocumentConversion() { + fileHandler.setupFileDropZone("doc-drop-zone", "doc-file-input", true); + this.setupFormatSelector("doc-target-format", [ + "pdf", + "docx", + "txt", + "html", + "xls", + "xlsx", + "ppt", + "pptx", + ]); + this.setupAcceptedFiles("doc", [ + "pdf", + "docx", + "txt", + "html", + "xls", + "xlsx", + "ppt", + "pptx", + ]); + } + + initPDFJoining() { + fileHandler.setupFileDropZone( + "ppf_join-drop-zone", + "pdf_join-file-input", + false, + ); + } + + initPDFScanning() { + fileHandler.setupFileDropZone( + "scan_pdf-drop-zone", + "scan_pdf-file-input", + false, + ); + } + + initPageExtraction() { + fileHandler.setupFileDropZone( + "extract_pages-drop-zone", + "extract_pages-file-input", + false, + ); + } + + initDocToImages() { + fileHandler.setupFileDropZone( + "doc2image-drop-zone", + "doc2image-file-input", + false, + ); + } + + initLongImageConversion() { + fileHandler.setupFileDropZone( + "doc_long_image-drop-zone", + "doc_long_image-file-input", + false, + ); + } + + ///=====OCR Operation==// + initOCR() { + fileHandler.setupFileDropZone("ocr-drop-zone", "ocr-file-input", true); + this.setupLanguageSelector(); + } + + ///=====Audio Operation==// + initAudioConversion() { + fileHandler.setupFileDropZone("audio-drop-zone", "audio-file-input", true); + this.setupFormatSelector("audio-target-format", [ + "mp3", + "wav", + "flac", + "m4a", + "ogg", + "aac", + "raw", + "aiff", + "ogv", + ]); + this.setupAcceptedFiles("audio", [ + "mp3", + "wav", + "flac", + "m4a", + "ogg", + "aac", + "raw", + "aiff", + "ogv", + ]); + } + + ///=====Video Operation==// + initVideoConversion() { + fileHandler.setupFileDropZone("video-drop-zone", "video-file-input", true); + this.setupFormatSelector("video-target-format", [ + "mp4", + "mkv", + "webm", + "mov", + "avi", + "flv", + "wmv", + , + ]); + this.setupAcceptedFiles("video", [ + "mp4", + "mkv", + "webm", + "mov", + "avi", + "flv", + "wmv", + , + ]); + } + + ///=====Image Operation==// + initImageConversion() { + fileHandler.setupFileDropZone("image-drop-zone", "image-file-input", true); + this.setupFormatSelector("image-target-format", [ + "png", + "jpg", + "jpeg", + "webp", + "gif", + "eps", + "pic", + "tiff", + "dib", + "bmp", + ]); + this.setupAcceptedFiles("image", [ + "png", + "jpg", + "jpeg", + "webp", + "gif", + "eps", + "pic", + "tiff", + "dib", + "bmp", + ]); + this.setupQualitySlider(); + } + + initImageToPDF() { + fileHandler.setupFileDropZone( + "image2pdf-drop-zone", + "image2pdf-file-input", + false, + ); + } + + // Utility methods for tool setup + setupFormatSelector(selectId, formats) { + const select = document.getElementById(selectId); + if (select) { + select.innerHTML = formats + .map( + (format) => + ``, + ) + .join(""); + } + } + + setupAcceptedFiles(inputId, accepts) { + if (accepts) { + const Finput = document.getElementById(`${inputId}-file-input`); + Finput + ? Finput.setAttribute( + "accept", + accepts.map((format) => `.${format}`).join(","), + ) + : ""; + } + } + + setupQualitySlider() { + const slider = document.querySelector('input[name="quality"]'); + const valueDisplay = document.getElementById("quality-value"); + + if (slider && valueDisplay) { + slider.addEventListener("input", (e) => { + valueDisplay.textContent = `${e.target.value}%`; + }); + } + } + + setupLanguageSelector() { + const languages = { + eng: "English", + spa: "Spanish", + fra: "French", + deu: "German", + chi_sim: "Chinese Simplified", + }; + + const selector = document.querySelector('select[name="language"]'); + if (selector) { + selector.innerHTML = Object.entries(languages) + .map(([code, name]) => ``) + .join(""); + } + } + + initializeFromURL() { + const urlParams = new URLSearchParams(window.location.search); + const toolParam = urlParams.get("tool"); + + if (toolParam) { + this.showTool(toolParam); + } else { + // Show first tool by default + this.showDefaultTool(); + } + } + + showDefaultTool() { + const firstToolNav = document.querySelector(".tool-nav"); + if (firstToolNav) { + const toolId = this.getToolIdFromElement(firstToolNav); + if (toolId) { + this.showTool(toolId); + } + } + } + + getCurrentTool() { + return this.currentTool; + } +} + +window.toolHandler = new ToolHandler(); diff --git a/fweb/core/static/js/UI-X/aos-animate.js b/fweb/core/static/js/UI-X/aos-animate.js new file mode 100644 index 0000000..dc332e3 --- /dev/null +++ b/fweb/core/static/js/UI-X/aos-animate.js @@ -0,0 +1,15 @@ +import './aos/aos.css'; +import AOS from 'aos'; + +window.onload = function() { + AOS.init({ + once: false, + mirror: true, + duration: 700, + startEvent: 'DOMContentLoaded', + }); + + setTimeout(() => { + AOS.refresh(); + }, 300); +} diff --git a/fweb/core/static/js/UI-X/aos/aos.css b/fweb/core/static/js/UI-X/aos/aos.css new file mode 100644 index 0000000..66923fe --- /dev/null +++ b/fweb/core/static/js/UI-X/aos/aos.css @@ -0,0 +1 @@ +[data-aos][data-aos][data-aos-duration="50"],body[data-aos-duration="50"] [data-aos]{transition-duration:50ms}[data-aos][data-aos][data-aos-delay="50"],body[data-aos-delay="50"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="50"].aos-animate,body[data-aos-delay="50"] [data-aos].aos-animate{transition-delay:50ms}[data-aos][data-aos][data-aos-duration="100"],body[data-aos-duration="100"] [data-aos]{transition-duration:.1s}[data-aos][data-aos][data-aos-delay="100"],body[data-aos-delay="100"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="100"].aos-animate,body[data-aos-delay="100"] [data-aos].aos-animate{transition-delay:.1s}[data-aos][data-aos][data-aos-duration="150"],body[data-aos-duration="150"] [data-aos]{transition-duration:.15s}[data-aos][data-aos][data-aos-delay="150"],body[data-aos-delay="150"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="150"].aos-animate,body[data-aos-delay="150"] [data-aos].aos-animate{transition-delay:.15s}[data-aos][data-aos][data-aos-duration="200"],body[data-aos-duration="200"] [data-aos]{transition-duration:.2s}[data-aos][data-aos][data-aos-delay="200"],body[data-aos-delay="200"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="200"].aos-animate,body[data-aos-delay="200"] [data-aos].aos-animate{transition-delay:.2s}[data-aos][data-aos][data-aos-duration="250"],body[data-aos-duration="250"] [data-aos]{transition-duration:.25s}[data-aos][data-aos][data-aos-delay="250"],body[data-aos-delay="250"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="250"].aos-animate,body[data-aos-delay="250"] [data-aos].aos-animate{transition-delay:.25s}[data-aos][data-aos][data-aos-duration="300"],body[data-aos-duration="300"] [data-aos]{transition-duration:.3s}[data-aos][data-aos][data-aos-delay="300"],body[data-aos-delay="300"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="300"].aos-animate,body[data-aos-delay="300"] [data-aos].aos-animate{transition-delay:.3s}[data-aos][data-aos][data-aos-duration="350"],body[data-aos-duration="350"] [data-aos]{transition-duration:.35s}[data-aos][data-aos][data-aos-delay="350"],body[data-aos-delay="350"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="350"].aos-animate,body[data-aos-delay="350"] [data-aos].aos-animate{transition-delay:.35s}[data-aos][data-aos][data-aos-duration="400"],body[data-aos-duration="400"] [data-aos]{transition-duration:.4s}[data-aos][data-aos][data-aos-delay="400"],body[data-aos-delay="400"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="400"].aos-animate,body[data-aos-delay="400"] [data-aos].aos-animate{transition-delay:.4s}[data-aos][data-aos][data-aos-duration="450"],body[data-aos-duration="450"] [data-aos]{transition-duration:.45s}[data-aos][data-aos][data-aos-delay="450"],body[data-aos-delay="450"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="450"].aos-animate,body[data-aos-delay="450"] [data-aos].aos-animate{transition-delay:.45s}[data-aos][data-aos][data-aos-duration="500"],body[data-aos-duration="500"] [data-aos]{transition-duration:.5s}[data-aos][data-aos][data-aos-delay="500"],body[data-aos-delay="500"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="500"].aos-animate,body[data-aos-delay="500"] [data-aos].aos-animate{transition-delay:.5s}[data-aos][data-aos][data-aos-duration="550"],body[data-aos-duration="550"] [data-aos]{transition-duration:.55s}[data-aos][data-aos][data-aos-delay="550"],body[data-aos-delay="550"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="550"].aos-animate,body[data-aos-delay="550"] [data-aos].aos-animate{transition-delay:.55s}[data-aos][data-aos][data-aos-duration="600"],body[data-aos-duration="600"] [data-aos]{transition-duration:.6s}[data-aos][data-aos][data-aos-delay="600"],body[data-aos-delay="600"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="600"].aos-animate,body[data-aos-delay="600"] [data-aos].aos-animate{transition-delay:.6s}[data-aos][data-aos][data-aos-duration="650"],body[data-aos-duration="650"] [data-aos]{transition-duration:.65s}[data-aos][data-aos][data-aos-delay="650"],body[data-aos-delay="650"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="650"].aos-animate,body[data-aos-delay="650"] [data-aos].aos-animate{transition-delay:.65s}[data-aos][data-aos][data-aos-duration="700"],body[data-aos-duration="700"] [data-aos]{transition-duration:.7s}[data-aos][data-aos][data-aos-delay="700"],body[data-aos-delay="700"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="700"].aos-animate,body[data-aos-delay="700"] [data-aos].aos-animate{transition-delay:.7s}[data-aos][data-aos][data-aos-duration="750"],body[data-aos-duration="750"] [data-aos]{transition-duration:.75s}[data-aos][data-aos][data-aos-delay="750"],body[data-aos-delay="750"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="750"].aos-animate,body[data-aos-delay="750"] [data-aos].aos-animate{transition-delay:.75s}[data-aos][data-aos][data-aos-duration="800"],body[data-aos-duration="800"] [data-aos]{transition-duration:.8s}[data-aos][data-aos][data-aos-delay="800"],body[data-aos-delay="800"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="800"].aos-animate,body[data-aos-delay="800"] [data-aos].aos-animate{transition-delay:.8s}[data-aos][data-aos][data-aos-duration="850"],body[data-aos-duration="850"] [data-aos]{transition-duration:.85s}[data-aos][data-aos][data-aos-delay="850"],body[data-aos-delay="850"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="850"].aos-animate,body[data-aos-delay="850"] [data-aos].aos-animate{transition-delay:.85s}[data-aos][data-aos][data-aos-duration="900"],body[data-aos-duration="900"] [data-aos]{transition-duration:.9s}[data-aos][data-aos][data-aos-delay="900"],body[data-aos-delay="900"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="900"].aos-animate,body[data-aos-delay="900"] [data-aos].aos-animate{transition-delay:.9s}[data-aos][data-aos][data-aos-duration="950"],body[data-aos-duration="950"] [data-aos]{transition-duration:.95s}[data-aos][data-aos][data-aos-delay="950"],body[data-aos-delay="950"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="950"].aos-animate,body[data-aos-delay="950"] [data-aos].aos-animate{transition-delay:.95s}[data-aos][data-aos][data-aos-duration="1000"],body[data-aos-duration="1000"] [data-aos]{transition-duration:1s}[data-aos][data-aos][data-aos-delay="1000"],body[data-aos-delay="1000"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="1000"].aos-animate,body[data-aos-delay="1000"] [data-aos].aos-animate{transition-delay:1s}[data-aos][data-aos][data-aos-duration="1050"],body[data-aos-duration="1050"] [data-aos]{transition-duration:1.05s}[data-aos][data-aos][data-aos-delay="1050"],body[data-aos-delay="1050"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="1050"].aos-animate,body[data-aos-delay="1050"] [data-aos].aos-animate{transition-delay:1.05s}[data-aos][data-aos][data-aos-duration="1100"],body[data-aos-duration="1100"] [data-aos]{transition-duration:1.1s}[data-aos][data-aos][data-aos-delay="1100"],body[data-aos-delay="1100"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="1100"].aos-animate,body[data-aos-delay="1100"] [data-aos].aos-animate{transition-delay:1.1s}[data-aos][data-aos][data-aos-duration="1150"],body[data-aos-duration="1150"] [data-aos]{transition-duration:1.15s}[data-aos][data-aos][data-aos-delay="1150"],body[data-aos-delay="1150"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="1150"].aos-animate,body[data-aos-delay="1150"] [data-aos].aos-animate{transition-delay:1.15s}[data-aos][data-aos][data-aos-duration="1200"],body[data-aos-duration="1200"] [data-aos]{transition-duration:1.2s}[data-aos][data-aos][data-aos-delay="1200"],body[data-aos-delay="1200"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="1200"].aos-animate,body[data-aos-delay="1200"] [data-aos].aos-animate{transition-delay:1.2s}[data-aos][data-aos][data-aos-duration="1250"],body[data-aos-duration="1250"] [data-aos]{transition-duration:1.25s}[data-aos][data-aos][data-aos-delay="1250"],body[data-aos-delay="1250"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="1250"].aos-animate,body[data-aos-delay="1250"] [data-aos].aos-animate{transition-delay:1.25s}[data-aos][data-aos][data-aos-duration="1300"],body[data-aos-duration="1300"] [data-aos]{transition-duration:1.3s}[data-aos][data-aos][data-aos-delay="1300"],body[data-aos-delay="1300"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="1300"].aos-animate,body[data-aos-delay="1300"] [data-aos].aos-animate{transition-delay:1.3s}[data-aos][data-aos][data-aos-duration="1350"],body[data-aos-duration="1350"] [data-aos]{transition-duration:1.35s}[data-aos][data-aos][data-aos-delay="1350"],body[data-aos-delay="1350"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="1350"].aos-animate,body[data-aos-delay="1350"] [data-aos].aos-animate{transition-delay:1.35s}[data-aos][data-aos][data-aos-duration="1400"],body[data-aos-duration="1400"] [data-aos]{transition-duration:1.4s}[data-aos][data-aos][data-aos-delay="1400"],body[data-aos-delay="1400"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="1400"].aos-animate,body[data-aos-delay="1400"] [data-aos].aos-animate{transition-delay:1.4s}[data-aos][data-aos][data-aos-duration="1450"],body[data-aos-duration="1450"] [data-aos]{transition-duration:1.45s}[data-aos][data-aos][data-aos-delay="1450"],body[data-aos-delay="1450"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="1450"].aos-animate,body[data-aos-delay="1450"] [data-aos].aos-animate{transition-delay:1.45s}[data-aos][data-aos][data-aos-duration="1500"],body[data-aos-duration="1500"] [data-aos]{transition-duration:1.5s}[data-aos][data-aos][data-aos-delay="1500"],body[data-aos-delay="1500"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="1500"].aos-animate,body[data-aos-delay="1500"] [data-aos].aos-animate{transition-delay:1.5s}[data-aos][data-aos][data-aos-duration="1550"],body[data-aos-duration="1550"] [data-aos]{transition-duration:1.55s}[data-aos][data-aos][data-aos-delay="1550"],body[data-aos-delay="1550"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="1550"].aos-animate,body[data-aos-delay="1550"] [data-aos].aos-animate{transition-delay:1.55s}[data-aos][data-aos][data-aos-duration="1600"],body[data-aos-duration="1600"] [data-aos]{transition-duration:1.6s}[data-aos][data-aos][data-aos-delay="1600"],body[data-aos-delay="1600"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="1600"].aos-animate,body[data-aos-delay="1600"] [data-aos].aos-animate{transition-delay:1.6s}[data-aos][data-aos][data-aos-duration="1650"],body[data-aos-duration="1650"] [data-aos]{transition-duration:1.65s}[data-aos][data-aos][data-aos-delay="1650"],body[data-aos-delay="1650"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="1650"].aos-animate,body[data-aos-delay="1650"] [data-aos].aos-animate{transition-delay:1.65s}[data-aos][data-aos][data-aos-duration="1700"],body[data-aos-duration="1700"] [data-aos]{transition-duration:1.7s}[data-aos][data-aos][data-aos-delay="1700"],body[data-aos-delay="1700"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="1700"].aos-animate,body[data-aos-delay="1700"] [data-aos].aos-animate{transition-delay:1.7s}[data-aos][data-aos][data-aos-duration="1750"],body[data-aos-duration="1750"] [data-aos]{transition-duration:1.75s}[data-aos][data-aos][data-aos-delay="1750"],body[data-aos-delay="1750"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="1750"].aos-animate,body[data-aos-delay="1750"] [data-aos].aos-animate{transition-delay:1.75s}[data-aos][data-aos][data-aos-duration="1800"],body[data-aos-duration="1800"] [data-aos]{transition-duration:1.8s}[data-aos][data-aos][data-aos-delay="1800"],body[data-aos-delay="1800"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="1800"].aos-animate,body[data-aos-delay="1800"] [data-aos].aos-animate{transition-delay:1.8s}[data-aos][data-aos][data-aos-duration="1850"],body[data-aos-duration="1850"] [data-aos]{transition-duration:1.85s}[data-aos][data-aos][data-aos-delay="1850"],body[data-aos-delay="1850"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="1850"].aos-animate,body[data-aos-delay="1850"] [data-aos].aos-animate{transition-delay:1.85s}[data-aos][data-aos][data-aos-duration="1900"],body[data-aos-duration="1900"] [data-aos]{transition-duration:1.9s}[data-aos][data-aos][data-aos-delay="1900"],body[data-aos-delay="1900"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="1900"].aos-animate,body[data-aos-delay="1900"] [data-aos].aos-animate{transition-delay:1.9s}[data-aos][data-aos][data-aos-duration="1950"],body[data-aos-duration="1950"] [data-aos]{transition-duration:1.95s}[data-aos][data-aos][data-aos-delay="1950"],body[data-aos-delay="1950"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="1950"].aos-animate,body[data-aos-delay="1950"] [data-aos].aos-animate{transition-delay:1.95s}[data-aos][data-aos][data-aos-duration="2000"],body[data-aos-duration="2000"] [data-aos]{transition-duration:2s}[data-aos][data-aos][data-aos-delay="2000"],body[data-aos-delay="2000"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="2000"].aos-animate,body[data-aos-delay="2000"] [data-aos].aos-animate{transition-delay:2s}[data-aos][data-aos][data-aos-duration="2050"],body[data-aos-duration="2050"] [data-aos]{transition-duration:2.05s}[data-aos][data-aos][data-aos-delay="2050"],body[data-aos-delay="2050"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="2050"].aos-animate,body[data-aos-delay="2050"] [data-aos].aos-animate{transition-delay:2.05s}[data-aos][data-aos][data-aos-duration="2100"],body[data-aos-duration="2100"] [data-aos]{transition-duration:2.1s}[data-aos][data-aos][data-aos-delay="2100"],body[data-aos-delay="2100"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="2100"].aos-animate,body[data-aos-delay="2100"] [data-aos].aos-animate{transition-delay:2.1s}[data-aos][data-aos][data-aos-duration="2150"],body[data-aos-duration="2150"] [data-aos]{transition-duration:2.15s}[data-aos][data-aos][data-aos-delay="2150"],body[data-aos-delay="2150"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="2150"].aos-animate,body[data-aos-delay="2150"] [data-aos].aos-animate{transition-delay:2.15s}[data-aos][data-aos][data-aos-duration="2200"],body[data-aos-duration="2200"] [data-aos]{transition-duration:2.2s}[data-aos][data-aos][data-aos-delay="2200"],body[data-aos-delay="2200"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="2200"].aos-animate,body[data-aos-delay="2200"] [data-aos].aos-animate{transition-delay:2.2s}[data-aos][data-aos][data-aos-duration="2250"],body[data-aos-duration="2250"] [data-aos]{transition-duration:2.25s}[data-aos][data-aos][data-aos-delay="2250"],body[data-aos-delay="2250"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="2250"].aos-animate,body[data-aos-delay="2250"] [data-aos].aos-animate{transition-delay:2.25s}[data-aos][data-aos][data-aos-duration="2300"],body[data-aos-duration="2300"] [data-aos]{transition-duration:2.3s}[data-aos][data-aos][data-aos-delay="2300"],body[data-aos-delay="2300"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="2300"].aos-animate,body[data-aos-delay="2300"] [data-aos].aos-animate{transition-delay:2.3s}[data-aos][data-aos][data-aos-duration="2350"],body[data-aos-duration="2350"] [data-aos]{transition-duration:2.35s}[data-aos][data-aos][data-aos-delay="2350"],body[data-aos-delay="2350"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="2350"].aos-animate,body[data-aos-delay="2350"] [data-aos].aos-animate{transition-delay:2.35s}[data-aos][data-aos][data-aos-duration="2400"],body[data-aos-duration="2400"] [data-aos]{transition-duration:2.4s}[data-aos][data-aos][data-aos-delay="2400"],body[data-aos-delay="2400"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="2400"].aos-animate,body[data-aos-delay="2400"] [data-aos].aos-animate{transition-delay:2.4s}[data-aos][data-aos][data-aos-duration="2450"],body[data-aos-duration="2450"] [data-aos]{transition-duration:2.45s}[data-aos][data-aos][data-aos-delay="2450"],body[data-aos-delay="2450"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="2450"].aos-animate,body[data-aos-delay="2450"] [data-aos].aos-animate{transition-delay:2.45s}[data-aos][data-aos][data-aos-duration="2500"],body[data-aos-duration="2500"] [data-aos]{transition-duration:2.5s}[data-aos][data-aos][data-aos-delay="2500"],body[data-aos-delay="2500"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="2500"].aos-animate,body[data-aos-delay="2500"] [data-aos].aos-animate{transition-delay:2.5s}[data-aos][data-aos][data-aos-duration="2550"],body[data-aos-duration="2550"] [data-aos]{transition-duration:2.55s}[data-aos][data-aos][data-aos-delay="2550"],body[data-aos-delay="2550"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="2550"].aos-animate,body[data-aos-delay="2550"] [data-aos].aos-animate{transition-delay:2.55s}[data-aos][data-aos][data-aos-duration="2600"],body[data-aos-duration="2600"] [data-aos]{transition-duration:2.6s}[data-aos][data-aos][data-aos-delay="2600"],body[data-aos-delay="2600"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="2600"].aos-animate,body[data-aos-delay="2600"] [data-aos].aos-animate{transition-delay:2.6s}[data-aos][data-aos][data-aos-duration="2650"],body[data-aos-duration="2650"] [data-aos]{transition-duration:2.65s}[data-aos][data-aos][data-aos-delay="2650"],body[data-aos-delay="2650"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="2650"].aos-animate,body[data-aos-delay="2650"] [data-aos].aos-animate{transition-delay:2.65s}[data-aos][data-aos][data-aos-duration="2700"],body[data-aos-duration="2700"] [data-aos]{transition-duration:2.7s}[data-aos][data-aos][data-aos-delay="2700"],body[data-aos-delay="2700"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="2700"].aos-animate,body[data-aos-delay="2700"] [data-aos].aos-animate{transition-delay:2.7s}[data-aos][data-aos][data-aos-duration="2750"],body[data-aos-duration="2750"] [data-aos]{transition-duration:2.75s}[data-aos][data-aos][data-aos-delay="2750"],body[data-aos-delay="2750"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="2750"].aos-animate,body[data-aos-delay="2750"] [data-aos].aos-animate{transition-delay:2.75s}[data-aos][data-aos][data-aos-duration="2800"],body[data-aos-duration="2800"] [data-aos]{transition-duration:2.8s}[data-aos][data-aos][data-aos-delay="2800"],body[data-aos-delay="2800"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="2800"].aos-animate,body[data-aos-delay="2800"] [data-aos].aos-animate{transition-delay:2.8s}[data-aos][data-aos][data-aos-duration="2850"],body[data-aos-duration="2850"] [data-aos]{transition-duration:2.85s}[data-aos][data-aos][data-aos-delay="2850"],body[data-aos-delay="2850"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="2850"].aos-animate,body[data-aos-delay="2850"] [data-aos].aos-animate{transition-delay:2.85s}[data-aos][data-aos][data-aos-duration="2900"],body[data-aos-duration="2900"] [data-aos]{transition-duration:2.9s}[data-aos][data-aos][data-aos-delay="2900"],body[data-aos-delay="2900"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="2900"].aos-animate,body[data-aos-delay="2900"] [data-aos].aos-animate{transition-delay:2.9s}[data-aos][data-aos][data-aos-duration="2950"],body[data-aos-duration="2950"] [data-aos]{transition-duration:2.95s}[data-aos][data-aos][data-aos-delay="2950"],body[data-aos-delay="2950"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="2950"].aos-animate,body[data-aos-delay="2950"] [data-aos].aos-animate{transition-delay:2.95s}[data-aos][data-aos][data-aos-duration="3000"],body[data-aos-duration="3000"] [data-aos]{transition-duration:3s}[data-aos][data-aos][data-aos-delay="3000"],body[data-aos-delay="3000"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="3000"].aos-animate,body[data-aos-delay="3000"] [data-aos].aos-animate{transition-delay:3s}[data-aos][data-aos][data-aos-easing=linear],body[data-aos-easing=linear] [data-aos]{transition-timing-function:cubic-bezier(.25,.25,.75,.75)}[data-aos][data-aos][data-aos-easing=ease],body[data-aos-easing=ease] [data-aos]{transition-timing-function:ease}[data-aos][data-aos][data-aos-easing=ease-in],body[data-aos-easing=ease-in] [data-aos]{transition-timing-function:ease-in}[data-aos][data-aos][data-aos-easing=ease-out],body[data-aos-easing=ease-out] [data-aos]{transition-timing-function:ease-out}[data-aos][data-aos][data-aos-easing=ease-in-out],body[data-aos-easing=ease-in-out] [data-aos]{transition-timing-function:ease-in-out}[data-aos][data-aos][data-aos-easing=ease-in-back],body[data-aos-easing=ease-in-back] [data-aos]{transition-timing-function:cubic-bezier(.6,-.28,.735,.045)}[data-aos][data-aos][data-aos-easing=ease-out-back],body[data-aos-easing=ease-out-back] [data-aos]{transition-timing-function:cubic-bezier(.175,.885,.32,1.275)}[data-aos][data-aos][data-aos-easing=ease-in-out-back],body[data-aos-easing=ease-in-out-back] [data-aos]{transition-timing-function:cubic-bezier(.68,-.55,.265,1.55)}[data-aos][data-aos][data-aos-easing=ease-in-sine],body[data-aos-easing=ease-in-sine] [data-aos]{transition-timing-function:cubic-bezier(.47,0,.745,.715)}[data-aos][data-aos][data-aos-easing=ease-out-sine],body[data-aos-easing=ease-out-sine] [data-aos]{transition-timing-function:cubic-bezier(.39,.575,.565,1)}[data-aos][data-aos][data-aos-easing=ease-in-out-sine],body[data-aos-easing=ease-in-out-sine] [data-aos]{transition-timing-function:cubic-bezier(.445,.05,.55,.95)}[data-aos][data-aos][data-aos-easing=ease-in-quad],body[data-aos-easing=ease-in-quad] [data-aos]{transition-timing-function:cubic-bezier(.55,.085,.68,.53)}[data-aos][data-aos][data-aos-easing=ease-out-quad],body[data-aos-easing=ease-out-quad] [data-aos]{transition-timing-function:cubic-bezier(.25,.46,.45,.94)}[data-aos][data-aos][data-aos-easing=ease-in-out-quad],body[data-aos-easing=ease-in-out-quad] [data-aos]{transition-timing-function:cubic-bezier(.455,.03,.515,.955)}[data-aos][data-aos][data-aos-easing=ease-in-cubic],body[data-aos-easing=ease-in-cubic] [data-aos]{transition-timing-function:cubic-bezier(.55,.085,.68,.53)}[data-aos][data-aos][data-aos-easing=ease-out-cubic],body[data-aos-easing=ease-out-cubic] [data-aos]{transition-timing-function:cubic-bezier(.25,.46,.45,.94)}[data-aos][data-aos][data-aos-easing=ease-in-out-cubic],body[data-aos-easing=ease-in-out-cubic] [data-aos]{transition-timing-function:cubic-bezier(.455,.03,.515,.955)}[data-aos][data-aos][data-aos-easing=ease-in-quart],body[data-aos-easing=ease-in-quart] [data-aos]{transition-timing-function:cubic-bezier(.55,.085,.68,.53)}[data-aos][data-aos][data-aos-easing=ease-out-quart],body[data-aos-easing=ease-out-quart] [data-aos]{transition-timing-function:cubic-bezier(.25,.46,.45,.94)}[data-aos][data-aos][data-aos-easing=ease-in-out-quart],body[data-aos-easing=ease-in-out-quart] [data-aos]{transition-timing-function:cubic-bezier(.455,.03,.515,.955)}[data-aos^=fade][data-aos^=fade]{opacity:0;transition-property:opacity,transform}[data-aos^=fade][data-aos^=fade].aos-animate{opacity:1;transform:translateZ(0)}[data-aos=fade-up]{transform:translate3d(0,100px,0)}[data-aos=fade-down]{transform:translate3d(0,-100px,0)}[data-aos=fade-right]{transform:translate3d(-100px,0,0)}[data-aos=fade-left]{transform:translate3d(100px,0,0)}[data-aos=fade-up-right]{transform:translate3d(-100px,100px,0)}[data-aos=fade-up-left]{transform:translate3d(100px,100px,0)}[data-aos=fade-down-right]{transform:translate3d(-100px,-100px,0)}[data-aos=fade-down-left]{transform:translate3d(100px,-100px,0)}[data-aos^=zoom][data-aos^=zoom]{opacity:0;transition-property:opacity,transform}[data-aos^=zoom][data-aos^=zoom].aos-animate{opacity:1;transform:translateZ(0) scale(1)}[data-aos=zoom-in]{transform:scale(.6)}[data-aos=zoom-in-up]{transform:translate3d(0,100px,0) scale(.6)}[data-aos=zoom-in-down]{transform:translate3d(0,-100px,0) scale(.6)}[data-aos=zoom-in-right]{transform:translate3d(-100px,0,0) scale(.6)}[data-aos=zoom-in-left]{transform:translate3d(100px,0,0) scale(.6)}[data-aos=zoom-out]{transform:scale(1.2)}[data-aos=zoom-out-up]{transform:translate3d(0,100px,0) scale(1.2)}[data-aos=zoom-out-down]{transform:translate3d(0,-100px,0) scale(1.2)}[data-aos=zoom-out-right]{transform:translate3d(-100px,0,0) scale(1.2)}[data-aos=zoom-out-left]{transform:translate3d(100px,0,0) scale(1.2)}[data-aos^=slide][data-aos^=slide]{transition-property:transform}[data-aos^=slide][data-aos^=slide].aos-animate{transform:translateZ(0)}[data-aos=slide-up]{transform:translate3d(0,100%,0)}[data-aos=slide-down]{transform:translate3d(0,-100%,0)}[data-aos=slide-right]{transform:translate3d(-100%,0,0)}[data-aos=slide-left]{transform:translate3d(100%,0,0)}[data-aos^=flip][data-aos^=flip]{backface-visibility:hidden;transition-property:transform}[data-aos=flip-left]{transform:perspective(2500px) rotateY(-100deg)}[data-aos=flip-left].aos-animate{transform:perspective(2500px) rotateY(0)}[data-aos=flip-right]{transform:perspective(2500px) rotateY(100deg)}[data-aos=flip-right].aos-animate{transform:perspective(2500px) rotateY(0)}[data-aos=flip-up]{transform:perspective(2500px) rotateX(-100deg)}[data-aos=flip-up].aos-animate{transform:perspective(2500px) rotateX(0)}[data-aos=flip-down]{transform:perspective(2500px) rotateX(100deg)}[data-aos=flip-down].aos-animate{transform:perspective(2500px) rotateX(0)} \ No newline at end of file diff --git a/fweb/core/static/js/UI-X/packed_aosanimate.js b/fweb/core/static/js/UI-X/packed_aosanimate.js new file mode 100644 index 0000000..1cbe6cf --- /dev/null +++ b/fweb/core/static/js/UI-X/packed_aosanimate.js @@ -0,0 +1,2 @@ +(()=>{var a={42:function(a){a.exports=function(a){function t(d){if(o[d])return o[d].exports;var s=o[d]={exports:{},id:d,loaded:!1};return a[d].call(s.exports,s,s.exports,t),s.loaded=!0,s.exports}var o={};return t.m=a,t.c=o,t.p="dist/",t(0)}([function(a,t,o){"use strict";function d(a){return a&&a.__esModule?a:{default:a}}var s=Object.assign||function(a){for(var t=1;t0&&void 0!==arguments[0]&&arguments[0]&&(b=!0),b)return m=(0,l.default)(m,c),(0,A.default)(m,c.once),m},f=function(){m=(0,u.default)(),C()};a.exports={init:function(a){c=s(c,a),m=(0,u.default)();var t=document.all&&!window.atob;return function(a){return!0===a||"mobile"===a&&y.default.mobile()||"phone"===a&&y.default.phone()||"tablet"===a&&y.default.tablet()||"function"==typeof a&&!0===a()}(c.disable)||t?void m.forEach((function(a,t){a.node.removeAttribute("data-aos"),a.node.removeAttribute("data-aos-easing"),a.node.removeAttribute("data-aos-duration"),a.node.removeAttribute("data-aos-delay")})):(c.disableMutationObserver||r.default.isSupported()||(console.info('\n aos: MutationObserver is not supported on this browser,\n code mutations observing has been disabled.\n You may have to call "refreshHard()" by yourself.\n '),c.disableMutationObserver=!0),document.querySelector("body").setAttribute("data-aos-easing",c.easing),document.querySelector("body").setAttribute("data-aos-duration",c.duration),document.querySelector("body").setAttribute("data-aos-delay",c.delay),"DOMContentLoaded"===c.startEvent&&["complete","interactive"].indexOf(document.readyState)>-1?C(!0):"load"===c.startEvent?window.addEventListener(c.startEvent,(function(){C(!0)})):document.addEventListener(c.startEvent,(function(){C(!0)})),window.addEventListener("resize",(0,e.default)(C,c.debounceDelay,!0)),window.addEventListener("orientationchange",(0,e.default)(C,c.debounceDelay,!0)),window.addEventListener("scroll",(0,i.default)((function(){(0,A.default)(m,c.once)}),c.throttleDelay)),c.disableMutationObserver||r.default.ready("[data-aos]",f),m)},refresh:C,refreshHard:f}},function(a,t){},,,,,function(a,t){(function(t){"use strict";function o(a,t,o){function s(t){var o=l,d=u;return l=u=void 0,f=t,b=a.apply(d,o)}function i(a){var o=a-C;return void 0===C||o>=t||o<0||v&&a-f>=m}function r(){var a=F();return i(a)?y(a):void(c=setTimeout(r,function(a){var o=t-(a-C);return v?g(o,m-(a-f)):o}(a)))}function y(a){return c=void 0,w&&l?s(a):(l=u=void 0,b)}function A(){var a=F(),o=i(a);if(l=arguments,u=this,C=a,o){if(void 0===c)return function(a){return f=a,c=setTimeout(r,t),p?s(a):b}(C);if(v)return c=setTimeout(r,t),s(C)}return void 0===c&&(c=setTimeout(r,t)),b}var l,u,m,b,c,C,f=0,p=!1,v=!1,w=!0;if("function"!=typeof a)throw new TypeError(e);return t=n(t)||0,d(o)&&(p=!!o.leading,m=(v="maxWait"in o)?B(n(o.maxWait)||0,t):m,w="trailing"in o?!!o.trailing:w),A.cancel=function(){void 0!==c&&clearTimeout(c),f=0,l=C=u=c=void 0},A.flush=function(){return void 0===c?b:y(F())},A}function d(a){var t=void 0===a?"undefined":i(a);return!!a&&("object"==t||"function"==t)}function s(a){return"symbol"==(void 0===a?"undefined":i(a))||function(a){return!!a&&"object"==(void 0===a?"undefined":i(a))}(a)&&p.call(a)==y}function n(a){if("number"==typeof a)return a;if(s(a))return r;if(d(a)){var t="function"==typeof a.valueOf?a.valueOf():a;a=d(t)?t+"":t}if("string"!=typeof a)return 0===a?a:+a;a=a.replace(A,"");var o=u.test(a);return o||m.test(a)?b(a.slice(2),o?2:8):l.test(a)?r:+a}var i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(a){return typeof a}:function(a){return a&&"function"==typeof Symbol&&a.constructor===Symbol&&a!==Symbol.prototype?"symbol":typeof a},e="Expected a function",r=NaN,y="[object Symbol]",A=/^\s+|\s+$/g,l=/^[-+]0x[0-9a-f]+$/i,u=/^0b[01]+$/i,m=/^0o[0-7]+$/i,b=parseInt,c="object"==(void 0===t?"undefined":i(t))&&t&&t.Object===Object&&t,C="object"==("undefined"==typeof self?"undefined":i(self))&&self&&self.Object===Object&&self,f=c||C||Function("return this")(),p=Object.prototype.toString,B=Math.max,g=Math.min,F=function(){return f.Date.now()};a.exports=function(a,t,s){var n=!0,i=!0;if("function"!=typeof a)throw new TypeError(e);return d(s)&&(n="leading"in s?!!s.leading:n,i="trailing"in s?!!s.trailing:i),o(a,t,{leading:n,maxWait:t,trailing:i})}}).call(t,function(){return this}())},function(a,t){(function(t){"use strict";function o(a){var t=void 0===a?"undefined":n(a);return!!a&&("object"==t||"function"==t)}function d(a){return"symbol"==(void 0===a?"undefined":n(a))||function(a){return!!a&&"object"==(void 0===a?"undefined":n(a))}(a)&&f.call(a)==r}function s(a){if("number"==typeof a)return a;if(d(a))return e;if(o(a)){var t="function"==typeof a.valueOf?a.valueOf():a;a=o(t)?t+"":t}if("string"!=typeof a)return 0===a?a:+a;a=a.replace(y,"");var s=l.test(a);return s||u.test(a)?m(a.slice(2),s?2:8):A.test(a)?e:+a}var n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(a){return typeof a}:function(a){return a&&"function"==typeof Symbol&&a.constructor===Symbol&&a!==Symbol.prototype?"symbol":typeof a},i="Expected a function",e=NaN,r="[object Symbol]",y=/^\s+|\s+$/g,A=/^[-+]0x[0-9a-f]+$/i,l=/^0b[01]+$/i,u=/^0o[0-7]+$/i,m=parseInt,b="object"==(void 0===t?"undefined":n(t))&&t&&t.Object===Object&&t,c="object"==("undefined"==typeof self?"undefined":n(self))&&self&&self.Object===Object&&self,C=b||c||Function("return this")(),f=Object.prototype.toString,p=Math.max,B=Math.min,g=function(){return C.Date.now()};a.exports=function(a,t,d){function n(t){var o=l,d=u;return l=u=void 0,f=t,b=a.apply(d,o)}function e(a){var o=a-C;return void 0===C||o>=t||o<0||v&&a-f>=m}function r(){var a=g();return e(a)?y(a):void(c=setTimeout(r,function(a){var o=t-(a-C);return v?B(o,m-(a-f)):o}(a)))}function y(a){return c=void 0,w&&l?n(a):(l=u=void 0,b)}function A(){var a=g(),o=e(a);if(l=arguments,u=this,C=a,o){if(void 0===c)return function(a){return f=a,c=setTimeout(r,t),F?n(a):b}(C);if(v)return c=setTimeout(r,t),n(C)}return void 0===c&&(c=setTimeout(r,t)),b}var l,u,m,b,c,C,f=0,F=!1,v=!1,w=!0;if("function"!=typeof a)throw new TypeError(i);return t=s(t)||0,o(d)&&(F=!!d.leading,m=(v="maxWait"in d)?p(s(d.maxWait)||0,t):m,w="trailing"in d?!!d.trailing:w),A.cancel=function(){void 0!==c&&clearTimeout(c),f=0,l=C=u=c=void 0},A.flush=function(){return void 0===c?b:y(g())},A}}).call(t,function(){return this}())},function(a,t){"use strict";function o(a){var t=void 0,d=void 0;for(t=0;ta.position?a.node.classList.add("aos-animate"):void 0!==d&&("false"===d||!o&&"true"!==d)&&a.node.classList.remove("aos-animate")}(a,d+o,t)}))}},function(a,t,o){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var d=function(a){return a&&a.__esModule?a:{default:a}}(o(12));t.default=function(a,t){return a.forEach((function(a,o){a.node.classList.add("aos-init"),a.position=(0,d.default)(a.node,t.offset)})),a}},function(a,t,o){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var d=function(a){return a&&a.__esModule?a:{default:a}}(o(13));t.default=function(a,t){var o=0,s=0,n=window.innerHeight,i={offset:a.getAttribute("data-aos-offset"),anchor:a.getAttribute("data-aos-anchor"),anchorPlacement:a.getAttribute("data-aos-anchor-placement")};switch(i.offset&&!isNaN(i.offset)&&(s=parseInt(i.offset)),i.anchor&&document.querySelectorAll(i.anchor)&&(a=document.querySelectorAll(i.anchor)[0]),o=(0,d.default)(a).top,i.anchorPlacement){case"top-bottom":break;case"center-bottom":o+=a.offsetHeight/2;break;case"bottom-bottom":o+=a.offsetHeight;break;case"top-center":o+=n/2;break;case"bottom-center":o+=n/2+a.offsetHeight;break;case"center-center":o+=n/2+a.offsetHeight/2;break;case"top-top":o+=n;break;case"bottom-top":o+=a.offsetHeight+n;break;case"center-top":o+=a.offsetHeight/2+n}return i.anchorPlacement||i.offset||isNaN(t)||(s=t),o+s}},function(a,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});t.default=function(a){for(var t=0,o=0;a&&!isNaN(a.offsetLeft)&&!isNaN(a.offsetTop);)t+=a.offsetLeft-("BODY"!=a.tagName?a.scrollLeft:0),o+=a.offsetTop-("BODY"!=a.tagName?a.scrollTop:0),a=a.offsetParent;return{top:o,left:t}}},function(a,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});t.default=function(a){return a=a||document.querySelectorAll("[data-aos]"),Array.prototype.map.call(a,(function(a){return{node:a}}))}}])},309:(a,t,o)=>{"use strict";o.d(t,{A:()=>e});var d=o(354),s=o.n(d),n=o(314),i=o.n(n)()(s());i.push([a.id,'[data-aos][data-aos][data-aos-duration="50"],body[data-aos-duration="50"] [data-aos]{transition-duration:50ms}[data-aos][data-aos][data-aos-delay="50"],body[data-aos-delay="50"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="50"].aos-animate,body[data-aos-delay="50"] [data-aos].aos-animate{transition-delay:50ms}[data-aos][data-aos][data-aos-duration="100"],body[data-aos-duration="100"] [data-aos]{transition-duration:.1s}[data-aos][data-aos][data-aos-delay="100"],body[data-aos-delay="100"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="100"].aos-animate,body[data-aos-delay="100"] [data-aos].aos-animate{transition-delay:.1s}[data-aos][data-aos][data-aos-duration="150"],body[data-aos-duration="150"] [data-aos]{transition-duration:.15s}[data-aos][data-aos][data-aos-delay="150"],body[data-aos-delay="150"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="150"].aos-animate,body[data-aos-delay="150"] [data-aos].aos-animate{transition-delay:.15s}[data-aos][data-aos][data-aos-duration="200"],body[data-aos-duration="200"] [data-aos]{transition-duration:.2s}[data-aos][data-aos][data-aos-delay="200"],body[data-aos-delay="200"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="200"].aos-animate,body[data-aos-delay="200"] [data-aos].aos-animate{transition-delay:.2s}[data-aos][data-aos][data-aos-duration="250"],body[data-aos-duration="250"] [data-aos]{transition-duration:.25s}[data-aos][data-aos][data-aos-delay="250"],body[data-aos-delay="250"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="250"].aos-animate,body[data-aos-delay="250"] [data-aos].aos-animate{transition-delay:.25s}[data-aos][data-aos][data-aos-duration="300"],body[data-aos-duration="300"] [data-aos]{transition-duration:.3s}[data-aos][data-aos][data-aos-delay="300"],body[data-aos-delay="300"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="300"].aos-animate,body[data-aos-delay="300"] [data-aos].aos-animate{transition-delay:.3s}[data-aos][data-aos][data-aos-duration="350"],body[data-aos-duration="350"] [data-aos]{transition-duration:.35s}[data-aos][data-aos][data-aos-delay="350"],body[data-aos-delay="350"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="350"].aos-animate,body[data-aos-delay="350"] [data-aos].aos-animate{transition-delay:.35s}[data-aos][data-aos][data-aos-duration="400"],body[data-aos-duration="400"] [data-aos]{transition-duration:.4s}[data-aos][data-aos][data-aos-delay="400"],body[data-aos-delay="400"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="400"].aos-animate,body[data-aos-delay="400"] [data-aos].aos-animate{transition-delay:.4s}[data-aos][data-aos][data-aos-duration="450"],body[data-aos-duration="450"] [data-aos]{transition-duration:.45s}[data-aos][data-aos][data-aos-delay="450"],body[data-aos-delay="450"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="450"].aos-animate,body[data-aos-delay="450"] [data-aos].aos-animate{transition-delay:.45s}[data-aos][data-aos][data-aos-duration="500"],body[data-aos-duration="500"] [data-aos]{transition-duration:.5s}[data-aos][data-aos][data-aos-delay="500"],body[data-aos-delay="500"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="500"].aos-animate,body[data-aos-delay="500"] [data-aos].aos-animate{transition-delay:.5s}[data-aos][data-aos][data-aos-duration="550"],body[data-aos-duration="550"] [data-aos]{transition-duration:.55s}[data-aos][data-aos][data-aos-delay="550"],body[data-aos-delay="550"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="550"].aos-animate,body[data-aos-delay="550"] [data-aos].aos-animate{transition-delay:.55s}[data-aos][data-aos][data-aos-duration="600"],body[data-aos-duration="600"] [data-aos]{transition-duration:.6s}[data-aos][data-aos][data-aos-delay="600"],body[data-aos-delay="600"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="600"].aos-animate,body[data-aos-delay="600"] [data-aos].aos-animate{transition-delay:.6s}[data-aos][data-aos][data-aos-duration="650"],body[data-aos-duration="650"] [data-aos]{transition-duration:.65s}[data-aos][data-aos][data-aos-delay="650"],body[data-aos-delay="650"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="650"].aos-animate,body[data-aos-delay="650"] [data-aos].aos-animate{transition-delay:.65s}[data-aos][data-aos][data-aos-duration="700"],body[data-aos-duration="700"] [data-aos]{transition-duration:.7s}[data-aos][data-aos][data-aos-delay="700"],body[data-aos-delay="700"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="700"].aos-animate,body[data-aos-delay="700"] [data-aos].aos-animate{transition-delay:.7s}[data-aos][data-aos][data-aos-duration="750"],body[data-aos-duration="750"] [data-aos]{transition-duration:.75s}[data-aos][data-aos][data-aos-delay="750"],body[data-aos-delay="750"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="750"].aos-animate,body[data-aos-delay="750"] [data-aos].aos-animate{transition-delay:.75s}[data-aos][data-aos][data-aos-duration="800"],body[data-aos-duration="800"] [data-aos]{transition-duration:.8s}[data-aos][data-aos][data-aos-delay="800"],body[data-aos-delay="800"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="800"].aos-animate,body[data-aos-delay="800"] [data-aos].aos-animate{transition-delay:.8s}[data-aos][data-aos][data-aos-duration="850"],body[data-aos-duration="850"] [data-aos]{transition-duration:.85s}[data-aos][data-aos][data-aos-delay="850"],body[data-aos-delay="850"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="850"].aos-animate,body[data-aos-delay="850"] [data-aos].aos-animate{transition-delay:.85s}[data-aos][data-aos][data-aos-duration="900"],body[data-aos-duration="900"] [data-aos]{transition-duration:.9s}[data-aos][data-aos][data-aos-delay="900"],body[data-aos-delay="900"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="900"].aos-animate,body[data-aos-delay="900"] [data-aos].aos-animate{transition-delay:.9s}[data-aos][data-aos][data-aos-duration="950"],body[data-aos-duration="950"] [data-aos]{transition-duration:.95s}[data-aos][data-aos][data-aos-delay="950"],body[data-aos-delay="950"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="950"].aos-animate,body[data-aos-delay="950"] [data-aos].aos-animate{transition-delay:.95s}[data-aos][data-aos][data-aos-duration="1000"],body[data-aos-duration="1000"] [data-aos]{transition-duration:1s}[data-aos][data-aos][data-aos-delay="1000"],body[data-aos-delay="1000"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="1000"].aos-animate,body[data-aos-delay="1000"] [data-aos].aos-animate{transition-delay:1s}[data-aos][data-aos][data-aos-duration="1050"],body[data-aos-duration="1050"] [data-aos]{transition-duration:1.05s}[data-aos][data-aos][data-aos-delay="1050"],body[data-aos-delay="1050"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="1050"].aos-animate,body[data-aos-delay="1050"] [data-aos].aos-animate{transition-delay:1.05s}[data-aos][data-aos][data-aos-duration="1100"],body[data-aos-duration="1100"] [data-aos]{transition-duration:1.1s}[data-aos][data-aos][data-aos-delay="1100"],body[data-aos-delay="1100"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="1100"].aos-animate,body[data-aos-delay="1100"] [data-aos].aos-animate{transition-delay:1.1s}[data-aos][data-aos][data-aos-duration="1150"],body[data-aos-duration="1150"] [data-aos]{transition-duration:1.15s}[data-aos][data-aos][data-aos-delay="1150"],body[data-aos-delay="1150"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="1150"].aos-animate,body[data-aos-delay="1150"] [data-aos].aos-animate{transition-delay:1.15s}[data-aos][data-aos][data-aos-duration="1200"],body[data-aos-duration="1200"] [data-aos]{transition-duration:1.2s}[data-aos][data-aos][data-aos-delay="1200"],body[data-aos-delay="1200"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="1200"].aos-animate,body[data-aos-delay="1200"] [data-aos].aos-animate{transition-delay:1.2s}[data-aos][data-aos][data-aos-duration="1250"],body[data-aos-duration="1250"] [data-aos]{transition-duration:1.25s}[data-aos][data-aos][data-aos-delay="1250"],body[data-aos-delay="1250"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="1250"].aos-animate,body[data-aos-delay="1250"] [data-aos].aos-animate{transition-delay:1.25s}[data-aos][data-aos][data-aos-duration="1300"],body[data-aos-duration="1300"] [data-aos]{transition-duration:1.3s}[data-aos][data-aos][data-aos-delay="1300"],body[data-aos-delay="1300"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="1300"].aos-animate,body[data-aos-delay="1300"] [data-aos].aos-animate{transition-delay:1.3s}[data-aos][data-aos][data-aos-duration="1350"],body[data-aos-duration="1350"] [data-aos]{transition-duration:1.35s}[data-aos][data-aos][data-aos-delay="1350"],body[data-aos-delay="1350"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="1350"].aos-animate,body[data-aos-delay="1350"] [data-aos].aos-animate{transition-delay:1.35s}[data-aos][data-aos][data-aos-duration="1400"],body[data-aos-duration="1400"] [data-aos]{transition-duration:1.4s}[data-aos][data-aos][data-aos-delay="1400"],body[data-aos-delay="1400"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="1400"].aos-animate,body[data-aos-delay="1400"] [data-aos].aos-animate{transition-delay:1.4s}[data-aos][data-aos][data-aos-duration="1450"],body[data-aos-duration="1450"] [data-aos]{transition-duration:1.45s}[data-aos][data-aos][data-aos-delay="1450"],body[data-aos-delay="1450"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="1450"].aos-animate,body[data-aos-delay="1450"] [data-aos].aos-animate{transition-delay:1.45s}[data-aos][data-aos][data-aos-duration="1500"],body[data-aos-duration="1500"] [data-aos]{transition-duration:1.5s}[data-aos][data-aos][data-aos-delay="1500"],body[data-aos-delay="1500"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="1500"].aos-animate,body[data-aos-delay="1500"] [data-aos].aos-animate{transition-delay:1.5s}[data-aos][data-aos][data-aos-duration="1550"],body[data-aos-duration="1550"] [data-aos]{transition-duration:1.55s}[data-aos][data-aos][data-aos-delay="1550"],body[data-aos-delay="1550"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="1550"].aos-animate,body[data-aos-delay="1550"] [data-aos].aos-animate{transition-delay:1.55s}[data-aos][data-aos][data-aos-duration="1600"],body[data-aos-duration="1600"] [data-aos]{transition-duration:1.6s}[data-aos][data-aos][data-aos-delay="1600"],body[data-aos-delay="1600"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="1600"].aos-animate,body[data-aos-delay="1600"] [data-aos].aos-animate{transition-delay:1.6s}[data-aos][data-aos][data-aos-duration="1650"],body[data-aos-duration="1650"] [data-aos]{transition-duration:1.65s}[data-aos][data-aos][data-aos-delay="1650"],body[data-aos-delay="1650"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="1650"].aos-animate,body[data-aos-delay="1650"] [data-aos].aos-animate{transition-delay:1.65s}[data-aos][data-aos][data-aos-duration="1700"],body[data-aos-duration="1700"] [data-aos]{transition-duration:1.7s}[data-aos][data-aos][data-aos-delay="1700"],body[data-aos-delay="1700"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="1700"].aos-animate,body[data-aos-delay="1700"] [data-aos].aos-animate{transition-delay:1.7s}[data-aos][data-aos][data-aos-duration="1750"],body[data-aos-duration="1750"] [data-aos]{transition-duration:1.75s}[data-aos][data-aos][data-aos-delay="1750"],body[data-aos-delay="1750"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="1750"].aos-animate,body[data-aos-delay="1750"] [data-aos].aos-animate{transition-delay:1.75s}[data-aos][data-aos][data-aos-duration="1800"],body[data-aos-duration="1800"] [data-aos]{transition-duration:1.8s}[data-aos][data-aos][data-aos-delay="1800"],body[data-aos-delay="1800"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="1800"].aos-animate,body[data-aos-delay="1800"] [data-aos].aos-animate{transition-delay:1.8s}[data-aos][data-aos][data-aos-duration="1850"],body[data-aos-duration="1850"] [data-aos]{transition-duration:1.85s}[data-aos][data-aos][data-aos-delay="1850"],body[data-aos-delay="1850"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="1850"].aos-animate,body[data-aos-delay="1850"] [data-aos].aos-animate{transition-delay:1.85s}[data-aos][data-aos][data-aos-duration="1900"],body[data-aos-duration="1900"] [data-aos]{transition-duration:1.9s}[data-aos][data-aos][data-aos-delay="1900"],body[data-aos-delay="1900"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="1900"].aos-animate,body[data-aos-delay="1900"] [data-aos].aos-animate{transition-delay:1.9s}[data-aos][data-aos][data-aos-duration="1950"],body[data-aos-duration="1950"] [data-aos]{transition-duration:1.95s}[data-aos][data-aos][data-aos-delay="1950"],body[data-aos-delay="1950"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="1950"].aos-animate,body[data-aos-delay="1950"] [data-aos].aos-animate{transition-delay:1.95s}[data-aos][data-aos][data-aos-duration="2000"],body[data-aos-duration="2000"] [data-aos]{transition-duration:2s}[data-aos][data-aos][data-aos-delay="2000"],body[data-aos-delay="2000"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="2000"].aos-animate,body[data-aos-delay="2000"] [data-aos].aos-animate{transition-delay:2s}[data-aos][data-aos][data-aos-duration="2050"],body[data-aos-duration="2050"] [data-aos]{transition-duration:2.05s}[data-aos][data-aos][data-aos-delay="2050"],body[data-aos-delay="2050"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="2050"].aos-animate,body[data-aos-delay="2050"] [data-aos].aos-animate{transition-delay:2.05s}[data-aos][data-aos][data-aos-duration="2100"],body[data-aos-duration="2100"] [data-aos]{transition-duration:2.1s}[data-aos][data-aos][data-aos-delay="2100"],body[data-aos-delay="2100"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="2100"].aos-animate,body[data-aos-delay="2100"] [data-aos].aos-animate{transition-delay:2.1s}[data-aos][data-aos][data-aos-duration="2150"],body[data-aos-duration="2150"] [data-aos]{transition-duration:2.15s}[data-aos][data-aos][data-aos-delay="2150"],body[data-aos-delay="2150"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="2150"].aos-animate,body[data-aos-delay="2150"] [data-aos].aos-animate{transition-delay:2.15s}[data-aos][data-aos][data-aos-duration="2200"],body[data-aos-duration="2200"] [data-aos]{transition-duration:2.2s}[data-aos][data-aos][data-aos-delay="2200"],body[data-aos-delay="2200"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="2200"].aos-animate,body[data-aos-delay="2200"] [data-aos].aos-animate{transition-delay:2.2s}[data-aos][data-aos][data-aos-duration="2250"],body[data-aos-duration="2250"] [data-aos]{transition-duration:2.25s}[data-aos][data-aos][data-aos-delay="2250"],body[data-aos-delay="2250"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="2250"].aos-animate,body[data-aos-delay="2250"] [data-aos].aos-animate{transition-delay:2.25s}[data-aos][data-aos][data-aos-duration="2300"],body[data-aos-duration="2300"] [data-aos]{transition-duration:2.3s}[data-aos][data-aos][data-aos-delay="2300"],body[data-aos-delay="2300"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="2300"].aos-animate,body[data-aos-delay="2300"] [data-aos].aos-animate{transition-delay:2.3s}[data-aos][data-aos][data-aos-duration="2350"],body[data-aos-duration="2350"] [data-aos]{transition-duration:2.35s}[data-aos][data-aos][data-aos-delay="2350"],body[data-aos-delay="2350"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="2350"].aos-animate,body[data-aos-delay="2350"] [data-aos].aos-animate{transition-delay:2.35s}[data-aos][data-aos][data-aos-duration="2400"],body[data-aos-duration="2400"] [data-aos]{transition-duration:2.4s}[data-aos][data-aos][data-aos-delay="2400"],body[data-aos-delay="2400"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="2400"].aos-animate,body[data-aos-delay="2400"] [data-aos].aos-animate{transition-delay:2.4s}[data-aos][data-aos][data-aos-duration="2450"],body[data-aos-duration="2450"] [data-aos]{transition-duration:2.45s}[data-aos][data-aos][data-aos-delay="2450"],body[data-aos-delay="2450"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="2450"].aos-animate,body[data-aos-delay="2450"] [data-aos].aos-animate{transition-delay:2.45s}[data-aos][data-aos][data-aos-duration="2500"],body[data-aos-duration="2500"] [data-aos]{transition-duration:2.5s}[data-aos][data-aos][data-aos-delay="2500"],body[data-aos-delay="2500"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="2500"].aos-animate,body[data-aos-delay="2500"] [data-aos].aos-animate{transition-delay:2.5s}[data-aos][data-aos][data-aos-duration="2550"],body[data-aos-duration="2550"] [data-aos]{transition-duration:2.55s}[data-aos][data-aos][data-aos-delay="2550"],body[data-aos-delay="2550"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="2550"].aos-animate,body[data-aos-delay="2550"] [data-aos].aos-animate{transition-delay:2.55s}[data-aos][data-aos][data-aos-duration="2600"],body[data-aos-duration="2600"] [data-aos]{transition-duration:2.6s}[data-aos][data-aos][data-aos-delay="2600"],body[data-aos-delay="2600"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="2600"].aos-animate,body[data-aos-delay="2600"] [data-aos].aos-animate{transition-delay:2.6s}[data-aos][data-aos][data-aos-duration="2650"],body[data-aos-duration="2650"] [data-aos]{transition-duration:2.65s}[data-aos][data-aos][data-aos-delay="2650"],body[data-aos-delay="2650"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="2650"].aos-animate,body[data-aos-delay="2650"] [data-aos].aos-animate{transition-delay:2.65s}[data-aos][data-aos][data-aos-duration="2700"],body[data-aos-duration="2700"] [data-aos]{transition-duration:2.7s}[data-aos][data-aos][data-aos-delay="2700"],body[data-aos-delay="2700"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="2700"].aos-animate,body[data-aos-delay="2700"] [data-aos].aos-animate{transition-delay:2.7s}[data-aos][data-aos][data-aos-duration="2750"],body[data-aos-duration="2750"] [data-aos]{transition-duration:2.75s}[data-aos][data-aos][data-aos-delay="2750"],body[data-aos-delay="2750"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="2750"].aos-animate,body[data-aos-delay="2750"] [data-aos].aos-animate{transition-delay:2.75s}[data-aos][data-aos][data-aos-duration="2800"],body[data-aos-duration="2800"] [data-aos]{transition-duration:2.8s}[data-aos][data-aos][data-aos-delay="2800"],body[data-aos-delay="2800"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="2800"].aos-animate,body[data-aos-delay="2800"] [data-aos].aos-animate{transition-delay:2.8s}[data-aos][data-aos][data-aos-duration="2850"],body[data-aos-duration="2850"] [data-aos]{transition-duration:2.85s}[data-aos][data-aos][data-aos-delay="2850"],body[data-aos-delay="2850"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="2850"].aos-animate,body[data-aos-delay="2850"] [data-aos].aos-animate{transition-delay:2.85s}[data-aos][data-aos][data-aos-duration="2900"],body[data-aos-duration="2900"] [data-aos]{transition-duration:2.9s}[data-aos][data-aos][data-aos-delay="2900"],body[data-aos-delay="2900"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="2900"].aos-animate,body[data-aos-delay="2900"] [data-aos].aos-animate{transition-delay:2.9s}[data-aos][data-aos][data-aos-duration="2950"],body[data-aos-duration="2950"] [data-aos]{transition-duration:2.95s}[data-aos][data-aos][data-aos-delay="2950"],body[data-aos-delay="2950"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="2950"].aos-animate,body[data-aos-delay="2950"] [data-aos].aos-animate{transition-delay:2.95s}[data-aos][data-aos][data-aos-duration="3000"],body[data-aos-duration="3000"] [data-aos]{transition-duration:3s}[data-aos][data-aos][data-aos-delay="3000"],body[data-aos-delay="3000"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="3000"].aos-animate,body[data-aos-delay="3000"] [data-aos].aos-animate{transition-delay:3s}[data-aos][data-aos][data-aos-easing=linear],body[data-aos-easing=linear] [data-aos]{transition-timing-function:cubic-bezier(.25,.25,.75,.75)}[data-aos][data-aos][data-aos-easing=ease],body[data-aos-easing=ease] [data-aos]{transition-timing-function:ease}[data-aos][data-aos][data-aos-easing=ease-in],body[data-aos-easing=ease-in] [data-aos]{transition-timing-function:ease-in}[data-aos][data-aos][data-aos-easing=ease-out],body[data-aos-easing=ease-out] [data-aos]{transition-timing-function:ease-out}[data-aos][data-aos][data-aos-easing=ease-in-out],body[data-aos-easing=ease-in-out] [data-aos]{transition-timing-function:ease-in-out}[data-aos][data-aos][data-aos-easing=ease-in-back],body[data-aos-easing=ease-in-back] [data-aos]{transition-timing-function:cubic-bezier(.6,-.28,.735,.045)}[data-aos][data-aos][data-aos-easing=ease-out-back],body[data-aos-easing=ease-out-back] [data-aos]{transition-timing-function:cubic-bezier(.175,.885,.32,1.275)}[data-aos][data-aos][data-aos-easing=ease-in-out-back],body[data-aos-easing=ease-in-out-back] [data-aos]{transition-timing-function:cubic-bezier(.68,-.55,.265,1.55)}[data-aos][data-aos][data-aos-easing=ease-in-sine],body[data-aos-easing=ease-in-sine] [data-aos]{transition-timing-function:cubic-bezier(.47,0,.745,.715)}[data-aos][data-aos][data-aos-easing=ease-out-sine],body[data-aos-easing=ease-out-sine] [data-aos]{transition-timing-function:cubic-bezier(.39,.575,.565,1)}[data-aos][data-aos][data-aos-easing=ease-in-out-sine],body[data-aos-easing=ease-in-out-sine] [data-aos]{transition-timing-function:cubic-bezier(.445,.05,.55,.95)}[data-aos][data-aos][data-aos-easing=ease-in-quad],body[data-aos-easing=ease-in-quad] [data-aos]{transition-timing-function:cubic-bezier(.55,.085,.68,.53)}[data-aos][data-aos][data-aos-easing=ease-out-quad],body[data-aos-easing=ease-out-quad] [data-aos]{transition-timing-function:cubic-bezier(.25,.46,.45,.94)}[data-aos][data-aos][data-aos-easing=ease-in-out-quad],body[data-aos-easing=ease-in-out-quad] [data-aos]{transition-timing-function:cubic-bezier(.455,.03,.515,.955)}[data-aos][data-aos][data-aos-easing=ease-in-cubic],body[data-aos-easing=ease-in-cubic] [data-aos]{transition-timing-function:cubic-bezier(.55,.085,.68,.53)}[data-aos][data-aos][data-aos-easing=ease-out-cubic],body[data-aos-easing=ease-out-cubic] [data-aos]{transition-timing-function:cubic-bezier(.25,.46,.45,.94)}[data-aos][data-aos][data-aos-easing=ease-in-out-cubic],body[data-aos-easing=ease-in-out-cubic] [data-aos]{transition-timing-function:cubic-bezier(.455,.03,.515,.955)}[data-aos][data-aos][data-aos-easing=ease-in-quart],body[data-aos-easing=ease-in-quart] [data-aos]{transition-timing-function:cubic-bezier(.55,.085,.68,.53)}[data-aos][data-aos][data-aos-easing=ease-out-quart],body[data-aos-easing=ease-out-quart] [data-aos]{transition-timing-function:cubic-bezier(.25,.46,.45,.94)}[data-aos][data-aos][data-aos-easing=ease-in-out-quart],body[data-aos-easing=ease-in-out-quart] [data-aos]{transition-timing-function:cubic-bezier(.455,.03,.515,.955)}[data-aos^=fade][data-aos^=fade]{opacity:0;transition-property:opacity,transform}[data-aos^=fade][data-aos^=fade].aos-animate{opacity:1;transform:translateZ(0)}[data-aos=fade-up]{transform:translate3d(0,100px,0)}[data-aos=fade-down]{transform:translate3d(0,-100px,0)}[data-aos=fade-right]{transform:translate3d(-100px,0,0)}[data-aos=fade-left]{transform:translate3d(100px,0,0)}[data-aos=fade-up-right]{transform:translate3d(-100px,100px,0)}[data-aos=fade-up-left]{transform:translate3d(100px,100px,0)}[data-aos=fade-down-right]{transform:translate3d(-100px,-100px,0)}[data-aos=fade-down-left]{transform:translate3d(100px,-100px,0)}[data-aos^=zoom][data-aos^=zoom]{opacity:0;transition-property:opacity,transform}[data-aos^=zoom][data-aos^=zoom].aos-animate{opacity:1;transform:translateZ(0) scale(1)}[data-aos=zoom-in]{transform:scale(.6)}[data-aos=zoom-in-up]{transform:translate3d(0,100px,0) scale(.6)}[data-aos=zoom-in-down]{transform:translate3d(0,-100px,0) scale(.6)}[data-aos=zoom-in-right]{transform:translate3d(-100px,0,0) scale(.6)}[data-aos=zoom-in-left]{transform:translate3d(100px,0,0) scale(.6)}[data-aos=zoom-out]{transform:scale(1.2)}[data-aos=zoom-out-up]{transform:translate3d(0,100px,0) scale(1.2)}[data-aos=zoom-out-down]{transform:translate3d(0,-100px,0) scale(1.2)}[data-aos=zoom-out-right]{transform:translate3d(-100px,0,0) scale(1.2)}[data-aos=zoom-out-left]{transform:translate3d(100px,0,0) scale(1.2)}[data-aos^=slide][data-aos^=slide]{transition-property:transform}[data-aos^=slide][data-aos^=slide].aos-animate{transform:translateZ(0)}[data-aos=slide-up]{transform:translate3d(0,100%,0)}[data-aos=slide-down]{transform:translate3d(0,-100%,0)}[data-aos=slide-right]{transform:translate3d(-100%,0,0)}[data-aos=slide-left]{transform:translate3d(100%,0,0)}[data-aos^=flip][data-aos^=flip]{backface-visibility:hidden;transition-property:transform}[data-aos=flip-left]{transform:perspective(2500px) rotateY(-100deg)}[data-aos=flip-left].aos-animate{transform:perspective(2500px) rotateY(0)}[data-aos=flip-right]{transform:perspective(2500px) rotateY(100deg)}[data-aos=flip-right].aos-animate{transform:perspective(2500px) rotateY(0)}[data-aos=flip-up]{transform:perspective(2500px) rotateX(-100deg)}[data-aos=flip-up].aos-animate{transform:perspective(2500px) rotateX(0)}[data-aos=flip-down]{transform:perspective(2500px) rotateX(100deg)}[data-aos=flip-down].aos-animate{transform:perspective(2500px) rotateX(0)}',"",{version:3,sources:["webpack://./src/components/UI-X/aos/aos.css"],names:[],mappings:"AAAA,qFAAqF,wBAAwB,CAAC,+EAA+E,kBAAkB,CAAC,uGAAuG,qBAAqB,CAAC,uFAAuF,uBAAuB,CAAC,iFAAiF,kBAAkB,CAAC,yGAAyG,oBAAoB,CAAC,uFAAuF,wBAAwB,CAAC,iFAAiF,kBAAkB,CAAC,yGAAyG,qBAAqB,CAAC,uFAAuF,uBAAuB,CAAC,iFAAiF,kBAAkB,CAAC,yGAAyG,oBAAoB,CAAC,uFAAuF,wBAAwB,CAAC,iFAAiF,kBAAkB,CAAC,yGAAyG,qBAAqB,CAAC,uFAAuF,uBAAuB,CAAC,iFAAiF,kBAAkB,CAAC,yGAAyG,oBAAoB,CAAC,uFAAuF,wBAAwB,CAAC,iFAAiF,kBAAkB,CAAC,yGAAyG,qBAAqB,CAAC,uFAAuF,uBAAuB,CAAC,iFAAiF,kBAAkB,CAAC,yGAAyG,oBAAoB,CAAC,uFAAuF,wBAAwB,CAAC,iFAAiF,kBAAkB,CAAC,yGAAyG,qBAAqB,CAAC,uFAAuF,uBAAuB,CAAC,iFAAiF,kBAAkB,CAAC,yGAAyG,oBAAoB,CAAC,uFAAuF,wBAAwB,CAAC,iFAAiF,kBAAkB,CAAC,yGAAyG,qBAAqB,CAAC,uFAAuF,uBAAuB,CAAC,iFAAiF,kBAAkB,CAAC,yGAAyG,oBAAoB,CAAC,uFAAuF,wBAAwB,CAAC,iFAAiF,kBAAkB,CAAC,yGAAyG,qBAAqB,CAAC,uFAAuF,uBAAuB,CAAC,iFAAiF,kBAAkB,CAAC,yGAAyG,oBAAoB,CAAC,uFAAuF,wBAAwB,CAAC,iFAAiF,kBAAkB,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iCAAiC,CAAC,qBAAqB,gCAAgC,CAAC,yBAAyB,qCAAqC,CAAC,wBAAwB,oCAAoC,CAAC,2BAA2B,sCAAsC,CAAC,0BAA0B,qCAAqC,CAAC,iCAAiC,SAAS,CAAC,qCAAqC,CAAC,6CAA6C,SAAS,CAAC,gCAAgC,CAAC,mBAAmB,mBAAmB,CAAC,sBAAsB,0CAA0C,CAAC,wBAAwB,2CAA2C,CAAC,yBAAyB,2CAA2C,CAAC,wBAAwB,0CAA0C,CAAC,oBAAoB,oBAAoB,CAAC,uBAAuB,2CAA2C,CAAC,yBAAyB,4CAA4C,CAAC,0BAA0B,4CAA4C,CAAC,yBAAyB,2CAA2C,CAAC,mCAAmC,6BAA6B,CAAC,+CAA+C,uBAAuB,CAAC,oBAAoB,+BAA+B,CAAC,sBAAsB,gCAAgC,CAAC,uBAAuB,gCAAgC,CAAC,sBAAsB,+BAA+B,CAAC,iCAAiC,0BAA0B,CAAC,6BAA6B,CAAC,qBAAqB,8CAA8C,CAAC,iCAAiC,wCAAwC,CAAC,sBAAsB,6CAA6C,CAAC,kCAAkC,wCAAwC,CAAC,mBAAmB,8CAA8C,CAAC,+BAA+B,wCAAwC,CAAC,qBAAqB,6CAA6C,CAAC,iCAAiC,wCAAwC",sourcesContent:['[data-aos][data-aos][data-aos-duration="50"],body[data-aos-duration="50"] [data-aos]{transition-duration:50ms}[data-aos][data-aos][data-aos-delay="50"],body[data-aos-delay="50"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="50"].aos-animate,body[data-aos-delay="50"] [data-aos].aos-animate{transition-delay:50ms}[data-aos][data-aos][data-aos-duration="100"],body[data-aos-duration="100"] [data-aos]{transition-duration:.1s}[data-aos][data-aos][data-aos-delay="100"],body[data-aos-delay="100"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="100"].aos-animate,body[data-aos-delay="100"] [data-aos].aos-animate{transition-delay:.1s}[data-aos][data-aos][data-aos-duration="150"],body[data-aos-duration="150"] [data-aos]{transition-duration:.15s}[data-aos][data-aos][data-aos-delay="150"],body[data-aos-delay="150"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="150"].aos-animate,body[data-aos-delay="150"] [data-aos].aos-animate{transition-delay:.15s}[data-aos][data-aos][data-aos-duration="200"],body[data-aos-duration="200"] [data-aos]{transition-duration:.2s}[data-aos][data-aos][data-aos-delay="200"],body[data-aos-delay="200"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="200"].aos-animate,body[data-aos-delay="200"] [data-aos].aos-animate{transition-delay:.2s}[data-aos][data-aos][data-aos-duration="250"],body[data-aos-duration="250"] [data-aos]{transition-duration:.25s}[data-aos][data-aos][data-aos-delay="250"],body[data-aos-delay="250"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="250"].aos-animate,body[data-aos-delay="250"] [data-aos].aos-animate{transition-delay:.25s}[data-aos][data-aos][data-aos-duration="300"],body[data-aos-duration="300"] [data-aos]{transition-duration:.3s}[data-aos][data-aos][data-aos-delay="300"],body[data-aos-delay="300"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="300"].aos-animate,body[data-aos-delay="300"] [data-aos].aos-animate{transition-delay:.3s}[data-aos][data-aos][data-aos-duration="350"],body[data-aos-duration="350"] [data-aos]{transition-duration:.35s}[data-aos][data-aos][data-aos-delay="350"],body[data-aos-delay="350"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="350"].aos-animate,body[data-aos-delay="350"] [data-aos].aos-animate{transition-delay:.35s}[data-aos][data-aos][data-aos-duration="400"],body[data-aos-duration="400"] [data-aos]{transition-duration:.4s}[data-aos][data-aos][data-aos-delay="400"],body[data-aos-delay="400"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="400"].aos-animate,body[data-aos-delay="400"] [data-aos].aos-animate{transition-delay:.4s}[data-aos][data-aos][data-aos-duration="450"],body[data-aos-duration="450"] [data-aos]{transition-duration:.45s}[data-aos][data-aos][data-aos-delay="450"],body[data-aos-delay="450"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="450"].aos-animate,body[data-aos-delay="450"] [data-aos].aos-animate{transition-delay:.45s}[data-aos][data-aos][data-aos-duration="500"],body[data-aos-duration="500"] [data-aos]{transition-duration:.5s}[data-aos][data-aos][data-aos-delay="500"],body[data-aos-delay="500"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="500"].aos-animate,body[data-aos-delay="500"] [data-aos].aos-animate{transition-delay:.5s}[data-aos][data-aos][data-aos-duration="550"],body[data-aos-duration="550"] [data-aos]{transition-duration:.55s}[data-aos][data-aos][data-aos-delay="550"],body[data-aos-delay="550"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="550"].aos-animate,body[data-aos-delay="550"] [data-aos].aos-animate{transition-delay:.55s}[data-aos][data-aos][data-aos-duration="600"],body[data-aos-duration="600"] [data-aos]{transition-duration:.6s}[data-aos][data-aos][data-aos-delay="600"],body[data-aos-delay="600"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="600"].aos-animate,body[data-aos-delay="600"] [data-aos].aos-animate{transition-delay:.6s}[data-aos][data-aos][data-aos-duration="650"],body[data-aos-duration="650"] [data-aos]{transition-duration:.65s}[data-aos][data-aos][data-aos-delay="650"],body[data-aos-delay="650"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="650"].aos-animate,body[data-aos-delay="650"] [data-aos].aos-animate{transition-delay:.65s}[data-aos][data-aos][data-aos-duration="700"],body[data-aos-duration="700"] [data-aos]{transition-duration:.7s}[data-aos][data-aos][data-aos-delay="700"],body[data-aos-delay="700"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="700"].aos-animate,body[data-aos-delay="700"] [data-aos].aos-animate{transition-delay:.7s}[data-aos][data-aos][data-aos-duration="750"],body[data-aos-duration="750"] [data-aos]{transition-duration:.75s}[data-aos][data-aos][data-aos-delay="750"],body[data-aos-delay="750"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="750"].aos-animate,body[data-aos-delay="750"] [data-aos].aos-animate{transition-delay:.75s}[data-aos][data-aos][data-aos-duration="800"],body[data-aos-duration="800"] [data-aos]{transition-duration:.8s}[data-aos][data-aos][data-aos-delay="800"],body[data-aos-delay="800"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="800"].aos-animate,body[data-aos-delay="800"] [data-aos].aos-animate{transition-delay:.8s}[data-aos][data-aos][data-aos-duration="850"],body[data-aos-duration="850"] [data-aos]{transition-duration:.85s}[data-aos][data-aos][data-aos-delay="850"],body[data-aos-delay="850"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="850"].aos-animate,body[data-aos-delay="850"] [data-aos].aos-animate{transition-delay:.85s}[data-aos][data-aos][data-aos-duration="900"],body[data-aos-duration="900"] [data-aos]{transition-duration:.9s}[data-aos][data-aos][data-aos-delay="900"],body[data-aos-delay="900"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="900"].aos-animate,body[data-aos-delay="900"] [data-aos].aos-animate{transition-delay:.9s}[data-aos][data-aos][data-aos-duration="950"],body[data-aos-duration="950"] [data-aos]{transition-duration:.95s}[data-aos][data-aos][data-aos-delay="950"],body[data-aos-delay="950"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="950"].aos-animate,body[data-aos-delay="950"] [data-aos].aos-animate{transition-delay:.95s}[data-aos][data-aos][data-aos-duration="1000"],body[data-aos-duration="1000"] [data-aos]{transition-duration:1s}[data-aos][data-aos][data-aos-delay="1000"],body[data-aos-delay="1000"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="1000"].aos-animate,body[data-aos-delay="1000"] [data-aos].aos-animate{transition-delay:1s}[data-aos][data-aos][data-aos-duration="1050"],body[data-aos-duration="1050"] [data-aos]{transition-duration:1.05s}[data-aos][data-aos][data-aos-delay="1050"],body[data-aos-delay="1050"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="1050"].aos-animate,body[data-aos-delay="1050"] [data-aos].aos-animate{transition-delay:1.05s}[data-aos][data-aos][data-aos-duration="1100"],body[data-aos-duration="1100"] [data-aos]{transition-duration:1.1s}[data-aos][data-aos][data-aos-delay="1100"],body[data-aos-delay="1100"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="1100"].aos-animate,body[data-aos-delay="1100"] [data-aos].aos-animate{transition-delay:1.1s}[data-aos][data-aos][data-aos-duration="1150"],body[data-aos-duration="1150"] [data-aos]{transition-duration:1.15s}[data-aos][data-aos][data-aos-delay="1150"],body[data-aos-delay="1150"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="1150"].aos-animate,body[data-aos-delay="1150"] [data-aos].aos-animate{transition-delay:1.15s}[data-aos][data-aos][data-aos-duration="1200"],body[data-aos-duration="1200"] [data-aos]{transition-duration:1.2s}[data-aos][data-aos][data-aos-delay="1200"],body[data-aos-delay="1200"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="1200"].aos-animate,body[data-aos-delay="1200"] [data-aos].aos-animate{transition-delay:1.2s}[data-aos][data-aos][data-aos-duration="1250"],body[data-aos-duration="1250"] [data-aos]{transition-duration:1.25s}[data-aos][data-aos][data-aos-delay="1250"],body[data-aos-delay="1250"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="1250"].aos-animate,body[data-aos-delay="1250"] [data-aos].aos-animate{transition-delay:1.25s}[data-aos][data-aos][data-aos-duration="1300"],body[data-aos-duration="1300"] [data-aos]{transition-duration:1.3s}[data-aos][data-aos][data-aos-delay="1300"],body[data-aos-delay="1300"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="1300"].aos-animate,body[data-aos-delay="1300"] [data-aos].aos-animate{transition-delay:1.3s}[data-aos][data-aos][data-aos-duration="1350"],body[data-aos-duration="1350"] [data-aos]{transition-duration:1.35s}[data-aos][data-aos][data-aos-delay="1350"],body[data-aos-delay="1350"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="1350"].aos-animate,body[data-aos-delay="1350"] [data-aos].aos-animate{transition-delay:1.35s}[data-aos][data-aos][data-aos-duration="1400"],body[data-aos-duration="1400"] [data-aos]{transition-duration:1.4s}[data-aos][data-aos][data-aos-delay="1400"],body[data-aos-delay="1400"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="1400"].aos-animate,body[data-aos-delay="1400"] [data-aos].aos-animate{transition-delay:1.4s}[data-aos][data-aos][data-aos-duration="1450"],body[data-aos-duration="1450"] [data-aos]{transition-duration:1.45s}[data-aos][data-aos][data-aos-delay="1450"],body[data-aos-delay="1450"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="1450"].aos-animate,body[data-aos-delay="1450"] [data-aos].aos-animate{transition-delay:1.45s}[data-aos][data-aos][data-aos-duration="1500"],body[data-aos-duration="1500"] [data-aos]{transition-duration:1.5s}[data-aos][data-aos][data-aos-delay="1500"],body[data-aos-delay="1500"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="1500"].aos-animate,body[data-aos-delay="1500"] [data-aos].aos-animate{transition-delay:1.5s}[data-aos][data-aos][data-aos-duration="1550"],body[data-aos-duration="1550"] [data-aos]{transition-duration:1.55s}[data-aos][data-aos][data-aos-delay="1550"],body[data-aos-delay="1550"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="1550"].aos-animate,body[data-aos-delay="1550"] [data-aos].aos-animate{transition-delay:1.55s}[data-aos][data-aos][data-aos-duration="1600"],body[data-aos-duration="1600"] [data-aos]{transition-duration:1.6s}[data-aos][data-aos][data-aos-delay="1600"],body[data-aos-delay="1600"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="1600"].aos-animate,body[data-aos-delay="1600"] [data-aos].aos-animate{transition-delay:1.6s}[data-aos][data-aos][data-aos-duration="1650"],body[data-aos-duration="1650"] [data-aos]{transition-duration:1.65s}[data-aos][data-aos][data-aos-delay="1650"],body[data-aos-delay="1650"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="1650"].aos-animate,body[data-aos-delay="1650"] [data-aos].aos-animate{transition-delay:1.65s}[data-aos][data-aos][data-aos-duration="1700"],body[data-aos-duration="1700"] [data-aos]{transition-duration:1.7s}[data-aos][data-aos][data-aos-delay="1700"],body[data-aos-delay="1700"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="1700"].aos-animate,body[data-aos-delay="1700"] [data-aos].aos-animate{transition-delay:1.7s}[data-aos][data-aos][data-aos-duration="1750"],body[data-aos-duration="1750"] [data-aos]{transition-duration:1.75s}[data-aos][data-aos][data-aos-delay="1750"],body[data-aos-delay="1750"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="1750"].aos-animate,body[data-aos-delay="1750"] [data-aos].aos-animate{transition-delay:1.75s}[data-aos][data-aos][data-aos-duration="1800"],body[data-aos-duration="1800"] [data-aos]{transition-duration:1.8s}[data-aos][data-aos][data-aos-delay="1800"],body[data-aos-delay="1800"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="1800"].aos-animate,body[data-aos-delay="1800"] [data-aos].aos-animate{transition-delay:1.8s}[data-aos][data-aos][data-aos-duration="1850"],body[data-aos-duration="1850"] [data-aos]{transition-duration:1.85s}[data-aos][data-aos][data-aos-delay="1850"],body[data-aos-delay="1850"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="1850"].aos-animate,body[data-aos-delay="1850"] [data-aos].aos-animate{transition-delay:1.85s}[data-aos][data-aos][data-aos-duration="1900"],body[data-aos-duration="1900"] [data-aos]{transition-duration:1.9s}[data-aos][data-aos][data-aos-delay="1900"],body[data-aos-delay="1900"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="1900"].aos-animate,body[data-aos-delay="1900"] [data-aos].aos-animate{transition-delay:1.9s}[data-aos][data-aos][data-aos-duration="1950"],body[data-aos-duration="1950"] [data-aos]{transition-duration:1.95s}[data-aos][data-aos][data-aos-delay="1950"],body[data-aos-delay="1950"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="1950"].aos-animate,body[data-aos-delay="1950"] [data-aos].aos-animate{transition-delay:1.95s}[data-aos][data-aos][data-aos-duration="2000"],body[data-aos-duration="2000"] [data-aos]{transition-duration:2s}[data-aos][data-aos][data-aos-delay="2000"],body[data-aos-delay="2000"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="2000"].aos-animate,body[data-aos-delay="2000"] [data-aos].aos-animate{transition-delay:2s}[data-aos][data-aos][data-aos-duration="2050"],body[data-aos-duration="2050"] [data-aos]{transition-duration:2.05s}[data-aos][data-aos][data-aos-delay="2050"],body[data-aos-delay="2050"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="2050"].aos-animate,body[data-aos-delay="2050"] [data-aos].aos-animate{transition-delay:2.05s}[data-aos][data-aos][data-aos-duration="2100"],body[data-aos-duration="2100"] [data-aos]{transition-duration:2.1s}[data-aos][data-aos][data-aos-delay="2100"],body[data-aos-delay="2100"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="2100"].aos-animate,body[data-aos-delay="2100"] [data-aos].aos-animate{transition-delay:2.1s}[data-aos][data-aos][data-aos-duration="2150"],body[data-aos-duration="2150"] [data-aos]{transition-duration:2.15s}[data-aos][data-aos][data-aos-delay="2150"],body[data-aos-delay="2150"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="2150"].aos-animate,body[data-aos-delay="2150"] [data-aos].aos-animate{transition-delay:2.15s}[data-aos][data-aos][data-aos-duration="2200"],body[data-aos-duration="2200"] [data-aos]{transition-duration:2.2s}[data-aos][data-aos][data-aos-delay="2200"],body[data-aos-delay="2200"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="2200"].aos-animate,body[data-aos-delay="2200"] [data-aos].aos-animate{transition-delay:2.2s}[data-aos][data-aos][data-aos-duration="2250"],body[data-aos-duration="2250"] [data-aos]{transition-duration:2.25s}[data-aos][data-aos][data-aos-delay="2250"],body[data-aos-delay="2250"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="2250"].aos-animate,body[data-aos-delay="2250"] [data-aos].aos-animate{transition-delay:2.25s}[data-aos][data-aos][data-aos-duration="2300"],body[data-aos-duration="2300"] [data-aos]{transition-duration:2.3s}[data-aos][data-aos][data-aos-delay="2300"],body[data-aos-delay="2300"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="2300"].aos-animate,body[data-aos-delay="2300"] [data-aos].aos-animate{transition-delay:2.3s}[data-aos][data-aos][data-aos-duration="2350"],body[data-aos-duration="2350"] [data-aos]{transition-duration:2.35s}[data-aos][data-aos][data-aos-delay="2350"],body[data-aos-delay="2350"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="2350"].aos-animate,body[data-aos-delay="2350"] [data-aos].aos-animate{transition-delay:2.35s}[data-aos][data-aos][data-aos-duration="2400"],body[data-aos-duration="2400"] [data-aos]{transition-duration:2.4s}[data-aos][data-aos][data-aos-delay="2400"],body[data-aos-delay="2400"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="2400"].aos-animate,body[data-aos-delay="2400"] [data-aos].aos-animate{transition-delay:2.4s}[data-aos][data-aos][data-aos-duration="2450"],body[data-aos-duration="2450"] [data-aos]{transition-duration:2.45s}[data-aos][data-aos][data-aos-delay="2450"],body[data-aos-delay="2450"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="2450"].aos-animate,body[data-aos-delay="2450"] [data-aos].aos-animate{transition-delay:2.45s}[data-aos][data-aos][data-aos-duration="2500"],body[data-aos-duration="2500"] [data-aos]{transition-duration:2.5s}[data-aos][data-aos][data-aos-delay="2500"],body[data-aos-delay="2500"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="2500"].aos-animate,body[data-aos-delay="2500"] [data-aos].aos-animate{transition-delay:2.5s}[data-aos][data-aos][data-aos-duration="2550"],body[data-aos-duration="2550"] [data-aos]{transition-duration:2.55s}[data-aos][data-aos][data-aos-delay="2550"],body[data-aos-delay="2550"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="2550"].aos-animate,body[data-aos-delay="2550"] [data-aos].aos-animate{transition-delay:2.55s}[data-aos][data-aos][data-aos-duration="2600"],body[data-aos-duration="2600"] [data-aos]{transition-duration:2.6s}[data-aos][data-aos][data-aos-delay="2600"],body[data-aos-delay="2600"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="2600"].aos-animate,body[data-aos-delay="2600"] [data-aos].aos-animate{transition-delay:2.6s}[data-aos][data-aos][data-aos-duration="2650"],body[data-aos-duration="2650"] [data-aos]{transition-duration:2.65s}[data-aos][data-aos][data-aos-delay="2650"],body[data-aos-delay="2650"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="2650"].aos-animate,body[data-aos-delay="2650"] [data-aos].aos-animate{transition-delay:2.65s}[data-aos][data-aos][data-aos-duration="2700"],body[data-aos-duration="2700"] [data-aos]{transition-duration:2.7s}[data-aos][data-aos][data-aos-delay="2700"],body[data-aos-delay="2700"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="2700"].aos-animate,body[data-aos-delay="2700"] [data-aos].aos-animate{transition-delay:2.7s}[data-aos][data-aos][data-aos-duration="2750"],body[data-aos-duration="2750"] [data-aos]{transition-duration:2.75s}[data-aos][data-aos][data-aos-delay="2750"],body[data-aos-delay="2750"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="2750"].aos-animate,body[data-aos-delay="2750"] [data-aos].aos-animate{transition-delay:2.75s}[data-aos][data-aos][data-aos-duration="2800"],body[data-aos-duration="2800"] [data-aos]{transition-duration:2.8s}[data-aos][data-aos][data-aos-delay="2800"],body[data-aos-delay="2800"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="2800"].aos-animate,body[data-aos-delay="2800"] [data-aos].aos-animate{transition-delay:2.8s}[data-aos][data-aos][data-aos-duration="2850"],body[data-aos-duration="2850"] [data-aos]{transition-duration:2.85s}[data-aos][data-aos][data-aos-delay="2850"],body[data-aos-delay="2850"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="2850"].aos-animate,body[data-aos-delay="2850"] [data-aos].aos-animate{transition-delay:2.85s}[data-aos][data-aos][data-aos-duration="2900"],body[data-aos-duration="2900"] [data-aos]{transition-duration:2.9s}[data-aos][data-aos][data-aos-delay="2900"],body[data-aos-delay="2900"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="2900"].aos-animate,body[data-aos-delay="2900"] [data-aos].aos-animate{transition-delay:2.9s}[data-aos][data-aos][data-aos-duration="2950"],body[data-aos-duration="2950"] [data-aos]{transition-duration:2.95s}[data-aos][data-aos][data-aos-delay="2950"],body[data-aos-delay="2950"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="2950"].aos-animate,body[data-aos-delay="2950"] [data-aos].aos-animate{transition-delay:2.95s}[data-aos][data-aos][data-aos-duration="3000"],body[data-aos-duration="3000"] [data-aos]{transition-duration:3s}[data-aos][data-aos][data-aos-delay="3000"],body[data-aos-delay="3000"] [data-aos]{transition-delay:0}[data-aos][data-aos][data-aos-delay="3000"].aos-animate,body[data-aos-delay="3000"] [data-aos].aos-animate{transition-delay:3s}[data-aos][data-aos][data-aos-easing=linear],body[data-aos-easing=linear] [data-aos]{transition-timing-function:cubic-bezier(.25,.25,.75,.75)}[data-aos][data-aos][data-aos-easing=ease],body[data-aos-easing=ease] [data-aos]{transition-timing-function:ease}[data-aos][data-aos][data-aos-easing=ease-in],body[data-aos-easing=ease-in] [data-aos]{transition-timing-function:ease-in}[data-aos][data-aos][data-aos-easing=ease-out],body[data-aos-easing=ease-out] [data-aos]{transition-timing-function:ease-out}[data-aos][data-aos][data-aos-easing=ease-in-out],body[data-aos-easing=ease-in-out] [data-aos]{transition-timing-function:ease-in-out}[data-aos][data-aos][data-aos-easing=ease-in-back],body[data-aos-easing=ease-in-back] [data-aos]{transition-timing-function:cubic-bezier(.6,-.28,.735,.045)}[data-aos][data-aos][data-aos-easing=ease-out-back],body[data-aos-easing=ease-out-back] [data-aos]{transition-timing-function:cubic-bezier(.175,.885,.32,1.275)}[data-aos][data-aos][data-aos-easing=ease-in-out-back],body[data-aos-easing=ease-in-out-back] [data-aos]{transition-timing-function:cubic-bezier(.68,-.55,.265,1.55)}[data-aos][data-aos][data-aos-easing=ease-in-sine],body[data-aos-easing=ease-in-sine] [data-aos]{transition-timing-function:cubic-bezier(.47,0,.745,.715)}[data-aos][data-aos][data-aos-easing=ease-out-sine],body[data-aos-easing=ease-out-sine] [data-aos]{transition-timing-function:cubic-bezier(.39,.575,.565,1)}[data-aos][data-aos][data-aos-easing=ease-in-out-sine],body[data-aos-easing=ease-in-out-sine] [data-aos]{transition-timing-function:cubic-bezier(.445,.05,.55,.95)}[data-aos][data-aos][data-aos-easing=ease-in-quad],body[data-aos-easing=ease-in-quad] [data-aos]{transition-timing-function:cubic-bezier(.55,.085,.68,.53)}[data-aos][data-aos][data-aos-easing=ease-out-quad],body[data-aos-easing=ease-out-quad] [data-aos]{transition-timing-function:cubic-bezier(.25,.46,.45,.94)}[data-aos][data-aos][data-aos-easing=ease-in-out-quad],body[data-aos-easing=ease-in-out-quad] [data-aos]{transition-timing-function:cubic-bezier(.455,.03,.515,.955)}[data-aos][data-aos][data-aos-easing=ease-in-cubic],body[data-aos-easing=ease-in-cubic] [data-aos]{transition-timing-function:cubic-bezier(.55,.085,.68,.53)}[data-aos][data-aos][data-aos-easing=ease-out-cubic],body[data-aos-easing=ease-out-cubic] [data-aos]{transition-timing-function:cubic-bezier(.25,.46,.45,.94)}[data-aos][data-aos][data-aos-easing=ease-in-out-cubic],body[data-aos-easing=ease-in-out-cubic] [data-aos]{transition-timing-function:cubic-bezier(.455,.03,.515,.955)}[data-aos][data-aos][data-aos-easing=ease-in-quart],body[data-aos-easing=ease-in-quart] [data-aos]{transition-timing-function:cubic-bezier(.55,.085,.68,.53)}[data-aos][data-aos][data-aos-easing=ease-out-quart],body[data-aos-easing=ease-out-quart] [data-aos]{transition-timing-function:cubic-bezier(.25,.46,.45,.94)}[data-aos][data-aos][data-aos-easing=ease-in-out-quart],body[data-aos-easing=ease-in-out-quart] [data-aos]{transition-timing-function:cubic-bezier(.455,.03,.515,.955)}[data-aos^=fade][data-aos^=fade]{opacity:0;transition-property:opacity,transform}[data-aos^=fade][data-aos^=fade].aos-animate{opacity:1;transform:translateZ(0)}[data-aos=fade-up]{transform:translate3d(0,100px,0)}[data-aos=fade-down]{transform:translate3d(0,-100px,0)}[data-aos=fade-right]{transform:translate3d(-100px,0,0)}[data-aos=fade-left]{transform:translate3d(100px,0,0)}[data-aos=fade-up-right]{transform:translate3d(-100px,100px,0)}[data-aos=fade-up-left]{transform:translate3d(100px,100px,0)}[data-aos=fade-down-right]{transform:translate3d(-100px,-100px,0)}[data-aos=fade-down-left]{transform:translate3d(100px,-100px,0)}[data-aos^=zoom][data-aos^=zoom]{opacity:0;transition-property:opacity,transform}[data-aos^=zoom][data-aos^=zoom].aos-animate{opacity:1;transform:translateZ(0) scale(1)}[data-aos=zoom-in]{transform:scale(.6)}[data-aos=zoom-in-up]{transform:translate3d(0,100px,0) scale(.6)}[data-aos=zoom-in-down]{transform:translate3d(0,-100px,0) scale(.6)}[data-aos=zoom-in-right]{transform:translate3d(-100px,0,0) scale(.6)}[data-aos=zoom-in-left]{transform:translate3d(100px,0,0) scale(.6)}[data-aos=zoom-out]{transform:scale(1.2)}[data-aos=zoom-out-up]{transform:translate3d(0,100px,0) scale(1.2)}[data-aos=zoom-out-down]{transform:translate3d(0,-100px,0) scale(1.2)}[data-aos=zoom-out-right]{transform:translate3d(-100px,0,0) scale(1.2)}[data-aos=zoom-out-left]{transform:translate3d(100px,0,0) scale(1.2)}[data-aos^=slide][data-aos^=slide]{transition-property:transform}[data-aos^=slide][data-aos^=slide].aos-animate{transform:translateZ(0)}[data-aos=slide-up]{transform:translate3d(0,100%,0)}[data-aos=slide-down]{transform:translate3d(0,-100%,0)}[data-aos=slide-right]{transform:translate3d(-100%,0,0)}[data-aos=slide-left]{transform:translate3d(100%,0,0)}[data-aos^=flip][data-aos^=flip]{backface-visibility:hidden;transition-property:transform}[data-aos=flip-left]{transform:perspective(2500px) rotateY(-100deg)}[data-aos=flip-left].aos-animate{transform:perspective(2500px) rotateY(0)}[data-aos=flip-right]{transform:perspective(2500px) rotateY(100deg)}[data-aos=flip-right].aos-animate{transform:perspective(2500px) rotateY(0)}[data-aos=flip-up]{transform:perspective(2500px) rotateX(-100deg)}[data-aos=flip-up].aos-animate{transform:perspective(2500px) rotateX(0)}[data-aos=flip-down]{transform:perspective(2500px) rotateX(100deg)}[data-aos=flip-down].aos-animate{transform:perspective(2500px) rotateX(0)}'],sourceRoot:""}]);const e=i},314:a=>{"use strict";a.exports=function(a){var t=[];return t.toString=function(){return this.map((function(t){var o="",d=void 0!==t[5];return t[4]&&(o+="@supports (".concat(t[4],") {")),t[2]&&(o+="@media ".concat(t[2]," {")),d&&(o+="@layer".concat(t[5].length>0?" ".concat(t[5]):""," {")),o+=a(t),d&&(o+="}"),t[2]&&(o+="}"),t[4]&&(o+="}"),o})).join("")},t.i=function(a,o,d,s,n){"string"==typeof a&&(a=[[null,a,void 0]]);var i={};if(d)for(var e=0;e0?" ".concat(A[5]):""," {").concat(A[1],"}")),A[5]=n),o&&(A[2]?(A[1]="@media ".concat(A[2]," {").concat(A[1],"}"),A[2]=o):A[2]=o),s&&(A[4]?(A[1]="@supports (".concat(A[4],") {").concat(A[1],"}"),A[4]=s):A[4]="".concat(s)),t.push(A))}},t}},354:a=>{"use strict";a.exports=function(a){var t=a[1],o=a[3];if(!o)return t;if("function"==typeof btoa){var d=btoa(unescape(encodeURIComponent(JSON.stringify(o)))),s="sourceMappingURL=data:application/json;charset=utf-8;base64,".concat(d),n="/*# ".concat(s," */");return[t].concat([n]).join("\n")}return[t].join("\n")}},72:a=>{"use strict";var t=[];function o(a){for(var o=-1,d=0;d{"use strict";var t={};a.exports=function(a,o){var d=function(a){if(void 0===t[a]){var o=document.querySelector(a);if(window.HTMLIFrameElement&&o instanceof window.HTMLIFrameElement)try{o=o.contentDocument.head}catch(a){o=null}t[a]=o}return t[a]}(a);if(!d)throw new Error("Couldn't find a style target. This probably means that the value for the 'insert' parameter is invalid.");d.appendChild(o)}},540:a=>{"use strict";a.exports=function(a){var t=document.createElement("style");return a.setAttributes(t,a.attributes),a.insert(t,a.options),t}},56:(a,t,o)=>{"use strict";a.exports=function(a){var t=o.nc;t&&a.setAttribute("nonce",t)}},825:a=>{"use strict";a.exports=function(a){if("undefined"==typeof document)return{update:function(){},remove:function(){}};var t=a.insertStyleElement(a);return{update:function(o){!function(a,t,o){var d="";o.supports&&(d+="@supports (".concat(o.supports,") {")),o.media&&(d+="@media ".concat(o.media," {"));var s=void 0!==o.layer;s&&(d+="@layer".concat(o.layer.length>0?" ".concat(o.layer):""," {")),d+=o.css,s&&(d+="}"),o.media&&(d+="}"),o.supports&&(d+="}");var n=o.sourceMap;n&&"undefined"!=typeof btoa&&(d+="\n/*# sourceMappingURL=data:application/json;base64,".concat(btoa(unescape(encodeURIComponent(JSON.stringify(n))))," */")),t.styleTagTransform(d,a,t.options)}(t,a,o)},remove:function(){!function(a){if(null===a.parentNode)return!1;a.parentNode.removeChild(a)}(t)}}}},113:a=>{"use strict";a.exports=function(a,t){if(t.styleSheet)t.styleSheet.cssText=a;else{for(;t.firstChild;)t.removeChild(t.firstChild);t.appendChild(document.createTextNode(a))}}}},t={};function o(d){var s=t[d];if(void 0!==s)return s.exports;var n=t[d]={id:d,exports:{}};return a[d].call(n.exports,n,n.exports,o),n.exports}o.n=a=>{var t=a&&a.__esModule?()=>a.default:()=>a;return o.d(t,{a:t}),t},o.d=(a,t)=>{for(var d in t)o.o(t,d)&&!o.o(a,d)&&Object.defineProperty(a,d,{enumerable:!0,get:t[d]})},o.o=(a,t)=>Object.prototype.hasOwnProperty.call(a,t),o.nc=void 0,(()=>{"use strict";var a=o(72),t=o.n(a),d=o(825),s=o.n(d),n=o(659),i=o.n(n),e=o(56),r=o.n(e),y=o(540),A=o.n(y),l=o(113),u=o.n(l),m=o(309),b={};b.styleTagTransform=u(),b.setAttributes=r(),b.insert=i().bind(null,"head"),b.domAPI=s(),b.insertStyleElement=A(),t()(m.A,b),m.A&&m.A.locals&&m.A.locals;var c=o(42),C=o.n(c);window.onload=function(){C().init({once:!1,duration:700,startEvent:"DOMContentLoaded"}),setTimeout((()=>{C().refresh()}),300)}})()})(); +//# sourceMappingURL=packed_aosanimate.js.map \ No newline at end of file diff --git a/fweb/core/static/js/apiClient.js b/fweb/core/static/js/apiClient.js new file mode 100644 index 0000000..d95063b --- /dev/null +++ b/fweb/core/static/js/apiClient.js @@ -0,0 +1,91 @@ +class APIClient { + constructor() { + this.baseURL = "/api"; + } + + async submitToolForm(form, toolId) { + const formData = new FormData(form); + + try { + uiManager.setSubmitButtonState(form, true); + uiManager.updateProgress(10, "Uploading files..."); + + const response = await fetch(`${this.baseURL}/process/${toolId}/`, { + method: "POST", + body: formData, + headers: { + "X-Requested-With": "XMLHttpRequest", + "X-CSRFToken": this.getCSRFToken(), + }, + }); + + if (!response.ok) { + throw new Error(`HTTP error! status: ${response.status}`); + } + + const data = await response.json(); + + if (data.success) { + uiManager.updateProgress(100, "Processing complete!"); + setTimeout(() => { + uiManager.hideProgressModal(); + this.handleSuccess(data, toolId); + }, 1000); + } else { + throw new Error(data.error || "Processing failed"); + } + } catch (error) { + console.error("API Error:", error); + uiManager.updateProgress(0, `Error: ${error.message}`); + uiManager.showNotification(error.message, "error"); + + setTimeout(() => { + uiManager.hideProgressModal(); + uiManager.setSubmitButtonState(form, false); + }, 2000); + } + } + + handleSuccess(data, toolId) { + uiManager.showNotification( + data.message || "Processing completed successfully", + "success", + ); + + // Redirect to results page or show results in modal + if (data.results && data.results.length > 0) { + this.displayResults(data.results, toolId); + } + } + + displayResults(results, toolId) { + // For now, just show a notification - will implement proper results display later + uiManager.showNotification( + `${results.length} files processed successfully`, + "success", + ); + } + + getCSRFToken() { + return document.querySelector("[name=csrfmiddlewaretoken]")?.value || ""; + } + + async cancelProcessing(jobId) { + try { + const response = await fetch(`${this.baseURL}/cancel/`, { + method: "POST", + headers: { + "Content-Type": "application/json", + "X-CSRFToken": this.getCSRFToken(), + }, + body: JSON.stringify({ job_id: jobId }), + }); + return await response.json(); + } catch (error) { + console.error("Cancel error:", error); + throw error; + } + } +} + +window.apiClient = new APIClient(); diff --git a/fweb/core/static/js/main.js b/fweb/core/static/js/main.js new file mode 100644 index 0000000..1a95382 --- /dev/null +++ b/fweb/core/static/js/main.js @@ -0,0 +1,26 @@ +document.addEventListener("DOMContentLoaded", function () { + console.log("FileMac UI initialized"); + + // Global cancel processing function + window.cancelProcessing = function () { + uiManager.hideProgressModal(); + uiManager.showNotification("Processing cancelled", "info"); + }; + + // Global advanced section toggle + window.toggleAdvanced = function (sectionId) { + uiManager.toggleAdvancedSection(sectionId); + }; + + // Make sure tool interfaces are properly initialized + const urlParams = new URLSearchParams(window.location.search); + const toolParam = urlParams.get("tool"); + + if (!toolParam) { + // Ensure default tool is visible + const firstTool = document.querySelector(".tool-interface"); + if (firstTool) { + firstTool.classList.remove("hidden"); + } + } +}); diff --git a/fweb/core/static/js/processor.js b/fweb/core/static/js/processor.js new file mode 100644 index 0000000..ac5f0ab --- /dev/null +++ b/fweb/core/static/js/processor.js @@ -0,0 +1,50 @@ +// AJAX file processing +function submitToolForm(formId, toolId) { + const form = document.getElementById(formId); + const formData = new FormData(form); + + // Show progress modal + showProgressModal(); + updateProgress(10, "Starting processing..."); + + // Add CSRF token + const csrfToken = document.querySelector("[name=csrfmiddlewaretoken]").value; + + fetch(`/api/process/${toolId}/`, { + method: "POST", + body: formData, + headers: { + "X-CSRFToken": csrfToken, + }, + }) + .then((response) => response.json()) + .then((data) => { + if (data.success) { + updateProgress(100, "Processing complete!"); + setTimeout(() => { + hideProgressModal(); + showResults(data.results); + }, 1000); + } else { + updateProgress(0, `Error: ${data.error}`); + setTimeout(hideProgressModal, 2000); + } + }) + .catch((error) => { + updateProgress(0, `Network error: ${error}`); + setTimeout(hideProgressModal, 2000); + }); +} + +// Update your form submission handlers +document.addEventListener("DOMContentLoaded", function () { + // Add event listeners to all tool forms + const forms = document.querySelectorAll('form[id$="-form"]'); + forms.forEach((form) => { + form.addEventListener("submit", function (e) { + e.preventDefault(); + const toolId = form.id.replace("-form", ""); + submitToolForm(form.id, toolId); + }); + }); +}); diff --git a/fweb/core/static/js/result_utils.js b/fweb/core/static/js/result_utils.js new file mode 100644 index 0000000..63b1f9b --- /dev/null +++ b/fweb/core/static/js/result_utils.js @@ -0,0 +1,21 @@ +function downloadAll() { + // Create a zip of all files and download + alert("Batch download functionality would be implemented here"); +} + +function previewFile(url) { + // Load and display file preview + document.getElementById("preview-modal").classList.remove("hidden"); + // Implementation would load the file content based on type +} + +function closePreview() { + document.getElementById("preview-modal").classList.add("hidden"); +} + +// Keyboard shortcut to close preview +document.addEventListener("keydown", function (e) { + if (e.key === "Escape") { + closePreview(); + } +}); diff --git a/fweb/core/static/js/themes.js b/fweb/core/static/js/themes.js new file mode 100644 index 0000000..eda3d78 --- /dev/null +++ b/fweb/core/static/js/themes.js @@ -0,0 +1,31 @@ +document.addEventListener("DOMContentLoaded", () => { + const themeSwitch = document.getElementById("theme-toggle"); + const rootElement = document.documentElement; + + // Initialize theme based on user's previous preference or system preference + const userTheme = localStorage.getItem("theme"); + const systemTheme = window.matchMedia("(prefers-color-scheme: dark)").matches + ? "dark" + : "light"; + const currentTheme = "light" //userTheme || systemTheme; + + // Set the initial theme + setTheme(currentTheme); + + // Function to set the theme + function setTheme(theme) { + if (theme === "dark") { + rootElement.classList.add("dark"); + themeSwitch.checked = true; + } else { + rootElement.classList.remove("dark"); + } + localStorage.setItem("theme", theme); + } + + // Toggle theme on switch click + themeSwitch.addEventListener("click", () => { + const newTheme = rootElement.classList.contains("dark") ? "light" : "dark"; + setTheme(newTheme); + }); +}); diff --git a/fweb/core/static/js/uiManager.js b/fweb/core/static/js/uiManager.js new file mode 100644 index 0000000..c1edfbf --- /dev/null +++ b/fweb/core/static/js/uiManager.js @@ -0,0 +1,126 @@ +class UIManager { + constructor() { + this.progressModal = document.getElementById("progress-modal"); + this.init(); + } + + init() { + this.setupGlobalUIHandlers(); + } + + setupGlobalUIHandlers() { + // Escape key to close modals + document.addEventListener("keydown", (e) => { + if (e.key === "Escape") { + this.closeAllModals(); + } + }); + + // Outside click to close modals + document.addEventListener("click", (e) => { + if (e.target.classList.contains("modal-overlay")) { + this.closeAllModals(); + } + }); + + // Form submissions + this.setupFormHandlers(); + } + + setupFormHandlers() { + document.addEventListener("submit", (e) => { + const form = e.target; + if (form.classList.contains("tool-form")) { + e.preventDefault(); + this.handleToolFormSubmit(form); + } + }); + } + + handleToolFormSubmit(form) { + const toolId = form.dataset.toolId; + if (!toolId) { + console.error("No tool ID found for form"); + return; + } + + this.showProgressModal(); + apiClient.submitToolForm(form, toolId); + } + + showProgressModal() { + if (this.progressModal) { + this.progressModal.classList.remove("hidden"); + this.updateProgress(0, "Initializing..."); + } + } + + hideProgressModal() { + if (this.progressModal) { + this.progressModal.classList.add("hidden"); + } + } + + updateProgress(percent, status) { + const progressBar = document.getElementById("progress-bar"); + const progressPercent = document.getElementById("progress-percent"); + const progressStatus = document.getElementById("progress-status"); + + if (progressBar) progressBar.style.width = percent + "%"; + if (progressPercent) progressPercent.textContent = percent + "%"; + if (progressStatus) progressStatus.textContent = status; + } + + closeAllModals() { + this.hideProgressModal(); + // Add other modals here as needed + } + + showNotification(message, type = "info") { + // Simple notification system - can be enhanced with Toast library + const notification = document.createElement("div"); + notification.className = `fixed top-4 right-4 p-4 rounded-lg shadow-lg z-50 ${ + type === "error" + ? "bg-red-500 text-white" + : type === "success" + ? "bg-green-500 text-white" + : "bg-blue-500 text-white" + }`; + notification.textContent = message; + + document.body.appendChild(notification); + + setTimeout(() => { + notification.remove(); + }, 5000); + } + + toggleAdvancedSection(sectionId) { + const section = document.getElementById(sectionId); + if (section) { + section.classList.toggle("hidden"); + + const svg = section.previousElementSibling?.querySelector("svg"); + if (svg) { + svg.classList.toggle("rotate-180"); + } + } + } + + setSubmitButtonState(form, loading) { + const submitButton = form.querySelector('button[type="submit"]'); + if (submitButton) { + if (loading) { + submitButton.disabled = true; + submitButton.innerHTML = + 'Processing... + Process Files`; + } + } + } +} + +window.uiManager = new UIManager(); diff --git a/fweb/core/static/js/utils.js b/fweb/core/static/js/utils.js new file mode 100644 index 0000000..37442ae --- /dev/null +++ b/fweb/core/static/js/utils.js @@ -0,0 +1,992 @@ +// Additional utility functions for the new tools +function toggleAdvanced(sectionId) { + const section = document.getElementById(sectionId); + section.classList.toggle("hidden"); + + const icon = section.previousElementSibling.querySelector("i"); + if (section.classList.contains("hidden")) { + icon.classList.remove("fa-chevron-up"); + icon.classList.add("fa-chevron-down"); + } else { + icon.classList.remove("fa-chevron-down"); + icon.classList.add("fa-chevron-up"); + } +} + +function browseFolder(type) { + // This would integrate with a file browser component + alert( + "Folder browser would open here. In a real implementation, this would use a file dialog.", + ); +} + +function scanFolder() { + // Simulate folder scanning + document.getElementById("folder-scan-results").classList.remove("hidden"); + document.getElementById("scan-total").textContent = "156"; + document.getElementById("scan-size").textContent = "245.7 MB"; + document.getElementById("scan-types").textContent = "8"; + + // Populate file type breakdown + const breakdown = document.getElementById("file-type-breakdown"); + breakdown.innerHTML = ` +
+ PDF Files + 42 files (67.3 MB) +
+
+ Images + 78 files (112.4 MB) +
+
+ Documents + 36 files (66.0 MB) +
+ `; +} + +function previewAnalysis() { + // Simulate analysis preview + document.getElementById("analysis-results").classList.remove("hidden"); + document.getElementById("info-duration").textContent = "02:45:18"; + document.getElementById("info-size").textContent = "1.2 GB"; + document.getElementById("info-format").textContent = "MP4"; + document.getElementById("video-resolution").textContent = "1920x1080"; + document.getElementById("video-codec").textContent = "H.264"; + document.getElementById("video-bitrate").textContent = "4.5 Mbps"; + document.getElementById("audio-codec").textContent = "AAC"; + document.getElementById("audio-channels").textContent = "2 (Stereo)"; + document.getElementById("audio-sample-rate").textContent = "44.1 kHz"; +} + +function previewOCR() { + // Simulate OCR preview + document.getElementById("ocr-results").classList.remove("hidden"); + document.getElementById("ocr-filename").textContent = "document.pdf"; + document.getElementById("ocr-text-output").textContent = + "This is a sample of extracted text from the document.\n\n" + + "The OCR engine has successfully processed the image and extracted\n" + + "readable text while preserving the original layout and formatting.\n\n" + + "Multiple languages are supported, and the accuracy can be adjusted\n" + + "based on the quality of the input document."; + document.getElementById("confidence-score").textContent = "92%"; + document.getElementById("word-count").textContent = "45"; + document.getElementById("processing-time").textContent = "2.3s"; +} + +function copyOCRText() { + const text = document.getElementById("ocr-text-output").textContent; + navigator.clipboard.writeText(text).then(() => { + // Show success message + alert("Text copied to clipboard!"); + }); +} + +function downloadOCRText() { + // Simulate download functionality + alert("Download functionality would be implemented here"); +} + +function scanBulkFiles() { + // Simulate bulk file scanning + const totalFiles = Math.floor(Math.random() * 100) + 50; + document.getElementById("bulk-total").textContent = totalFiles; + document.getElementById("bulk-processed").textContent = "0"; + document.getElementById("bulk-success").textContent = "0"; + document.getElementById("bulk-failed").textContent = "0"; + document.getElementById("bulk-progress").classList.remove("hidden"); +} + +// Handle separator selection change +document.addEventListener("change", function (e) { + if (e.target.name === "separator") { + const customDiv = document.getElementById("custom-separator"); + if (e.target.value === "custom") { + customDiv.classList.remove("hidden"); + } else { + customDiv.classList.add("hidden"); + } + } +}); + +// Initialize tool-specific functionality +function initializeTool(toolId) { + const setupFunctions = { + batch_doc_convert: () => + setupFileDropZone("batch-doc-drop-zone", "batch-doc-file-input", true), + folder_operations: () => { + /* Folder operations setup */ + }, + convert_video: () => + setupFileDropZone("video-drop-zone", "video-file-input", true), + analyze_video: () => + setupFileDropZone( + "analyze-video-drop-zone", + "analyze-video-file-input", + false, + ), + extract_audio: () => + setupFileDropZone( + "extract-video-drop-zone", + "extract-video-file-input", + true, + ), + ocr: () => setupFileDropZone("ocr-drop-zone", "ocr-file-input", true), + bulk_ocr: () => + setupFileDropZone("bulk-ocr-drop-zone", "bulk-ocr-file-input", true), + }; + + if (setupFunctions[toolId]) { + setupFunctions[toolId](); + } +} + +// Tool-specific initialization function +function initializeTool(toolId) { + // Remove hidden class from all tool interfaces first + document.querySelectorAll(".tool-interface").forEach((interface) => { + interface.classList.add("hidden"); + }); + + // Show the selected tool + const toolElement = document.getElementById(`tool-${toolId}`); + if (toolElement) { + toolElement.classList.remove("hidden"); + } + + // Tool-specific initialization + const initializationFunctions = { + // Document Tools + convert_doc: () => { + setupFileDropZone("doc-drop-zone", "doc-file-input", true); + setupFormatOptions("doc-format-select", [ + "pdf", + "docx", + "txt", + "html", + "image", + ]); + setupAdvancedToggle("doc-advanced"); + }, + pdf_join: () => { + setupFileDropZone("pdf-join-drop-zone", "pdf-join-file-input", true); + setupOrderOptions(); + }, + scan_pdf: () => { + setupFileDropZone("scan-pdf-drop-zone", "scan-pdf-file-input", true); + setupScanOptions(); + }, + doc_long_image: () => { + setupFileDropZone( + "doc-longimg-drop-zone", + "doc-longimg-file-input", + true, + ); + setupLongImageOptions(); + }, + extract_pages: () => { + setupFileDropZone( + "extract-pages-drop-zone", + "extract-pages-file-input", + false, + ); + setupPageRangeSelector(); + }, + Atext2word: () => { + setupFileDropZone("atext2word-drop-zone", "atext2word-file-input", true); + setupFontOptions(); + }, + doc2image: () => { + setupFileDropZone("doc2image-drop-zone", "doc2image-file-input", true); + setupImageFormatOptions(); + }, + + // Image Tools + convert_image: () => { + setupFileDropZone("image-drop-zone", "image-file-input", true); + setupFormatOptions("image-format-select", [ + "png", + "jpg", + "webp", + "gif", + "bmp", + ]); + setupQualitySlider(); + setupAdvancedToggle("resize-options"); + }, + resize_image: () => { + setupFileDropZone( + "resize-image-drop-zone", + "resize-image-file-input", + true, + ); + setupSizeOptions(); + setupDimensionControls(); + }, + image2pdf: () => { + setupFileDropZone("image2pdf-drop-zone", "image2pdf-file-input", true); + setupPDFOptions(); + }, + image2word: () => { + setupFileDropZone("image2word-drop-zone", "image2word-file-input", true); + setupWordOptions(); + }, + image2gray: () => { + setupFileDropZone("image2gray-drop-zone", "image2gray-file-input", true); + setupGrayscaleOptions(); + }, + ocr: () => { + setupFileDropZone("ocr-drop-zone", "ocr-file-input", true); + setupOCROptions(); + setupLanguageSelector(); + }, + + // Audio Tools + convert_audio: () => { + setupFileDropZone("audio-drop-zone", "audio-file-input", true); + setupFormatOptions("audio-format-select", [ + "mp3", + "wav", + "flac", + "m4a", + "aac", + ]); + setupAudioQualityOptions(); + setupAdvancedToggle("audio-effects"); + }, + audio_join: () => { + setupFileDropZone("audio-join-drop-zone", "audio-join-file-input", true); + setupJoinOrder(); + }, + extract_audio: () => { + setupFileDropZone( + "extract-audio-drop-zone", + "extract-audio-file-input", + true, + ); + setupExtractionOptions(); + }, + audio_effect: () => { + setupFileDropZone( + "audio-effect-drop-zone", + "audio-effect-file-input", + true, + ); + setupAudioEffects(); + }, + + // Video Tools + convert_video: () => { + setupFileDropZone("video-drop-zone", "video-file-input", true); + setupFormatOptions("video-format-select", [ + "mp4", + "mkv", + "avi", + "mov", + "webm", + ]); + setupVideoQualityOptions(); + setupAdvancedToggle("video-codec"); + setupAdvancedToggle("video-resolution"); + }, + analyze_video: () => { + setupFileDropZone( + "analyze-video-drop-zone", + "analyze-video-file-input", + false, + ); + setupAnalysisOptions(); + }, + + // Batch Tools + batch_dashboard: () => { + // Dashboard doesn't need file drop zone + setupBatchDashboard(); + }, + batch_doc_convert: () => { + setupFileDropZone( + "batch-doc-drop-zone", + "batch-doc-file-input", + true, + true, + ); + setupBatchOptions(); + setupAdvancedToggle("batch-advanced"); + }, + folder_operations: () => { + setupFolderOperations(); + }, + bulk_ocr: () => { + setupFileDropZone( + "bulk-ocr-drop-zone", + "bulk-ocr-file-input", + true, + true, + ); + setupBulkOCROptions(); + }, + }; + + // Execute the initialization function for the current tool + if (initializationFunctions[toolId]) { + initializationFunctions[toolId](); + } + + // Initialize form submission for this tool + initializeFormSubmission(toolId); +} + +// Enhanced file drop zone setup +function setupFileDropZone( + dropZoneId, + inputId, + multiple = true, + allowFolders = false, +) { + const dropZone = document.getElementById(dropZoneId); + const fileInput = document.getElementById(inputId); + + if (!dropZone || !fileInput) return; + + // Set multiple attribute + fileInput.multiple = multiple; + + // Allow folder selection if specified + if (allowFolders) { + fileInput.setAttribute("webkitdirectory", ""); + fileInput.setAttribute("directory", ""); + } + + // Click to select files + dropZone.addEventListener("click", () => fileInput.click()); + + // Drag and drop handlers + dropZone.addEventListener("dragover", (e) => { + e.preventDefault(); + dropZone.classList.add("dragover"); + dropZone.querySelector(".drop-placeholder").style.opacity = "0.5"; + }); + + dropZone.addEventListener("dragleave", () => { + dropZone.classList.remove("dragover"); + dropZone.querySelector(".drop-placeholder").style.opacity = "1"; + }); + + dropZone.addEventListener("drop", (e) => { + e.preventDefault(); + dropZone.classList.remove("dragover"); + dropZone.querySelector(".drop-placeholder").style.opacity = "1"; + + const files = allowFolders ? e.dataTransfer.items : e.dataTransfer.files; + handleDroppedFiles(files, fileInput, dropZoneId, allowFolders); + }); + + // File input change handler + fileInput.addEventListener("change", () => { + updateFileList(dropZoneId, fileInput.files, allowFolders); + }); +} + +function handleDroppedFiles(dataTransfer, fileInput, dropZoneId, allowFolders) { + if (allowFolders && dataTransfer.items) { + // Handle folder drop + processDroppedItems(dataTransfer.items, fileInput, dropZoneId); + } else { + // Handle file drop + fileInput.files = dataTransfer.files; + updateFileList(dropZoneId, dataTransfer.files, allowFolders); + } +} + +async function processDroppedItems(items, fileInput, dropZoneId) { + const files = []; + + for (let i = 0; i < items.length; i++) { + const item = items[i]; + if (item.kind === "file") { + const file = item.getAsFile(); + if (file) files.push(file); + } + } + + // Create a new FileList-like object + const dataTransfer = new DataTransfer(); + files.forEach((file) => dataTransfer.items.add(file)); + fileInput.files = dataTransfer.files; + + updateFileList(dropZoneId, dataTransfer.files, true); +} + +// Enhanced file list update +function updateFileList(dropZoneId, files, showFolderInfo = false) { + const dropZone = document.getElementById(dropZoneId); + const fileList = dropZone.querySelector(".file-list"); + const placeholder = dropZone.querySelector(".drop-placeholder"); + + if (!fileList) return; + + if (files.length > 0) { + if (placeholder) placeholder.style.display = "none"; + fileList.innerHTML = ""; + + let totalSize = 0; + let fileCount = 0; + let folderCount = 0; + + Array.from(files).forEach((file, index) => { + totalSize += file.size; + fileCount++; + + // Check if it's a folder (based on webkitRelativePath) + const isFolder = + file.webkitRelativePath && file.webkitRelativePath.includes("/"); + if (isFolder) folderCount++; + + const fileItem = document.createElement("div"); + fileItem.className = + "flex items-center justify-between p-3 bg-gray-50 dark:bg-gray-700 rounded-lg mb-2"; + fileItem.innerHTML = ` +
+ +
+
${file.name}
+ ${isFolder ? '
' + file.webkitRelativePath + "
" : ""} +
+
+
+ ${formatFileSize(file.size)} + +
+ `; + fileList.appendChild(fileItem); + }); + + // Add summary for folders + if (showFolderInfo && folderCount > 0) { + const summary = document.createElement("div"); + summary.className = + "mt-3 p-2 bg-blue-50 dark:bg-blue-900 rounded text-xs"; + summary.innerHTML = ` +
+ Files: ${fileCount} + Folders: ${folderCount} + Total: ${formatFileSize(totalSize)} +
+ `; + fileList.appendChild(summary); + } + } else { + if (placeholder) placeholder.style.display = "block"; + fileList.innerHTML = ""; + } +} + +// Format file size +function formatFileSize(bytes) { + if (bytes === 0) return "0 B"; + const k = 1024; + const sizes = ["B", "KB", "MB", "GB"]; + const i = Math.floor(Math.log(bytes) / Math.log(k)); + return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + " " + sizes[i]; +} + +// Remove file from list +function removeFile(dropZoneId, index) { + const inputId = dropZoneId.replace("-drop-zone", "-file-input"); + const fileInput = document.getElementById(inputId); + const dt = new DataTransfer(); + + Array.from(fileInput.files).forEach((file, i) => { + if (i !== index) dt.items.add(file); + }); + + fileInput.files = dt.files; + updateFileList(dropZoneId, fileInput.files); +} + +// Setup functions for different tool options +function setupFormatOptions(selectId, formats) { + const select = document.getElementById(selectId); + if (!select) return; + + select.innerHTML = formats + .map( + (format) => ``, + ) + .join(""); +} + +function setupAdvancedToggle(sectionId) { + const toggle = document.querySelector( + `[onclick="toggleAdvanced('${sectionId}')"]`, + ); + if (toggle) { + toggle.addEventListener("click", () => toggleAdvanced(sectionId)); + } +} + +function toggleAdvanced(sectionId) { + const section = document.getElementById(sectionId); + if (!section) return; + + section.classList.toggle("hidden"); + + const icon = section.previousElementSibling?.querySelector("i"); + if (icon) { + if (section.classList.contains("hidden")) { + icon.classList.replace("fa-chevron-up", "fa-chevron-down"); + } else { + icon.classList.replace("fa-chevron-down", "fa-chevron-up"); + } + } +} + +// Quality slider setup +function setupQualitySlider() { + const slider = document.querySelector('input[name="quality"]'); + const valueDisplay = document.getElementById("quality-value"); + + if (slider && valueDisplay) { + slider.addEventListener("input", (e) => { + valueDisplay.textContent = e.target.value + "%"; + }); + } +} + +// Language selector setup +function setupLanguageSelector() { + const selector = document.querySelector('select[name="language"]'); + if (selector) { + selector.addEventListener("change", (e) => { + // You can add language-specific options here + console.log("Selected language:", e.target.value); + }); + } +} + +// Page range selector +function setupPageRangeSelector() { + const container = document.getElementById("page-range-container"); + if (!container) return; + + container.innerHTML = ` +
+
+ + to + + (leave empty for single page) +
+
+ + +
+
+ `; +} + +// Font options setup +function setupFontOptions() { + const fontSelect = document.querySelector('select[name="font_name"]'); + if (fontSelect) { + const fonts = [ + "Arial", + "Times New Roman", + "Helvetica", + "Courier New", + "Verdana", + "Georgia", + "Palatino", + "Garamond", + ]; + + fontSelect.innerHTML = fonts + .map((font) => ``) + .join(""); + } + + const sizeSelect = document.querySelector('select[name="font_size"]'); + if (sizeSelect) { + const sizes = [8, 9, 10, 11, 12, 14, 16, 18, 20, 24, 28, 32]; + sizeSelect.innerHTML = sizes + .map((size) => ``) + .join(""); + } +} + +// Audio effects setup +function setupAudioEffects() { + const effectsContainer = document.getElementById("audio-effects-container"); + if (!effectsContainer) return; + + const effects = [ + { id: "noise_reduce", name: "Noise Reduction", icon: "volume-mute" }, + { id: "normalize", name: "Normalize", icon: "wave-square" }, + { id: "compressor", name: "Compressor", icon: "compress" }, + { id: "equalizer", name: "Equalizer", icon: "sliders-h" }, + { id: "reverb", name: "Reverb", icon: "expand" }, + { id: "delay", name: "Delay", icon: "clock" }, + ]; + + effectsContainer.innerHTML = effects + .map( + (effect) => ` +
+ + +
+ `, + ) + .join(""); +} + +// Video analysis options +function setupAnalysisOptions() { + const optionsContainer = document.getElementById("analysis-options"); + if (!optionsContainer) return; + + optionsContainer.innerHTML = ` +
+
+ +
+
+ +
+
+ +
+
+ +
+
+ `; +} + +// Batch processing options +function setupBatchOptions() { + const modeSelect = document.querySelector('select[name="processing_mode"]'); + if (modeSelect) { + modeSelect.addEventListener("change", (e) => { + const threadsContainer = document.getElementById("threads-container"); + if (threadsContainer) { + threadsContainer.style.display = + e.target.value === "parallel" ? "block" : "none"; + } + }); + } +} + +// Initialize form submission +function initializeFormSubmission(toolId) { + const form = document.getElementById(`${toolId}-form`); + if (!form) return; + + form.addEventListener("submit", function (e) { + e.preventDefault(); + submitToolForm(this, toolId); + }); +} + +// Enhanced form submission +async function submitToolForm(form, toolId) { + const formData = new FormData(form); + const submitButton = form.querySelector('button[type="submit"]'); + const originalButtonText = submitButton.innerHTML; + + // Show loading state + submitButton.disabled = true; + submitButton.innerHTML = + 'Processing...'; + + try { + // Show progress modal + showProgressModal(); + updateProgress(10, "Validating files..."); + + // Add CSRF token + const csrfToken = getCSRFToken(); + formData.append("csrfmiddlewaretoken", csrfToken); + + const response = await fetch(`/api/process/${toolId}/`, { + method: "POST", + body: formData, + headers: { + "X-Requested-With": "XMLHttpRequest", + }, + }); + + if (!response.ok) { + throw new Error(`HTTP error! status: ${response.status}`); + } + + const data = await response.json(); + + if (data.success) { + updateProgress(100, "Processing complete!"); + setTimeout(() => { + hideProgressModal(); + showResults(data.results, toolId); + }, 1000); + } else { + throw new Error(data.error || "Processing failed"); + } + } catch (error) { + console.error("Error:", error); + updateProgress(0, `Error: ${error.message}`); + showError(error.message); + + setTimeout(() => { + hideProgressModal(); + }, 3000); + } finally { + // Restore button state + submitButton.disabled = false; + submitButton.innerHTML = originalButtonText; + } +} + +// Progress modal functions +function showProgressModal() { + const modal = document.getElementById("progress-modal"); + if (modal) { + modal.classList.remove("hidden"); + modal.classList.add("flex"); + } +} + +function hideProgressModal() { + const modal = document.getElementById("progress-modal"); + if (modal) { + modal.classList.add("hidden"); + modal.classList.remove("flex"); + } +} + +function updateProgress(percent, status) { + const progressBar = document.getElementById("progress-bar"); + const progressPercent = document.getElementById("progress-percent"); + const progressStatus = document.getElementById("progress-status"); + + if (progressBar) progressBar.style.width = percent + "%"; + if (progressPercent) progressPercent.textContent = percent + "%"; + if (progressStatus) progressStatus.textContent = status; +} + +// Results display +function showResults(results, toolId) { + // Create results container or redirect to results page + const resultsContainer = document.getElementById("results-container"); + + if (resultsContainer) { + resultsContainer.classList.remove("hidden"); + resultsContainer.innerHTML = generateResultsHTML(results, toolId); + } else { + // Redirect to results page or show modal + window.location.href = `/results/?tool=${toolId}&results=${encodeURIComponent(JSON.stringify(results))}`; + } +} + +function generateResultsHTML(results, toolId) { + return ` +
+
+

+ + Processing Complete +

+ + ${results.length} files processed + +
+
+ ${results + .map( + (result, index) => ` +
+
+ +
+
${result.original_name}
+
${result.converted_name}
+
+
+
+ ${result.size} + +
+
+ `, + ) + .join("")} +
+
+ + +
+
+ `; +} + +// Utility functions +function getCSRFToken() { + return document.querySelector("[name=csrfmiddlewaretoken]")?.value || ""; +} + +function showError(message) { + // Create or show error notification + const errorDiv = + document.getElementById("error-notification") || createErrorNotification(); + errorDiv.querySelector(".error-message").textContent = message; + errorDiv.classList.remove("hidden"); + + setTimeout(() => { + errorDiv.classList.add("hidden"); + }, 5000); +} + +function createErrorNotification() { + const div = document.createElement("div"); + div.id = "error-notification"; + div.className = + "fixed top-4 right-4 bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded shadow-lg z-50 hidden"; + div.innerHTML = ` +
+ + + +
+ `; + document.body.appendChild(div); + return div; +} + +// Additional utility functions for specific tools +function addPageRange() { + // Implementation for adding page ranges + console.log("Add page range functionality"); +} + +function clearPageRanges() { + // Implementation for clearing page ranges + console.log("Clear page ranges functionality"); +} + +function downloadFile(url) { + window.open(url, "_blank"); +} + +function downloadAllFiles(results) { + // Implementation for downloading all files + results.forEach((result) => { + downloadFile(result.download_url); + }); +} + +function processNew() { + // Reset form and UI for new processing + document.querySelectorAll("form").forEach((form) => form.reset()); + document + .querySelectorAll(".file-list") + .forEach((list) => (list.innerHTML = "")); + document.querySelectorAll(".drop-placeholder").forEach((placeholder) => { + placeholder.style.display = "block"; + }); + + const resultsContainer = document.getElementById("results-container"); + if (resultsContainer) { + resultsContainer.classList.add("hidden"); + } +} + +// Cancel processing +function cancelProcessing() { + // Send cancel request to server + fetch("/api/cancel/", { + method: "POST", + headers: { + "X-CSRFToken": getCSRFToken(), + "Content-Type": "application/json", + }, + }).then(() => { + hideProgressModal(); + showError("Processing cancelled"); + }); +} + +// Initialize when DOM is loaded +document.addEventListener("DOMContentLoaded", function () { + // Initialize tool based on URL parameter + const urlParams = new URLSearchParams(window.location.search); + const toolParam = urlParams.get("tool"); + + if (toolParam) { + initializeTool(toolParam); + } + + // Add global event listeners + setupGlobalEventListeners(); +}); + +function setupGlobalEventListeners() { + // Escape key to close modals + document.addEventListener("keydown", function (e) { + if (e.key === "Escape") { + hideProgressModal(); + const errorNotification = document.getElementById("error-notification"); + if (errorNotification) errorNotification.classList.add("hidden"); + } + }); + + // Click outside to close modals + document.addEventListener("click", function (e) { + const progressModal = document.getElementById("progress-modal"); + if (progressModal && e.target === progressModal) { + hideProgressModal(); + } + }); +} + +// Export functions for global access +window.initializeTool = initializeTool; +window.removeFile = removeFile; +window.toggleAdvanced = toggleAdvanced; +window.cancelProcessing = cancelProcessing; +window.downloadFile = downloadFile; +window.processNew = processNew; diff --git a/fweb/core/tests.py b/fweb/core/tests.py new file mode 100644 index 0000000..7ce503c --- /dev/null +++ b/fweb/core/tests.py @@ -0,0 +1,3 @@ +from django.test import TestCase + +# Create your tests here. diff --git a/fweb/core/urls.py b/fweb/core/urls.py new file mode 100644 index 0000000..f68a24e --- /dev/null +++ b/fweb/core/urls.py @@ -0,0 +1,21 @@ +from django.urls import path +from . import views + +app_name = "core" + +urlpatterns = [ + path("", views.Dashboard, name="dashboard"), + path("dashboard/", views.Dashboard, name="get_dashboard"), + path("tools//", views.CategoryTools, name="category_tools"), + path("process/batch/", views.BatchProcessing, name="batch_processing"), + # API endpoints + path("api/process//", views.process_tool, name="process_tool"), + path("api/progress//", views.get_progress, name="get_progress"), + path("api/tool//", views.get_tool_config, name="get_tool_config"), + path("download//", views.download_file, name="download_file"), + # Specific tool endpoints (for backward compatibility) + # path("convert/doc/", views.ConvertDoc, name="convert_doc"), + # path("convert/image/", views.ConvertImgae, name="convert_image"), + # path("convert/video/", views.ConvertVideo, name="convert_video"), + # path("convert/audio/", views.ConvertAudio, name="convert_audio"), +] diff --git a/fweb/core/utils.py b/fweb/core/utils.py new file mode 100644 index 0000000..fa236ee --- /dev/null +++ b/fweb/core/utils.py @@ -0,0 +1,149 @@ +import os +import json +import tempfile +import logging +from pathlib import Path +from django.core.files.storage import FileSystemStorage +from django.conf import settings + +logger = logging.getLogger("fweb") + + +class FileProcessor: + """Handle file processing operations""" + + def __init__(self): + self.storage = FileSystemStorage() + self.media_root = settings.MEDIA_ROOT + self.processed_dir = os.path.join(self.media_root, "processed") + + # Create processed directory if it doesn't exist + os.makedirs(self.processed_dir, exist_ok=True) + + def save_uploaded_files(self, files): + """Save uploaded files to temporary location""" + saved_paths = [] + for file in files: + # Save to temporary directory + temp_path = os.path.join(self.processed_dir, file.name) + with open(temp_path, "wb") as f: + for chunk in file.chunks(): + f.write(chunk) + saved_paths.append(temp_path) + return saved_paths + + def cleanup_files(self, file_paths): + """Clean up processed files""" + for file_path in file_paths: + try: + if os.path.exists(file_path): + os.remove(file_path) + except Exception as e: + logger.warning(f"Could not delete file {file_path}: {e}") + + def get_file_info(self, file_path): + """Get information about a file""" + stat = os.stat(file_path) + return { + "name": os.path.basename(file_path), + "size": stat.st_size, + "modified": stat.st_mtime, + "extension": os.path.splitext(file_path)[1].lower(), + } + + +class CLIInterface: + """Interface with the CLI functionality""" + + def __init__(self): + # Import your CLI modules here + try: + # Adjust these imports based on your actual module structure + from filemac.main import Cmd_arg_Handler, argsOPMaper + + self.cli_handler = Cmd_arg_Handler + self.arg_mapper = argsOPMaper + except ImportError as e: + logger.error(f"Could not import CLI modules: {e}") + self.cli_handler = None + self.arg_mapper = None + + def execute_command(self, args): + """Execute CLI command with given arguments""" + if not self.cli_handler: + raise ImportError("CLI modules not available") + + try: + # Mock execution - replace with actual CLI call + # In a real implementation, you would call your CLI functions here + logger.info(f"Executing CLI command with args: {args}") + + # This is where you'd integrate with your actual CLI code + # For now, return mock results + return self._mock_execution(args) + + except Exception as e: + logger.error(f"CLI execution failed: {e}") + raise + + def _mock_execution(self, args): + """Mock CLI execution for demonstration""" + # Simulate processing time + import time + + time.sleep(2) + + # Generate mock results + results = [] + for arg in args: + if arg.startswith("--") or arg.startswith("-"): + continue + if os.path.exists(arg): + results.append( + { + "input": os.path.basename(arg), + "output": f"{os.path.splitext(arg)[0]}_converted{os.path.splitext(arg)[1]}", + "status": "success", + } + ) + + return { + "success": True, + "message": f"Processed {len(results)} files", + "results": results, + } + + +# Utility functions +def validate_file_type(file_path, allowed_extensions): + """Validate file type based on extension""" + extension = os.path.splitext(file_path)[1].lower() + return extension in allowed_extensions + + +def get_supported_formats(tool_id): + """Get supported formats for a tool""" + format_map = { + "convert_doc": [".pdf", ".docx", ".doc", ".txt", ".html"], + "convert_image": [".png", ".jpg", ".jpeg", ".webp", ".gif", ".bmp"], + "convert_audio": [".mp3", ".wav", ".flac", ".m4a", ".aac"], + "convert_video": [".mp4", ".mkv", ".avi", ".mov", ".wmv"], + "ocr": [".png", ".jpg", ".jpeg", ".pdf", ".tiff"], + "pdf_join": [".pdf"], + "audio_join": [".mp3", ".wav", ".flac", ".m4a"], + } + return format_map.get(tool_id, []) + + +def format_file_size(size_bytes): + """Format file size in human-readable format""" + if size_bytes == 0: + return "0 B" + + size_names = ["B", "KB", "MB", "GB"] + i = 0 + while size_bytes >= 1024 and i < len(size_names) - 1: + size_bytes /= 1024.0 + i += 1 + + return f"{size_bytes:.2f} {size_names[i]}" diff --git a/fweb/core/views.py b/fweb/core/views.py new file mode 100644 index 0000000..c7d93fe --- /dev/null +++ b/fweb/core/views.py @@ -0,0 +1,280 @@ +import os +import json +import tempfile +import logging +from django.shortcuts import render, redirect +from django.http import JsonResponse, HttpResponse +from django.views.decorators.csrf import csrf_exempt +from django.views.decorators.http import require_http_methods +from django.core.files.storage import FileSystemStorage +from django.conf import settings + +# Import CLI functionality +import sys +import argparse +from pathlib import Path +from .config import TOOL_CONFIGS + +# Add the CLI module to the path +sys.path.append(str(Path(__file__).parent.parent)) + +# Configure logging +logger = logging.getLogger("fweb") + + +def Dashboard(request): + """Main dashboard view""" + return render( + request, + "core/dashboard.html", + { + "category_icon": "tachometer-alt", + "category_color": "blue", + "category_description": "File management and processing dashboard", + }, + ) + + +def Results(request): + """Results page view""" + return render(request, "core/results.html") + + +def CategoryTools(request, category): + """Category-specific tools view""" + category = category.lower() + config = TOOL_CONFIGS.get(category, TOOL_CONFIGS["document"]) + + return render( + request, + "core/tools/base_tools.html", + { + "category": category, + "category_icon": config["icon"], + "category_color": config["color"], + "category_description": config["description"], + "tools": config["tools"], + }, + ) + + +def BatchProcessing(request): + """Batch processing dashboard""" + return render( + request, + "core/tools/base_tools.html", + { + "category": "batch", + "category_icon": TOOL_CONFIGS["batch"]["icon"], + "category_color": TOOL_CONFIGS["batch"]["color"], + "category_description": TOOL_CONFIGS["batch"]["description"], + "tools": TOOL_CONFIGS["batch"]["tools"], + }, + ) + + +# Processing views +@csrf_exempt +@require_http_methods(["POST"]) +def process_tool(request, tool_id): + """Process files using the specified tool""" + try: + # Get uploaded files + files = request.FILES.getlist("files") + if not files: + return JsonResponse({"error": "No files uploaded"}, status=400) + + # Get form data + form_data = request.POST.dict() + + # Create temporary directory for processing + with tempfile.TemporaryDirectory() as temp_dir: + # Save uploaded files + file_paths = [] + for file in files: + file_path = os.path.join(temp_dir, file.name) + with open(file_path, "wb") as f: + for chunk in file.chunks(): + f.write(chunk) + file_paths.append(file_path) + + # Process based on tool ID + result = process_with_cli(tool_id, file_paths, form_data, temp_dir) + + if result["success"]: + return JsonResponse( + { + "success": True, + "message": result["message"], + "results": result.get("results", []), + "download_urls": result.get("download_urls", []), + } + ) + else: + return JsonResponse( + {"success": False, "error": result["error"]}, status=500 + ) + + except Exception as e: + logger.error(f"Error processing tool {tool_id}: {str(e)}") + return JsonResponse({"error": str(e)}, status=500) + + +def process_with_cli(tool_id, file_paths, form_data, temp_dir): + """Bridge function to call CLI functionality""" + try: + # Import your CLI modules + from filemac.main import Argsmain # Adjust import based on your structure + + # Map tool_id to CLI arguments + cli_args = map_tool_to_cli_args(tool_id, file_paths, form_data) + + # Execute CLI command + result = execute_cli_command(cli_args, temp_dir) + + return result + + except Exception as e: + logger.error(f"CLI processing error: {str(e)}") + return {"success": False, "error": str(e)} + + +def map_tool_to_cli_args(tool_id, file_paths, form_data): + """Map web tool to CLI arguments""" + arg_mapping = { + "convert_doc": { + "args": ["--convert_doc"] + + file_paths + + ["-tf", form_data.get("target_format", "pdf")], + "extras": ["--use_extras"] if form_data.get("use_extras") else [], + }, + "convert_image": { + "args": ["--convert_image"] + + file_paths + + ["-tf", form_data.get("target_format", "png")], + "extras": [], + }, + "convert_audio": { + "args": ["--convert_audio"] + + file_paths + + ["-tf", form_data.get("target_format", "mp3")], + "extras": [], + }, + "convert_video": { + "args": ["--convert_video"] + + file_paths[0] + + ["-tf", form_data.get("target_format", "mp4")], + "extras": [], + }, + "ocr": { + "args": ["--OCR"] + file_paths, + "extras": ["-sep", form_data.get("separator", "\\n")] + if form_data.get("separator") + else [], + }, + "pdf_join": { + "args": ["--pdfjoin"] + file_paths, + "extras": ["--order", form_data.get("order", "AAB")] + if form_data.get("order") + else [], + }, + "audio_join": {"args": ["--AudioJoin"] + file_paths, "extras": []}, + "extract_audio": {"args": ["-xA", file_paths[0]], "extras": []}, + "analyze_video": {"args": ["-Av", file_paths[0]], "extras": []}, + "resize_image": { + "args": ["--resize_image"] + file_paths, + "extras": ["-t_size", form_data.get("target_size")] + if form_data.get("target_size") + else [], + }, + "image2pdf": { + "args": ["--image2pdf"] + file_paths, + "extras": ["--sort"] if form_data.get("sort") else [], + }, + "image2word": {"args": ["--image2word"] + file_paths, "extras": []}, + "image2gray": {"args": ["--image2gray"] + file_paths, "extras": []}, + } + + mapping = arg_mapping.get(tool_id, {"args": [], "extras": []}) + return mapping["args"] + mapping["extras"] + + +def execute_cli_command(cli_args, temp_dir): + """Execute the CLI command with the given arguments""" + try: + # This is where you'll integrate with your actual CLI code + # For now, let's create a mock implementation + + # Import your CLI argument handler + from filemac.main import Cmd_arg_Handler, argsOPMaper + + # Mock execution - replace with actual CLI call + print(f"Executing CLI command: filemac {' '.join(cli_args)}") + + # Here you would actually call your CLI functionality + # For demonstration, we'll create mock results + + results = [] + download_urls = [] + + for file_path in cli_args[1:]: # Skip the command argument + if os.path.isfile(file_path): + # Create mock output file + output_file = file_path + ".converted" + with open(output_file, "w") as f: + f.write(f"Converted version of {file_path}") + + results.append( + { + "original_name": os.path.basename(file_path), + "converted_name": os.path.basename(output_file), + "status": "success", + "size": "1.2 MB", + } + ) + download_urls.append(f"/download/{os.path.basename(output_file)}") + + return { + "success": True, + "message": f"Processed {len(results)} files successfully", + "results": results, + "download_urls": download_urls, + } + + except Exception as e: + logger.error(f"CLI execution error: {str(e)}") + return {"success": False, "error": str(e)} + + +# File download view +def download_file(request, filename): + """Serve processed files for download""" + file_path = os.path.join(settings.MEDIA_ROOT, "processed", filename) + + if os.path.exists(file_path): + with open(file_path, "rb") as f: + response = HttpResponse(f.read(), content_type="application/octet-stream") + response["Content-Disposition"] = f'attachment; filename="{filename}"' + return response + else: + return HttpResponse("File not found", status=404) + + +# Progress tracking view +@csrf_exempt +def get_progress(request, job_id): + """Get processing progress for a job""" + # Implement progress tracking logic + return JsonResponse({"progress": 50, "status": "Processing..."}) + + +# Tool configuration API +def get_tool_config(request, tool_id): + """Get configuration for a specific tool""" + # Find tool configuration + for category, config in TOOL_CONFIGS.items(): + for tool in config["tools"]: + if tool["id"] == tool_id: + return JsonResponse({"tool": tool, "category": category}) + + return JsonResponse({"error": "Tool not found"}, status=404) diff --git a/fweb/db.sqlite3 b/fweb/db.sqlite3 new file mode 100644 index 0000000000000000000000000000000000000000..7b97a289be83f2bf90e1d76e2409a398a9928d14 GIT binary patch literal 151552 zcmeI5ZEPFKdB?dTC5o2Fl`YHk*_K7g*4eC1((aPW7hf-TvaGXpmStO#?eigr?UGzk zEAvexWmyhTK)$;qP1-LldPNJgmoEhhv>)1{KnkSyB}H+4OVbuffi{-{?UzG=rYQn6 zDbNJy%p_(?{|CqqHpTqMmII)|A*Q{jsJEtM?MIE00@8p2!H?x zfB*=900@8p2!O!TCops}Oq>q(jrjPF`1kn&KN|Um$S+1NhJO!(Vulw8fB*=900@8p2!H?x9ApC1gWbNN@tJ(Jt_gx5Dtbk4>S{?6BzaQE zPD-hmn7Sa!7o_ZzAV}$?lsMAu8y=r&XpM$mtu%HkBwi5Hv`|V;OUcBQ!=#owGwNn@ zjZ`8jYN@H!mCXi8R`q(LsZ`Xmrj*qON=d5}n`_SMEl)`?lgP-g4G>S4El;AdSu3bb zO{vwZ54M$>Rxj&@u1+3EUOJPV<%x%DmIuMqQmj`uYx|KQWQ1foaXCVq+%laAS!aVv z>VDdjnaZXTaw_q9m^fOt9A%u2D4xf1$xNjaayB7e?I(WTw)~_`Kljy=PWV*o4Mi;! z6s=yb)|E2pI<=@Z+7V@@Qb{2#i8Fn~*}UZ}rPQ^JO}(xu`D&%9RhrH1n$}QA&r6+L z$O$Qx%3M4|TwJwW$j){#K&5I?uPBwxl540LeVv&~O373*`C5qhu=-j^I(@X*RBO$S z4H46sR8pGlB_6E477|VmT3OXgdk(qGlptm^a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R71N*j2MpVIOvP7#jB3CmJ7K%=U*-r=64LlBjk+2(fUF zRmr)^8sE7xLbg~YxSh|j-tQnpAq%ZaNzG{`rA+$1q@+{1LZXl$zu%L6i5&_AI(B{s z!@WJbJ_5aDTAJuK1SX3NYk z00ck)1V8`;KmY_l00ck)1VG?v5TJkmznA~4kN+P3kNjWqf5Lyje~E9947@-91V8`; zKmY_l00ck)1V8`;KmY{xMPR5m;2Szezhuk&HZkKXw1$G7Y~zd8273a&;gja~{g5xL zW8au`vOC}#KV$yY{^oW~YdGHb2Z*B~`UM^In+L*vaulUU?5kRibdkeRdT4(=$6+qu ziw?8zAs}C=qg9&qZF>Lj8`xKKU<3jn00JNY0w4eaAOHd&00JNY0wD0562Sid=d|M> z8w5ZA1V8`;KmY_l00ck)1V8`;J_P}K|IhLN>LWjRfdB}A00@8p2!H?xfB*=900@8p z2t2n0hW#@kNs#18Q6N7tF?B&qUXU|WX)z;7N$mfBZaWsjK>!3m00ck)1V8`;KmY_l z00cl_-vqG#f8VHJ2m&Ag0w4eaAOHd&00JNY0w4ea&n*G0|39}~2jL(90w4eaAOHd& z00JNY0w4eaAh2%&SpVNQDj0$Q2!H?xfB*=900@8p2!H?xfWUK00QdjTZP!6K2!H?x XfB*=900@8p2!H?xfB*>Wo5249{#9$H literal 0 HcmV?d00001 diff --git a/fweb/fweb/__init__.py b/fweb/fweb/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/fweb/fweb/asgi.py b/fweb/fweb/asgi.py new file mode 100644 index 0000000..b13a6c6 --- /dev/null +++ b/fweb/fweb/asgi.py @@ -0,0 +1,16 @@ +""" +ASGI config for fweb project. + +It exposes the ASGI callable as a module-level variable named ``application``. + +For more information on this file, see +https://docs.djangoproject.com/en/5.1/howto/deployment/asgi/ +""" + +import os + +from django.core.asgi import get_asgi_application + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'fweb.settings') + +application = get_asgi_application() diff --git a/fweb/fweb/settings.py b/fweb/fweb/settings.py new file mode 100644 index 0000000..e8c6875 --- /dev/null +++ b/fweb/fweb/settings.py @@ -0,0 +1,146 @@ +""" +Django settings for fweb project. + +Generated by 'django-admin startproject' using Django 5.1.6. + +For more information on this file, see +https://docs.djangoproject.com/en/5.1/topics/settings/ + +For the full list of settings and their values, see +https://docs.djangoproject.com/en/5.1/ref/settings/ +""" + +from pathlib import Path + +# Build paths inside the project like this: BASE_DIR / 'subdir'. +BASE_DIR = Path(__file__).resolve().parent.parent + + +# Quick-start development settings - unsuitable for production +# See https://docs.djangoproject.com/en/5.1/howto/deployment/checklist/ + +# SECURITY WARNING: keep the secret key used in production secret! +SECRET_KEY = "django-insecure-$5l7z2cy6a*dsns5f29xh#z)*mdex1=nt$_5*l*fc5u(42gkdl" + +# SECURITY WARNING: don't run with debug turned on in production! +DEBUG = True + +ALLOWED_HOSTS = ["0.0.0.0", "127.0.0.0", "localhost"] + + +# Application definition + +INSTALLED_APPS = [ + "django.contrib.admin", + "django.contrib.auth", + "django.contrib.contenttypes", + "django.contrib.sessions", + "django.contrib.messages", + "django.contrib.staticfiles", + "django_browser_reload", + "widget_tweaks", + "core", +] + +MIDDLEWARE = [ + "django.middleware.security.SecurityMiddleware", + "django.contrib.sessions.middleware.SessionMiddleware", + "django.middleware.common.CommonMiddleware", + "django.middleware.csrf.CsrfViewMiddleware", + "django.contrib.auth.middleware.AuthenticationMiddleware", + "django.contrib.messages.middleware.MessageMiddleware", + "django.middleware.clickjacking.XFrameOptionsMiddleware", + "django_browser_reload.middleware.BrowserReloadMiddleware", +] + +ROOT_URLCONF = "fweb.urls" + +TEMPLATES = [ + { + "BACKEND": "django.template.backends.django.DjangoTemplates", + "DIRS": [BASE_DIR / "templates"], + "APP_DIRS": True, + "OPTIONS": { + "context_processors": [ + "django.template.context_processors.debug", + "django.template.context_processors.request", + "django.contrib.auth.context_processors.auth", + "django.contrib.messages.context_processors.messages", + ], + }, + }, +] + +WSGI_APPLICATION = "fweb.wsgi.application" + + +ROOT_URLCONF = "fweb.urls" + +# Database +# https://docs.djangoproject.com/en/5.1/ref/settings/#databases + +DATABASES = { + "default": { + "ENGINE": "django.db.backends.sqlite3", + "NAME": BASE_DIR / "db.sqlite3", + } +} + + +# Password validation +# https://docs.djangoproject.com/en/5.1/ref/settings/#auth-password-validators + +AUTH_PASSWORD_VALIDATORS = [ + { + "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator", + }, + { + "NAME": "django.contrib.auth.password_validation.MinimumLengthValidator", + }, + { + "NAME": "django.contrib.auth.password_validation.CommonPasswordValidator", + }, + { + "NAME": "django.contrib.auth.password_validation.NumericPasswordValidator", + }, +] + + +# Internationalization +# https://docs.djangoproject.com/en/5.1/topics/i18n/ + +LANGUAGE_CODE = "en-us" + +TIME_ZONE = "Africa/Nairobi" + +USE_I18N = True + +USE_TZ = True + + +# Static files (CSS, JavaScript, Images) +# https://docs.djangoproject.com/en/5.1/howto/static-files/ + +STATIC_URL = "static/" + +STATIC_ROOT = BASE_DIR / "static" + + +# Media settings +MEDIA_ROOT = BASE_DIR / "media" + +MEDIA_URL = "/media/" + +# File upload settings +FILE_UPLOAD_MAX_MEMORY_SIZE = 100 * 1024 * 1024 # 100MB +DATA_UPLOAD_MAX_MEMORY_SIZE = 100 * 1024 * 1024 # 100MB + +# Temporary file handling +FILE_UPLOAD_HANDLERS = [ + "django.core.files.uploadhandler.TemporaryFileUploadHandler", +] + +# Default primary key field type +# https://docs.djangoproject.com/en/5.1/ref/settings/#default-auto-field + +DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField" diff --git a/fweb/fweb/urls.py b/fweb/fweb/urls.py new file mode 100644 index 0000000..a1e985c --- /dev/null +++ b/fweb/fweb/urls.py @@ -0,0 +1,32 @@ +""" +URL configuration for fweb project. + +The `urlpatterns` list routes URLs to views. For more information please see: + https://docs.djangoproject.com/en/5.1/topics/http/urls/ +Examples: +Function views + 1. Add an import: from my_app import views + 2. Add a URL to urlpatterns: path('', views.home, name='home') +Class-based views + 1. Add an import: from other_app.views import Home + 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') +Including another URLconf + 1. Import the include() function: from django.urls import include, path + 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) +""" + +from django.conf.urls.static import static +from django.contrib import admin +from django.urls import path, include +from django.conf import settings + + +urlpatterns = [ + path("admin/", admin.site.urls), + path("", include("core.urls")), + path("__reload__/", include("django_browser_reload.urls")), +] + + +if settings.DEBUG: + urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) diff --git a/fweb/fweb/wsgi.py b/fweb/fweb/wsgi.py new file mode 100644 index 0000000..2b00a00 --- /dev/null +++ b/fweb/fweb/wsgi.py @@ -0,0 +1,16 @@ +""" +WSGI config for fweb project. + +It exposes the WSGI callable as a module-level variable named ``application``. + +For more information on this file, see +https://docs.djangoproject.com/en/5.1/howto/deployment/wsgi/ +""" + +import os + +from django.core.wsgi import get_wsgi_application + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'fweb.settings') + +application = get_wsgi_application() diff --git a/fweb/manage.py b/fweb/manage.py new file mode 100755 index 0000000..82d9449 --- /dev/null +++ b/fweb/manage.py @@ -0,0 +1,22 @@ +#!/usr/bin/env python +"""Django's command-line utility for administrative tasks.""" +import os +import sys + + +def main(): + """Run administrative tasks.""" + os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'fweb.settings') + try: + from django.core.management import execute_from_command_line + except ImportError as exc: + raise ImportError( + "Couldn't import Django. Are you sure it's installed and " + "available on your PYTHONPATH environment variable? Did you " + "forget to activate a virtual environment?" + ) from exc + execute_from_command_line(sys.argv) + + +if __name__ == '__main__': + main() diff --git a/fweb/package.json b/fweb/package.json new file mode 100644 index 0000000..a0cdba6 --- /dev/null +++ b/fweb/package.json @@ -0,0 +1,43 @@ +{ + "name": "filemac_web", + "version": "1.0", + "private": true, + "description": "File Management Suite", + "scripts": { + "tailwindcss": "tailwindcss -i core/static/css/config.css -o core/static/css/styles.css --watch --minify" + }, + "eslintConfig": { + "extends": [ + "react-app", + "react-app/jest" + ] + }, + "browserslist": { + "production": [ + ">0.2%", + "not dead", + "not op_mini all" + ], + "development": [ + "last 1 chrome version", + "last 1 firefox version", + "last 1 safari version" + ] + }, + "keywords": [ + "filemac", + "file_conversion" + ], + "bugs": { + "url": "https://github.com/skye-cyber/FileMAC/issues" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/skye-cyber/FileMAC.git" + }, + "license": "GPL", + "author": "skye", + "main": "index.js", + "dependencies": {}, + "devDependencies": {} +} diff --git a/fweb/static/admin/css/autocomplete.css b/fweb/static/admin/css/autocomplete.css new file mode 100644 index 0000000..7478c2c --- /dev/null +++ b/fweb/static/admin/css/autocomplete.css @@ -0,0 +1,279 @@ +select.admin-autocomplete { + width: 20em; +} + +.select2-container--admin-autocomplete.select2-container { + min-height: 30px; +} + +.select2-container--admin-autocomplete .select2-selection--single, +.select2-container--admin-autocomplete .select2-selection--multiple { + min-height: 30px; + padding: 0; +} + +.select2-container--admin-autocomplete.select2-container--focus .select2-selection, +.select2-container--admin-autocomplete.select2-container--open .select2-selection { + border-color: var(--body-quiet-color); + min-height: 30px; +} + +.select2-container--admin-autocomplete.select2-container--focus .select2-selection.select2-selection--single, +.select2-container--admin-autocomplete.select2-container--open .select2-selection.select2-selection--single { + padding: 0; +} + +.select2-container--admin-autocomplete.select2-container--focus .select2-selection.select2-selection--multiple, +.select2-container--admin-autocomplete.select2-container--open .select2-selection.select2-selection--multiple { + padding: 0; +} + +.select2-container--admin-autocomplete .select2-selection--single { + background-color: var(--body-bg); + border: 1px solid var(--border-color); + border-radius: 4px; +} + +.select2-container--admin-autocomplete .select2-selection--single .select2-selection__rendered { + color: var(--body-fg); + line-height: 30px; +} + +.select2-container--admin-autocomplete .select2-selection--single .select2-selection__clear { + cursor: pointer; + float: right; + font-weight: bold; +} + +.select2-container--admin-autocomplete .select2-selection--single .select2-selection__placeholder { + color: var(--body-quiet-color); +} + +.select2-container--admin-autocomplete .select2-selection--single .select2-selection__arrow { + height: 26px; + position: absolute; + top: 1px; + right: 1px; + width: 20px; +} + +.select2-container--admin-autocomplete .select2-selection--single .select2-selection__arrow b { + border-color: #888 transparent transparent transparent; + border-style: solid; + border-width: 5px 4px 0 4px; + height: 0; + left: 50%; + margin-left: -4px; + margin-top: -2px; + position: absolute; + top: 50%; + width: 0; +} + +.select2-container--admin-autocomplete[dir="rtl"] .select2-selection--single .select2-selection__clear { + float: left; +} + +.select2-container--admin-autocomplete[dir="rtl"] .select2-selection--single .select2-selection__arrow { + left: 1px; + right: auto; +} + +.select2-container--admin-autocomplete.select2-container--disabled .select2-selection--single { + background-color: var(--darkened-bg); + cursor: default; +} + +.select2-container--admin-autocomplete.select2-container--disabled .select2-selection--single .select2-selection__clear { + display: none; +} + +.select2-container--admin-autocomplete.select2-container--open .select2-selection--single .select2-selection__arrow b { + border-color: transparent transparent #888 transparent; + border-width: 0 4px 5px 4px; +} + +.select2-container--admin-autocomplete .select2-selection--multiple { + background-color: var(--body-bg); + border: 1px solid var(--border-color); + border-radius: 4px; + cursor: text; +} + +.select2-container--admin-autocomplete .select2-selection--multiple .select2-selection__rendered { + box-sizing: border-box; + list-style: none; + margin: 0; + padding: 0 10px 5px 5px; + width: 100%; + display: flex; + flex-wrap: wrap; +} + +.select2-container--admin-autocomplete .select2-selection--multiple .select2-selection__rendered li { + list-style: none; +} + +.select2-container--admin-autocomplete .select2-selection--multiple .select2-selection__placeholder { + color: var(--body-quiet-color); + margin-top: 5px; + float: left; +} + +.select2-container--admin-autocomplete .select2-selection--multiple .select2-selection__clear { + cursor: pointer; + float: right; + font-weight: bold; + margin: 5px; + position: absolute; + right: 0; +} + +.select2-container--admin-autocomplete .select2-selection--multiple .select2-selection__choice { + background-color: var(--darkened-bg); + border: 1px solid var(--border-color); + border-radius: 4px; + cursor: default; + float: left; + margin-right: 5px; + margin-top: 5px; + padding: 0 5px; +} + +.select2-container--admin-autocomplete .select2-selection--multiple .select2-selection__choice__remove { + color: var(--body-quiet-color); + cursor: pointer; + display: inline-block; + font-weight: bold; + margin-right: 2px; +} + +.select2-container--admin-autocomplete .select2-selection--multiple .select2-selection__choice__remove:hover { + color: var(--body-fg); +} + +.select2-container--admin-autocomplete[dir="rtl"] .select2-selection--multiple .select2-selection__choice, .select2-container--admin-autocomplete[dir="rtl"] .select2-selection--multiple .select2-selection__placeholder, .select2-container--admin-autocomplete[dir="rtl"] .select2-selection--multiple .select2-search--inline { + float: right; +} + +.select2-container--admin-autocomplete[dir="rtl"] .select2-selection--multiple .select2-selection__choice { + margin-left: 5px; + margin-right: auto; +} + +.select2-container--admin-autocomplete[dir="rtl"] .select2-selection--multiple .select2-selection__choice__remove { + margin-left: 2px; + margin-right: auto; +} + +.select2-container--admin-autocomplete.select2-container--focus .select2-selection--multiple { + border: solid var(--body-quiet-color) 1px; + outline: 0; +} + +.select2-container--admin-autocomplete.select2-container--disabled .select2-selection--multiple { + background-color: var(--darkened-bg); + cursor: default; +} + +.select2-container--admin-autocomplete.select2-container--disabled .select2-selection__choice__remove { + display: none; +} + +.select2-container--admin-autocomplete.select2-container--open.select2-container--above .select2-selection--single, .select2-container--admin-autocomplete.select2-container--open.select2-container--above .select2-selection--multiple { + border-top-left-radius: 0; + border-top-right-radius: 0; +} + +.select2-container--admin-autocomplete.select2-container--open.select2-container--below .select2-selection--single, .select2-container--admin-autocomplete.select2-container--open.select2-container--below .select2-selection--multiple { + border-bottom-left-radius: 0; + border-bottom-right-radius: 0; +} + +.select2-container--admin-autocomplete .select2-search--dropdown { + background: var(--darkened-bg); +} + +.select2-container--admin-autocomplete .select2-search--dropdown .select2-search__field { + background: var(--body-bg); + color: var(--body-fg); + border: 1px solid var(--border-color); + border-radius: 4px; +} + +.select2-container--admin-autocomplete .select2-search--inline .select2-search__field { + background: transparent; + color: var(--body-fg); + border: none; + outline: 0; + box-shadow: none; + -webkit-appearance: textfield; +} + +.select2-container--admin-autocomplete .select2-results > .select2-results__options { + max-height: 200px; + overflow-y: auto; + color: var(--body-fg); + background: var(--body-bg); +} + +.select2-container--admin-autocomplete .select2-results__option[role=group] { + padding: 0; +} + +.select2-container--admin-autocomplete .select2-results__option[aria-disabled=true] { + color: var(--body-quiet-color); +} + +.select2-container--admin-autocomplete .select2-results__option[aria-selected=true] { + background-color: var(--selected-bg); + color: var(--body-fg); +} + +.select2-container--admin-autocomplete .select2-results__option .select2-results__option { + padding-left: 1em; +} + +.select2-container--admin-autocomplete .select2-results__option .select2-results__option .select2-results__group { + padding-left: 0; +} + +.select2-container--admin-autocomplete .select2-results__option .select2-results__option .select2-results__option { + margin-left: -1em; + padding-left: 2em; +} + +.select2-container--admin-autocomplete .select2-results__option .select2-results__option .select2-results__option .select2-results__option { + margin-left: -2em; + padding-left: 3em; +} + +.select2-container--admin-autocomplete .select2-results__option .select2-results__option .select2-results__option .select2-results__option .select2-results__option { + margin-left: -3em; + padding-left: 4em; +} + +.select2-container--admin-autocomplete .select2-results__option .select2-results__option .select2-results__option .select2-results__option .select2-results__option .select2-results__option { + margin-left: -4em; + padding-left: 5em; +} + +.select2-container--admin-autocomplete .select2-results__option .select2-results__option .select2-results__option .select2-results__option .select2-results__option .select2-results__option .select2-results__option { + margin-left: -5em; + padding-left: 6em; +} + +.select2-container--admin-autocomplete .select2-results__option--highlighted[aria-selected] { + background-color: var(--primary); + color: var(--primary-fg); +} + +.select2-container--admin-autocomplete .select2-results__group { + cursor: default; + display: block; + padding: 6px; +} + +.errors .select2-selection { + border: 1px solid var(--error-fg); +} diff --git a/fweb/static/admin/css/base.css b/fweb/static/admin/css/base.css new file mode 100644 index 0000000..ac28326 --- /dev/null +++ b/fweb/static/admin/css/base.css @@ -0,0 +1,1179 @@ +/* + DJANGO Admin styles +*/ + +/* VARIABLE DEFINITIONS */ +html[data-theme="light"], +:root { + --primary: #79aec8; + --secondary: #417690; + --accent: #f5dd5d; + --primary-fg: #fff; + + --body-fg: #333; + --body-bg: #fff; + --body-quiet-color: #666; + --body-medium-color: #444; + --body-loud-color: #000; + + --header-color: #ffc; + --header-branding-color: var(--accent); + --header-bg: var(--secondary); + --header-link-color: var(--primary-fg); + + --breadcrumbs-fg: #c4dce8; + --breadcrumbs-link-fg: var(--body-bg); + --breadcrumbs-bg: #264b5d; + + --link-fg: #417893; + --link-hover-color: #036; + --link-selected-fg: var(--secondary); + + --hairline-color: #e8e8e8; + --border-color: #ccc; + + --error-fg: #ba2121; + + --message-success-bg: #dfd; + --message-warning-bg: #ffc; + --message-error-bg: #ffefef; + + --darkened-bg: #f8f8f8; /* A bit darker than --body-bg */ + --selected-bg: #e4e4e4; /* E.g. selected table cells */ + --selected-row: #ffc; + + --button-fg: #fff; + --button-bg: var(--secondary); + --button-hover-bg: #205067; + --default-button-bg: #205067; + --default-button-hover-bg: var(--secondary); + --close-button-bg: #747474; + --close-button-hover-bg: #333; + --delete-button-bg: #ba2121; + --delete-button-hover-bg: #a41515; + + --object-tools-fg: var(--button-fg); + --object-tools-bg: var(--close-button-bg); + --object-tools-hover-bg: var(--close-button-hover-bg); + + --font-family-primary: + "Segoe UI", + system-ui, + Roboto, + "Helvetica Neue", + Arial, + sans-serif, + "Apple Color Emoji", + "Segoe UI Emoji", + "Segoe UI Symbol", + "Noto Color Emoji"; + --font-family-monospace: + ui-monospace, + Menlo, + Monaco, + "Cascadia Mono", + "Segoe UI Mono", + "Roboto Mono", + "Oxygen Mono", + "Ubuntu Monospace", + "Source Code Pro", + "Fira Mono", + "Droid Sans Mono", + "Courier New", + monospace, + "Apple Color Emoji", + "Segoe UI Emoji", + "Segoe UI Symbol", + "Noto Color Emoji"; + + color-scheme: light; +} + +html, body { + height: 100%; +} + +body { + margin: 0; + padding: 0; + font-size: 0.875rem; + font-family: var(--font-family-primary); + color: var(--body-fg); + background: var(--body-bg); +} + +/* LINKS */ + +a:link, a:visited { + color: var(--link-fg); + text-decoration: none; + transition: color 0.15s, background 0.15s; +} + +a:focus, a:hover { + color: var(--link-hover-color); +} + +a:focus { + text-decoration: underline; +} + +a img { + border: none; +} + +a.section:link, a.section:visited { + color: var(--header-link-color); + text-decoration: none; +} + +a.section:focus, a.section:hover { + text-decoration: underline; +} + +/* GLOBAL DEFAULTS */ + +p, ol, ul, dl { + margin: .2em 0 .8em 0; +} + +p { + padding: 0; + line-height: 140%; +} + +h1,h2,h3,h4,h5 { + font-weight: bold; +} + +h1 { + margin: 0 0 20px; + font-weight: 300; + font-size: 1.25rem; +} + +h2 { + font-size: 1rem; + margin: 1em 0 .5em 0; +} + +h2.subhead { + font-weight: normal; + margin-top: 0; +} + +h3 { + font-size: 0.875rem; + margin: .8em 0 .3em 0; + color: var(--body-medium-color); + font-weight: bold; +} + +h4 { + font-size: 0.75rem; + margin: 1em 0 .8em 0; + padding-bottom: 3px; + color: var(--body-medium-color); +} + +h5 { + font-size: 0.625rem; + margin: 1.5em 0 .5em 0; + color: var(--body-quiet-color); + text-transform: uppercase; + letter-spacing: 1px; +} + +ul > li { + list-style-type: square; + padding: 1px 0; +} + +li ul { + margin-bottom: 0; +} + +li, dt, dd { + font-size: 0.8125rem; + line-height: 1.25rem; +} + +dt { + font-weight: bold; + margin-top: 4px; +} + +dd { + margin-left: 0; +} + +form { + margin: 0; + padding: 0; +} + +fieldset { + margin: 0; + min-width: 0; + padding: 0; + border: none; + border-top: 1px solid var(--hairline-color); +} + +details summary { + cursor: pointer; +} + +blockquote { + font-size: 0.6875rem; + color: #777; + margin-left: 2px; + padding-left: 10px; + border-left: 5px solid #ddd; +} + +code, pre { + font-family: var(--font-family-monospace); + color: var(--body-quiet-color); + font-size: 0.75rem; + overflow-x: auto; +} + +pre.literal-block { + margin: 10px; + background: var(--darkened-bg); + padding: 6px 8px; +} + +code strong { + color: #930; +} + +hr { + clear: both; + color: var(--hairline-color); + background-color: var(--hairline-color); + height: 1px; + border: none; + margin: 0; + padding: 0; + line-height: 1px; +} + +/* TEXT STYLES & MODIFIERS */ + +.small { + font-size: 0.6875rem; +} + +.mini { + font-size: 0.625rem; +} + +.help, p.help, form p.help, div.help, form div.help, div.help li { + font-size: 0.6875rem; + color: var(--body-quiet-color); +} + +div.help ul { + margin-bottom: 0; +} + +.help-tooltip { + cursor: help; +} + +p img, h1 img, h2 img, h3 img, h4 img, td img { + vertical-align: middle; +} + +.quiet, a.quiet:link, a.quiet:visited { + color: var(--body-quiet-color); + font-weight: normal; +} + +.clear { + clear: both; +} + +.nowrap { + white-space: nowrap; +} + +.hidden { + display: none !important; +} + +/* TABLES */ + +table { + border-collapse: collapse; + border-color: var(--border-color); +} + +td, th { + font-size: 0.8125rem; + line-height: 1rem; + border-bottom: 1px solid var(--hairline-color); + vertical-align: top; + padding: 8px; +} + +th { + font-weight: 500; + text-align: left; +} + +thead th, +tfoot td { + color: var(--body-quiet-color); + padding: 5px 10px; + font-size: 0.6875rem; + background: var(--body-bg); + border: none; + border-top: 1px solid var(--hairline-color); + border-bottom: 1px solid var(--hairline-color); +} + +tfoot td { + border-bottom: none; + border-top: 1px solid var(--hairline-color); +} + +thead th.required { + font-weight: bold; +} + +tr.alt { + background: var(--darkened-bg); +} + +tr:nth-child(odd), .row-form-errors { + background: var(--body-bg); +} + +tr:nth-child(even), +tr:nth-child(even) .errorlist, +tr:nth-child(odd) + .row-form-errors, +tr:nth-child(odd) + .row-form-errors .errorlist { + background: var(--darkened-bg); +} + +/* SORTABLE TABLES */ + +thead th { + padding: 5px 10px; + line-height: normal; + text-transform: uppercase; + background: var(--darkened-bg); +} + +thead th a:link, thead th a:visited { + color: var(--body-quiet-color); +} + +thead th.sorted { + background: var(--selected-bg); +} + +thead th.sorted .text { + padding-right: 42px; +} + +table thead th .text span { + padding: 8px 10px; + display: block; +} + +table thead th .text a { + display: block; + cursor: pointer; + padding: 8px 10px; +} + +table thead th .text a:focus, table thead th .text a:hover { + background: var(--selected-bg); +} + +thead th.sorted a.sortremove { + visibility: hidden; +} + +table thead th.sorted:hover a.sortremove { + visibility: visible; +} + +table thead th.sorted .sortoptions { + display: block; + padding: 9px 5px 0 5px; + float: right; + text-align: right; +} + +table thead th.sorted .sortpriority { + font-size: .8em; + min-width: 12px; + text-align: center; + vertical-align: 3px; + margin-left: 2px; + margin-right: 2px; +} + +table thead th.sorted .sortoptions a { + position: relative; + width: 14px; + height: 14px; + display: inline-block; + background: url(../img/sorting-icons.svg) 0 0 no-repeat; + background-size: 14px auto; +} + +table thead th.sorted .sortoptions a.sortremove { + background-position: 0 0; +} + +table thead th.sorted .sortoptions a.sortremove:after { + content: '\\'; + position: absolute; + top: -6px; + left: 3px; + font-weight: 200; + font-size: 1.125rem; + color: var(--body-quiet-color); +} + +table thead th.sorted .sortoptions a.sortremove:focus:after, +table thead th.sorted .sortoptions a.sortremove:hover:after { + color: var(--link-fg); +} + +table thead th.sorted .sortoptions a.sortremove:focus, +table thead th.sorted .sortoptions a.sortremove:hover { + background-position: 0 -14px; +} + +table thead th.sorted .sortoptions a.ascending { + background-position: 0 -28px; +} + +table thead th.sorted .sortoptions a.ascending:focus, +table thead th.sorted .sortoptions a.ascending:hover { + background-position: 0 -42px; +} + +table thead th.sorted .sortoptions a.descending { + top: 1px; + background-position: 0 -56px; +} + +table thead th.sorted .sortoptions a.descending:focus, +table thead th.sorted .sortoptions a.descending:hover { + background-position: 0 -70px; +} + +/* FORM DEFAULTS */ + +input, textarea, select, .form-row p, form .button { + margin: 2px 0; + padding: 2px 3px; + vertical-align: middle; + font-family: var(--font-family-primary); + font-weight: normal; + font-size: 0.8125rem; +} +.form-row div.help { + padding: 2px 3px; +} + +textarea { + vertical-align: top; +} + +/* +Minifiers remove the default (text) "type" attribute from "input" HTML tags. +Add input:not([type]) to make the CSS stylesheet work the same. +*/ +input:not([type]), input[type=text], input[type=password], input[type=email], +input[type=url], input[type=number], input[type=tel], textarea, select, +.vTextField { + border: 1px solid var(--border-color); + border-radius: 4px; + padding: 5px 6px; + margin-top: 0; + color: var(--body-fg); + background-color: var(--body-bg); +} + +/* +Minifiers remove the default (text) "type" attribute from "input" HTML tags. +Add input:not([type]) to make the CSS stylesheet work the same. +*/ +input:not([type]):focus, input[type=text]:focus, input[type=password]:focus, +input[type=email]:focus, input[type=url]:focus, input[type=number]:focus, +input[type=tel]:focus, textarea:focus, select:focus, .vTextField:focus { + border-color: var(--body-quiet-color); +} + +select { + height: 1.875rem; +} + +select[multiple] { + /* Allow HTML size attribute to override the height in the rule above. */ + height: auto; + min-height: 150px; +} + +/* FORM BUTTONS */ + +.button, input[type=submit], input[type=button], .submit-row input, a.button { + background: var(--button-bg); + padding: 10px 15px; + border: none; + border-radius: 4px; + color: var(--button-fg); + cursor: pointer; + transition: background 0.15s; +} + +a.button { + padding: 4px 5px; +} + +.button:active, input[type=submit]:active, input[type=button]:active, +.button:focus, input[type=submit]:focus, input[type=button]:focus, +.button:hover, input[type=submit]:hover, input[type=button]:hover { + background: var(--button-hover-bg); +} + +.button[disabled], input[type=submit][disabled], input[type=button][disabled] { + opacity: 0.4; +} + +.button.default, input[type=submit].default, .submit-row input.default { + border: none; + font-weight: 400; + background: var(--default-button-bg); +} + +.button.default:active, input[type=submit].default:active, +.button.default:focus, input[type=submit].default:focus, +.button.default:hover, input[type=submit].default:hover { + background: var(--default-button-hover-bg); +} + +.button[disabled].default, +input[type=submit][disabled].default, +input[type=button][disabled].default { + opacity: 0.4; +} + + +/* MODULES */ + +.module { + border: none; + margin-bottom: 30px; + background: var(--body-bg); +} + +.module p, .module ul, .module h3, .module h4, .module dl, .module pre { + padding-left: 10px; + padding-right: 10px; +} + +.module blockquote { + margin-left: 12px; +} + +.module ul, .module ol { + margin-left: 1.5em; +} + +.module h3 { + margin-top: .6em; +} + +.module h2, .module caption, .inline-group h2 { + margin: 0; + padding: 8px; + font-weight: 400; + font-size: 0.8125rem; + text-align: left; + background: var(--header-bg); + color: var(--header-link-color); +} + +.module caption, +.inline-group h2 { + font-size: 0.75rem; + letter-spacing: 0.5px; + text-transform: uppercase; +} + +.module table { + border-collapse: collapse; +} + +/* MESSAGES & ERRORS */ + +ul.messagelist { + padding: 0; + margin: 0; +} + +ul.messagelist li { + display: block; + font-weight: 400; + font-size: 0.8125rem; + padding: 10px 10px 10px 65px; + margin: 0 0 10px 0; + background: var(--message-success-bg) url(../img/icon-yes.svg) 40px 12px no-repeat; + background-size: 16px auto; + color: var(--body-fg); + word-break: break-word; +} + +ul.messagelist li.warning { + background: var(--message-warning-bg) url(../img/icon-alert.svg) 40px 14px no-repeat; + background-size: 14px auto; +} + +ul.messagelist li.error { + background: var(--message-error-bg) url(../img/icon-no.svg) 40px 12px no-repeat; + background-size: 16px auto; +} + +.errornote { + font-size: 0.875rem; + font-weight: 700; + display: block; + padding: 10px 12px; + margin: 0 0 10px 0; + color: var(--error-fg); + border: 1px solid var(--error-fg); + border-radius: 4px; + background-color: var(--body-bg); + background-position: 5px 12px; + overflow-wrap: break-word; +} + +ul.errorlist { + margin: 0 0 4px; + padding: 0; + color: var(--error-fg); + background: var(--body-bg); +} + +ul.errorlist li { + font-size: 0.8125rem; + display: block; + margin-bottom: 4px; + overflow-wrap: break-word; +} + +ul.errorlist li:first-child { + margin-top: 0; +} + +ul.errorlist li a { + color: inherit; + text-decoration: underline; +} + +td ul.errorlist { + margin: 0; + padding: 0; +} + +td ul.errorlist li { + margin: 0; +} + +.form-row.errors { + margin: 0; + border: none; + border-bottom: 1px solid var(--hairline-color); + background: none; +} + +.form-row.errors ul.errorlist li { + padding-left: 0; +} + +.errors input, .errors select, .errors textarea, +td ul.errorlist + input, td ul.errorlist + select, td ul.errorlist + textarea { + border: 1px solid var(--error-fg); +} + +.description { + font-size: 0.75rem; + padding: 5px 0 0 12px; +} + +/* BREADCRUMBS */ + +div.breadcrumbs { + background: var(--breadcrumbs-bg); + padding: 10px 40px; + border: none; + color: var(--breadcrumbs-fg); + text-align: left; +} + +div.breadcrumbs a { + color: var(--breadcrumbs-link-fg); +} + +div.breadcrumbs a:focus, div.breadcrumbs a:hover { + color: var(--breadcrumbs-fg); +} + +/* ACTION ICONS */ + +.viewlink, .inlineviewlink { + padding-left: 16px; + background: url(../img/icon-viewlink.svg) 0 1px no-repeat; +} + +.hidelink { + padding-left: 16px; + background: url(../img/icon-hidelink.svg) 0 1px no-repeat; +} + +.addlink { + padding-left: 16px; + background: url(../img/icon-addlink.svg) 0 1px no-repeat; +} + +.changelink, .inlinechangelink { + padding-left: 16px; + background: url(../img/icon-changelink.svg) 0 1px no-repeat; +} + +.deletelink { + padding-left: 16px; + background: url(../img/icon-deletelink.svg) 0 1px no-repeat; +} + +a.deletelink:link, a.deletelink:visited { + color: #CC3434; /* XXX Probably unused? */ +} + +a.deletelink:focus, a.deletelink:hover { + color: #993333; /* XXX Probably unused? */ + text-decoration: none; +} + +/* OBJECT TOOLS */ + +.object-tools { + font-size: 0.625rem; + font-weight: bold; + padding-left: 0; + float: right; + position: relative; + margin-top: -48px; +} + +.object-tools li { + display: block; + float: left; + margin-left: 5px; + height: 1rem; +} + +.object-tools a { + border-radius: 15px; +} + +.object-tools a:link, .object-tools a:visited { + display: block; + float: left; + padding: 3px 12px; + background: var(--object-tools-bg); + color: var(--object-tools-fg); + font-weight: 400; + font-size: 0.6875rem; + text-transform: uppercase; + letter-spacing: 0.5px; +} + +.object-tools a:focus, .object-tools a:hover { + background-color: var(--object-tools-hover-bg); +} + +.object-tools a:focus{ + text-decoration: none; +} + +.object-tools a.viewsitelink, .object-tools a.addlink { + background-repeat: no-repeat; + background-position: right 7px center; + padding-right: 26px; +} + +.object-tools a.viewsitelink { + background-image: url(../img/tooltag-arrowright.svg); +} + +.object-tools a.addlink { + background-image: url(../img/tooltag-add.svg); +} + +/* OBJECT HISTORY */ + +#change-history table { + width: 100%; +} + +#change-history table tbody th { + width: 16em; +} + +#change-history .paginator { + color: var(--body-quiet-color); + border-bottom: 1px solid var(--hairline-color); + background: var(--body-bg); + overflow: hidden; +} + +/* PAGE STRUCTURE */ + +#container { + position: relative; + width: 100%; + min-width: 980px; + padding: 0; + display: flex; + flex-direction: column; + height: 100%; +} + +#container > .main { + display: flex; + flex: 1 0 auto; +} + +.main > .content { + flex: 1 0; + max-width: 100%; +} + +.skip-to-content-link { + position: absolute; + top: -999px; + margin: 5px; + padding: 5px; + background: var(--body-bg); + z-index: 1; +} + +.skip-to-content-link:focus { + left: 0px; + top: 0px; +} + +#content { + padding: 20px 40px; +} + +.dashboard #content { + width: 600px; +} + +#content-main { + float: left; + width: 100%; +} + +#content-related { + float: right; + width: 260px; + position: relative; + margin-right: -300px; +} + +@media (forced-colors: active) { + #content-related { + border: 1px solid; + } +} + +/* COLUMN TYPES */ + +.colMS { + margin-right: 300px; +} + +.colSM { + margin-left: 300px; +} + +.colSM #content-related { + float: left; + margin-right: 0; + margin-left: -300px; +} + +.colSM #content-main { + float: right; +} + +.popup .colM { + width: auto; +} + +/* HEADER */ + +#header { + width: auto; + height: auto; + display: flex; + justify-content: space-between; + align-items: center; + padding: 10px 40px; + background: var(--header-bg); + color: var(--header-color); +} + +#header a:link, #header a:visited, #logout-form button { + color: var(--header-link-color); +} + +#header a:focus , #header a:hover { + text-decoration: underline; +} + +@media (forced-colors: active) { + #header { + border-bottom: 1px solid; + } +} + +#branding { + display: flex; +} + +#site-name { + padding: 0; + margin: 0; + margin-inline-end: 20px; + font-weight: 300; + font-size: 1.5rem; + color: var(--header-branding-color); +} + +#site-name a:link, #site-name a:visited { + color: var(--accent); +} + +#branding h2 { + padding: 0 10px; + font-size: 0.875rem; + margin: -8px 0 8px 0; + font-weight: normal; + color: var(--header-color); +} + +#branding a:hover { + text-decoration: none; +} + +#logout-form { + display: inline; +} + +#logout-form button { + background: none; + border: 0; + cursor: pointer; + font-family: var(--font-family-primary); +} + +#user-tools { + float: right; + margin: 0 0 0 20px; + text-align: right; +} + +#user-tools, #logout-form button{ + padding: 0; + font-weight: 300; + font-size: 0.6875rem; + letter-spacing: 0.5px; + text-transform: uppercase; +} + +#user-tools a, #logout-form button { + border-bottom: 1px solid rgba(255, 255, 255, 0.25); +} + +#user-tools a:focus, #user-tools a:hover, +#logout-form button:active, #logout-form button:hover { + text-decoration: none; + border-bottom: 0; +} + +#logout-form button:active, #logout-form button:hover { + margin-bottom: 1px; +} + +/* SIDEBAR */ + +#content-related { + background: var(--darkened-bg); +} + +#content-related .module { + background: none; +} + +#content-related h3 { + color: var(--body-quiet-color); + padding: 0 16px; + margin: 0 0 16px; +} + +#content-related h4 { + font-size: 0.8125rem; +} + +#content-related p { + padding-left: 16px; + padding-right: 16px; +} + +#content-related .actionlist { + padding: 0; + margin: 16px; +} + +#content-related .actionlist li { + line-height: 1.2; + margin-bottom: 10px; + padding-left: 18px; +} + +#content-related .module h2 { + background: none; + padding: 16px; + margin-bottom: 16px; + border-bottom: 1px solid var(--hairline-color); + font-size: 1.125rem; + color: var(--body-fg); +} + +.delete-confirmation form input[type="submit"] { + background: var(--delete-button-bg); + border-radius: 4px; + padding: 10px 15px; + color: var(--button-fg); +} + +.delete-confirmation form input[type="submit"]:active, +.delete-confirmation form input[type="submit"]:focus, +.delete-confirmation form input[type="submit"]:hover { + background: var(--delete-button-hover-bg); +} + +.delete-confirmation form .cancel-link { + display: inline-block; + vertical-align: middle; + height: 0.9375rem; + line-height: 0.9375rem; + border-radius: 4px; + padding: 10px 15px; + color: var(--button-fg); + background: var(--close-button-bg); + margin: 0 0 0 10px; +} + +.delete-confirmation form .cancel-link:active, +.delete-confirmation form .cancel-link:focus, +.delete-confirmation form .cancel-link:hover { + background: var(--close-button-hover-bg); +} + +/* POPUP */ +.popup #content { + padding: 20px; +} + +.popup #container { + min-width: 0; +} + +.popup #header { + padding: 10px 20px; +} + +/* PAGINATOR */ + +.paginator { + display: flex; + align-items: center; + gap: 4px; + font-size: 0.8125rem; + padding-top: 10px; + padding-bottom: 10px; + line-height: 22px; + margin: 0; + border-top: 1px solid var(--hairline-color); + width: 100%; +} + +.paginator a:link, .paginator a:visited { + padding: 2px 6px; + background: var(--button-bg); + text-decoration: none; + color: var(--button-fg); +} + +.paginator a.showall { + border: none; + background: none; + color: var(--link-fg); +} + +.paginator a.showall:focus, .paginator a.showall:hover { + background: none; + color: var(--link-hover-color); +} + +.paginator .end { + margin-right: 6px; +} + +.paginator .this-page { + padding: 2px 6px; + font-weight: bold; + font-size: 0.8125rem; + vertical-align: top; +} + +.paginator a:focus, .paginator a:hover { + color: white; + background: var(--link-hover-color); +} + +.paginator input { + margin-left: auto; +} + +.base-svgs { + display: none; +} + +.visually-hidden { + position: absolute; + width: 1px; + height: 1px; + padding: 0; + overflow: hidden; + clip: rect(0,0,0,0); + white-space: nowrap; + border: 0; + color: var(--body-fg); + background-color: var(--body-bg); +} diff --git a/fweb/static/admin/css/changelists.css b/fweb/static/admin/css/changelists.css new file mode 100644 index 0000000..005b776 --- /dev/null +++ b/fweb/static/admin/css/changelists.css @@ -0,0 +1,343 @@ +/* CHANGELISTS */ + +#changelist { + display: flex; + align-items: flex-start; + justify-content: space-between; +} + +#changelist .changelist-form-container { + flex: 1 1 auto; + min-width: 0; +} + +#changelist table { + width: 100%; +} + +.change-list .hiddenfields { display:none; } + +.change-list .filtered table { + border-right: none; +} + +.change-list .filtered { + min-height: 400px; +} + +.change-list .filtered .results, .change-list .filtered .paginator, +.filtered #toolbar, .filtered div.xfull { + width: auto; +} + +.change-list .filtered table tbody th { + padding-right: 1em; +} + +#changelist-form .results { + overflow-x: auto; + width: 100%; +} + +#changelist .toplinks { + border-bottom: 1px solid var(--hairline-color); +} + +#changelist .paginator { + color: var(--body-quiet-color); + border-bottom: 1px solid var(--hairline-color); + background: var(--body-bg); + overflow: hidden; +} + +/* CHANGELIST TABLES */ + +#changelist table thead th { + padding: 0; + white-space: nowrap; + vertical-align: middle; +} + +#changelist table thead th.action-checkbox-column { + width: 1.5em; + text-align: center; +} + +#changelist table tbody td.action-checkbox { + text-align: center; +} + +#changelist table tfoot { + color: var(--body-quiet-color); +} + +/* TOOLBAR */ + +#toolbar { + padding: 8px 10px; + margin-bottom: 15px; + border-top: 1px solid var(--hairline-color); + border-bottom: 1px solid var(--hairline-color); + background: var(--darkened-bg); + color: var(--body-quiet-color); +} + +#toolbar form input { + border-radius: 4px; + font-size: 0.875rem; + padding: 5px; + color: var(--body-fg); +} + +#toolbar #searchbar { + height: 1.1875rem; + border: 1px solid var(--border-color); + padding: 2px 5px; + margin: 0; + vertical-align: top; + font-size: 0.8125rem; + max-width: 100%; +} + +#toolbar #searchbar:focus { + border-color: var(--body-quiet-color); +} + +#toolbar form input[type="submit"] { + border: 1px solid var(--border-color); + font-size: 0.8125rem; + padding: 4px 8px; + margin: 0; + vertical-align: middle; + background: var(--body-bg); + box-shadow: 0 -15px 20px -10px rgba(0, 0, 0, 0.15) inset; + cursor: pointer; + color: var(--body-fg); +} + +#toolbar form input[type="submit"]:focus, +#toolbar form input[type="submit"]:hover { + border-color: var(--body-quiet-color); +} + +#changelist-search img { + vertical-align: middle; + margin-right: 4px; +} + +#changelist-search .help { + word-break: break-word; +} + +/* FILTER COLUMN */ + +#changelist-filter { + flex: 0 0 240px; + order: 1; + background: var(--darkened-bg); + border-left: none; + margin: 0 0 0 30px; +} + +@media (forced-colors: active) { + #changelist-filter { + border: 1px solid; + } +} + +#changelist-filter h2 { + font-size: 0.875rem; + text-transform: uppercase; + letter-spacing: 0.5px; + padding: 5px 15px; + margin-bottom: 12px; + border-bottom: none; +} + +#changelist-filter h3, +#changelist-filter details summary { + font-weight: 400; + padding: 0 15px; + margin-bottom: 10px; +} + +#changelist-filter details summary > * { + display: inline; +} + +#changelist-filter details > summary { + list-style-type: none; +} + +#changelist-filter details > summary::-webkit-details-marker { + display: none; +} + +#changelist-filter details > summary::before { + content: '→'; + font-weight: bold; + color: var(--link-hover-color); +} + +#changelist-filter details[open] > summary::before { + content: '↓'; +} + +#changelist-filter ul { + margin: 5px 0; + padding: 0 15px 15px; + border-bottom: 1px solid var(--hairline-color); +} + +#changelist-filter ul:last-child { + border-bottom: none; +} + +#changelist-filter li { + list-style-type: none; + margin-left: 0; + padding-left: 0; +} + +#changelist-filter a { + display: block; + color: var(--body-quiet-color); + word-break: break-word; +} + +#changelist-filter li.selected { + border-left: 5px solid var(--hairline-color); + padding-left: 10px; + margin-left: -15px; +} + +#changelist-filter li.selected a { + color: var(--link-selected-fg); +} + +#changelist-filter a:focus, #changelist-filter a:hover, +#changelist-filter li.selected a:focus, +#changelist-filter li.selected a:hover { + color: var(--link-hover-color); +} + +#changelist-filter #changelist-filter-extra-actions { + font-size: 0.8125rem; + margin-bottom: 10px; + border-bottom: 1px solid var(--hairline-color); +} + +/* DATE DRILLDOWN */ + +.change-list .toplinks { + display: flex; + padding-bottom: 5px; + flex-wrap: wrap; + gap: 3px 17px; + font-weight: bold; +} + +.change-list .toplinks a { + font-size: 0.8125rem; +} + +.change-list .toplinks .date-back { + color: var(--body-quiet-color); +} + +.change-list .toplinks .date-back:focus, +.change-list .toplinks .date-back:hover { + color: var(--link-hover-color); +} + +/* ACTIONS */ + +.filtered .actions { + border-right: none; +} + +#changelist table input { + margin: 0; + vertical-align: baseline; +} + +/* Once the :has() pseudo-class is supported by all browsers, the tr.selected + selector and the JS adding the class can be removed. */ +#changelist tbody tr.selected { + background-color: var(--selected-row); +} + +#changelist tbody tr:has(.action-select:checked) { + background-color: var(--selected-row); +} + +@media (forced-colors: active) { + #changelist tbody tr.selected { + background-color: SelectedItem; + } + #changelist tbody tr:has(.action-select:checked) { + background-color: SelectedItem; + } +} + +#changelist .actions { + padding: 10px; + background: var(--body-bg); + border-top: none; + border-bottom: none; + line-height: 1.5rem; + color: var(--body-quiet-color); + width: 100%; +} + +#changelist .actions span.all, +#changelist .actions span.action-counter, +#changelist .actions span.clear, +#changelist .actions span.question { + font-size: 0.8125rem; + margin: 0 0.5em; +} + +#changelist .actions:last-child { + border-bottom: none; +} + +#changelist .actions select { + vertical-align: top; + height: 1.5rem; + color: var(--body-fg); + border: 1px solid var(--border-color); + border-radius: 4px; + font-size: 0.875rem; + padding: 0 0 0 4px; + margin: 0; + margin-left: 10px; +} + +#changelist .actions select:focus { + border-color: var(--body-quiet-color); +} + +#changelist .actions label { + display: inline-block; + vertical-align: middle; + font-size: 0.8125rem; +} + +#changelist .actions .button { + font-size: 0.8125rem; + border: 1px solid var(--border-color); + border-radius: 4px; + background: var(--body-bg); + box-shadow: 0 -15px 20px -10px rgba(0, 0, 0, 0.15) inset; + cursor: pointer; + height: 1.5rem; + line-height: 1; + padding: 4px 8px; + margin: 0; + color: var(--body-fg); +} + +#changelist .actions .button:focus, #changelist .actions .button:hover { + border-color: var(--body-quiet-color); +} diff --git a/fweb/static/admin/css/dark_mode.css b/fweb/static/admin/css/dark_mode.css new file mode 100644 index 0000000..7e12a81 --- /dev/null +++ b/fweb/static/admin/css/dark_mode.css @@ -0,0 +1,130 @@ +@media (prefers-color-scheme: dark) { + :root { + --primary: #264b5d; + --primary-fg: #f7f7f7; + + --body-fg: #eeeeee; + --body-bg: #121212; + --body-quiet-color: #d0d0d0; + --body-medium-color: #e0e0e0; + --body-loud-color: #ffffff; + + --breadcrumbs-link-fg: #e0e0e0; + --breadcrumbs-bg: var(--primary); + + --link-fg: #81d4fa; + --link-hover-color: #4ac1f7; + --link-selected-fg: #6f94c6; + + --hairline-color: #272727; + --border-color: #353535; + + --error-fg: #e35f5f; + --message-success-bg: #006b1b; + --message-warning-bg: #583305; + --message-error-bg: #570808; + + --darkened-bg: #212121; + --selected-bg: #1b1b1b; + --selected-row: #00363a; + + --close-button-bg: #333333; + --close-button-hover-bg: #666666; + + color-scheme: dark; + } + } + + +html[data-theme="dark"] { + --primary: #264b5d; + --primary-fg: #f7f7f7; + + --body-fg: #eeeeee; + --body-bg: #121212; + --body-quiet-color: #d0d0d0; + --body-medium-color: #e0e0e0; + --body-loud-color: #ffffff; + + --breadcrumbs-link-fg: #e0e0e0; + --breadcrumbs-bg: var(--primary); + + --link-fg: #81d4fa; + --link-hover-color: #4ac1f7; + --link-selected-fg: #6f94c6; + + --hairline-color: #272727; + --border-color: #353535; + + --error-fg: #e35f5f; + --message-success-bg: #006b1b; + --message-warning-bg: #583305; + --message-error-bg: #570808; + + --darkened-bg: #212121; + --selected-bg: #1b1b1b; + --selected-row: #00363a; + + --close-button-bg: #333333; + --close-button-hover-bg: #666666; + + color-scheme: dark; +} + +/* THEME SWITCH */ +.theme-toggle { + cursor: pointer; + border: none; + padding: 0; + background: transparent; + vertical-align: middle; + margin-inline-start: 5px; + margin-top: -1px; +} + +.theme-toggle svg { + vertical-align: middle; + height: 1rem; + width: 1rem; + display: none; +} + +/* +Fully hide screen reader text so we only show the one matching the current +theme. +*/ +.theme-toggle .visually-hidden { + display: none; +} + +html[data-theme="auto"] .theme-toggle .theme-label-when-auto { + display: block; +} + +html[data-theme="dark"] .theme-toggle .theme-label-when-dark { + display: block; +} + +html[data-theme="light"] .theme-toggle .theme-label-when-light { + display: block; +} + +/* ICONS */ +.theme-toggle svg.theme-icon-when-auto, +.theme-toggle svg.theme-icon-when-dark, +.theme-toggle svg.theme-icon-when-light { + fill: var(--header-link-color); + color: var(--header-bg); +} + +html[data-theme="auto"] .theme-toggle svg.theme-icon-when-auto { + display: block; +} + +html[data-theme="dark"] .theme-toggle svg.theme-icon-when-dark { + display: block; +} + +html[data-theme="light"] .theme-toggle svg.theme-icon-when-light { + display: block; +} diff --git a/fweb/static/admin/css/dashboard.css b/fweb/static/admin/css/dashboard.css new file mode 100644 index 0000000..242b81a --- /dev/null +++ b/fweb/static/admin/css/dashboard.css @@ -0,0 +1,29 @@ +/* DASHBOARD */ +.dashboard td, .dashboard th { + word-break: break-word; +} + +.dashboard .module table th { + width: 100%; +} + +.dashboard .module table td { + white-space: nowrap; +} + +.dashboard .module table td a { + display: block; + padding-right: .6em; +} + +/* RECENT ACTIONS MODULE */ + +.module ul.actionlist { + margin-left: 0; +} + +ul.actionlist li { + list-style-type: none; + overflow: hidden; + text-overflow: ellipsis; +} diff --git a/fweb/static/admin/css/forms.css b/fweb/static/admin/css/forms.css new file mode 100644 index 0000000..4f49b61 --- /dev/null +++ b/fweb/static/admin/css/forms.css @@ -0,0 +1,512 @@ +@import url('widgets.css'); + +/* FORM ROWS */ + +.form-row { + overflow: hidden; + padding: 10px; + font-size: 0.8125rem; + border-bottom: 1px solid var(--hairline-color); +} + +.form-row img, .form-row input { + vertical-align: middle; +} + +.form-row label input[type="checkbox"] { + margin-top: 0; + vertical-align: 0; +} + +form .form-row p { + padding-left: 0; +} + +.flex-container { + display: flex; +} + +.form-multiline { + flex-wrap: wrap; +} + +.form-multiline > div { + padding-bottom: 10px; +} + +/* FORM LABELS */ + +label { + font-weight: normal; + color: var(--body-quiet-color); + font-size: 0.8125rem; +} + +.required label, label.required { + font-weight: bold; +} + +/* RADIO BUTTONS */ + +form div.radiolist div { + padding-right: 7px; +} + +form div.radiolist.inline div { + display: inline-block; +} + +form div.radiolist label { + width: auto; +} + +form div.radiolist input[type="radio"] { + margin: -2px 4px 0 0; + padding: 0; +} + +form ul.inline { + margin-left: 0; + padding: 0; +} + +form ul.inline li { + float: left; + padding-right: 7px; +} + +/* FIELDSETS */ + +fieldset .fieldset-heading, +fieldset .inline-heading, +:not(.inline-related) .collapse summary { + border: 1px solid var(--header-bg); + margin: 0; + padding: 8px; + font-weight: 400; + font-size: 0.8125rem; + background: var(--header-bg); + color: var(--header-link-color); +} + +/* ALIGNED FIELDSETS */ + +.aligned label { + display: block; + padding: 4px 10px 0 0; + min-width: 160px; + width: 160px; + word-wrap: break-word; +} + +.aligned label:not(.vCheckboxLabel):after { + content: ''; + display: inline-block; + vertical-align: middle; +} + +.aligned label + p, .aligned .checkbox-row + div.help, .aligned label + div.readonly { + padding: 6px 0; + margin-top: 0; + margin-bottom: 0; + margin-left: 0; + overflow-wrap: break-word; +} + +.aligned ul label { + display: inline; + float: none; + width: auto; +} + +.aligned .form-row input { + margin-bottom: 0; +} + +.colMS .aligned .vLargeTextField, .colMS .aligned .vXMLLargeTextField { + width: 350px; +} + +form .aligned ul { + margin-left: 160px; + padding-left: 10px; +} + +form .aligned div.radiolist { + display: inline-block; + margin: 0; + padding: 0; +} + +form .aligned p.help, +form .aligned div.help { + margin-top: 0; + margin-left: 160px; + padding-left: 10px; +} + +form .aligned p.date div.help.timezonewarning, +form .aligned p.datetime div.help.timezonewarning, +form .aligned p.time div.help.timezonewarning { + margin-left: 0; + padding-left: 0; + font-weight: normal; +} + +form .aligned p.help:last-child, +form .aligned div.help:last-child { + margin-bottom: 0; + padding-bottom: 0; +} + +form .aligned input + p.help, +form .aligned textarea + p.help, +form .aligned select + p.help, +form .aligned input + div.help, +form .aligned textarea + div.help, +form .aligned select + div.help { + margin-left: 160px; + padding-left: 10px; +} + +form .aligned select option:checked { + background-color: var(--selected-row); +} + +form .aligned ul li { + list-style: none; +} + +form .aligned table p { + margin-left: 0; + padding-left: 0; +} + +.aligned .vCheckboxLabel { + padding: 1px 0 0 5px; +} + +.aligned .vCheckboxLabel + p.help, +.aligned .vCheckboxLabel + div.help { + margin-top: -4px; +} + +.colM .aligned .vLargeTextField, .colM .aligned .vXMLLargeTextField { + width: 610px; +} + +fieldset .fieldBox { + margin-right: 20px; +} + +/* WIDE FIELDSETS */ + +.wide label { + width: 200px; +} + +form .wide p.help, +form .wide ul.errorlist, +form .wide div.help { + padding-left: 50px; +} + +form div.help ul { + padding-left: 0; + margin-left: 0; +} + +.colM fieldset.wide .vLargeTextField, .colM fieldset.wide .vXMLLargeTextField { + width: 450px; +} + +/* COLLAPSIBLE FIELDSETS */ + +.collapse summary .fieldset-heading, +.collapse summary .inline-heading { + background: transparent; + border: none; + color: currentColor; + display: inline; + margin: 0; + padding: 0; +} + +/* MONOSPACE TEXTAREAS */ + +fieldset.monospace textarea { + font-family: var(--font-family-monospace); +} + +/* SUBMIT ROW */ + +.submit-row { + padding: 12px 14px 12px; + margin: 0 0 20px; + background: var(--darkened-bg); + border: 1px solid var(--hairline-color); + border-radius: 4px; + overflow: hidden; + display: flex; + gap: 10px; + flex-wrap: wrap; +} + +body.popup .submit-row { + overflow: auto; +} + +.submit-row input { + height: 2.1875rem; + line-height: 0.9375rem; +} + +.submit-row input, .submit-row a { + margin: 0; +} + +.submit-row input.default { + text-transform: uppercase; +} + +.submit-row a.deletelink { + margin-left: auto; +} + +.submit-row a.deletelink { + display: block; + background: var(--delete-button-bg); + border-radius: 4px; + padding: 0.625rem 0.9375rem; + height: 0.9375rem; + line-height: 0.9375rem; + color: var(--button-fg); +} + +.submit-row a.closelink { + display: inline-block; + background: var(--close-button-bg); + border-radius: 4px; + padding: 10px 15px; + height: 0.9375rem; + line-height: 0.9375rem; + color: var(--button-fg); +} + +.submit-row a.deletelink:focus, +.submit-row a.deletelink:hover, +.submit-row a.deletelink:active { + background: var(--delete-button-hover-bg); + text-decoration: none; +} + +.submit-row a.closelink:focus, +.submit-row a.closelink:hover, +.submit-row a.closelink:active { + background: var(--close-button-hover-bg); + text-decoration: none; +} + +/* CUSTOM FORM FIELDS */ + +.vSelectMultipleField { + vertical-align: top; +} + +.vCheckboxField { + border: none; +} + +.vDateField, .vTimeField { + margin-right: 2px; + margin-bottom: 4px; +} + +.vDateField { + min-width: 6.85em; +} + +.vTimeField { + min-width: 4.7em; +} + +.vURLField { + width: 30em; +} + +.vLargeTextField, .vXMLLargeTextField { + width: 48em; +} + +.flatpages-flatpage #id_content { + height: 40.2em; +} + +.module table .vPositiveSmallIntegerField { + width: 2.2em; +} + +.vIntegerField { + width: 5em; +} + +.vBigIntegerField { + width: 10em; +} + +.vForeignKeyRawIdAdminField { + width: 5em; +} + +.vTextField, .vUUIDField { + width: 20em; +} + +/* INLINES */ + +.inline-group { + padding: 0; + margin: 0 0 30px; +} + +.inline-group thead th { + padding: 8px 10px; +} + +.inline-group .aligned label { + width: 160px; +} + +.inline-related { + position: relative; +} + +.inline-related h4, +.inline-related:not(.tabular) .collapse summary { + margin: 0; + color: var(--body-medium-color); + padding: 5px; + font-size: 0.8125rem; + background: var(--darkened-bg); + border: 1px solid var(--hairline-color); + border-left-color: var(--darkened-bg); + border-right-color: var(--darkened-bg); +} + +.inline-related h3 span.delete { + float: right; +} + +.inline-related h3 span.delete label { + margin-left: 2px; + font-size: 0.6875rem; +} + +.inline-related fieldset { + margin: 0; + background: var(--body-bg); + border: none; + width: 100%; +} + +.inline-group .tabular fieldset.module { + border: none; +} + +.inline-related.tabular fieldset.module table { + width: 100%; + overflow-x: scroll; +} + +.last-related fieldset { + border: none; +} + +.inline-group .tabular tr.has_original td { + padding-top: 2em; +} + +.inline-group .tabular tr td.original { + padding: 2px 0 0 0; + width: 0; + _position: relative; +} + +.inline-group .tabular th.original { + width: 0px; + padding: 0; +} + +.inline-group .tabular td.original p { + position: absolute; + left: 0; + height: 1.1em; + padding: 2px 9px; + overflow: hidden; + font-size: 0.5625rem; + font-weight: bold; + color: var(--body-quiet-color); + _width: 700px; +} + +.inline-group ul.tools { + padding: 0; + margin: 0; + list-style: none; +} + +.inline-group ul.tools li { + display: inline; + padding: 0 5px; +} + +.inline-group div.add-row, +.inline-group .tabular tr.add-row td { + color: var(--body-quiet-color); + background: var(--darkened-bg); + padding: 8px 10px; + border-bottom: 1px solid var(--hairline-color); +} + +.inline-group .tabular tr.add-row td { + padding: 8px 10px; + border-bottom: 1px solid var(--hairline-color); +} + +.inline-group ul.tools a.add, +.inline-group div.add-row a, +.inline-group .tabular tr.add-row td a { + background: url(../img/icon-addlink.svg) 0 1px no-repeat; + padding-left: 16px; + font-size: 0.75rem; +} + +.empty-form { + display: none; +} + +/* RELATED FIELD ADD ONE / LOOKUP */ + +.related-lookup { + margin-left: 5px; + display: inline-block; + vertical-align: middle; + background-repeat: no-repeat; + background-size: 14px; +} + +.related-lookup { + width: 1rem; + height: 1rem; + background-image: url(../img/search.svg); +} + +form .related-widget-wrapper ul { + display: inline-block; + margin-left: 0; + padding-left: 0; +} + +.clearable-file-input input { + margin-top: 0; +} diff --git a/fweb/static/admin/css/login.css b/fweb/static/admin/css/login.css new file mode 100644 index 0000000..805a34b --- /dev/null +++ b/fweb/static/admin/css/login.css @@ -0,0 +1,61 @@ +/* LOGIN FORM */ + +.login { + background: var(--darkened-bg); + height: auto; +} + +.login #header { + height: auto; + padding: 15px 16px; + justify-content: center; +} + +.login #header h1 { + font-size: 1.125rem; + margin: 0; +} + +.login #header h1 a { + color: var(--header-link-color); +} + +.login #content { + padding: 20px; +} + +.login #container { + background: var(--body-bg); + border: 1px solid var(--hairline-color); + border-radius: 4px; + overflow: hidden; + width: 28em; + min-width: 300px; + margin: 100px auto; + height: auto; +} + +.login .form-row { + padding: 4px 0; +} + +.login .form-row label { + display: block; + line-height: 2em; +} + +.login .form-row #id_username, .login .form-row #id_password { + padding: 8px; + width: 100%; + box-sizing: border-box; +} + +.login .submit-row { + padding: 1em 0 0 0; + margin: 0; + text-align: center; +} + +.login .password-reset-link { + text-align: center; +} diff --git a/fweb/static/admin/css/nav_sidebar.css b/fweb/static/admin/css/nav_sidebar.css new file mode 100644 index 0000000..7eb0de9 --- /dev/null +++ b/fweb/static/admin/css/nav_sidebar.css @@ -0,0 +1,150 @@ +.sticky { + position: sticky; + top: 0; + max-height: 100vh; +} + +.toggle-nav-sidebar { + z-index: 20; + left: 0; + display: flex; + align-items: center; + justify-content: center; + flex: 0 0 23px; + width: 23px; + border: 0; + border-right: 1px solid var(--hairline-color); + background-color: var(--body-bg); + cursor: pointer; + font-size: 1.25rem; + color: var(--link-fg); + padding: 0; +} + +[dir="rtl"] .toggle-nav-sidebar { + border-left: 1px solid var(--hairline-color); + border-right: 0; +} + +.toggle-nav-sidebar:hover, +.toggle-nav-sidebar:focus { + background-color: var(--darkened-bg); +} + +#nav-sidebar { + z-index: 15; + flex: 0 0 275px; + left: -276px; + margin-left: -276px; + border-top: 1px solid transparent; + border-right: 1px solid var(--hairline-color); + background-color: var(--body-bg); + overflow: auto; +} + +[dir="rtl"] #nav-sidebar { + border-left: 1px solid var(--hairline-color); + border-right: 0; + left: 0; + margin-left: 0; + right: -276px; + margin-right: -276px; +} + +.toggle-nav-sidebar::before { + content: '\00BB'; +} + +.main.shifted .toggle-nav-sidebar::before { + content: '\00AB'; +} + +.main > #nav-sidebar { + visibility: hidden; +} + +.main.shifted > #nav-sidebar { + margin-left: 0; + visibility: visible; +} + +[dir="rtl"] .main.shifted > #nav-sidebar { + margin-right: 0; +} + +#nav-sidebar .module th { + width: 100%; + overflow-wrap: anywhere; +} + +#nav-sidebar .module th, +#nav-sidebar .module caption { + padding-left: 16px; +} + +#nav-sidebar .module td { + white-space: nowrap; +} + +[dir="rtl"] #nav-sidebar .module th, +[dir="rtl"] #nav-sidebar .module caption { + padding-left: 8px; + padding-right: 16px; +} + +#nav-sidebar .current-app .section:link, +#nav-sidebar .current-app .section:visited { + color: var(--header-color); + font-weight: bold; +} + +#nav-sidebar .current-model { + background: var(--selected-row); +} + +@media (forced-colors: active) { + #nav-sidebar .current-model { + background-color: SelectedItem; + } +} + +.main > #nav-sidebar + .content { + max-width: calc(100% - 23px); +} + +.main.shifted > #nav-sidebar + .content { + max-width: calc(100% - 299px); +} + +@media (max-width: 767px) { + #nav-sidebar, #toggle-nav-sidebar { + display: none; + } + + .main > #nav-sidebar + .content, + .main.shifted > #nav-sidebar + .content { + max-width: 100%; + } +} + +#nav-filter { + width: 100%; + box-sizing: border-box; + padding: 2px 5px; + margin: 5px 0; + border: 1px solid var(--border-color); + background-color: var(--darkened-bg); + color: var(--body-fg); +} + +#nav-filter:focus { + border-color: var(--body-quiet-color); +} + +#nav-filter.no-results { + background: var(--message-error-bg); +} + +#nav-sidebar table { + width: 100%; +} diff --git a/fweb/static/admin/css/responsive.css b/fweb/static/admin/css/responsive.css new file mode 100644 index 0000000..932e824 --- /dev/null +++ b/fweb/static/admin/css/responsive.css @@ -0,0 +1,967 @@ +/* Tablets */ + +input[type="submit"], button { + -webkit-appearance: none; + appearance: none; +} + +@media (max-width: 1024px) { + /* Basic */ + + html { + -webkit-text-size-adjust: 100%; + } + + td, th { + padding: 10px; + font-size: 0.875rem; + } + + .small { + font-size: 0.75rem; + } + + /* Layout */ + + #container { + min-width: 0; + } + + #content { + padding: 15px 20px 20px; + } + + div.breadcrumbs { + padding: 10px 30px; + } + + /* Header */ + + #header { + flex-direction: column; + padding: 15px 30px; + justify-content: flex-start; + } + + #site-name { + margin: 0 0 8px; + line-height: 1.2; + } + + #user-tools { + margin: 0; + font-weight: 400; + line-height: 1.85; + text-align: left; + } + + #user-tools a { + display: inline-block; + line-height: 1.4; + } + + /* Dashboard */ + + .dashboard #content { + width: auto; + } + + #content-related { + margin-right: -290px; + } + + .colSM #content-related { + margin-left: -290px; + } + + .colMS { + margin-right: 290px; + } + + .colSM { + margin-left: 290px; + } + + .dashboard .module table td a { + padding-right: 0; + } + + td .changelink, td .addlink { + font-size: 0.8125rem; + } + + /* Changelist */ + + #toolbar { + border: none; + padding: 15px; + } + + #changelist-search > div { + display: flex; + flex-wrap: nowrap; + max-width: 480px; + } + + #changelist-search label { + line-height: 1.375rem; + } + + #toolbar form #searchbar { + flex: 1 0 auto; + width: 0; + height: 1.375rem; + margin: 0 10px 0 6px; + } + + #toolbar form input[type=submit] { + flex: 0 1 auto; + } + + #changelist-search .quiet { + width: 0; + flex: 1 0 auto; + margin: 5px 0 0 25px; + } + + #changelist .actions { + display: flex; + flex-wrap: wrap; + padding: 15px 0; + } + + #changelist .actions label { + display: flex; + } + + #changelist .actions select { + background: var(--body-bg); + } + + #changelist .actions .button { + min-width: 48px; + margin: 0 10px; + } + + #changelist .actions span.all, + #changelist .actions span.clear, + #changelist .actions span.question, + #changelist .actions span.action-counter { + font-size: 0.6875rem; + margin: 0 10px 0 0; + } + + #changelist-filter { + flex-basis: 200px; + } + + .change-list .filtered .results, + .change-list .filtered .paginator, + .filtered #toolbar, + .filtered .actions, + + #changelist .paginator { + border-top-color: var(--hairline-color); /* XXX Is this used at all? */ + } + + #changelist .results + .paginator { + border-top: none; + } + + /* Forms */ + + label { + font-size: 1rem; + } + + /* + Minifiers remove the default (text) "type" attribute from "input" HTML + tags. Add input:not([type]) to make the CSS stylesheet work the same. + */ + .form-row input:not([type]), + .form-row input[type=text], + .form-row input[type=password], + .form-row input[type=email], + .form-row input[type=url], + .form-row input[type=tel], + .form-row input[type=number], + .form-row textarea, + .form-row select, + .form-row .vTextField { + box-sizing: border-box; + margin: 0; + padding: 6px 8px; + min-height: 2.25rem; + font-size: 1rem; + } + + .form-row select { + height: 2.25rem; + } + + .form-row select[multiple] { + height: auto; + min-height: 0; + } + + fieldset .fieldBox + .fieldBox { + margin-top: 10px; + padding-top: 10px; + border-top: 1px solid var(--hairline-color); + } + + textarea { + max-width: 100%; + max-height: 120px; + } + + .aligned label { + padding-top: 6px; + } + + .aligned .related-lookup, + .aligned .datetimeshortcuts, + .aligned .related-lookup + strong { + align-self: center; + margin-left: 15px; + } + + form .aligned div.radiolist { + margin-left: 2px; + } + + .submit-row { + padding: 8px; + } + + .submit-row a.deletelink { + padding: 10px 7px; + } + + .button, input[type=submit], input[type=button], .submit-row input, a.button { + padding: 7px; + } + + /* Selector */ + + .selector { + display: flex; + width: 100%; + } + + .selector .selector-filter { + display: flex; + align-items: center; + } + + .selector .selector-filter label { + margin: 0 8px 0 0; + } + + .selector .selector-filter input { + width: 100%; + min-height: 0; + flex: 1 1; + } + + .selector-available, .selector-chosen { + width: auto; + flex: 1 1; + display: flex; + flex-direction: column; + } + + .selector select { + width: 100%; + flex: 1 0 auto; + margin-bottom: 5px; + } + + .selector ul.selector-chooser { + width: 26px; + height: 52px; + padding: 2px 0; + border-radius: 20px; + transform: translateY(-10px); + } + + .selector-add, .selector-remove { + width: 20px; + height: 20px; + background-size: 20px auto; + } + + .selector-add { + background-position: 0 -120px; + } + + .selector-remove { + background-position: 0 -80px; + } + + a.selector-chooseall, a.selector-clearall { + align-self: center; + } + + .stacked { + flex-direction: column; + max-width: 480px; + } + + .stacked > * { + flex: 0 1 auto; + } + + .stacked select { + margin-bottom: 0; + } + + .stacked .selector-available, .stacked .selector-chosen { + width: auto; + } + + .stacked ul.selector-chooser { + width: 52px; + height: 26px; + padding: 0 2px; + transform: none; + } + + .stacked .selector-chooser li { + padding: 3px; + } + + .stacked .selector-add, .stacked .selector-remove { + background-size: 20px auto; + } + + .stacked .selector-add { + background-position: 0 -40px; + } + + .stacked .active.selector-add { + background-position: 0 -40px; + } + + .active.selector-add:focus, .active.selector-add:hover { + background-position: 0 -140px; + } + + .stacked .active.selector-add:focus, .stacked .active.selector-add:hover { + background-position: 0 -60px; + } + + .stacked .selector-remove { + background-position: 0 0; + } + + .stacked .active.selector-remove { + background-position: 0 0; + } + + .active.selector-remove:focus, .active.selector-remove:hover { + background-position: 0 -100px; + } + + .stacked .active.selector-remove:focus, .stacked .active.selector-remove:hover { + background-position: 0 -20px; + } + + .help-tooltip, .selector .help-icon { + display: none; + } + + .datetime input { + width: 50%; + max-width: 120px; + } + + .datetime span { + font-size: 0.8125rem; + } + + .datetime .timezonewarning { + display: block; + font-size: 0.6875rem; + color: var(--body-quiet-color); + } + + .datetimeshortcuts { + color: var(--border-color); /* XXX Redundant, .datetime span also sets #ccc */ + } + + .form-row .datetime input.vDateField, .form-row .datetime input.vTimeField { + width: 75%; + } + + .inline-group { + overflow: auto; + } + + /* Messages */ + + ul.messagelist li { + padding-left: 55px; + background-position: 30px 12px; + } + + ul.messagelist li.error { + background-position: 30px 12px; + } + + ul.messagelist li.warning { + background-position: 30px 14px; + } + + /* Login */ + + .login #header { + padding: 15px 20px; + } + + .login #site-name { + margin: 0; + } + + /* GIS */ + + div.olMap { + max-width: calc(100vw - 30px); + max-height: 300px; + } + + .olMap + .clear_features { + display: block; + margin-top: 10px; + } + + /* Docs */ + + .module table.xfull { + width: 100%; + } + + pre.literal-block { + overflow: auto; + } +} + +/* Mobile */ + +@media (max-width: 767px) { + /* Layout */ + + #header, #content { + padding: 15px; + } + + div.breadcrumbs { + padding: 10px 15px; + } + + /* Dashboard */ + + .colMS, .colSM { + margin: 0; + } + + #content-related, .colSM #content-related { + width: 100%; + margin: 0; + } + + #content-related .module { + margin-bottom: 0; + } + + #content-related .module h2 { + padding: 10px 15px; + font-size: 1rem; + } + + /* Changelist */ + + #changelist { + align-items: stretch; + flex-direction: column; + } + + #toolbar { + padding: 10px; + } + + #changelist-filter { + margin-left: 0; + } + + #changelist .actions label { + flex: 1 1; + } + + #changelist .actions select { + flex: 1 0; + width: 100%; + } + + #changelist .actions span { + flex: 1 0 100%; + } + + #changelist-filter { + position: static; + width: auto; + margin-top: 30px; + } + + .object-tools { + float: none; + margin: 0 0 15px; + padding: 0; + overflow: hidden; + } + + .object-tools li { + height: auto; + margin-left: 0; + } + + .object-tools li + li { + margin-left: 15px; + } + + /* Forms */ + + .form-row { + padding: 15px 0; + } + + .aligned .form-row, + .aligned .form-row > div { + max-width: 100vw; + } + + .aligned .form-row > div { + width: calc(100vw - 30px); + } + + .flex-container { + flex-flow: column; + } + + .flex-container.checkbox-row { + flex-flow: row; + } + + textarea { + max-width: none; + } + + .vURLField { + width: auto; + } + + fieldset .fieldBox + .fieldBox { + margin-top: 15px; + padding-top: 15px; + } + + .aligned label { + width: 100%; + min-width: auto; + padding: 0 0 10px; + } + + .aligned label:after { + max-height: 0; + } + + .aligned .form-row input, + .aligned .form-row select, + .aligned .form-row textarea { + flex: 1 1 auto; + max-width: 100%; + } + + .aligned .checkbox-row input { + flex: 0 1 auto; + margin: 0; + } + + .aligned .vCheckboxLabel { + flex: 1 0; + padding: 1px 0 0 5px; + } + + .aligned label + p, + .aligned label + div.help, + .aligned label + div.readonly { + padding: 0; + margin-left: 0; + } + + .aligned p.file-upload { + font-size: 0.8125rem; + } + + span.clearable-file-input { + margin-left: 15px; + } + + span.clearable-file-input label { + font-size: 0.8125rem; + padding-bottom: 0; + } + + .aligned .timezonewarning { + flex: 1 0 100%; + margin-top: 5px; + } + + form .aligned .form-row div.help { + width: 100%; + margin: 5px 0 0; + padding: 0; + } + + form .aligned ul, + form .aligned ul.errorlist { + margin-left: 0; + padding-left: 0; + } + + form .aligned div.radiolist { + margin-top: 5px; + margin-right: 15px; + margin-bottom: -3px; + } + + form .aligned div.radiolist:not(.inline) div + div { + margin-top: 5px; + } + + /* Related widget */ + + .related-widget-wrapper { + width: 100%; + display: flex; + align-items: flex-start; + } + + .related-widget-wrapper .selector { + order: 1; + } + + .related-widget-wrapper > a { + order: 2; + } + + .related-widget-wrapper .radiolist ~ a { + align-self: flex-end; + } + + .related-widget-wrapper > select ~ a { + align-self: center; + } + + /* Selector */ + + .selector { + flex-direction: column; + gap: 10px 0; + } + + .selector-available, .selector-chosen { + flex: 1 1 auto; + } + + .selector select { + max-height: 96px; + } + + .selector ul.selector-chooser { + display: block; + width: 52px; + height: 26px; + padding: 0 2px; + transform: none; + } + + .selector ul.selector-chooser li { + float: left; + } + + .selector-remove { + background-position: 0 0; + } + + .active.selector-remove:focus, .active.selector-remove:hover { + background-position: 0 -20px; + } + + .selector-add { + background-position: 0 -40px; + } + + .active.selector-add:focus, .active.selector-add:hover { + background-position: 0 -60px; + } + + /* Inlines */ + + .inline-group[data-inline-type="stacked"] .inline-related { + border: 1px solid var(--hairline-color); + border-radius: 4px; + margin-top: 15px; + overflow: auto; + } + + .inline-group[data-inline-type="stacked"] .inline-related > * { + box-sizing: border-box; + } + + .inline-group[data-inline-type="stacked"] .inline-related .module { + padding: 0 10px; + } + + .inline-group[data-inline-type="stacked"] .inline-related .module .form-row { + border-top: 1px solid var(--hairline-color); + border-bottom: none; + } + + .inline-group[data-inline-type="stacked"] .inline-related .module .form-row:first-child { + border-top: none; + } + + .inline-group[data-inline-type="stacked"] .inline-related h3 { + padding: 10px; + border-top-width: 0; + border-bottom-width: 2px; + display: flex; + flex-wrap: wrap; + align-items: center; + } + + .inline-group[data-inline-type="stacked"] .inline-related h3 .inline_label { + margin-right: auto; + } + + .inline-group[data-inline-type="stacked"] .inline-related h3 span.delete { + float: none; + flex: 1 1 100%; + margin-top: 5px; + } + + .inline-group[data-inline-type="stacked"] .aligned .form-row > div:not([class]) { + width: 100%; + } + + .inline-group[data-inline-type="stacked"] .aligned label { + width: 100%; + } + + .inline-group[data-inline-type="stacked"] div.add-row { + margin-top: 15px; + border: 1px solid var(--hairline-color); + border-radius: 4px; + } + + .inline-group div.add-row, + .inline-group .tabular tr.add-row td { + padding: 0; + } + + .inline-group div.add-row a, + .inline-group .tabular tr.add-row td a { + display: block; + padding: 8px 10px 8px 26px; + background-position: 8px 9px; + } + + /* Submit row */ + + .submit-row { + padding: 10px; + margin: 0 0 15px; + flex-direction: column; + gap: 8px; + } + + .submit-row input, .submit-row input.default, .submit-row a { + text-align: center; + } + + .submit-row a.closelink { + padding: 10px 0; + text-align: center; + } + + .submit-row a.deletelink { + margin: 0; + } + + /* Messages */ + + ul.messagelist li { + padding-left: 40px; + background-position: 15px 12px; + } + + ul.messagelist li.error { + background-position: 15px 12px; + } + + ul.messagelist li.warning { + background-position: 15px 14px; + } + + /* Paginator */ + + .paginator .this-page, .paginator a:link, .paginator a:visited { + padding: 4px 10px; + } + + /* Login */ + + body.login { + padding: 0 15px; + } + + .login #container { + width: auto; + max-width: 480px; + margin: 50px auto; + } + + .login #header, + .login #content { + padding: 15px; + } + + .login #content-main { + float: none; + } + + .login .form-row { + padding: 0; + } + + .login .form-row + .form-row { + margin-top: 15px; + } + + .login .form-row label { + margin: 0 0 5px; + line-height: 1.2; + } + + .login .submit-row { + padding: 15px 0 0; + } + + .login br { + display: none; + } + + .login .submit-row input { + margin: 0; + text-transform: uppercase; + } + + .errornote { + margin: 0 0 20px; + padding: 8px 12px; + font-size: 0.8125rem; + } + + /* Calendar and clock */ + + .calendarbox, .clockbox { + position: fixed !important; + top: 50% !important; + left: 50% !important; + transform: translate(-50%, -50%); + margin: 0; + border: none; + overflow: visible; + } + + .calendarbox:before, .clockbox:before { + content: ''; + position: fixed; + top: 50%; + left: 50%; + width: 100vw; + height: 100vh; + background: rgba(0, 0, 0, 0.75); + transform: translate(-50%, -50%); + } + + .calendarbox > *, .clockbox > * { + position: relative; + z-index: 1; + } + + .calendarbox > div:first-child { + z-index: 2; + } + + .calendarbox .calendar, .clockbox h2 { + border-radius: 4px 4px 0 0; + overflow: hidden; + } + + .calendarbox .calendar-cancel, .clockbox .calendar-cancel { + border-radius: 0 0 4px 4px; + overflow: hidden; + } + + .calendar-shortcuts { + padding: 10px 0; + font-size: 0.75rem; + line-height: 0.75rem; + } + + .calendar-shortcuts a { + margin: 0 4px; + } + + .timelist a { + background: var(--body-bg); + padding: 4px; + } + + .calendar-cancel { + padding: 8px 10px; + } + + .clockbox h2 { + padding: 8px 15px; + } + + .calendar caption { + padding: 10px; + } + + .calendarbox .calendarnav-previous, .calendarbox .calendarnav-next { + z-index: 1; + top: 10px; + } + + /* History */ + + table#change-history tbody th, table#change-history tbody td { + font-size: 0.8125rem; + word-break: break-word; + } + + table#change-history tbody th { + width: auto; + } + + /* Docs */ + + table.model tbody th, table.model tbody td { + font-size: 0.8125rem; + word-break: break-word; + } +} diff --git a/fweb/static/admin/css/responsive_rtl.css b/fweb/static/admin/css/responsive_rtl.css new file mode 100644 index 0000000..33b5784 --- /dev/null +++ b/fweb/static/admin/css/responsive_rtl.css @@ -0,0 +1,111 @@ +/* TABLETS */ + +@media (max-width: 1024px) { + [dir="rtl"] .colMS { + margin-right: 0; + } + + [dir="rtl"] #user-tools { + text-align: right; + } + + [dir="rtl"] #changelist .actions label { + padding-left: 10px; + padding-right: 0; + } + + [dir="rtl"] #changelist .actions select { + margin-left: 0; + margin-right: 15px; + } + + [dir="rtl"] .change-list .filtered .results, + [dir="rtl"] .change-list .filtered .paginator, + [dir="rtl"] .filtered #toolbar, + [dir="rtl"] .filtered div.xfull, + [dir="rtl"] .filtered .actions, + [dir="rtl"] #changelist-filter { + margin-left: 0; + } + + [dir="rtl"] .inline-group ul.tools a.add, + [dir="rtl"] .inline-group div.add-row a, + [dir="rtl"] .inline-group .tabular tr.add-row td a { + padding: 8px 26px 8px 10px; + background-position: calc(100% - 8px) 9px; + } + + [dir="rtl"] .selector .selector-filter label { + margin-right: 0; + margin-left: 8px; + } + + [dir="rtl"] .object-tools li { + float: right; + } + + [dir="rtl"] .object-tools li + li { + margin-left: 0; + margin-right: 15px; + } + + [dir="rtl"] .dashboard .module table td a { + padding-left: 0; + padding-right: 16px; + } + + [dir="rtl"] .selector-add { + background-position: 0 -80px; + } + + [dir="rtl"] .selector-remove { + background-position: 0 -120px; + } + + [dir="rtl"] .active.selector-add:focus, .active.selector-add:hover { + background-position: 0 -100px; + } + + [dir="rtl"] .active.selector-remove:focus, .active.selector-remove:hover { + background-position: 0 -140px; + } +} + +/* MOBILE */ + +@media (max-width: 767px) { + [dir="rtl"] .aligned .related-lookup, + [dir="rtl"] .aligned .datetimeshortcuts { + margin-left: 0; + margin-right: 15px; + } + + [dir="rtl"] .aligned ul, + [dir="rtl"] form .aligned ul.errorlist { + margin-right: 0; + } + + [dir="rtl"] #changelist-filter { + margin-left: 0; + margin-right: 0; + } + [dir="rtl"] .aligned .vCheckboxLabel { + padding: 1px 5px 0 0; + } + + [dir="rtl"] .selector-remove { + background-position: 0 0; + } + + [dir="rtl"] .active.selector-remove:focus, .active.selector-remove:hover { + background-position: 0 -20px; + } + + [dir="rtl"] .selector-add { + background-position: 0 -40px; + } + + [dir="rtl"] .active.selector-add:focus, .active.selector-add:hover { + background-position: 0 -60px; + } +} diff --git a/fweb/static/admin/css/rtl.css b/fweb/static/admin/css/rtl.css new file mode 100644 index 0000000..b8f60e0 --- /dev/null +++ b/fweb/static/admin/css/rtl.css @@ -0,0 +1,291 @@ +/* GLOBAL */ + +th { + text-align: right; +} + +.module h2, .module caption { + text-align: right; +} + +.module ul, .module ol { + margin-left: 0; + margin-right: 1.5em; +} + +.viewlink, .addlink, .changelink, .hidelink { + padding-left: 0; + padding-right: 16px; + background-position: 100% 1px; +} + +.deletelink { + padding-left: 0; + padding-right: 16px; + background-position: 100% 1px; +} + +.object-tools { + float: left; +} + +thead th:first-child, +tfoot td:first-child { + border-left: none; +} + +/* LAYOUT */ + +#user-tools { + right: auto; + left: 0; + text-align: left; +} + +div.breadcrumbs { + text-align: right; +} + +#content-main { + float: right; +} + +#content-related { + float: left; + margin-left: -300px; + margin-right: auto; +} + +.colMS { + margin-left: 300px; + margin-right: 0; +} + +/* SORTABLE TABLES */ + +table thead th.sorted .sortoptions { + float: left; +} + +thead th.sorted .text { + padding-right: 0; + padding-left: 42px; +} + +/* dashboard styles */ + +.dashboard .module table td a { + padding-left: .6em; + padding-right: 16px; +} + +/* changelists styles */ + +.change-list .filtered table { + border-left: none; + border-right: 0px none; +} + +#changelist-filter { + border-left: none; + border-right: none; + margin-left: 0; + margin-right: 30px; +} + +#changelist-filter li.selected { + border-left: none; + padding-left: 10px; + margin-left: 0; + border-right: 5px solid var(--hairline-color); + padding-right: 10px; + margin-right: -15px; +} + +#changelist table tbody td:first-child, #changelist table tbody th:first-child { + border-right: none; + border-left: none; +} + +.paginator .end { + margin-left: 6px; + margin-right: 0; +} + +.paginator input { + margin-left: 0; + margin-right: auto; +} + +/* FORMS */ + +.aligned label { + padding: 0 0 3px 1em; +} + +.submit-row a.deletelink { + margin-left: 0; + margin-right: auto; +} + +.vDateField, .vTimeField { + margin-left: 2px; +} + +.aligned .form-row input { + margin-left: 5px; +} + +form .aligned ul { + margin-right: 163px; + padding-right: 10px; + margin-left: 0; + padding-left: 0; +} + +form ul.inline li { + float: right; + padding-right: 0; + padding-left: 7px; +} + +form .aligned p.help, +form .aligned div.help { + margin-left: 0; + margin-right: 160px; + padding-right: 10px; +} + +form div.help ul, +form .aligned .checkbox-row + .help, +form .aligned p.date div.help.timezonewarning, +form .aligned p.datetime div.help.timezonewarning, +form .aligned p.time div.help.timezonewarning { + margin-right: 0; + padding-right: 0; +} + +form .wide p.help, +form .wide ul.errorlist, +form .wide div.help { + padding-left: 0; + padding-right: 50px; +} + +.submit-row { + text-align: right; +} + +fieldset .fieldBox { + margin-left: 20px; + margin-right: 0; +} + +.errorlist li { + background-position: 100% 12px; + padding: 0; +} + +.errornote { + background-position: 100% 12px; + padding: 10px 12px; +} + +/* WIDGETS */ + +.calendarnav-previous { + top: 0; + left: auto; + right: 10px; + background: url(../img/calendar-icons.svg) 0 -15px no-repeat; +} + +.calendarnav-next { + top: 0; + right: auto; + left: 10px; + background: url(../img/calendar-icons.svg) 0 0 no-repeat; +} + +.calendar caption, .calendarbox h2 { + text-align: center; +} + +.selector { + float: right; +} + +.selector .selector-filter { + text-align: right; +} + +.selector-add { + background: url(../img/selector-icons.svg) 0 -64px no-repeat; +} + +.active.selector-add:focus, .active.selector-add:hover { + background-position: 0 -80px; +} + +.selector-remove { + background: url(../img/selector-icons.svg) 0 -96px no-repeat; +} + +.active.selector-remove:focus, .active.selector-remove:hover { + background-position: 0 -112px; +} + +a.selector-chooseall { + background: url(../img/selector-icons.svg) right -128px no-repeat; +} + +a.active.selector-chooseall:focus, a.active.selector-chooseall:hover { + background-position: 100% -144px; +} + +a.selector-clearall { + background: url(../img/selector-icons.svg) 0 -160px no-repeat; +} + +a.active.selector-clearall:focus, a.active.selector-clearall:hover { + background-position: 0 -176px; +} + +.inline-deletelink { + float: left; +} + +form .form-row p.datetime { + overflow: hidden; +} + +.related-widget-wrapper { + float: right; +} + +/* MISC */ + +.inline-related h2, .inline-group h2 { + text-align: right +} + +.inline-related h3 span.delete { + padding-right: 20px; + padding-left: inherit; + left: 10px; + right: inherit; + float:left; +} + +.inline-related h3 span.delete label { + margin-left: inherit; + margin-right: 2px; +} + +.inline-group .tabular td.original p { + right: 0; +} + +.selector .selector-chooser { + margin: 0; +} diff --git a/fweb/static/admin/css/unusable_password_field.css b/fweb/static/admin/css/unusable_password_field.css new file mode 100644 index 0000000..d46eb03 --- /dev/null +++ b/fweb/static/admin/css/unusable_password_field.css @@ -0,0 +1,19 @@ +/* Hide warnings fields if usable password is selected */ +form:has(#id_usable_password input[value="true"]:checked) .messagelist { + display: none; +} + +/* Hide password fields if unusable password is selected */ +form:has(#id_usable_password input[value="false"]:checked) .field-password1, +form:has(#id_usable_password input[value="false"]:checked) .field-password2 { + display: none; +} + +/* Select appropriate submit button */ +form:has(#id_usable_password input[value="true"]:checked) input[type="submit"].unset-password { + display: none; +} + +form:has(#id_usable_password input[value="false"]:checked) input[type="submit"].set-password { + display: none; +} diff --git a/fweb/static/admin/css/vendor/select2/LICENSE-SELECT2.md b/fweb/static/admin/css/vendor/select2/LICENSE-SELECT2.md new file mode 100644 index 0000000..8cb8a2b --- /dev/null +++ b/fweb/static/admin/css/vendor/select2/LICENSE-SELECT2.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2012-2017 Kevin Brown, Igor Vaynberg, and Select2 contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/fweb/static/admin/css/vendor/select2/select2.css b/fweb/static/admin/css/vendor/select2/select2.css new file mode 100644 index 0000000..750b320 --- /dev/null +++ b/fweb/static/admin/css/vendor/select2/select2.css @@ -0,0 +1,481 @@ +.select2-container { + box-sizing: border-box; + display: inline-block; + margin: 0; + position: relative; + vertical-align: middle; } + .select2-container .select2-selection--single { + box-sizing: border-box; + cursor: pointer; + display: block; + height: 28px; + user-select: none; + -webkit-user-select: none; } + .select2-container .select2-selection--single .select2-selection__rendered { + display: block; + padding-left: 8px; + padding-right: 20px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; } + .select2-container .select2-selection--single .select2-selection__clear { + position: relative; } + .select2-container[dir="rtl"] .select2-selection--single .select2-selection__rendered { + padding-right: 8px; + padding-left: 20px; } + .select2-container .select2-selection--multiple { + box-sizing: border-box; + cursor: pointer; + display: block; + min-height: 32px; + user-select: none; + -webkit-user-select: none; } + .select2-container .select2-selection--multiple .select2-selection__rendered { + display: inline-block; + overflow: hidden; + padding-left: 8px; + text-overflow: ellipsis; + white-space: nowrap; } + .select2-container .select2-search--inline { + float: left; } + .select2-container .select2-search--inline .select2-search__field { + box-sizing: border-box; + border: none; + font-size: 100%; + margin-top: 5px; + padding: 0; } + .select2-container .select2-search--inline .select2-search__field::-webkit-search-cancel-button { + -webkit-appearance: none; } + +.select2-dropdown { + background-color: white; + border: 1px solid #aaa; + border-radius: 4px; + box-sizing: border-box; + display: block; + position: absolute; + left: -100000px; + width: 100%; + z-index: 1051; } + +.select2-results { + display: block; } + +.select2-results__options { + list-style: none; + margin: 0; + padding: 0; } + +.select2-results__option { + padding: 6px; + user-select: none; + -webkit-user-select: none; } + .select2-results__option[aria-selected] { + cursor: pointer; } + +.select2-container--open .select2-dropdown { + left: 0; } + +.select2-container--open .select2-dropdown--above { + border-bottom: none; + border-bottom-left-radius: 0; + border-bottom-right-radius: 0; } + +.select2-container--open .select2-dropdown--below { + border-top: none; + border-top-left-radius: 0; + border-top-right-radius: 0; } + +.select2-search--dropdown { + display: block; + padding: 4px; } + .select2-search--dropdown .select2-search__field { + padding: 4px; + width: 100%; + box-sizing: border-box; } + .select2-search--dropdown .select2-search__field::-webkit-search-cancel-button { + -webkit-appearance: none; } + .select2-search--dropdown.select2-search--hide { + display: none; } + +.select2-close-mask { + border: 0; + margin: 0; + padding: 0; + display: block; + position: fixed; + left: 0; + top: 0; + min-height: 100%; + min-width: 100%; + height: auto; + width: auto; + opacity: 0; + z-index: 99; + background-color: #fff; + filter: alpha(opacity=0); } + +.select2-hidden-accessible { + border: 0 !important; + clip: rect(0 0 0 0) !important; + -webkit-clip-path: inset(50%) !important; + clip-path: inset(50%) !important; + height: 1px !important; + overflow: hidden !important; + padding: 0 !important; + position: absolute !important; + width: 1px !important; + white-space: nowrap !important; } + +.select2-container--default .select2-selection--single { + background-color: #fff; + border: 1px solid #aaa; + border-radius: 4px; } + .select2-container--default .select2-selection--single .select2-selection__rendered { + color: #444; + line-height: 28px; } + .select2-container--default .select2-selection--single .select2-selection__clear { + cursor: pointer; + float: right; + font-weight: bold; } + .select2-container--default .select2-selection--single .select2-selection__placeholder { + color: #999; } + .select2-container--default .select2-selection--single .select2-selection__arrow { + height: 26px; + position: absolute; + top: 1px; + right: 1px; + width: 20px; } + .select2-container--default .select2-selection--single .select2-selection__arrow b { + border-color: #888 transparent transparent transparent; + border-style: solid; + border-width: 5px 4px 0 4px; + height: 0; + left: 50%; + margin-left: -4px; + margin-top: -2px; + position: absolute; + top: 50%; + width: 0; } + +.select2-container--default[dir="rtl"] .select2-selection--single .select2-selection__clear { + float: left; } + +.select2-container--default[dir="rtl"] .select2-selection--single .select2-selection__arrow { + left: 1px; + right: auto; } + +.select2-container--default.select2-container--disabled .select2-selection--single { + background-color: #eee; + cursor: default; } + .select2-container--default.select2-container--disabled .select2-selection--single .select2-selection__clear { + display: none; } + +.select2-container--default.select2-container--open .select2-selection--single .select2-selection__arrow b { + border-color: transparent transparent #888 transparent; + border-width: 0 4px 5px 4px; } + +.select2-container--default .select2-selection--multiple { + background-color: white; + border: 1px solid #aaa; + border-radius: 4px; + cursor: text; } + .select2-container--default .select2-selection--multiple .select2-selection__rendered { + box-sizing: border-box; + list-style: none; + margin: 0; + padding: 0 5px; + width: 100%; } + .select2-container--default .select2-selection--multiple .select2-selection__rendered li { + list-style: none; } + .select2-container--default .select2-selection--multiple .select2-selection__clear { + cursor: pointer; + float: right; + font-weight: bold; + margin-top: 5px; + margin-right: 10px; + padding: 1px; } + .select2-container--default .select2-selection--multiple .select2-selection__choice { + background-color: #e4e4e4; + border: 1px solid #aaa; + border-radius: 4px; + cursor: default; + float: left; + margin-right: 5px; + margin-top: 5px; + padding: 0 5px; } + .select2-container--default .select2-selection--multiple .select2-selection__choice__remove { + color: #999; + cursor: pointer; + display: inline-block; + font-weight: bold; + margin-right: 2px; } + .select2-container--default .select2-selection--multiple .select2-selection__choice__remove:hover { + color: #333; } + +.select2-container--default[dir="rtl"] .select2-selection--multiple .select2-selection__choice, .select2-container--default[dir="rtl"] .select2-selection--multiple .select2-search--inline { + float: right; } + +.select2-container--default[dir="rtl"] .select2-selection--multiple .select2-selection__choice { + margin-left: 5px; + margin-right: auto; } + +.select2-container--default[dir="rtl"] .select2-selection--multiple .select2-selection__choice__remove { + margin-left: 2px; + margin-right: auto; } + +.select2-container--default.select2-container--focus .select2-selection--multiple { + border: solid black 1px; + outline: 0; } + +.select2-container--default.select2-container--disabled .select2-selection--multiple { + background-color: #eee; + cursor: default; } + +.select2-container--default.select2-container--disabled .select2-selection__choice__remove { + display: none; } + +.select2-container--default.select2-container--open.select2-container--above .select2-selection--single, .select2-container--default.select2-container--open.select2-container--above .select2-selection--multiple { + border-top-left-radius: 0; + border-top-right-radius: 0; } + +.select2-container--default.select2-container--open.select2-container--below .select2-selection--single, .select2-container--default.select2-container--open.select2-container--below .select2-selection--multiple { + border-bottom-left-radius: 0; + border-bottom-right-radius: 0; } + +.select2-container--default .select2-search--dropdown .select2-search__field { + border: 1px solid #aaa; } + +.select2-container--default .select2-search--inline .select2-search__field { + background: transparent; + border: none; + outline: 0; + box-shadow: none; + -webkit-appearance: textfield; } + +.select2-container--default .select2-results > .select2-results__options { + max-height: 200px; + overflow-y: auto; } + +.select2-container--default .select2-results__option[role=group] { + padding: 0; } + +.select2-container--default .select2-results__option[aria-disabled=true] { + color: #999; } + +.select2-container--default .select2-results__option[aria-selected=true] { + background-color: #ddd; } + +.select2-container--default .select2-results__option .select2-results__option { + padding-left: 1em; } + .select2-container--default .select2-results__option .select2-results__option .select2-results__group { + padding-left: 0; } + .select2-container--default .select2-results__option .select2-results__option .select2-results__option { + margin-left: -1em; + padding-left: 2em; } + .select2-container--default .select2-results__option .select2-results__option .select2-results__option .select2-results__option { + margin-left: -2em; + padding-left: 3em; } + .select2-container--default .select2-results__option .select2-results__option .select2-results__option .select2-results__option .select2-results__option { + margin-left: -3em; + padding-left: 4em; } + .select2-container--default .select2-results__option .select2-results__option .select2-results__option .select2-results__option .select2-results__option .select2-results__option { + margin-left: -4em; + padding-left: 5em; } + .select2-container--default .select2-results__option .select2-results__option .select2-results__option .select2-results__option .select2-results__option .select2-results__option .select2-results__option { + margin-left: -5em; + padding-left: 6em; } + +.select2-container--default .select2-results__option--highlighted[aria-selected] { + background-color: #5897fb; + color: white; } + +.select2-container--default .select2-results__group { + cursor: default; + display: block; + padding: 6px; } + +.select2-container--classic .select2-selection--single { + background-color: #f7f7f7; + border: 1px solid #aaa; + border-radius: 4px; + outline: 0; + background-image: -webkit-linear-gradient(top, white 50%, #eeeeee 100%); + background-image: -o-linear-gradient(top, white 50%, #eeeeee 100%); + background-image: linear-gradient(to bottom, white 50%, #eeeeee 100%); + background-repeat: repeat-x; + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#FFFFFFFF', endColorstr='#FFEEEEEE', GradientType=0); } + .select2-container--classic .select2-selection--single:focus { + border: 1px solid #5897fb; } + .select2-container--classic .select2-selection--single .select2-selection__rendered { + color: #444; + line-height: 28px; } + .select2-container--classic .select2-selection--single .select2-selection__clear { + cursor: pointer; + float: right; + font-weight: bold; + margin-right: 10px; } + .select2-container--classic .select2-selection--single .select2-selection__placeholder { + color: #999; } + .select2-container--classic .select2-selection--single .select2-selection__arrow { + background-color: #ddd; + border: none; + border-left: 1px solid #aaa; + border-top-right-radius: 4px; + border-bottom-right-radius: 4px; + height: 26px; + position: absolute; + top: 1px; + right: 1px; + width: 20px; + background-image: -webkit-linear-gradient(top, #eeeeee 50%, #cccccc 100%); + background-image: -o-linear-gradient(top, #eeeeee 50%, #cccccc 100%); + background-image: linear-gradient(to bottom, #eeeeee 50%, #cccccc 100%); + background-repeat: repeat-x; + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#FFEEEEEE', endColorstr='#FFCCCCCC', GradientType=0); } + .select2-container--classic .select2-selection--single .select2-selection__arrow b { + border-color: #888 transparent transparent transparent; + border-style: solid; + border-width: 5px 4px 0 4px; + height: 0; + left: 50%; + margin-left: -4px; + margin-top: -2px; + position: absolute; + top: 50%; + width: 0; } + +.select2-container--classic[dir="rtl"] .select2-selection--single .select2-selection__clear { + float: left; } + +.select2-container--classic[dir="rtl"] .select2-selection--single .select2-selection__arrow { + border: none; + border-right: 1px solid #aaa; + border-radius: 0; + border-top-left-radius: 4px; + border-bottom-left-radius: 4px; + left: 1px; + right: auto; } + +.select2-container--classic.select2-container--open .select2-selection--single { + border: 1px solid #5897fb; } + .select2-container--classic.select2-container--open .select2-selection--single .select2-selection__arrow { + background: transparent; + border: none; } + .select2-container--classic.select2-container--open .select2-selection--single .select2-selection__arrow b { + border-color: transparent transparent #888 transparent; + border-width: 0 4px 5px 4px; } + +.select2-container--classic.select2-container--open.select2-container--above .select2-selection--single { + border-top: none; + border-top-left-radius: 0; + border-top-right-radius: 0; + background-image: -webkit-linear-gradient(top, white 0%, #eeeeee 50%); + background-image: -o-linear-gradient(top, white 0%, #eeeeee 50%); + background-image: linear-gradient(to bottom, white 0%, #eeeeee 50%); + background-repeat: repeat-x; + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#FFFFFFFF', endColorstr='#FFEEEEEE', GradientType=0); } + +.select2-container--classic.select2-container--open.select2-container--below .select2-selection--single { + border-bottom: none; + border-bottom-left-radius: 0; + border-bottom-right-radius: 0; + background-image: -webkit-linear-gradient(top, #eeeeee 50%, white 100%); + background-image: -o-linear-gradient(top, #eeeeee 50%, white 100%); + background-image: linear-gradient(to bottom, #eeeeee 50%, white 100%); + background-repeat: repeat-x; + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#FFEEEEEE', endColorstr='#FFFFFFFF', GradientType=0); } + +.select2-container--classic .select2-selection--multiple { + background-color: white; + border: 1px solid #aaa; + border-radius: 4px; + cursor: text; + outline: 0; } + .select2-container--classic .select2-selection--multiple:focus { + border: 1px solid #5897fb; } + .select2-container--classic .select2-selection--multiple .select2-selection__rendered { + list-style: none; + margin: 0; + padding: 0 5px; } + .select2-container--classic .select2-selection--multiple .select2-selection__clear { + display: none; } + .select2-container--classic .select2-selection--multiple .select2-selection__choice { + background-color: #e4e4e4; + border: 1px solid #aaa; + border-radius: 4px; + cursor: default; + float: left; + margin-right: 5px; + margin-top: 5px; + padding: 0 5px; } + .select2-container--classic .select2-selection--multiple .select2-selection__choice__remove { + color: #888; + cursor: pointer; + display: inline-block; + font-weight: bold; + margin-right: 2px; } + .select2-container--classic .select2-selection--multiple .select2-selection__choice__remove:hover { + color: #555; } + +.select2-container--classic[dir="rtl"] .select2-selection--multiple .select2-selection__choice { + float: right; + margin-left: 5px; + margin-right: auto; } + +.select2-container--classic[dir="rtl"] .select2-selection--multiple .select2-selection__choice__remove { + margin-left: 2px; + margin-right: auto; } + +.select2-container--classic.select2-container--open .select2-selection--multiple { + border: 1px solid #5897fb; } + +.select2-container--classic.select2-container--open.select2-container--above .select2-selection--multiple { + border-top: none; + border-top-left-radius: 0; + border-top-right-radius: 0; } + +.select2-container--classic.select2-container--open.select2-container--below .select2-selection--multiple { + border-bottom: none; + border-bottom-left-radius: 0; + border-bottom-right-radius: 0; } + +.select2-container--classic .select2-search--dropdown .select2-search__field { + border: 1px solid #aaa; + outline: 0; } + +.select2-container--classic .select2-search--inline .select2-search__field { + outline: 0; + box-shadow: none; } + +.select2-container--classic .select2-dropdown { + background-color: white; + border: 1px solid transparent; } + +.select2-container--classic .select2-dropdown--above { + border-bottom: none; } + +.select2-container--classic .select2-dropdown--below { + border-top: none; } + +.select2-container--classic .select2-results > .select2-results__options { + max-height: 200px; + overflow-y: auto; } + +.select2-container--classic .select2-results__option[role=group] { + padding: 0; } + +.select2-container--classic .select2-results__option[aria-disabled=true] { + color: grey; } + +.select2-container--classic .select2-results__option--highlighted[aria-selected] { + background-color: #3875d7; + color: white; } + +.select2-container--classic .select2-results__group { + cursor: default; + display: block; + padding: 6px; } + +.select2-container--classic.select2-container--open .select2-dropdown { + border-color: #5897fb; } diff --git a/fweb/static/admin/css/vendor/select2/select2.min.css b/fweb/static/admin/css/vendor/select2/select2.min.css new file mode 100644 index 0000000..7c18ad5 --- /dev/null +++ b/fweb/static/admin/css/vendor/select2/select2.min.css @@ -0,0 +1 @@ +.select2-container{box-sizing:border-box;display:inline-block;margin:0;position:relative;vertical-align:middle}.select2-container .select2-selection--single{box-sizing:border-box;cursor:pointer;display:block;height:28px;user-select:none;-webkit-user-select:none}.select2-container .select2-selection--single .select2-selection__rendered{display:block;padding-left:8px;padding-right:20px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.select2-container .select2-selection--single .select2-selection__clear{position:relative}.select2-container[dir="rtl"] .select2-selection--single .select2-selection__rendered{padding-right:8px;padding-left:20px}.select2-container .select2-selection--multiple{box-sizing:border-box;cursor:pointer;display:block;min-height:32px;user-select:none;-webkit-user-select:none}.select2-container .select2-selection--multiple .select2-selection__rendered{display:inline-block;overflow:hidden;padding-left:8px;text-overflow:ellipsis;white-space:nowrap}.select2-container .select2-search--inline{float:left}.select2-container .select2-search--inline .select2-search__field{box-sizing:border-box;border:none;font-size:100%;margin-top:5px;padding:0}.select2-container .select2-search--inline .select2-search__field::-webkit-search-cancel-button{-webkit-appearance:none}.select2-dropdown{background-color:white;border:1px solid #aaa;border-radius:4px;box-sizing:border-box;display:block;position:absolute;left:-100000px;width:100%;z-index:1051}.select2-results{display:block}.select2-results__options{list-style:none;margin:0;padding:0}.select2-results__option{padding:6px;user-select:none;-webkit-user-select:none}.select2-results__option[aria-selected]{cursor:pointer}.select2-container--open .select2-dropdown{left:0}.select2-container--open .select2-dropdown--above{border-bottom:none;border-bottom-left-radius:0;border-bottom-right-radius:0}.select2-container--open .select2-dropdown--below{border-top:none;border-top-left-radius:0;border-top-right-radius:0}.select2-search--dropdown{display:block;padding:4px}.select2-search--dropdown .select2-search__field{padding:4px;width:100%;box-sizing:border-box}.select2-search--dropdown .select2-search__field::-webkit-search-cancel-button{-webkit-appearance:none}.select2-search--dropdown.select2-search--hide{display:none}.select2-close-mask{border:0;margin:0;padding:0;display:block;position:fixed;left:0;top:0;min-height:100%;min-width:100%;height:auto;width:auto;opacity:0;z-index:99;background-color:#fff;filter:alpha(opacity=0)}.select2-hidden-accessible{border:0 !important;clip:rect(0 0 0 0) !important;-webkit-clip-path:inset(50%) !important;clip-path:inset(50%) !important;height:1px !important;overflow:hidden !important;padding:0 !important;position:absolute !important;width:1px !important;white-space:nowrap !important}.select2-container--default .select2-selection--single{background-color:#fff;border:1px solid #aaa;border-radius:4px}.select2-container--default .select2-selection--single .select2-selection__rendered{color:#444;line-height:28px}.select2-container--default .select2-selection--single .select2-selection__clear{cursor:pointer;float:right;font-weight:bold}.select2-container--default .select2-selection--single .select2-selection__placeholder{color:#999}.select2-container--default .select2-selection--single .select2-selection__arrow{height:26px;position:absolute;top:1px;right:1px;width:20px}.select2-container--default .select2-selection--single .select2-selection__arrow b{border-color:#888 transparent transparent transparent;border-style:solid;border-width:5px 4px 0 4px;height:0;left:50%;margin-left:-4px;margin-top:-2px;position:absolute;top:50%;width:0}.select2-container--default[dir="rtl"] .select2-selection--single .select2-selection__clear{float:left}.select2-container--default[dir="rtl"] .select2-selection--single .select2-selection__arrow{left:1px;right:auto}.select2-container--default.select2-container--disabled .select2-selection--single{background-color:#eee;cursor:default}.select2-container--default.select2-container--disabled .select2-selection--single .select2-selection__clear{display:none}.select2-container--default.select2-container--open .select2-selection--single .select2-selection__arrow b{border-color:transparent transparent #888 transparent;border-width:0 4px 5px 4px}.select2-container--default .select2-selection--multiple{background-color:white;border:1px solid #aaa;border-radius:4px;cursor:text}.select2-container--default .select2-selection--multiple .select2-selection__rendered{box-sizing:border-box;list-style:none;margin:0;padding:0 5px;width:100%}.select2-container--default .select2-selection--multiple .select2-selection__rendered li{list-style:none}.select2-container--default .select2-selection--multiple .select2-selection__clear{cursor:pointer;float:right;font-weight:bold;margin-top:5px;margin-right:10px;padding:1px}.select2-container--default .select2-selection--multiple .select2-selection__choice{background-color:#e4e4e4;border:1px solid #aaa;border-radius:4px;cursor:default;float:left;margin-right:5px;margin-top:5px;padding:0 5px}.select2-container--default .select2-selection--multiple .select2-selection__choice__remove{color:#999;cursor:pointer;display:inline-block;font-weight:bold;margin-right:2px}.select2-container--default .select2-selection--multiple .select2-selection__choice__remove:hover{color:#333}.select2-container--default[dir="rtl"] .select2-selection--multiple .select2-selection__choice,.select2-container--default[dir="rtl"] .select2-selection--multiple .select2-search--inline{float:right}.select2-container--default[dir="rtl"] .select2-selection--multiple .select2-selection__choice{margin-left:5px;margin-right:auto}.select2-container--default[dir="rtl"] .select2-selection--multiple .select2-selection__choice__remove{margin-left:2px;margin-right:auto}.select2-container--default.select2-container--focus .select2-selection--multiple{border:solid black 1px;outline:0}.select2-container--default.select2-container--disabled .select2-selection--multiple{background-color:#eee;cursor:default}.select2-container--default.select2-container--disabled .select2-selection__choice__remove{display:none}.select2-container--default.select2-container--open.select2-container--above .select2-selection--single,.select2-container--default.select2-container--open.select2-container--above .select2-selection--multiple{border-top-left-radius:0;border-top-right-radius:0}.select2-container--default.select2-container--open.select2-container--below .select2-selection--single,.select2-container--default.select2-container--open.select2-container--below .select2-selection--multiple{border-bottom-left-radius:0;border-bottom-right-radius:0}.select2-container--default .select2-search--dropdown .select2-search__field{border:1px solid #aaa}.select2-container--default .select2-search--inline .select2-search__field{background:transparent;border:none;outline:0;box-shadow:none;-webkit-appearance:textfield}.select2-container--default .select2-results>.select2-results__options{max-height:200px;overflow-y:auto}.select2-container--default .select2-results__option[role=group]{padding:0}.select2-container--default .select2-results__option[aria-disabled=true]{color:#999}.select2-container--default .select2-results__option[aria-selected=true]{background-color:#ddd}.select2-container--default .select2-results__option .select2-results__option{padding-left:1em}.select2-container--default .select2-results__option .select2-results__option .select2-results__group{padding-left:0}.select2-container--default .select2-results__option .select2-results__option .select2-results__option{margin-left:-1em;padding-left:2em}.select2-container--default .select2-results__option .select2-results__option .select2-results__option .select2-results__option{margin-left:-2em;padding-left:3em}.select2-container--default .select2-results__option .select2-results__option .select2-results__option .select2-results__option .select2-results__option{margin-left:-3em;padding-left:4em}.select2-container--default .select2-results__option .select2-results__option .select2-results__option .select2-results__option .select2-results__option .select2-results__option{margin-left:-4em;padding-left:5em}.select2-container--default .select2-results__option .select2-results__option .select2-results__option .select2-results__option .select2-results__option .select2-results__option .select2-results__option{margin-left:-5em;padding-left:6em}.select2-container--default .select2-results__option--highlighted[aria-selected]{background-color:#5897fb;color:white}.select2-container--default .select2-results__group{cursor:default;display:block;padding:6px}.select2-container--classic .select2-selection--single{background-color:#f7f7f7;border:1px solid #aaa;border-radius:4px;outline:0;background-image:-webkit-linear-gradient(top, #fff 50%, #eee 100%);background-image:-o-linear-gradient(top, #fff 50%, #eee 100%);background-image:linear-gradient(to bottom, #fff 50%, #eee 100%);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#FFFFFFFF', endColorstr='#FFEEEEEE', GradientType=0)}.select2-container--classic .select2-selection--single:focus{border:1px solid #5897fb}.select2-container--classic .select2-selection--single .select2-selection__rendered{color:#444;line-height:28px}.select2-container--classic .select2-selection--single .select2-selection__clear{cursor:pointer;float:right;font-weight:bold;margin-right:10px}.select2-container--classic .select2-selection--single .select2-selection__placeholder{color:#999}.select2-container--classic .select2-selection--single .select2-selection__arrow{background-color:#ddd;border:none;border-left:1px solid #aaa;border-top-right-radius:4px;border-bottom-right-radius:4px;height:26px;position:absolute;top:1px;right:1px;width:20px;background-image:-webkit-linear-gradient(top, #eee 50%, #ccc 100%);background-image:-o-linear-gradient(top, #eee 50%, #ccc 100%);background-image:linear-gradient(to bottom, #eee 50%, #ccc 100%);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#FFEEEEEE', endColorstr='#FFCCCCCC', GradientType=0)}.select2-container--classic .select2-selection--single .select2-selection__arrow b{border-color:#888 transparent transparent transparent;border-style:solid;border-width:5px 4px 0 4px;height:0;left:50%;margin-left:-4px;margin-top:-2px;position:absolute;top:50%;width:0}.select2-container--classic[dir="rtl"] .select2-selection--single .select2-selection__clear{float:left}.select2-container--classic[dir="rtl"] .select2-selection--single .select2-selection__arrow{border:none;border-right:1px solid #aaa;border-radius:0;border-top-left-radius:4px;border-bottom-left-radius:4px;left:1px;right:auto}.select2-container--classic.select2-container--open .select2-selection--single{border:1px solid #5897fb}.select2-container--classic.select2-container--open .select2-selection--single .select2-selection__arrow{background:transparent;border:none}.select2-container--classic.select2-container--open .select2-selection--single .select2-selection__arrow b{border-color:transparent transparent #888 transparent;border-width:0 4px 5px 4px}.select2-container--classic.select2-container--open.select2-container--above .select2-selection--single{border-top:none;border-top-left-radius:0;border-top-right-radius:0;background-image:-webkit-linear-gradient(top, #fff 0%, #eee 50%);background-image:-o-linear-gradient(top, #fff 0%, #eee 50%);background-image:linear-gradient(to bottom, #fff 0%, #eee 50%);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#FFFFFFFF', endColorstr='#FFEEEEEE', GradientType=0)}.select2-container--classic.select2-container--open.select2-container--below .select2-selection--single{border-bottom:none;border-bottom-left-radius:0;border-bottom-right-radius:0;background-image:-webkit-linear-gradient(top, #eee 50%, #fff 100%);background-image:-o-linear-gradient(top, #eee 50%, #fff 100%);background-image:linear-gradient(to bottom, #eee 50%, #fff 100%);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#FFEEEEEE', endColorstr='#FFFFFFFF', GradientType=0)}.select2-container--classic .select2-selection--multiple{background-color:white;border:1px solid #aaa;border-radius:4px;cursor:text;outline:0}.select2-container--classic .select2-selection--multiple:focus{border:1px solid #5897fb}.select2-container--classic .select2-selection--multiple .select2-selection__rendered{list-style:none;margin:0;padding:0 5px}.select2-container--classic .select2-selection--multiple .select2-selection__clear{display:none}.select2-container--classic .select2-selection--multiple .select2-selection__choice{background-color:#e4e4e4;border:1px solid #aaa;border-radius:4px;cursor:default;float:left;margin-right:5px;margin-top:5px;padding:0 5px}.select2-container--classic .select2-selection--multiple .select2-selection__choice__remove{color:#888;cursor:pointer;display:inline-block;font-weight:bold;margin-right:2px}.select2-container--classic .select2-selection--multiple .select2-selection__choice__remove:hover{color:#555}.select2-container--classic[dir="rtl"] .select2-selection--multiple .select2-selection__choice{float:right;margin-left:5px;margin-right:auto}.select2-container--classic[dir="rtl"] .select2-selection--multiple .select2-selection__choice__remove{margin-left:2px;margin-right:auto}.select2-container--classic.select2-container--open .select2-selection--multiple{border:1px solid #5897fb}.select2-container--classic.select2-container--open.select2-container--above .select2-selection--multiple{border-top:none;border-top-left-radius:0;border-top-right-radius:0}.select2-container--classic.select2-container--open.select2-container--below .select2-selection--multiple{border-bottom:none;border-bottom-left-radius:0;border-bottom-right-radius:0}.select2-container--classic .select2-search--dropdown .select2-search__field{border:1px solid #aaa;outline:0}.select2-container--classic .select2-search--inline .select2-search__field{outline:0;box-shadow:none}.select2-container--classic .select2-dropdown{background-color:#fff;border:1px solid transparent}.select2-container--classic .select2-dropdown--above{border-bottom:none}.select2-container--classic .select2-dropdown--below{border-top:none}.select2-container--classic .select2-results>.select2-results__options{max-height:200px;overflow-y:auto}.select2-container--classic .select2-results__option[role=group]{padding:0}.select2-container--classic .select2-results__option[aria-disabled=true]{color:grey}.select2-container--classic .select2-results__option--highlighted[aria-selected]{background-color:#3875d7;color:#fff}.select2-container--classic .select2-results__group{cursor:default;display:block;padding:6px}.select2-container--classic.select2-container--open .select2-dropdown{border-color:#5897fb} diff --git a/fweb/static/admin/css/widgets.css b/fweb/static/admin/css/widgets.css new file mode 100644 index 0000000..cc64811 --- /dev/null +++ b/fweb/static/admin/css/widgets.css @@ -0,0 +1,593 @@ +/* SELECTOR (FILTER INTERFACE) */ + +.selector { + display: flex; + flex-grow: 1; + gap: 0 10px; +} + +.selector select { + height: 17.2em; + flex: 1 0 auto; + overflow: scroll; + width: 100%; +} + +.selector-available, .selector-chosen { + text-align: center; + display: flex; + flex-direction: column; + flex: 1 1; +} + +.selector-available h2, .selector-chosen h2 { + border: 1px solid var(--border-color); + border-radius: 4px 4px 0 0; +} + +.selector-chosen .list-footer-display { + border: 1px solid var(--border-color); + border-top: none; + border-radius: 0 0 4px 4px; + margin: 0 0 10px; + padding: 8px; + text-align: center; + background: var(--primary); + color: var(--header-link-color); + cursor: pointer; +} +.selector-chosen .list-footer-display__clear { + color: var(--breadcrumbs-fg); +} + +.selector-chosen h2 { + background: var(--secondary); + color: var(--header-link-color); +} + +.selector .selector-available h2 { + background: var(--darkened-bg); + color: var(--body-quiet-color); +} + +.selector .selector-filter { + border: 1px solid var(--border-color); + border-width: 0 1px; + padding: 8px; + color: var(--body-quiet-color); + font-size: 0.625rem; + margin: 0; + text-align: left; + display: flex; +} + +.selector .selector-filter label, +.inline-group .aligned .selector .selector-filter label { + float: left; + margin: 7px 0 0; + width: 18px; + height: 18px; + padding: 0; + overflow: hidden; + line-height: 1; + min-width: auto; +} + +.selector-filter input { + flex-grow: 1; +} + +.selector .selector-available input, +.selector .selector-chosen input { + margin-left: 8px; +} + +.selector ul.selector-chooser { + align-self: center; + width: 22px; + background-color: var(--selected-bg); + border-radius: 10px; + margin: 0; + padding: 0; + transform: translateY(-17px); +} + +.selector-chooser li { + margin: 0; + padding: 3px; + list-style-type: none; +} + +.selector select { + padding: 0 10px; + margin: 0 0 10px; + border-radius: 0 0 4px 4px; +} +.selector .selector-chosen--with-filtered select { + margin: 0; + border-radius: 0; + height: 14em; +} + +.selector .selector-chosen:not(.selector-chosen--with-filtered) .list-footer-display { + display: none; +} + +.selector-add, .selector-remove { + width: 16px; + height: 16px; + display: block; + text-indent: -3000px; + overflow: hidden; + cursor: default; + opacity: 0.55; +} + +.active.selector-add, .active.selector-remove { + opacity: 1; +} + +.active.selector-add:hover, .active.selector-remove:hover { + cursor: pointer; +} + +.selector-add { + background: url(../img/selector-icons.svg) 0 -96px no-repeat; +} + +.active.selector-add:focus, .active.selector-add:hover { + background-position: 0 -112px; +} + +.selector-remove { + background: url(../img/selector-icons.svg) 0 -64px no-repeat; +} + +.active.selector-remove:focus, .active.selector-remove:hover { + background-position: 0 -80px; +} + +a.selector-chooseall, a.selector-clearall { + display: inline-block; + height: 16px; + text-align: left; + margin: 0 auto; + overflow: hidden; + font-weight: bold; + line-height: 16px; + color: var(--body-quiet-color); + text-decoration: none; + opacity: 0.55; +} + +a.active.selector-chooseall:focus, a.active.selector-clearall:focus, +a.active.selector-chooseall:hover, a.active.selector-clearall:hover { + color: var(--link-fg); +} + +a.active.selector-chooseall, a.active.selector-clearall { + opacity: 1; +} + +a.active.selector-chooseall:hover, a.active.selector-clearall:hover { + cursor: pointer; +} + +a.selector-chooseall { + padding: 0 18px 0 0; + background: url(../img/selector-icons.svg) right -160px no-repeat; + cursor: default; +} + +a.active.selector-chooseall:focus, a.active.selector-chooseall:hover { + background-position: 100% -176px; +} + +a.selector-clearall { + padding: 0 0 0 18px; + background: url(../img/selector-icons.svg) 0 -128px no-repeat; + cursor: default; +} + +a.active.selector-clearall:focus, a.active.selector-clearall:hover { + background-position: 0 -144px; +} + +/* STACKED SELECTORS */ + +.stacked { + float: left; + width: 490px; + display: block; +} + +.stacked select { + width: 480px; + height: 10.1em; +} + +.stacked .selector-available, .stacked .selector-chosen { + width: 480px; +} + +.stacked .selector-available { + margin-bottom: 0; +} + +.stacked .selector-available input { + width: 422px; +} + +.stacked ul.selector-chooser { + height: 22px; + width: 50px; + margin: 0 0 10px 40%; + background-color: #eee; + border-radius: 10px; + transform: none; +} + +.stacked .selector-chooser li { + float: left; + padding: 3px 3px 3px 5px; +} + +.stacked .selector-chooseall, .stacked .selector-clearall { + display: none; +} + +.stacked .selector-add { + background: url(../img/selector-icons.svg) 0 -32px no-repeat; + cursor: default; +} + +.stacked .active.selector-add { + background-position: 0 -32px; + cursor: pointer; +} + +.stacked .active.selector-add:focus, .stacked .active.selector-add:hover { + background-position: 0 -48px; + cursor: pointer; +} + +.stacked .selector-remove { + background: url(../img/selector-icons.svg) 0 0 no-repeat; + cursor: default; +} + +.stacked .active.selector-remove { + background-position: 0 0px; + cursor: pointer; +} + +.stacked .active.selector-remove:focus, .stacked .active.selector-remove:hover { + background-position: 0 -16px; + cursor: pointer; +} + +.selector .help-icon { + background: url(../img/icon-unknown.svg) 0 0 no-repeat; + display: inline-block; + vertical-align: middle; + margin: -2px 0 0 2px; + width: 13px; + height: 13px; +} + +.selector .selector-chosen .help-icon { + background: url(../img/icon-unknown-alt.svg) 0 0 no-repeat; +} + +.selector .search-label-icon { + background: url(../img/search.svg) 0 0 no-repeat; + display: inline-block; + height: 1.125rem; + width: 1.125rem; +} + +/* DATE AND TIME */ + +p.datetime { + line-height: 20px; + margin: 0; + padding: 0; + color: var(--body-quiet-color); + font-weight: bold; +} + +.datetime span { + white-space: nowrap; + font-weight: normal; + font-size: 0.6875rem; + color: var(--body-quiet-color); +} + +.datetime input, .form-row .datetime input.vDateField, .form-row .datetime input.vTimeField { + margin-left: 5px; + margin-bottom: 4px; +} + +table p.datetime { + font-size: 0.6875rem; + margin-left: 0; + padding-left: 0; +} + +.datetimeshortcuts .clock-icon, .datetimeshortcuts .date-icon { + position: relative; + display: inline-block; + vertical-align: middle; + height: 16px; + width: 16px; + overflow: hidden; +} + +.datetimeshortcuts .clock-icon { + background: url(../img/icon-clock.svg) 0 0 no-repeat; +} + +.datetimeshortcuts a:focus .clock-icon, +.datetimeshortcuts a:hover .clock-icon { + background-position: 0 -16px; +} + +.datetimeshortcuts .date-icon { + background: url(../img/icon-calendar.svg) 0 0 no-repeat; + top: -1px; +} + +.datetimeshortcuts a:focus .date-icon, +.datetimeshortcuts a:hover .date-icon { + background-position: 0 -16px; +} + +.timezonewarning { + font-size: 0.6875rem; + color: var(--body-quiet-color); +} + +/* URL */ + +p.url { + line-height: 20px; + margin: 0; + padding: 0; + color: var(--body-quiet-color); + font-size: 0.6875rem; + font-weight: bold; +} + +.url a { + font-weight: normal; +} + +/* FILE UPLOADS */ + +p.file-upload { + line-height: 20px; + margin: 0; + padding: 0; + color: var(--body-quiet-color); + font-size: 0.6875rem; + font-weight: bold; +} + +.file-upload a { + font-weight: normal; +} + +.file-upload .deletelink { + margin-left: 5px; +} + +span.clearable-file-input label { + color: var(--body-fg); + font-size: 0.6875rem; + display: inline; + float: none; +} + +/* CALENDARS & CLOCKS */ + +.calendarbox, .clockbox { + margin: 5px auto; + font-size: 0.75rem; + width: 19em; + text-align: center; + background: var(--body-bg); + color: var(--body-fg); + border: 1px solid var(--hairline-color); + border-radius: 4px; + box-shadow: 0 2px 4px rgba(0, 0, 0, 0.15); + overflow: hidden; + position: relative; +} + +.clockbox { + width: auto; +} + +.calendar { + margin: 0; + padding: 0; +} + +.calendar table { + margin: 0; + padding: 0; + border-collapse: collapse; + background: white; + width: 100%; +} + +.calendar caption, .calendarbox h2 { + margin: 0; + text-align: center; + border-top: none; + font-weight: 700; + font-size: 0.75rem; + color: #333; + background: var(--accent); +} + +.calendar th { + padding: 8px 5px; + background: var(--darkened-bg); + border-bottom: 1px solid var(--border-color); + font-weight: 400; + font-size: 0.75rem; + text-align: center; + color: var(--body-quiet-color); +} + +.calendar td { + font-weight: 400; + font-size: 0.75rem; + text-align: center; + padding: 0; + border-top: 1px solid var(--hairline-color); + border-bottom: none; +} + +.calendar td.selected a { + background: var(--secondary); + color: var(--button-fg); +} + +.calendar td.nonday { + background: var(--darkened-bg); +} + +.calendar td.today a { + font-weight: 700; +} + +.calendar td a, .timelist a { + display: block; + font-weight: 400; + padding: 6px; + text-decoration: none; + color: var(--body-quiet-color); +} + +.calendar td a:focus, .timelist a:focus, +.calendar td a:hover, .timelist a:hover { + background: var(--primary); + color: white; +} + +.calendar td a:active, .timelist a:active { + background: var(--header-bg); + color: white; +} + +.calendarnav { + font-size: 0.625rem; + text-align: center; + color: #ccc; + margin: 0; + padding: 1px 3px; +} + +.calendarnav a:link, #calendarnav a:visited, +#calendarnav a:focus, #calendarnav a:hover { + color: var(--body-quiet-color); +} + +.calendar-shortcuts { + background: var(--body-bg); + color: var(--body-quiet-color); + font-size: 0.6875rem; + line-height: 0.6875rem; + border-top: 1px solid var(--hairline-color); + padding: 8px 0; +} + +.calendarbox .calendarnav-previous, .calendarbox .calendarnav-next { + display: block; + position: absolute; + top: 8px; + width: 15px; + height: 15px; + text-indent: -9999px; + padding: 0; +} + +.calendarnav-previous { + left: 10px; + background: url(../img/calendar-icons.svg) 0 0 no-repeat; +} + +.calendarnav-next { + right: 10px; + background: url(../img/calendar-icons.svg) 0 -15px no-repeat; +} + +.calendar-cancel { + margin: 0; + padding: 4px 0; + font-size: 0.75rem; + background: var(--close-button-bg); + border-top: 1px solid var(--border-color); + color: var(--button-fg); +} + +.calendar-cancel:focus, .calendar-cancel:hover { + background: var(--close-button-hover-bg); +} + +.calendar-cancel a { + color: var(--button-fg); + display: block; +} + +ul.timelist, .timelist li { + list-style-type: none; + margin: 0; + padding: 0; +} + +.timelist a { + padding: 2px; +} + +/* EDIT INLINE */ + +.inline-deletelink { + float: right; + text-indent: -9999px; + background: url(../img/inline-delete.svg) 0 0 no-repeat; + width: 16px; + height: 16px; + border: 0px none; +} + +.inline-deletelink:focus, .inline-deletelink:hover { + cursor: pointer; +} + +/* RELATED WIDGET WRAPPER */ +.related-widget-wrapper { + display: flex; + gap: 0 10px; + flex-grow: 1; + flex-wrap: wrap; + margin-bottom: 5px; +} + +.related-widget-wrapper-link { + opacity: .6; + filter: grayscale(1); +} + +.related-widget-wrapper-link:link { + opacity: 1; + filter: grayscale(0); +} + +/* GIS MAPS */ +.dj_map { + width: 600px; + height: 400px; +} diff --git a/fweb/static/admin/img/LICENSE b/fweb/static/admin/img/LICENSE new file mode 100644 index 0000000..a4faaa1 --- /dev/null +++ b/fweb/static/admin/img/LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright (c) 2014 Code Charm Ltd + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/fweb/static/admin/img/README.txt b/fweb/static/admin/img/README.txt new file mode 100644 index 0000000..bf81f35 --- /dev/null +++ b/fweb/static/admin/img/README.txt @@ -0,0 +1,7 @@ +All icons are taken from Font Awesome (https://fontawesome.com/) project. +The Font Awesome font is licensed under the SIL OFL 1.1: +- https://scripts.sil.org/OFL + +SVG icons source: https://github.com/encharm/Font-Awesome-SVG-PNG +Font-Awesome-SVG-PNG is licensed under the MIT license (see file license +in current folder). diff --git a/fweb/static/admin/img/calendar-icons.svg b/fweb/static/admin/img/calendar-icons.svg new file mode 100644 index 0000000..04c0274 --- /dev/null +++ b/fweb/static/admin/img/calendar-icons.svg @@ -0,0 +1,63 @@ + + + + + + + + + + + + + + diff --git a/fweb/static/admin/img/gis/move_vertex_off.svg b/fweb/static/admin/img/gis/move_vertex_off.svg new file mode 100644 index 0000000..228854f --- /dev/null +++ b/fweb/static/admin/img/gis/move_vertex_off.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/fweb/static/admin/img/gis/move_vertex_on.svg b/fweb/static/admin/img/gis/move_vertex_on.svg new file mode 100644 index 0000000..96b87fd --- /dev/null +++ b/fweb/static/admin/img/gis/move_vertex_on.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/fweb/static/admin/img/icon-addlink.svg b/fweb/static/admin/img/icon-addlink.svg new file mode 100644 index 0000000..8d5c6a3 --- /dev/null +++ b/fweb/static/admin/img/icon-addlink.svg @@ -0,0 +1,3 @@ + + + diff --git a/fweb/static/admin/img/icon-alert.svg b/fweb/static/admin/img/icon-alert.svg new file mode 100644 index 0000000..e51ea83 --- /dev/null +++ b/fweb/static/admin/img/icon-alert.svg @@ -0,0 +1,3 @@ + + + diff --git a/fweb/static/admin/img/icon-calendar.svg b/fweb/static/admin/img/icon-calendar.svg new file mode 100644 index 0000000..97910a9 --- /dev/null +++ b/fweb/static/admin/img/icon-calendar.svg @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/fweb/static/admin/img/icon-changelink.svg b/fweb/static/admin/img/icon-changelink.svg new file mode 100644 index 0000000..592b093 --- /dev/null +++ b/fweb/static/admin/img/icon-changelink.svg @@ -0,0 +1,3 @@ + + + diff --git a/fweb/static/admin/img/icon-clock.svg b/fweb/static/admin/img/icon-clock.svg new file mode 100644 index 0000000..bf9985d --- /dev/null +++ b/fweb/static/admin/img/icon-clock.svg @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/fweb/static/admin/img/icon-deletelink.svg b/fweb/static/admin/img/icon-deletelink.svg new file mode 100644 index 0000000..4059b15 --- /dev/null +++ b/fweb/static/admin/img/icon-deletelink.svg @@ -0,0 +1,3 @@ + + + diff --git a/fweb/static/admin/img/icon-hidelink.svg b/fweb/static/admin/img/icon-hidelink.svg new file mode 100644 index 0000000..2a8b404 --- /dev/null +++ b/fweb/static/admin/img/icon-hidelink.svg @@ -0,0 +1,3 @@ + + + diff --git a/fweb/static/admin/img/icon-no.svg b/fweb/static/admin/img/icon-no.svg new file mode 100644 index 0000000..2e0d383 --- /dev/null +++ b/fweb/static/admin/img/icon-no.svg @@ -0,0 +1,3 @@ + + + diff --git a/fweb/static/admin/img/icon-unknown-alt.svg b/fweb/static/admin/img/icon-unknown-alt.svg new file mode 100644 index 0000000..1c6b99f --- /dev/null +++ b/fweb/static/admin/img/icon-unknown-alt.svg @@ -0,0 +1,3 @@ + + + diff --git a/fweb/static/admin/img/icon-unknown.svg b/fweb/static/admin/img/icon-unknown.svg new file mode 100644 index 0000000..50b4f97 --- /dev/null +++ b/fweb/static/admin/img/icon-unknown.svg @@ -0,0 +1,3 @@ + + + diff --git a/fweb/static/admin/img/icon-viewlink.svg b/fweb/static/admin/img/icon-viewlink.svg new file mode 100644 index 0000000..a1ca1d3 --- /dev/null +++ b/fweb/static/admin/img/icon-viewlink.svg @@ -0,0 +1,3 @@ + + + diff --git a/fweb/static/admin/img/icon-yes.svg b/fweb/static/admin/img/icon-yes.svg new file mode 100644 index 0000000..5883d87 --- /dev/null +++ b/fweb/static/admin/img/icon-yes.svg @@ -0,0 +1,3 @@ + + + diff --git a/fweb/static/admin/img/inline-delete.svg b/fweb/static/admin/img/inline-delete.svg new file mode 100644 index 0000000..17d1ad6 --- /dev/null +++ b/fweb/static/admin/img/inline-delete.svg @@ -0,0 +1,3 @@ + + + diff --git a/fweb/static/admin/img/search.svg b/fweb/static/admin/img/search.svg new file mode 100644 index 0000000..c8c69b2 --- /dev/null +++ b/fweb/static/admin/img/search.svg @@ -0,0 +1,3 @@ + + + diff --git a/fweb/static/admin/img/selector-icons.svg b/fweb/static/admin/img/selector-icons.svg new file mode 100644 index 0000000..926b8e2 --- /dev/null +++ b/fweb/static/admin/img/selector-icons.svg @@ -0,0 +1,34 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/fweb/static/admin/img/sorting-icons.svg b/fweb/static/admin/img/sorting-icons.svg new file mode 100644 index 0000000..7c31ec9 --- /dev/null +++ b/fweb/static/admin/img/sorting-icons.svg @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + + + + + + diff --git a/fweb/static/admin/img/tooltag-add.svg b/fweb/static/admin/img/tooltag-add.svg new file mode 100644 index 0000000..1ca64ae --- /dev/null +++ b/fweb/static/admin/img/tooltag-add.svg @@ -0,0 +1,3 @@ + + + diff --git a/fweb/static/admin/img/tooltag-arrowright.svg b/fweb/static/admin/img/tooltag-arrowright.svg new file mode 100644 index 0000000..b664d61 --- /dev/null +++ b/fweb/static/admin/img/tooltag-arrowright.svg @@ -0,0 +1,3 @@ + + + diff --git a/fweb/static/admin/js/SelectBox.js b/fweb/static/admin/js/SelectBox.js new file mode 100644 index 0000000..3db4ec7 --- /dev/null +++ b/fweb/static/admin/js/SelectBox.js @@ -0,0 +1,116 @@ +'use strict'; +{ + const SelectBox = { + cache: {}, + init: function(id) { + const box = document.getElementById(id); + SelectBox.cache[id] = []; + const cache = SelectBox.cache[id]; + for (const node of box.options) { + cache.push({value: node.value, text: node.text, displayed: 1}); + } + }, + redisplay: function(id) { + // Repopulate HTML select box from cache + const box = document.getElementById(id); + const scroll_value_from_top = box.scrollTop; + box.innerHTML = ''; + for (const node of SelectBox.cache[id]) { + if (node.displayed) { + const new_option = new Option(node.text, node.value, false, false); + // Shows a tooltip when hovering over the option + new_option.title = node.text; + box.appendChild(new_option); + } + } + box.scrollTop = scroll_value_from_top; + }, + filter: function(id, text) { + // Redisplay the HTML select box, displaying only the choices containing ALL + // the words in text. (It's an AND search.) + const tokens = text.toLowerCase().split(/\s+/); + for (const node of SelectBox.cache[id]) { + node.displayed = 1; + const node_text = node.text.toLowerCase(); + for (const token of tokens) { + if (!node_text.includes(token)) { + node.displayed = 0; + break; // Once the first token isn't found we're done + } + } + } + SelectBox.redisplay(id); + }, + get_hidden_node_count(id) { + const cache = SelectBox.cache[id] || []; + return cache.filter(node => node.displayed === 0).length; + }, + delete_from_cache: function(id, value) { + let delete_index = null; + const cache = SelectBox.cache[id]; + for (const [i, node] of cache.entries()) { + if (node.value === value) { + delete_index = i; + break; + } + } + cache.splice(delete_index, 1); + }, + add_to_cache: function(id, option) { + SelectBox.cache[id].push({value: option.value, text: option.text, displayed: 1}); + }, + cache_contains: function(id, value) { + // Check if an item is contained in the cache + for (const node of SelectBox.cache[id]) { + if (node.value === value) { + return true; + } + } + return false; + }, + move: function(from, to) { + const from_box = document.getElementById(from); + for (const option of from_box.options) { + const option_value = option.value; + if (option.selected && SelectBox.cache_contains(from, option_value)) { + SelectBox.add_to_cache(to, {value: option_value, text: option.text, displayed: 1}); + SelectBox.delete_from_cache(from, option_value); + } + } + SelectBox.redisplay(from); + SelectBox.redisplay(to); + }, + move_all: function(from, to) { + const from_box = document.getElementById(from); + for (const option of from_box.options) { + const option_value = option.value; + if (SelectBox.cache_contains(from, option_value)) { + SelectBox.add_to_cache(to, {value: option_value, text: option.text, displayed: 1}); + SelectBox.delete_from_cache(from, option_value); + } + } + SelectBox.redisplay(from); + SelectBox.redisplay(to); + }, + sort: function(id) { + SelectBox.cache[id].sort(function(a, b) { + a = a.text.toLowerCase(); + b = b.text.toLowerCase(); + if (a > b) { + return 1; + } + if (a < b) { + return -1; + } + return 0; + } ); + }, + select_all: function(id) { + const box = document.getElementById(id); + for (const option of box.options) { + option.selected = true; + } + } + }; + window.SelectBox = SelectBox; +} diff --git a/fweb/static/admin/js/SelectFilter2.js b/fweb/static/admin/js/SelectFilter2.js new file mode 100644 index 0000000..6957412 --- /dev/null +++ b/fweb/static/admin/js/SelectFilter2.js @@ -0,0 +1,286 @@ +/*global SelectBox, gettext, ngettext, interpolate, quickElement, SelectFilter*/ +/* +SelectFilter2 - Turns a multiple-select box into a filter interface. + +Requires core.js and SelectBox.js. +*/ +'use strict'; +{ + window.SelectFilter = { + init: function(field_id, field_name, is_stacked) { + if (field_id.match(/__prefix__/)) { + // Don't initialize on empty forms. + return; + } + const from_box = document.getElementById(field_id); + from_box.id += '_from'; // change its ID + from_box.className = 'filtered'; + + for (const p of from_box.parentNode.getElementsByTagName('p')) { + if (p.classList.contains("info")) { + // Remove

, because it just gets in the way. + from_box.parentNode.removeChild(p); + } else if (p.classList.contains("help")) { + // Move help text up to the top so it isn't below the select + // boxes or wrapped off on the side to the right of the add + // button: + from_box.parentNode.insertBefore(p, from_box.parentNode.firstChild); + } + } + + //

or
+ const selector_div = quickElement('div', from_box.parentNode); + // Make sure the selector div is at the beginning so that the + // add link would be displayed to the right of the widget. + from_box.parentNode.prepend(selector_div); + selector_div.className = is_stacked ? 'selector stacked' : 'selector'; + + //
+ const selector_available = quickElement('div', selector_div); + selector_available.className = 'selector-available'; + const title_available = quickElement('h2', selector_available, interpolate(gettext('Available %s') + ' ', [field_name])); + quickElement( + 'span', title_available, '', + 'class', 'help help-tooltip help-icon', + 'title', interpolate( + gettext( + 'This is the list of available %s. You may choose some by ' + + 'selecting them in the box below and then clicking the ' + + '"Choose" arrow between the two boxes.' + ), + [field_name] + ) + ); + + const filter_p = quickElement('p', selector_available, '', 'id', field_id + '_filter'); + filter_p.className = 'selector-filter'; + + const search_filter_label = quickElement('label', filter_p, '', 'for', field_id + '_input'); + + quickElement( + 'span', search_filter_label, '', + 'class', 'help-tooltip search-label-icon', + 'title', interpolate(gettext("Type into this box to filter down the list of available %s."), [field_name]) + ); + + filter_p.appendChild(document.createTextNode(' ')); + + const filter_input = quickElement('input', filter_p, '', 'type', 'text', 'placeholder', gettext("Filter")); + filter_input.id = field_id + '_input'; + + selector_available.appendChild(from_box); + const choose_all = quickElement('a', selector_available, gettext('Choose all'), 'title', interpolate(gettext('Click to choose all %s at once.'), [field_name]), 'href', '#', 'id', field_id + '_add_all_link'); + choose_all.className = 'selector-chooseall'; + + //