diff --git a/.github/workflows/python-package.yml b/.github/workflows/python-package.yml new file mode 100644 index 0000000..dbda311 --- /dev/null +++ b/.github/workflows/python-package.yml @@ -0,0 +1,41 @@ +# 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"] + +permissions: + contents: read + actions: write + packages: write + +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..2f89d16 100644 --- a/.github/workflows/python-publish.yml +++ b/.github/workflows/python-publish.yml @@ -9,31 +9,33 @@ name: filemac on: - release: - types: [published] + release: + types: [published] permissions: - contents: read + contents: read + actions: read + packages: read jobs: - deploy: + deploy: + runs-on: ubuntu-latest - runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + - name: Set up Python + uses: actions/setup-python@v3 + with: + python-version: "3.x" - steps: - - uses: actions/checkout@v3 - - name: Set up Python - uses: actions/setup-python@v3 - with: - python-version: '3.x' - - name: Install dependencies - run: | - python -m pip install --upgrade pip - pip install build - - name: Build package - run: python -m build - - name: Publish package - uses: pypa/gh-action-pypi-publish@27b31702a0e7fc50959f5ad993c78deac1bdfc29 - with: - user: __token__ - password: ${{ secrets.PYPI_API_TOKEN }} + - name: Install dependencies + run: | + python -m pip install --upgrade pip + pip install build + - name: Build package + run: python -m build + - name: Publish package + uses: pypa/gh-action-pypi-publish@27b31702a0e7fc50959f5ad993c78deac1bdfc29 + with: + user: __token__ + password: ${{ secrets.PYPI_API_TOKEN }} diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..5a7f40d --- /dev/null +++ b/.gitignore @@ -0,0 +1,39 @@ +# 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 +*.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 +*~ +*.db 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..0fd77c3 --- /dev/null +++ b/.pyproject.toml @@ -0,0 +1,84 @@ +[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", + "frontend", +] + +[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..d7b45cd 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`: --assetsize_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/assets/demo.html) + +**Result**
+ [Listen to Modified Audio](https://skye-cyber.github.io/FileMAC/assets/demo.html) + +--- + +#### Video +```shell +filemac --audio_effect 'demo.mp4' --effect high +``` +**Original**
+ [Listen to Original Video](https://skye-cyber.github.io/FileMAC/assets/demo.html) + +**Result**
+ [Listen to Modified Video](https://skye-cyber.github.io/FileMAC/assets/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/__pycache__/Analyzer.cpython-311.pyc b/__pycache__/Analyzer.cpython-311.pyc deleted file mode 100644 index d502d8b..0000000 Binary files a/__pycache__/Analyzer.cpython-311.pyc and /dev/null differ diff --git a/__pycache__/AudioExtractor.cpython-311.pyc b/__pycache__/AudioExtractor.cpython-311.pyc deleted file mode 100644 index 1a8d426..0000000 Binary files a/__pycache__/AudioExtractor.cpython-311.pyc and /dev/null differ diff --git a/__pycache__/OCRTextExtractor.cpython-311.pyc b/__pycache__/OCRTextExtractor.cpython-311.pyc deleted file mode 100644 index f4c49b9..0000000 Binary files a/__pycache__/OCRTextExtractor.cpython-311.pyc and /dev/null differ diff --git a/__pycache__/Simple_v_Analyzer.cpython-311.pyc b/__pycache__/Simple_v_Analyzer.cpython-311.pyc deleted file mode 100644 index 2e9d71a..0000000 Binary files a/__pycache__/Simple_v_Analyzer.cpython-311.pyc and /dev/null differ diff --git a/__pycache__/converter.cpython-311.pyc b/__pycache__/converter.cpython-311.pyc deleted file mode 100644 index d22d623..0000000 Binary files a/__pycache__/converter.cpython-311.pyc and /dev/null differ diff --git a/__pycache__/formarts.cpython-311.pyc b/__pycache__/formarts.cpython-311.pyc deleted file mode 100644 index 15358ab..0000000 Binary files a/__pycache__/formarts.cpython-311.pyc and /dev/null differ diff --git a/__pycache__/formats.cpython-311.pyc b/__pycache__/formats.cpython-311.pyc deleted file mode 100644 index 514208e..0000000 Binary files a/__pycache__/formats.cpython-311.pyc and /dev/null differ diff --git a/__pycache__/show_progress.cpython-311.pyc b/__pycache__/show_progress.cpython-311.pyc deleted file mode 100644 index cf779b2..0000000 Binary files a/__pycache__/show_progress.cpython-311.pyc and /dev/null differ diff --git a/assets/audio_effects/chipmunk_demo_v.mp4 b/assets/audio_effects/chipmunk_demo_v.mp4 new file mode 100644 index 0000000..8e44250 Binary files /dev/null and b/assets/audio_effects/chipmunk_demo_v.mp4 differ diff --git a/assets/audio_effects/demo.mp3 b/assets/audio_effects/demo.mp3 new file mode 100644 index 0000000..b23cec6 Binary files /dev/null and b/assets/audio_effects/demo.mp3 differ diff --git a/assets/audio_effects/demo_v.mp4 b/assets/audio_effects/demo_v.mp4 new file mode 100644 index 0000000..6ea564d Binary files /dev/null and b/assets/audio_effects/demo_v.mp4 differ diff --git a/assets/audio_effects/high_demo.mp3 b/assets/audio_effects/high_demo.mp3 new file mode 100644 index 0000000..7150d0c Binary files /dev/null and b/assets/audio_effects/high_demo.mp3 differ diff --git a/assets/demo.html b/assets/demo.html new file mode 100644 index 0000000..d54578a --- /dev/null +++ b/assets/demo.html @@ -0,0 +1,96 @@ + + + + + + Audio and Video Examples + + + +

Audio

+
filemac --audio_effect 'demo.mp3' --effect high
+

Original:

+ + +

Result:

+ + +
+ +

Video

+
filemac --audio_effect 'demo_v.mp4' --effect high
+

Original:

+ + +

Result:

+ + + diff --git a/assets/init.css b/assets/init.css new file mode 100644 index 0000000..8a196d1 --- /dev/null +++ b/assets/init.css @@ -0,0 +1,316 @@ +@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 */ + } +} +/* global.css or within a Tailwind plugin */ +@layer utilities { + h1, + h2, + h3, + h4, + h5, + h6 { + margin: 0; /* Reset margin for consistency */ + } + + h1 { + font-size: 2.5rem; /* 40px */ + font-weight: 700; /* bold */ + } + + h2 { + font-size: 2rem; /* 32px */ + font-weight: 600; /* semi-bold */ + } + + h3 { + font-size: 1.75rem; /* 28px */ + font-weight: 500; /* medium */ + } + + h4 { + font-size: 1.5rem; /* 24px */ + font-weight: 400; /* normal */ + } + + h5 { + font-size: 1.25rem; /* 20px */ + font-weight: 300; /* light */ + } + + h6 { + font-size: 1rem; /* 16px */ + font-weight: 200; /* extra light */ + } +} +.pulse { + display: inline-block; + transition: transform 0.3s ease-in-out; +} + +.pulse:hover { + transform: scale(1.1); +} + +@keyframes pulse { + 0% { + transform: scale(1); + } + 50% { + transform: scale(1.5); + } + 100% { + transform: scale(1); + } +} + +.pulse-hover { + display: inline-block; +} + +.pulse-hover:hover { + animation: pulse 1s infinite; +} +/* Reset default scrollbar */ +::-webkit-scrollbar { + width: 8px; + height: 8px; +} + +/* Light theme scrollbar */ +::-webkit-scrollbar-track { + background: #2c2c2c; + border-radius: 4px; + opacity: 0.5; +} + +.dark ::-webkit-scrollbar-track { + background: #24486b; + border-radius: 4px; + opacity: 0.5; +} + +::-webkit-scrollbar-thumb { + background: linear-gradient(145deg, #00aa7f, #aaffff, #00aaff); + border-radius: 4px; + transition: background-color 0.3s ease; +} + +::-webkit-scrollbar-thumb:hover { + background: #555500; +} + +.dark ::-webkit-scrollbar-thumb { + background: #ffffff; +} + +::-webkit-scrollbar-thumb:active { + background: linear-gradient(135deg, #aa55ff, #aaaaff, #ff55ff); +} + +/* Optional: Add transitions for more natural feel */ +ython.assistant-unused .note:-webkit-scrollbar { + scroll-behavior: smooth; +} + +/* Simulate a placeholder on the contenteditable div */ +#userInput:empty:before { + content: attr(data-placeholder); + color: #9ca3af; +} +/* Always ensure an extra empty row at the bottom */ +#userInput::after { + content: "\A"; /* Inserts a newline */ + white-space: pre; + display: block; + visibility: hidden; + height: 2.4em; /* Adjust this value to match the height of an empty row */ +} + +@keyframes modalEnter { + from { + transform: scale(0); + opacity: 0; + } + to { + transform: scale(1); + opacity: 1; + } +} + +@keyframes modalExit { + from { + transform: scale(1); + opacity: 1; + } + to { + transform: scale(0); + opacity: 0; + } +} + +.animate-enter { + animation: modalEnter 0.4s ease-out forwards; +} + +.animate-exit { + animation: modalExit 0.3s ease-in forwards; +} + +@keyframes singleRipple { + 0% { + transform: scale(0.8); + opacity: 1; + } + 100% { + transform: scale(2.5); + opacity: 0; + } +} +.ripple-single-1 { + position: absolute; + border: 3px solid; + border-image: linear-gradient(45deg, #ff8a65, #ff7043) 1; + width: 80%; + height: 80%; + animation: singleRipple 1.8s infinite; + pointer-events: none; +} + +.ripple-single-2 { + position: absolute; + border: 3px solid; + border-image: linear-gradient(45deg, #ff8a65, #55aaff) 1; + width: 80%; + height: 80%; + animation: singleRipple 1.8s infinite; + pointer-events: none; +} +.ripple-single-3 { + position: absolute; + border: 3px solid; + border-image: linear-gradient(45deg, #55ff7f, #ff7043) 1; + border-radius: 50%; + width: 80%; + height: 80%; + animation: singleRipple 1.8s infinite; + pointer-events: none; +} +.ripple-single-1 { + animation-delay: 0s; +} +.ripple-single-2 { + animation-delay: 0.6s; +} +.ripple-single-3 { + animation-delay: 1.2s; +} + +/* Light code theme*/ + +/* Dark code theme*/ +.hljs { + background-color: #282c34; + color: #abb2bf; + padding: 15px; + border-radius: 8px; + line-height: 1.5; + font-family: "Fira Code", monospace; +} + +.hljs-keyword { + color: #c678dd; + font-weight: bold; +} + +.hljs-built_in { + color: #e06c74; +} + +.hljs-string { + color: #98c379; +} + +.hljs-number { + color: #d19a66; +} + +.hljs-comment { + color: #5c6370; + font-style: italic; +} + +.hljs-function { + color: #61afef; +} + +.hljs-params { + color: #abb2bf; +} + +.hljs-variable { + color: #d19a66; +} + +.hljs-class { + color: #e5c07b; +} + +.hljs-title { + color: #61afef; +} + +.hljs-attribute { + color: #d19a66; +} + +.hljs-symbol { + color: #61afef; +} + +.hljs-bullet { + color: #abb2bf; +} + +.hljs-meta { + color: #5c6370; +} + +.hljs-link { + color: #61afef; + text-decoration: underline; +} + +.hljs-doctag { + color: #c678dd; + font-weight: bold; +} + +.hljs-tag { + color: #e06c74; +} + +.hljs-name { + color: #61afef; +} + +.hljs-attr { + color: #d19a66; +} + +.hljs-attr { + color: #00aaff; +} + +.hljs-literal { + color: #d19a66; +} diff --git a/assets/styles.css b/assets/styles.css new file mode 100644 index 0000000..51d299d --- /dev/null +++ b/assets/styles.css @@ -0,0 +1,1094 @@ +*, ::before, ::after { + --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: rgb(59 130 246 / 0.5); + --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: ; +} + +::backdrop { + --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: rgb(59 130 246 / 0.5); + --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 +*/ + +/* +1. Prevent padding and border from affecting element width. (https://github.com/mozdevs/cssremedy/issues/4) +2. Allow adding a border to an element by just adding a border-width. (https://github.com/tailwindcss/tailwindcss/pull/116) +*/ + +*, +::before, +::after { + box-sizing: border-box; + /* 1 */ + border-width: 0; + /* 2 */ + border-style: solid; + /* 2 */ + border-color: #e5e7eb; + /* 2 */ +} + +::before, +::after { + --tw-content: ''; +} + +/* +1. Use a consistent sensible line-height in all browsers. +2. Prevent adjustments of font size after orientation changes in iOS. +3. Use a more readable tab size. +4. Use the user's configured `sans` font-family by default. +5. Use the user's configured `sans` font-feature-settings by default. +6. Use the user's configured `sans` font-variation-settings by default. +7. Disable tap highlights on iOS +*/ + +html, +:host { + line-height: 1.5; + /* 1 */ + -webkit-text-size-adjust: 100%; + /* 2 */ + -moz-tab-size: 4; + /* 3 */ + -o-tab-size: 4; + tab-size: 4; + /* 3 */ + font-family: ui-sans-serif, system-ui, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji"; + /* 4 */ + font-feature-settings: normal; + /* 5 */ + font-variation-settings: normal; + /* 6 */ + -webkit-tap-highlight-color: transparent; + /* 7 */ +} + +/* +1. Remove the margin in all browsers. +2. Inherit line-height from `html` so users can set them as a class directly on the `html` element. +*/ + +body { + margin: 0; + /* 1 */ + line-height: inherit; + /* 2 */ +} + +/* +1. Add the correct height in Firefox. +2. Correct the inheritance of border color in Firefox. (https://bugzilla.mozilla.org/show_bug.cgi?id=190655) +3. Ensure horizontal rules are visible by default. +*/ + +hr { + height: 0; + /* 1 */ + color: inherit; + /* 2 */ + border-top-width: 1px; + /* 3 */ +} + +/* +Add the correct text decoration in Chrome, Edge, and Safari. +*/ + +abbr:where([title]) { + -webkit-text-decoration: underline dotted; + text-decoration: underline dotted; +} + +/* +Remove the default font size and weight for headings. +*/ + +h1, +h2, +h3, +h4, +h5, +h6 { + font-size: inherit; + font-weight: inherit; +} + +/* +Reset links to optimize for opt-in styling instead of opt-out. +*/ + +a { + color: inherit; + text-decoration: inherit; +} + +/* +Add the correct font weight in Edge and Safari. +*/ + +b, +strong { + font-weight: bolder; +} + +/* +1. Use the user's configured `mono` font-family by default. +2. Use the user's configured `mono` font-feature-settings by default. +3. Use the user's configured `mono` font-variation-settings by default. +4. Correct the odd `em` font sizing in all browsers. +*/ + +code, +kbd, +samp, +pre { + font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; + /* 1 */ + font-feature-settings: normal; + /* 2 */ + font-variation-settings: normal; + /* 3 */ + font-size: 1em; + /* 4 */ +} + +/* +Add the correct font size in all browsers. +*/ + +small { + font-size: 80%; +} + +/* +Prevent `sub` and `sup` elements from affecting the line height in all browsers. +*/ + +sub, +sup { + font-size: 75%; + line-height: 0; + position: relative; + vertical-align: baseline; +} + +sub { + bottom: -0.25em; +} + +sup { + top: -0.5em; +} + +/* +1. Remove text indentation from table contents in Chrome and Safari. (https://bugs.chromium.org/p/chromium/issues/detail?id=999088, https://bugs.webkit.org/show_bug.cgi?id=201297) +2. Correct table border color inheritance in all Chrome and Safari. (https://bugs.chromium.org/p/chromium/issues/detail?id=935729, https://bugs.webkit.org/show_bug.cgi?id=195016) +3. Remove gaps between table borders by default. +*/ + +table { + text-indent: 0; + /* 1 */ + border-color: inherit; + /* 2 */ + border-collapse: collapse; + /* 3 */ +} + +/* +1. Change the font styles in all browsers. +2. Remove the margin in Firefox and Safari. +3. Remove default padding in all browsers. +*/ + +button, +input, +optgroup, +select, +textarea { + font-family: inherit; + /* 1 */ + font-feature-settings: inherit; + /* 1 */ + font-variation-settings: inherit; + /* 1 */ + font-size: 100%; + /* 1 */ + font-weight: inherit; + /* 1 */ + line-height: inherit; + /* 1 */ + letter-spacing: inherit; + /* 1 */ + color: inherit; + /* 1 */ + margin: 0; + /* 2 */ + padding: 0; + /* 3 */ +} + +/* +Remove the inheritance of text transform in Edge and Firefox. +*/ + +button, +select { + text-transform: none; +} + +/* +1. Correct the inability to style clickable types in iOS and Safari. +2. Remove default button styles. +*/ + +button, +input:where([type='button']), +input:where([type='reset']), +input:where([type='submit']) { + -webkit-appearance: button; + /* 1 */ + background-color: transparent; + /* 2 */ + background-image: none; + /* 2 */ +} + +/* +Use the modern Firefox focus style for all focusable elements. +*/ + +:-moz-focusring { + outline: auto; +} + +/* +Remove the additional `:invalid` styles in Firefox. (https://github.com/mozilla/gecko-dev/blob/2f9eacd9d3d995c937b4251a5557d95d494c9be1/layout/style/res/forms.css#L728-L737) +*/ + +:-moz-ui-invalid { + box-shadow: none; +} + +/* +Add the correct vertical alignment in Chrome and Firefox. +*/ + +progress { + vertical-align: baseline; +} + +/* +Correct the cursor style of increment and decrement buttons in Safari. +*/ + +::-webkit-inner-spin-button, +::-webkit-outer-spin-button { + height: auto; +} + +/* +1. Correct the odd appearance in Chrome and Safari. +2. Correct the outline style in Safari. +*/ + +[type='search'] { + -webkit-appearance: textfield; + /* 1 */ + outline-offset: -2px; + /* 2 */ +} + +/* +Remove the inner padding in Chrome and Safari on macOS. +*/ + +::-webkit-search-decoration { + -webkit-appearance: none; +} + +/* +1. Correct the inability to style clickable types in iOS and Safari. +2. Change font properties to `inherit` in Safari. +*/ + +::-webkit-file-upload-button { + -webkit-appearance: button; + /* 1 */ + font: inherit; + /* 2 */ +} + +/* +Add the correct display in Chrome and Safari. +*/ + +summary { + display: list-item; +} + +/* +Removes the default spacing and border for appropriate elements. +*/ + +blockquote, +dl, +dd, +h1, +h2, +h3, +h4, +h5, +h6, +hr, +figure, +p, +pre { + margin: 0; +} + +fieldset { + margin: 0; + padding: 0; +} + +legend { + padding: 0; +} + +ol, +ul, +menu { + list-style: none; + margin: 0; + padding: 0; +} + +/* +Reset default styling for dialogs. +*/ + +dialog { + padding: 0; +} + +/* +Prevent resizing textareas horizontally by default. +*/ + +textarea { + resize: vertical; +} + +/* +1. Reset the default placeholder opacity in Firefox. (https://github.com/tailwindlabs/tailwindcss/issues/3300) +2. Set the default placeholder color to the user's configured gray 400 color. +*/ + +input::-moz-placeholder, textarea::-moz-placeholder { + opacity: 1; + /* 1 */ + color: #9ca3af; + /* 2 */ +} + +input::placeholder, +textarea::placeholder { + opacity: 1; + /* 1 */ + color: #9ca3af; + /* 2 */ +} + +/* +Set the default cursor for buttons. +*/ + +button, +[role="button"] { + cursor: pointer; +} + +/* +Make sure disabled buttons don't get the pointer cursor. +*/ + +:disabled { + cursor: default; +} + +/* +1. Make replaced elements `display: block` by default. (https://github.com/mozdevs/cssremedy/issues/14) +2. Add `vertical-align: middle` to align replaced elements more sensibly by default. (https://github.com/jensimmons/cssremedy/issues/14#issuecomment-634934210) + This can trigger a poorly considered lint error in some tools but is included by design. +*/ + +img, +svg, +video, +canvas, +audio, +iframe, +embed, +object { + display: block; + /* 1 */ + vertical-align: middle; + /* 2 */ +} + +/* +Constrain images and videos to the parent width and preserve their intrinsic aspect ratio. (https://github.com/mozdevs/cssremedy/issues/14) +*/ + +img, +video { + max-width: 100%; + height: auto; +} + +/* Make elements with the HTML hidden attribute stay hidden by default */ + +[hidden]:where(:not([hidden="until-found"])) { + display: none; +} + +.container { + width: 100%; +} + +@media (min-width: 640px) { + .container { + max-width: 640px; + } +} + +@media (min-width: 768px) { + .container { + max-width: 768px; + } +} + +@media (min-width: 1024px) { + .container { + max-width: 1024px; + } +} + +@media (min-width: 1280px) { + .container { + max-width: 1280px; + } +} + +@media (min-width: 1536px) { + .container { + max-width: 1536px; + } +} + +.mx-auto { + margin-left: auto; + margin-right: auto; +} + +.my-8 { + margin-top: 2rem; + margin-bottom: 2rem; +} + +.mb-4 { + margin-bottom: 1rem; +} + +.mb-6 { + margin-bottom: 1.5rem; +} + +.mt-2 { + margin-top: 0.5rem; +} + +.mt-8 { + margin-top: 2rem; +} + +.list-inside { + list-style-position: inside; +} + +.list-disc { + list-style-type: disc; +} + +.rounded-lg { + border-radius: 0.5rem; +} + +.bg-gray-200 { + --tw-bg-opacity: 1; + background-color: rgb(229 231 235 / var(--tw-bg-opacity, 1)); +} + +.bg-gray-800 { + --tw-bg-opacity: 1; + background-color: rgb(31 41 55 / var(--tw-bg-opacity, 1)); +} + +.bg-white { + --tw-bg-opacity: 1; + background-color: rgb(255 255 255 / var(--tw-bg-opacity, 1)); +} + +.bg-gradient-to-r { + background-image: linear-gradient(to right, var(--tw-gradient-stops)); +} + +.from-blue-800 { + --tw-gradient-from: #1e40af var(--tw-gradient-from-position); + --tw-gradient-to: rgb(30 64 175 / 0) var(--tw-gradient-to-position); + --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to); +} + +.to-blue-600 { + --tw-gradient-to: #2563eb var(--tw-gradient-to-position); +} + +.p-4 { + padding: 1rem; +} + +.p-6 { + padding: 1.5rem; +} + +.py-4 { + padding-top: 1rem; + padding-bottom: 1rem; +} + +.py-8 { + padding-top: 2rem; + padding-bottom: 2rem; +} + +.text-center { + text-align: center; +} + +.text-3xl { + font-size: 1.875rem; + line-height: 2.25rem; +} + +.text-5xl { + font-size: 3rem; + line-height: 1; +} + +.text-lg { + font-size: 1.125rem; + line-height: 1.75rem; +} + +.font-bold { + font-weight: 700; +} + +.font-semibold { + font-weight: 600; +} + +.leading-normal { + line-height: 1.5; +} + +.tracking-normal { + letter-spacing: 0em; +} + +.text-blue-800 { + --tw-text-opacity: 1; + color: rgb(30 64 175 / var(--tw-text-opacity, 1)); +} + +.text-gray-800 { + --tw-text-opacity: 1; + color: rgb(31 41 55 / var(--tw-text-opacity, 1)); +} + +.text-white { + --tw-text-opacity: 1; + color: rgb(255 255 255 / var(--tw-text-opacity, 1)); +} + +.shadow-lg { + --tw-shadow: 0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1); + --tw-shadow-colored: 0 10px 15px -3px var(--tw-shadow-color), 0 4px 6px -4px var(--tw-shadow-color); + box-shadow: var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow); +} + +.shadow-md { + --tw-shadow: 0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1); + --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); +} + +h1, + h2, + h3, + h4, + h5, + h6 { + margin: 0; + /* Reset margin for consistency */ +} + +h1 { + font-size: 2.5rem; + /* 40px */ + font-weight: 700; + /* bold */ +} + +h2 { + font-size: 2rem; + /* 32px */ + font-weight: 600; + /* semi-bold */ +} + +h3 { + font-size: 1.75rem; + /* 28px */ + font-weight: 500; + /* medium */ +} + +h4 { + font-size: 1.5rem; + /* 24px */ + font-weight: 400; + /* normal */ +} + +h5 { + font-size: 1.25rem; + /* 20px */ + font-weight: 300; + /* light */ +} + +h6 { + font-size: 1rem; + /* 16px */ + font-weight: 200; + /* extra light */ +} + +.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 */ + } +} + +/* global.css or within a Tailwind plugin */ + +.pulse { + display: inline-block; + transition: transform 0.3s ease-in-out; +} + +.pulse:hover { + transform: scale(1.1); +} + +@keyframes pulse { + 0% { + transform: scale(1); + } + + 50% { + transform: scale(1.5); + } + + 100% { + transform: scale(1); + } +} + +.pulse-hover { + display: inline-block; +} + +.pulse-hover:hover { + animation: pulse 1s infinite; +} + +/* Reset default scrollbar */ + +::-webkit-scrollbar { + width: 8px; + height: 8px; +} + +/* Light theme scrollbar */ + +::-webkit-scrollbar-track { + background: #2c2c2c; + border-radius: 4px; + opacity: 0.5; +} + +.dark ::-webkit-scrollbar-track { + background: #24486b; + border-radius: 4px; + opacity: 0.5; +} + +::-webkit-scrollbar-thumb { + background: linear-gradient(145deg, #00aa7f, #aaffff, #00aaff); + border-radius: 4px; + -webkit-transition: background-color 0.3s ease; + transition: background-color 0.3s ease; +} + +::-webkit-scrollbar-thumb:hover { + background: #555500; +} + +.dark ::-webkit-scrollbar-thumb { + background: #ffffff; +} + +::-webkit-scrollbar-thumb:active { + background: linear-gradient(135deg, #aa55ff, #aaaaff, #ff55ff); +} + +/* Optional: Add transitions for more natural feel */ + +ython.assistant-unused .note:-webkit-scrollbar { + scroll-behavior: smooth; +} + +/* Simulate a placeholder on the contenteditable div */ + +#userInput:empty:before { + content: attr(data-placeholder); + color: #9ca3af; +} + +/* Always ensure an extra empty row at the bottom */ + +#userInput::after { + content: "\A"; + /* Inserts a newline */ + white-space: pre; + display: block; + visibility: hidden; + height: 2.4em; + /* Adjust this value to match the height of an empty row */ +} + +@keyframes modalEnter { + from { + transform: scale(0); + opacity: 0; + } + + to { + transform: scale(1); + opacity: 1; + } +} + +@keyframes modalExit { + from { + transform: scale(1); + opacity: 1; + } + + to { + transform: scale(0); + opacity: 0; + } +} + +.animate-enter { + animation: modalEnter 0.4s ease-out forwards; +} + +.animate-exit { + animation: modalExit 0.3s ease-in forwards; +} + +@keyframes singleRipple { + 0% { + transform: scale(0.8); + opacity: 1; + } + + 100% { + transform: scale(2.5); + opacity: 0; + } +} + +.ripple-single-1 { + position: absolute; + border: 3px solid; + -o-border-image: linear-gradient(45deg, #ff8a65, #ff7043) 1; + border-image: linear-gradient(45deg, #ff8a65, #ff7043) 1; + width: 80%; + height: 80%; + animation: singleRipple 1.8s infinite; + pointer-events: none; +} + +.ripple-single-2 { + position: absolute; + border: 3px solid; + -o-border-image: linear-gradient(45deg, #ff8a65, #55aaff) 1; + border-image: linear-gradient(45deg, #ff8a65, #55aaff) 1; + width: 80%; + height: 80%; + animation: singleRipple 1.8s infinite; + pointer-events: none; +} + +.ripple-single-3 { + position: absolute; + border: 3px solid; + -o-border-image: linear-gradient(45deg, #55ff7f, #ff7043) 1; + border-image: linear-gradient(45deg, #55ff7f, #ff7043) 1; + border-radius: 50%; + width: 80%; + height: 80%; + animation: singleRipple 1.8s infinite; + pointer-events: none; +} + +.ripple-single-1 { + animation-delay: 0s; +} + +.ripple-single-2 { + animation-delay: 0.6s; +} + +.ripple-single-3 { + animation-delay: 1.2s; +} + +/* Light code theme*/ + +/* Dark code theme*/ + +.hljs { + background-color: #282c34; + color: #abb2bf; + padding: 15px; + border-radius: 8px; + line-height: 1.5; + font-family: "Fira Code", monospace; +} + +.hljs-keyword { + color: #c678dd; + font-weight: bold; +} + +.hljs-built_in { + color: #e06c74; +} + +.hljs-string { + color: #98c379; +} + +.hljs-number { + color: #d19a66; +} + +.hljs-comment { + color: #5c6370; + font-style: italic; +} + +.hljs-function { + color: #61afef; +} + +.hljs-params { + color: #abb2bf; +} + +.hljs-variable { + color: #d19a66; +} + +.hljs-class { + color: #e5c07b; +} + +.hljs-title { + color: #61afef; +} + +.hljs-attribute { + color: #d19a66; +} + +.hljs-symbol { + color: #61afef; +} + +.hljs-bullet { + color: #abb2bf; +} + +.hljs-meta { + color: #5c6370; +} + +.hljs-link { + color: #61afef; + text-decoration: underline; +} + +.hljs-doctag { + color: #c678dd; + font-weight: bold; +} + +.hljs-tag { + color: #e06c74; +} + +.hljs-name { + color: #61afef; +} + +.hljs-attr { + color: #d19a66; + color: #00aaff; +} + +.hljs-literal { + color: #d19a66; +} + +.hover\:underline:hover { + text-decoration-line: underline; +} 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: + +""" + +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/build/lib/filemac/AudioExtractor.py b/build/lib/filemac/AudioExtractor.py deleted file mode 100644 index 65172b1..0000000 --- a/build/lib/filemac/AudioExtractor.py +++ /dev/null @@ -1,56 +0,0 @@ -import os -import sys -from moviepy.editor import VideoFileClip -import logging -import logging.handlers -############################################################################### -logging.basicConfig(level=logging.INFO, format='%(levelname)-8s %(message)s') -logger = logging.getLogger(__name__) - - -class ExtractAudio: - 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("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) - 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("\033[1;33mExtracting..\033[1;36m") - 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) - - -if __name__ == "__main__": - vi = ExtractAudio( - "/home/skye/Music/Melody in My Mind.mp4") - vi.moviepyextract() diff --git a/build/lib/filemac/OCRTextExtractor.py b/build/lib/filemac/OCRTextExtractor.py deleted file mode 100644 index 392ff6d..0000000 --- a/build/lib/filemac/OCRTextExtractor.py +++ /dev/null @@ -1,101 +0,0 @@ -import os -import sys -import cv2 -import pytesseract -from PIL import Image -import logging -import logging.handlers -############################################################################### -logging.basicConfig(level=logging.INFO, format='%(levelname)-8s %(message)s') -logger = logging.getLogger(__name__) -############################################################################### -'''Do OCR text extraction from a given image file and display the extracted - text - to the screen finally save it to a text file assuming the name of the input - file''' - -############################################################################### - - -class ExtractText: - def __init__(self, input_file): - self.input_file = input_file - - 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("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 - - def OCR(self): - image_list = self.preprocess() - ls = ['png', 'jpg'] - image_list = [ - item for item in image_list if any(item.lower().endswith(ext) - for ext in ls)] - - def ocr_text_extraction(image_path): - '''Load image using OpenCV''' - img = cv2.imread(image_path) - - logger.info(f"\033[2;95mprocessing {image_path}...\033[0m") - - try: - '''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)[1] - img_pil = Image.fromarray(thresh) - - '''Perform OCR using pytesseract''' - config = ("-l eng --oem 3 --psm 6") - text = pytesseract.image_to_string((img_pil), config=config) - - '''Remove extra whitespaces and newlines - text = ' '.join(text.split()).strip()''' - logger.info("\033[36mFound:\n\033[0m") - print(text) - current_path = os.getcwd() - file_path = os.path.join(current_path, OCR_file) - ''' Save the extracted text to specified file ''' - logger.info("\033[1;92mGenerating text file for the extracted \ -text..\033[0m") - - with open(file_path, 'w') as file: - file.write(text) - logger.info( - f"File saved as \033[1;93m{OCR_file}\033[0m:") - '''If there are multiple candidate images for text extraction, - wait for key press before proceeding to the next - image otherwise don't wait - size = [i for i in enumerate(image_list)]''' - if len(image_list) >= 2: - input("\033[5;97mPress Enter to continue\033[0m") - except KeyboardInterrupt: - print("\nExiting") - sys.exit(0) - except FileNotFoundError as e: - logger.error(f"Error: {str(e)}") - except IOError as e: - logger.error( - f"Could not write to output file '{OCR_file}'. \ -Reason: {str(e)}\033[0m") - except Exception as e: - logger.error(f"Error: {type(e).__name__}: {str(e)}") - except Exception as e: - logger.error(f"Error:>>\033[31m{e}\033[0m") - return text - - for image_path in image_list: - OCR_file = image_path[:-4] + ".txt" - ocr_text_extraction(image_path) diff --git a/build/lib/filemac/__init__.py b/build/lib/filemac/__init__.py deleted file mode 100644 index e32c40a..0000000 --- a/build/lib/filemac/__init__.py +++ /dev/null @@ -1 +0,0 @@ -from .fmac import main diff --git a/build/lib/filemac/__pycache__/AudioExtractor.cpython-311.pyc b/build/lib/filemac/__pycache__/AudioExtractor.cpython-311.pyc deleted file mode 100644 index 36b350c..0000000 Binary files a/build/lib/filemac/__pycache__/AudioExtractor.cpython-311.pyc and /dev/null differ diff --git a/build/lib/filemac/__pycache__/OCRTextExtractor.cpython-311.pyc b/build/lib/filemac/__pycache__/OCRTextExtractor.cpython-311.pyc deleted file mode 100644 index 2e0efeb..0000000 Binary files a/build/lib/filemac/__pycache__/OCRTextExtractor.cpython-311.pyc and /dev/null differ diff --git a/build/lib/filemac/__pycache__/Simple_v_Analyzer.cpython-311.pyc b/build/lib/filemac/__pycache__/Simple_v_Analyzer.cpython-311.pyc deleted file mode 100644 index a29f114..0000000 Binary files a/build/lib/filemac/__pycache__/Simple_v_Analyzer.cpython-311.pyc and /dev/null differ diff --git a/build/lib/filemac/__pycache__/converter.cpython-311.pyc b/build/lib/filemac/__pycache__/converter.cpython-311.pyc deleted file mode 100644 index cbc7e1f..0000000 Binary files a/build/lib/filemac/__pycache__/converter.cpython-311.pyc and /dev/null differ diff --git a/build/lib/filemac/__pycache__/formats.cpython-311.pyc b/build/lib/filemac/__pycache__/formats.cpython-311.pyc deleted file mode 100644 index d2b6f26..0000000 Binary files a/build/lib/filemac/__pycache__/formats.cpython-311.pyc and /dev/null differ diff --git a/build/lib/filemac/colors.py b/build/lib/filemac/colors.py deleted file mode 100644 index 7e03e49..0000000 --- a/build/lib/filemac/colors.py +++ /dev/null @@ -1,40 +0,0 @@ -import os - -from colorama import Fore, Style, init - -init(autoreset=True) - -if os.name == "posix": - RESET = '\033[0m' - RED = '\033[91m' - DRED = '\033[1;91m' - GREEN = '\033[92m' - DGREEN = '\033[1;92m' - YELLOW = '\033[93m' - DYELLOW = '\033[1;93m' - BLUE = '\033[94m' - DBLUE = '\033[1;94m' - MAGENTA = '\033[95m' - DMAGENTA = '\033[1;95m' - CYAN = '\033[96m' - DCYAN = '\033[1;96m' - ICYAN = '\033[3;96m' - -elif os.name == "nt": - RESET = Style.RESET_ALL - RED = Fore.LIGHTRED_EX - DRED = Fore.RED - GREEN = Fore.LIGHTGREEN_EX - DGREEN = Fore.GREEN - YELLOW = Fore.LIGHTYELLOW_EX - DYELLOW = Fore.YELLOW - BLUE = Fore.LIGHTBLUE_EX - DBLUE = Fore.BLUE - MAGENTA = Fore.LIGHTMAGENTA_EX - DMAGENTA = Fore.MAGENTA - CYAN = Fore.LIGHTCYAN_EX - DCYAN = Fore.CYAN - ICYAN = Fore.WHITE - -#return RESET, RED, DRED, GREEN, DGREEN, YELLOW, DYELLOW, BLUE, DBLUE, -#MAGENTA, DMAGENTA, CYAN, DCYAN diff --git a/build/lib/filemac/converter.py b/build/lib/filemac/converter.py deleted file mode 100644 index a46a46f..0000000 --- a/build/lib/filemac/converter.py +++ /dev/null @@ -1,1027 +0,0 @@ -############################################################################# -import logging -import logging.handlers -# import math -import os -import re -import sqlite3 -import subprocess -import sys -import time -import traceback -# import pdfminer.high_level -# from typing import Iterable -from pdf2image import convert_from_path -import cv2 -import pandas as pd -import pydub -import PyPDF2 -# import pytesseract -import requests -import speedtest -from docx import Document -# from pydub.playback import play -from gtts import gTTS -# from PyPDF2 import PdfFileReader -from moviepy.editor import VideoFileClip -from pdf2docx import parse -from PIL import Image -from pptx import Presentation -from pydub import AudioSegment -from .colors import (RESET, GREEN, DGREEN, YELLOW, DYELLOW, CYAN, BLUE, DBLUE, - MAGENTA, DMAGENTA, RED, DRED, ICYAN) -from reportlab.lib.pagesizes import letter -from reportlab.platypus import Paragraph, SimpleDocTemplate - -from .formats import (SUPPORTED_AUDIO_FORMATS, SUPPORTED_IMAGE_FORMATS, - SUPPORTED_VIDEO_FORMATS) - -# import pygame -# from aspose.words import Document as aspose_document -# from aspose.slides import Presentation as aspose_presentation -# from show_progress import progress_show -# from PIL import ImageDraw, ImageFont -############################################################################### - -PYGAME_DETECT_AVX2 = 1 -logging.basicConfig(level=logging.INFO, format='%(levelname)-8s %(message)s') -logger = logging.getLogger(__name__) - - -class MakeConversion: - - '''Initialize the class''' - - def __init__(self, input_file): - self.input_file = input_file - - '''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 sam - directory as the 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("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) - -############################################################################### -# Convert word file to pdf document (docx) -############################################################################### - def word_to_pdf(self): - word_list = self.preprocess() - ls = ["doc", "docx"] - word_list = [ - item for item in word_list if any(item.lower().endswith(ext) for ext in ls)] - for word_file in word_list: - if word_file.lower().endswith("doc"): - pdf_file = word_file[:-3] + "pdf" - elif word_file.lower().endswith("docx"): - pdf_file = word_file[:-4] + "pdf" - - try: - print( - f'{BLUE}Converting: {RESET}{word_file} {BLUE}to {RESET}{pdf_file}') - if os.name == 'posix': # Check if running on Linux - # Use subprocess to run the dpkg and grep commands - result = subprocess.run( - ['dpkg', '-l', 'libreoffice'], stdout=subprocess.PIPE, text=True) - if result.returncode != 0: - print( - "Please install libreoffice to use this functionality !") - sys.exit(1) - subprocess.run(['soffice', '--convert-to', - 'pdf', word_file, pdf_file]) - # print(f"{DMAGENTA} Successfully converted {word_file} to {pdf_file}{RESET}") - elif os.name == "nt": - try: - from docx2pdf import convert - except ImportError: - print("Run pip install docx2pdf for this function to work") - sys.exit(1) - convert(word_file, pdf_file) - print( - f"{DMAGENTA} Successfully converted {word_file} to {pdf_file}{RESET}") - - except Exception as e: - print(f"Error converting {word_file} to {pdf_file}: {e}") - -############################################################################### -# Convert pdf file to word document (docx) -############################################################################### - def pdf_to_word(self): - pdf_list = self.preprocess() - pdf_list = [item for item in pdf_list if item.lower().endswith("pdf")] - for pdf_file in pdf_list: - if pdf_file.lower().endswith("pdf"): - word_file = pdf_file[:-3] + "docx" - - try: - - parse(pdf_file, word_file, start=0, end=None) - - print(f'{GREEN}Converting to word..{RESET}', end='\r') - - logger.info(f"{DMAGENTA} Successfully converted{pdf_file} \ -to {word_file}{RESET}") - except KeyboardInterrupt: - print("\nExiting..") - sys.exit(1) - except Exception as e: - logger.info(f'{DRED}All conversion attempts have failed: \ -{e}{RESET}') - -############################################################################### -# Convert text file(s) to pdf document (docx) -############################################################################### - def txt_to_pdf(input_file, output_file): - """Convert a .txt file to a PDF.""" - - # Read the contents of the input .txt file - with open(input_file, 'r', encoding='utf-8') as file: - text_contents = file.readlines() - - # Initialize the PDF document - doc = SimpleDocTemplate(output_file, pagesize=letter) - - # Create a story to hold the elements of the PDF - story = [] - - # Iterate through each line in the input .txt file and add it to the PDF - for line in text_contents: - story.append(Paragraph(line.strip(), style="normalText")) - - # Build and write the PDF document - doc.build(story) - -############################################################################### -# Convert word file(s) to pptx document (pptx/ppt) -############################################################################### - def word_to_pptx(self): - word_list = self.preprocess() - word_list = [item for item in word_list if item.lower().endswith( - "docx") or item.lower().endswith("doc")] - - for word_file in word_list: - - if word_list is None: - print("Please provide appropriate file type") - sys.exit(1) - if word_file.lower().endswith("docx"): - pptx_file = word_file[:-4] + "pptx" - elif word_file.lower().endswith("doc"): - pptx_file = word_file[:-3] + "pptx" - try: - # Load the Word document - print(F"{DYELLOW}Load the Word document..{RESET}") - doc = Document(word_file) - - # Create a new PowerPoint presentation - print(F"{DYELLOW}Create a new PowerPoint presentation..{RESET}") - prs = Presentation() - - # Iterate through each paragraph in the Word document - print( - f"{DGREEN}Populating pptx slides with {DYELLOW}{len(doc.paragraphs)}{DGREEN} entries..{RESET}") - count = 0 - for paragraph in doc.paragraphs: - count += 1 - perc = (count/len(doc.paragraphs))*100 - print( - f"{DMAGENTA}Progress:: \033[1;36m{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) - print(f"\n{DGREEN}Done{RESET}") - except KeyboardInterrupt: - print("\nExiting") - sys.exit(1) - except KeyboardInterrupt: - print("\nExiting..") - sys.exit(1) - except Exception as e: - logger.error(e) - -############################################################################### -# Convert word file to txt file''' -############################################################################### - - def word_to_txt(self): - word_list = self.preprocess() - word_list = [item for item in word_list if item.lower().endswith( - "docx") or item.lower().endswith("doc")] - for file_path in word_list: - if file_path.lower().endswith("docx"): - txt_file = file_path[:-4] + "txt" - elif file_path.lower().endswith("doc"): - txt_file = file_path[:-3] + "txt" - try: - doc = Document(file_path) - print("INFO Processing...") - - 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:{BLUE}{Par}/{len(doc.paragraphs)}{RESET}", end='\r') - logger.info(f"{DMAGENTA}Conversion of file to txt success{RESET}") - - except KeyboardInterrupt: - print("\nExit") - sys.exit() - except Exception as e: - logger.error( - f"Dear user something went amiss while attempting the conversion:\n {e}") - with open("conversion.log", "a") as log_file: - log_file.write(f"Couldn't convert {file_path} to {txt_file}:\ -REASON->{e}") - -############################################################################### -# Convert pdf file to text file -############################################################################### - def pdf_to_txt(self): - 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: - with open(file_path, 'rb') as file: - pdf_reader = PyPDF2.PdfReader(file) - text = '' - for page_num in range(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"{DMAGENTA}Successfully converted {file_path} to \ -{txt_file}{RESET}") - except Exception as e: - logger.error( - f"Oops somethin went astray while converting {file_path} \ -to {txt_file}: {e}") - with open("conversion.log", "a") as log_file: - log_file.write( - f"Error converting {file_path} to {txt_file}: {e}\n") - -############################################################################### -# Convert ppt file to word document -############################################################################### - def ppt_to_word(self): - ppt_list = self.preprocess() - ppt_list = [item for item in ppt_list if item.lower().endswith( - "pptx") or item.lower().endswith("ppt")] - for file_path in ppt_list: - if file_path.lower().endswith("pptx"): - word_file = file_path[:-4] + "docx" - elif file_path.lower().endswith("ppt"): - word_file = file_path[:-3] + "docx" - try: - presentation = Presentation(file_path) - document = Document() - - for slide in presentation.slides: - for shape in slide.shapes: - if shape.has_text_frame: - text_frame = shape.text_frame - for paragraph in text_frame.paragraphs: - new_paragraph = document.add_paragraph() - for run in paragraph.runs: - new_run = new_paragraph.add_run(run.text) - # Preserve bold formatting - new_run.bold = run.font.bold - # Preserve italic formatting - new_run.italic = run.font.italic - # Preserve underline formatting - new_run.underline = run.font.underline - # Preserve font name - new_run.font.name = run.font.name - # Preserve font size - new_run.font.size = run.font.size - try: - # Preserve font color - new_run.font.color.rgb = run.font.color.rgb - except AttributeError: - # Ignore error and continue without - # setting the font color - pass - # Add a new paragraph after each slide - document.add_paragraph() - document.save(word_file) - logger.info(f"{DMAGENTA}Successfully converted {file_path} to \ - {word_file}{RESET}") - except Exception as e: - logger.error( - f"Oops somethin gwent awry while attempting to convert \ - {file_path} to {word_file}:\n>>>{e}") - with open("conversion.log", "a") as log_file: - log_file.write( - f"Oops something went astray while attempting \ - convert {file_path} to {word_file}:{e}\n") - -############################################################################### -# Convert text file to word -############################################################################### - def text_to_word(self): - 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 - 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 - 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"{DMAGENTA}Successfully converted {file_path} to \ - {word_file}{RESET}") - except FileExistsError as e: - logger.error(f"{str(e)}") - except Exception as e: - logger.error( - f"Oops Unable to perfom requested conversion: {e}\n") - with open("conversion.log", "a") as log_file: - log_file.write( - f"Error converting {file_path} to {word_file}: \ -{e}\n") - -############################################################################### -# Convert xlsx file(s) to word file(s) -############################################################################### - def convert_xls_to_word(self): - xls_list = self.preprocess() - ls = ["xlsx", "xls"] - xls_list = [item for item in xls_list if any( - item.lower().endswith(ext) for ext in ls)] - print(F"{DGREEN}Initializing conversion sequence{RESET}") - for xls_file in xls_list: - if xls_file.lower().endswith("xlsx"): - word_file = xls_file[:-4] + "docx" - elif xls_file.lower().endswith("xls"): - word_file = xls_file[:-3] + "docx" - 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"{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 {DYELLOW}{current_row}/{total_rows} \ -{DBLUE}{percentage:.1f}%{RESET}", end="\r") - # print(f"\033[1;36m{row}{RESET}") - - # Save the Word document - doc.save(word_file) - print(F"{DGREEN}Conversion successful!{RESET}", end="\n") - except KeyboardInterrupt: - print("\nExiting") - sys.exit(1) - except Exception as e: - print("Oops Conversion failed:", str(e)) - -############################################################################### - '''Convert xlsx/xls file/files to text file format''' -############################################################################### - - def convert_xls_to_text(self): - xls_list = self.preprocess() - ls = ["xlsx", "xls"] - xls_list = [ - item for item in xls_list if any(item.lower().endswith(ext) - for ext in ls)] - print(F"{DGREEN}Initializing conversion sequence{RESET}") - for xls_file in xls_list: - if xls_file .lower().endswith("xlsx"): - txt_file = xls_file[:-4] + "txt" - elif xls_file .lower().endswith("xls"): - txt_file = xls_file[:-3] + "txt" - 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: {DYELLOW}{chars} \033[1;30m \ -characters{DYELLOW} {words}\033[1;30m words {DYELLOW}{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"{DGREEN}Conversion successful!{RESET}", end="\n") - except KeyboardInterrupt: - print("\nExiting") - sys.exit(1) - except Exception as e: - print("Oops Conversion failed:", str(e)) - -############################################################################### - '''Convert xlsx/xls file to csv(comma seperated values) format''' -############################################################################### - - def convert_xlsx_to_csv(self): - xls_list = self.preprocess() - ls = ["xlsx", "xls"] - xls_list = [ - item for item in xls_list if any(item.lower().endswith(ext) - for ext in ls)] - for xls_file in xls_list: - if xls_file.lower().endswith("xlsx"): - csv_file = xls_file[:-4] + "csv" - elif xls_file.lower().endswith("xls"): - csv_file = xls_file[:-3] + "csv" - try: - '''Load the Excel file''' - print(F"{DGREEN}Initializing conversion sequence{RESET}") - df = pd.read_excel(xls_file) - logger.info(f"Converting {xls_file}..") - total_rows = df.shape[0] - print(f"Writing {DYELLOW}{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"{DMAGENTA} Conversion successful{RESET}") - except KeyboardInterrupt: - print("Exiting") - sys.exit(1) - except Exception as e: - print(e) - -############################################################################### -# Convert xlsx file(s) to sqlite -############################################################################### - - def convert_xlsx_to_database(self): - xlsx_list = self.preprocess() - ls = ["xlsx", "xls"] - xlsx_list = [ - item for item in xlsx_list if any(item.lower().endswith(ext) - for ext in ls)] - for xlsx_file in xlsx_list: - if xlsx_file.lower().endswith("xlsx"): - sqlfile = xlsx_file[:-4] - elif xlsx_file.lower().endswith("xls"): - sqlfile = xlsx_file[:-3] - try: - db_file = input( - F"{DBLUE}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 + "sql" - table_name = sqlfile - if not db_file.endswith(".sql"): - db_file = db_file + ".sql" - 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"{DGREEN}Initializing conversion sequence{RESET}") - print(f"{DGREEN} Connected to sqlite3 database::{RESET}") - # Create a connection to the SQLite database - conn = sqlite3.connect(db_file) - print(F"{DYELLOW} 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("\nExiting") - sys.exit(1) - except Exception as e: - logger.error(f"{e}") - -############################################################################### -# Create image objects from given files -############################################################################### - def doc2image(self, outf="png"): - outf_list = ['png', 'jpg'] - if outf not in outf_list: - outf = "png" - path_list = self.preprocess() - ls = ["pdf", "doc", "docx"] - file_list = [ - item for item in path_list if any(item.lower().endswith(ext) - for ext in ls)] - imgs = [] - for file in file_list: - if file.lower().endswith("pdf"): - # Convert the PDF to a list of PIL image objects - print("Generate image objects ..") - images = convert_from_path(file) - - # Save each image to a file - fname = file[:-4] - print(f"{YELLOW}Target images{BLUE} {len(images)}{RESET}") - for i, image in enumerate(images): - print(f"{DBLUE}{i}{RESET}", end="\r") - yd = f"{fname}_{i+1}.{outf}" - image.save(yd) - imgs.append(yd) - print(f"{GREEN}Ok{RESET}") - - return imgs - - -class Scanner: - - def __init__(self, input_file): - self.input_file = input_file - - 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): - pdf_list = self.preprocess() - pdf_list = [item for item in pdf_list if item.lower().endswith("pdf")] - - for pdf in pdf_list: - out_f = pdf[:-3] + 'txt' - print(f"{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"{DYELLOW}Progress:{RESET}", end="") - print(f"{CYAN}{pg}/{len(reader.pages)}{RESET}", end="\r") - page = reader.pages[page_num] - text += page.extract_text() - - print(f"\n{text}") - print(F"\n{YELLOW}Write text to {GREEN}{out_f}{RESET}") - with open(out_f, 'w') as f: - f.write(text) - - print(F"{DGREEN}Ok{RESET}") - - def scanAsImgs(self): - file = self.input_file - mc = MakeConversion(file) - img_objs = mc.doc2image() - # print(img_objs) - from .OCRTextExtractor import ExtractText - text = '' - for i in img_objs: - extract = ExtractText(i) - tx = extract.OCR() - if tx is not None: - text += tx - print(text) - print(f"{GREEN}Ok{RESET}") - return text - - -class FileSynthesis: - - def __init__(self, input_file): - self.input_file = input_file - # self.CHUNK_SIZE = 20_000 - - 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 - - @staticmethod - def join_audios(files, output_file): - masterfile = output_file + "_master.mp3" - print( - f"{DBLUE}Create a master file {DMAGENTA}{masterfile}{RESET}", end='\r') - # Create a list to store files - ogg_files = [] - # loop through the directory while adding the ogg files to the list - print(files) - for filename in files: - print(f"Join {DBLUE}{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"{DGREEN}Master file:Ok {RESET}") - - def Synthesise(self, text: str, output_file: str, CHUNK_SIZE: int = 20_000, ogg_folder: str = 'tempfile', retries: int = 5) -> None: - """Converts given text to speech using Google Text-to-Speech API.""" - out_ls = [] - try: - if not os.path.exists(ogg_folder): - os.mkdir(ogg_folder) - print(f"{DYELLOW}Get initial net speed..{RESET}") - st = speedtest.Speedtest() # get initial network speed - st.get_best_server() - download_speed: float = st.download() # Keep units as bytes - logger.info( - - f"{GREEN} Conversion to mp3 sequence initialized start\ -speed {CYAN}{download_speed/1_000_000:.2f}Kbps{RESET}") - - for attempt in range(retries): - try: - '''Split input text into smaller parts and generate - individual gTTS objects''' - counter = 0 - for i in range(0, len(text), CHUNK_SIZE): - chunk = text[i:i+CHUNK_SIZE] - output_filename = f"{output_file}_{counter}.ogg" - counter += 1 - # print(output_filename) - if os.path.exists(output_filename): - output_filename = f"{output_file}_{counter+1}.ogg" - # print(output_filename) - tts = gTTS(text=chunk, lang='en', slow=False) - tts.save(output_filename) - out_ls.append(output_filename) - break - # print(out_ls) - '''Handle any network related issue gracefully''' - except Exception in (ConnectionError, ConnectionAbortedError, - ConnectionRefusedError, - ConnectionResetError) as e: - logger.error(f"Sorry boss connection problem encountered: {e} in {attempt+1}/{retries}:") - time.sleep(5) # Wait 5 seconds before retrying - - # Handle connectivity/network error - except requests.exceptions.RequestException as e: - logger.error(f"{e}") - except Exception as e: - logger.error(f'{DRED} Error during conversion attempt \ -{attempt+1}/{retries}:{e}{RESET}') - tb = traceback.extract_tb(sys.exc_info()[2]) - logger.info("\n".join([f" > {line}" - for line in map(str, tb)])) - time.sleep(3) # Wait 5 seconds before retrying - pass - - if attempt >= retries: - logger.error( - f"Conversion unsuccessful after {retries} attempts.") - sys.exit(2) - - finally: - # print(out_ls) - # Combine generated gTTS objects - if len(out_ls) >= 1: - FileSynthesis.join_audios(out_ls, output_file) - - st = speedtest.Speedtest() - logger.info("Done") - print("Get final speed ...") - logger.info( - - f"{YELLOW}Final Network Speed: {st.download()/(10**6):.2f} Kbps{RESET}") - - @staticmethod - def pdf_to_text(pdf_path): - logger.info('''Processing the file...\n''') - logger.info( - F'{GREEN} Initializing pdf to text conversion sequence...{RESET}') - try: - with open(pdf_path, 'rb') as file: - pdf_reader = PyPDF2.PdfReader(file) - text = '' - for page_num in range(len(pdf_reader.pages)): - page = pdf_reader.pages[page_num] - text += page.extract_text() - print(F"{DGREEN}Ok{RESET}") - return text - except Exception as e: - logger.error( - f"{DRED}Failed to extract text from '{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"{DRED}Error converting {input_file} to text: {str(e)}\ -{RESET}") - - @staticmethod - def docx_to_text(docx_path): - try: - logger.info(f"{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"{DRED}Error converting {docx_path} to text: {e}\ -{RESET}") - - '''Handle input files based on type to initialize conversion sequence''' - - def audiofy(self): - input_list = self.preprocess() - extdoc = ["docx", "doc"] - ls = {"pdf", "docx", "doc", "txt"} - input_list = [item for item in input_list if item.lower().endswith(tuple(ls))] - for input_file in input_list: - if input_file.endswith('.pdf'): - text = FileSynthesis.pdf_to_text(input_file) - output_file = input_file[:-4] - - elif input_file.lower().endswith(tuple(extdoc)): - - text = FileSynthesis.docx_to_text(input_file) - output_file = input_file[:-5] - - elif input_file.endswith('.txt'): - text = FileSynthesis.text_file(input_file) - output_file = input_file[:-4] - - else: - logger.error('Unsupported file format. Please provide \ -a PDF, txt, or Word document.') - sys.exit(1) - try: - FileSynthesis.Synthesise(None, text, output_file) - except KeyboardInterrupt: - sys.exit(1) - - -############################################################################### -# Convert video file to from one format to another''' -############################################################################### - - -class VideoConverter: - - 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("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 - - 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"{DYELLOW}Initializing conversion..{RESET}") - - for file in input_list: - if out_f.upper() in SUPPORTED_VIDEO_FORMATS: - _, ext = os.path.splitext(file) - output_filename = _ + '.' + out_f.lower() - print(output_filename) - else: - print("Unsupported output format") - sys.exit(1) - format_codec = { - "MP4": "mpeg4", - "AVI": "rawvideo", - # "OGV": "avc", - "WEBM": "libvpx", - "MOV": "mpeg4", - "MKV": "MPEG4", - "FLV": "flv" - # "WMV": "WMV" - } - '''Load the video file''' - print(f"{DBLUE}oad file{RESET}") - video = VideoFileClip(file) - '''Export the video to a different format''' - print(f"{DMAGENTA}Converting file to {output_filename}{RESET}") - video.write_videofile( - output_filename, codec=format_codec[out_f]) - '''Close the video file''' - print(f"{DGREEN}Done{RESET}") - video.close() - except KeyboardInterrupt: - print("\nExiting..") - sys.exit(1) - except Exception as e: - print(e) - - -############################################################################### -# Convert Audio file to from one format to another''' -############################################################################### - - -class AudioConverter: - - 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("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 - - def pydub_conv(self): - 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"{DYELLOW}Initializing conversion..{RESET}") - for file in input_list: - if out_f.lower() in SUPPORTED_AUDIO_FORMATS: - _, ext = os.path.splitext(file) - output_filename = _ + '.' + out_f - else: - print("Unsupported output format") - sys.exit(1) - fmt = ext[1:] - print(fmt, out_f) - audio = pydub.AudioSegment.from_file(file, fmt) - print(f"{DMAGENTA}Converting to {output_filename}{RESET}") - audio.export(output_filename, format=out_f) - # new_audio = pydub.AudioSegment.from_file('output_audio.') - print(f"{DGREEN}Done{RESET}") - # play(new_audio) - # new_audio.close() - - -############################################################################### -# Convert images file to from one format to another -############################################################################### - - -class ImageConverter: - - def __init__(self, input_file, out_format): - self.input_file = input_file - self.out_format = out_format - - 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("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): - try: - input_list = self.preprocess() - out_f = self.out_format.upper() - - input_list = [item for item in input_list if any( - item.lower().endswith(ext) for ext in SUPPORTED_IMAGE_FORMATS[out_f])] - for file in input_list: - print(file) - if out_f.upper() in SUPPORTED_IMAGE_FORMATS: - _, ext = os.path.splitext(file) - output_filename = _ + \ - SUPPORTED_IMAGE_FORMATS[out_f].lower() - else: - print("Unsupported output format") - sys.exit(1) - '''Load the image using OpenCV: ''' - print(F"{DYELLOW}Reading input image..{RESET}") - img = cv2.imread(file) - '''Convert the OpenCV image to a PIL image: ''' - print(f"{DMAGENTA}Converting to PIL image{RESET}") - pil_img = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB)) - '''Save the PIL image to a different format: ''' - print(f"\033[1;36mSaving image as {output_filename}{RESET}") - pil_img.save(output_filename, out_f) - print(f"{DGREEN}Done{RESET}") - '''Load the image back into OpenCV: ''' - print(f"{DMAGENTA}Load and display image{RESET}") - opencv_img = cv2.imread(output_filename) - '''Display the images: ''' - cv2.imshow('OpenCV Image', opencv_img) - # pil_img.show() - '''Wait for the user to press a key and close the windows: ''' - cv2.waitKey(0) - cv2.destroyAllWindows() - except KeyboardInterrupt: - print("\nExiting..") - sys.exit(1) diff --git a/build/lib/filemac/dd.py b/build/lib/filemac/dd.py deleted file mode 100644 index 90fbe1f..0000000 --- a/build/lib/filemac/dd.py +++ /dev/null @@ -1,10 +0,0 @@ -from OCRTextExtractor import ExtractText -img_objs = ['/home/skye/Software Engineering/Y2/SEM2/RV/SPE 2210 Client Side Programming Year II Semester II_1.png'] -text = '' -for i in img_objs: - extract = ExtractText(i) - tx = extract.OCR() - print(tx) - if tx is not None: - text += tx -print(text) diff --git a/build/lib/filemac/fmac.py b/build/lib/filemac/fmac.py deleted file mode 100644 index 91b28ba..0000000 --- a/build/lib/filemac/fmac.py +++ /dev/null @@ -1,212 +0,0 @@ -#!/usr/bin/env python3.11.7 -# multimedia_cli/main.py -import argparse -import logging -import logging.handlers -import sys - -from . import handle_warnings -from .AudioExtractor import ExtractAudio -from .colors import (RESET, DYELLOW) -from .converter import (AudioConverter, FileSynthesis, ImageConverter, - MakeConversion, Scanner, VideoConverter) -from .formats import (SUPPORTED_AUDIO_FORMATS_SHOW, SUPPORTED_DOC_FORMATS, - SUPPORTED_IMAGE_FORMATS_SHOW, - SUPPORTED_VIDEO_FORMATS_SHOW) -from .image_op import Compress_Size -from .OCRTextExtractor import ExtractText -from .Simple_v_Analyzer import SA - -# from .formats import SUPPORTED_INPUT_FORMATS, SUPPORTED_OUTPUT_FORMATS -handle_warnings -logging.basicConfig(level=logging.INFO, format='%(levelname)-8s %(message)s') -logger = logging.getLogger(__name__) - - -class Eval: - - def __init__(self, file, outf): - self.file = file - self.outf = outf - - def document_eval(self): - ls = ["docx", "doc"] - sheetls = ["xlsx", "xls"] - try: - conv = MakeConversion(self.file) - if self.file.lower().endswith(tuple(sheetls)): - if self.outf.lower() == "csv": - conv.convert_xlsx_to_csv() - elif self.outf.lower() == "txt": - conv.convert_xls_to_text() - elif self.outf.lower() == "doc" or self.outf == "docx": - conv.convert_xls_to_word() - elif self.outf.lower() == "db": - conv.convert_xlsx_to_database() - - elif self.file.lower().endswith(tuple(ls)): - if self.outf.lower() == "txt": - conv.word_to_txt() - elif self.outf.lower() == "pdf": - conv.word_to_pdf() - elif self.outf.lower() == "pptx": - conv.word_to_pptx() - elif self.outf.lower() == "audio" or self.outf.lower() == "ogg": - conv = FileSynthesis(self.file) - conv.audiofy() - - elif self.file.endswith('txt'): - if self.outf.lower() == "pdf": - conv.txt_to_pdf() - elif self.outf.lower() == "doc" or self.outf == "docx" or self.outf == "word": - conv.text_to_word() - elif self.outf.lower() == "audio" or self.outf.lower() == "ogg": - conv = FileSynthesis(self.file) - conv.audiofy() - - elif self.file.lower().endswith('ppt') or self.file.lower().endswith('pptx'): - if self.outf.lower() == "doc" or self.outf.lower() == "docx" or self.outf == "word": - conv.ppt_to_word() - - elif self.file.lower().endswith('pdf'): - if self.outf.lower() == "doc" or self.outf.lower() == "docx" or self.outf == "word": - conv.pdf_to_word() - elif self.outf.lower() == "txt": - conv.pdf_to_txt() - elif self.outf.lower() == "audio" or self.outf.lower() == "ogg": - conv = FileSynthesis(self.file) - conv.audiofy() - - else: - print(f"{DYELLOW}Unsupported Conversion type{RESET}") - except Exception as e: - logger.error(e) - - -def main(): - parser = argparse.ArgumentParser( - description="Multimedia Element Operations") - - parser.add_argument( - "--convert_doc", help=f"Converter document file(s) to different format ie pdf_to_docx.\ - example {DYELLOW}filemac --convert_doc example.docx -t pdf{RESET}") - - parser.add_argument( - "--convert_audio", help=f"Convert audio file(s) to and from different format ie mp3 to wav\ - example {DYELLOW}filemac --convert_audio example.mp3 -t wav{RESET}") - - parser.add_argument( - "--convert_video", help=f"Convert video file(s) to and from different format ie mp4 to mkv.\ - example {DYELLOW}filemac --convert_video example.mp4 -t mkv{RESET}") - - parser.add_argument( - "--convert_image", help=f"Convert image file(s) to and from different format ie png to jpg.\ - example {DYELLOW}filemac --convert_image example.jpg -t png{RESET}") - - parser.add_argument( - - "--convert_doc2image", help=f"Convert documents to images ie png to jpg.\ - example {DYELLOW}filemac --convert_doc2image example.pdf -t png{RESET}") - - parser.add_argument("-xA", "--extract_audio", - help=f"Extract audio from a video.\ - example {DYELLOW}filemac -xA example.mp4 {RESET}") - - parser.add_argument( - "-Av", "--Analyze_video", help=f"Analyze a given video.\ - example {DYELLOW}filemac --analyze_video example.mp4 {RESET}") - - parser.add_argument("-t", "--target_format", - help="Target format for conversion (optional)") - - parser.add_argument( - "--resize_image", help=f"change size of an image compress/decompress \ - example {DYELLOW}filemac --resize_image example.png -t 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 {DYELLOW}filemac --scan example.pdf {RESET}") - - parser.add_argument( - "-SA", "--scanAsImg", help=f"Scan pdf file and extract text\ - example {DYELLOW}filemac --scanAsImg example.pdf {RESET}") - - parser.add_argument("--OCR", help=f"Extract text from an image.\ - example {DYELLOW}filemac --OCR image.png{RESET}") - - args = parser.parse_args() - - -# Call function to handle document conversion inputs before begining conversion - if args.convert_doc == 'help': - print(SUPPORTED_DOC_FORMATS) - sys.exit(1) - if args.convert_doc: - ev = Eval(args.convert_doc, args.target_format) - ev.document_eval() - - -# 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: - print(SUPPORTED_VIDEO_FORMATS_SHOW) - sys.exit(1) - ev = VideoConverter(args.convert_video, args.target_format) - ev.CONVERT_VIDEO() -# 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: - print(SUPPORTED_IMAGE_FORMATS_SHOW) - sys.exit(1) - conv = ImageConverter(args.convert_image, args.target_format) - conv.convert_image() - -# Handle image resizing - elif args.resize_image: - res = Compress_Size(args.resize_image) - res.resize_image(args.t_size) - -# Handle documents to images conversion - elif args.convert_doc2image: - conv = MakeConversion(args.convert_doc2image) - conv.doc2image(args.target_format) - -# 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: - print(SUPPORTED_AUDIO_FORMATS_SHOW) - sys.exit(1) - ev = AudioConverter(args.convert_audio, args.target_format) - ev.pydub_conv() - - -# Call module to evaluate audio files before making audio extraction from input video files conversion - elif args.extract_audio: - vi = ExtractAudio(args.extract_audio) - vi.moviepyextract() - -# Call module to scan the input and extract text - elif args.scan: - sc = Scanner(args.scan) - sc.scanPDF() - -# Call module to scan the input FILE as image object and extract text - elif args.scanAsImg: - sc = Scanner(args.scanAsImg) - tx = sc.scanAsImgs() -# Call module to handle Candidate images for text extraction inputs before begining conversion - elif args.OCR: - conv = ExtractText(args.OCR) - conv.OCR() - - elif args.Analyze_video: - analyzer = SA(args.Analyze_video) - analyzer.SimpleAnalyzer() - - -if __name__ == "__main__": - main() diff --git a/build/lib/filemac/formats.py b/build/lib/filemac/formats.py deleted file mode 100644 index 6490294..0000000 --- a/build/lib/filemac/formats.py +++ /dev/null @@ -1,121 +0,0 @@ -# multimedia_cli/formats.py -from .colors import CYAN, DBLUE, DMAGENTA, DYELLOW, RESET - -SUPPORTED_DOC_FORMATS = f""" -|--------------------------------------------------------------------------- -|{DBLUE}Input format{RESET} |{DBLUE}Output format{RESET} | -|________________________________|__________________________________________| -| xlsx {DYELLOW}-------------------->{RESET}|csv txt doc/docx db(sql) | -| | | -| doc/docx{DYELLOW}-------------------->{RESET}|txt pdf ppt/pptx audio(ogg) | -| | | -| txt {DYELLOW}-------------------->{RESET}|pdf docx/doc audio(ogg) | -| | | -| pdf {DYELLOW}-------------------->{RESET}|doc/docx txt audio(ogg) | -| | | -| pptx/ppt{DYELLOW}-------------------->{RESET}|doc/docx | -| | -|___________________________________________________________________________| -""" - - -def p(): - print(SUPPORTED_DOC_FORMATS) - - -# 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", - "aac", # Advanced Audio Codec - "bpf", - "aiff", - "flac"] # Free Lossless Audio Codec) - -SUPPORTED_AUDIO_FORMATS_SHOW = f''' -|==============================| -| {DBLUE}Supported I/O formats {RESET} | -|==============================| -| {CYAN} wav {DYELLOW} | -| {CYAN} mp3 {DYELLOW} | -| {CYAN} ogg {DYELLOW} | -| {CYAN} flv {DYELLOW} | -| {CYAN} ogv {DYELLOW} | -| {CYAN} matroska {DYELLOW} | -| {CYAN} mov {DYELLOW} | -| {CYAN} webm {DYELLOW} | -| {CYAN} aac {DYELLOW} | -| {CYAN} bpf {DYELLOW} | --------------------------------- - -''' - -SUPPORTED_VIDEO_FORMATS = ["MP4", # MPEG-4 part 14 - "AVI", # Audio Video Interleave - "OGV", - "WEBM", - "MOV", # QuickTime Movie - "MKV", # Matroska Multimedia Container - MKV is known for its support of high-quality content. - "FLV", # - "WMV"] - -SUPPORTED_VIDEO_FORMATS_SHOW = f''' -,_______________________________________, -|x| {DBLUE}Supported I/O formats{RESET} |x| -|x|-----------------------------------{DYELLOW}|x| -|x| {DMAGENTA} MP4 {DYELLOW} |x| -|x| {DMAGENTA} AVI {DYELLOW} |x| -|x| {DMAGENTA} OGV {DYELLOW} |x| -|x| {DMAGENTA} WEBM{DYELLOW} |x| -|x| {DMAGENTA} MOV {DYELLOW} |x| -|x| {DMAGENTA} MKV {DYELLOW} |x| -|x| {DMAGENTA} FLV {DYELLOW} |x| -|x| {DMAGENTA} WMV {DYELLOW} |x| -|,|___________________________________|,|{DYELLOW} -''' - -SUPPORTED_IMAGE_FORMATS = { - "JPEG": ".jpg", # Joint Photographic Experts Group -Lossy compression - "PNG": ".png", # Joint Photographic Experts Group - not lossy - "GIF": ".gif", # Graphics Interchange Format - "BM": ".bmp", - "BMP": ".dib", - "DXF": ".dxf", # Autocad format 2D - "TIFF": ".tiff", # Tagged Image File Format A flexible and high-quality image format that supports lossless compression - "EXR": ".exr", - "pic": ".pic", - "pict": "pct", - "PDF": ".pdf", - "WebP": ".webp", - "ICNS": ".icns", - "PSD": ".psd", - "SVG": ".svg", # Scalable vector Graphics - "EPS": ".eps", - "PostSciript": ".ps", - "PS": ".ps"} - -SUPPORTED_IMAGE_FORMATS_SHOW = f''' -__________________________________________ -|x|{DBLUE}Supported I/O formats{RESET} |x| -|x|_____________________________________{DYELLOW}|x| -|x| {DMAGENTA} JPEG {DYELLOW} |x| -|x| {DMAGENTA} PNG {DYELLOW} |x| -|x| {DMAGENTA} GIF {DYELLOW} |x| -|x| {DMAGENTA} BM {DYELLOW} |x| -|x| {DMAGENTA} TIFF {DYELLOW} |x| -|x| {DMAGENTA} EXR {DYELLOW} |x| -|x| {DMAGENTA} PDF {DYELLOW} |x| -|x| {DMAGENTA} WebP{DYELLOW} |x| -|x| {DMAGENTA} ICNS {DYELLOW} |x| -|x| {DMAGENTA} PSD {DYELLOW} |x| -|x| {DMAGENTA} SVG {DYELLOW} |x| -|x| {DMAGENTA} EPS {DYELLOW} |x| -|x| {DMAGENTA} Postscript {DYELLOW} |x| -|_|_____________________________________|x| -''' - -SUPPORTED_DOCUMENT_FORMATS = ['pdf', 'doc', 'docx', 'csv', 'xlsx', 'xls', - 'ppt', 'pptx', 'txt', 'ogg', 'mp3', 'audio'] diff --git a/build/lib/filemac/image_op.py b/build/lib/filemac/image_op.py deleted file mode 100644 index 61cfe6d..0000000 --- a/build/lib/filemac/image_op.py +++ /dev/null @@ -1,64 +0,0 @@ -from PIL import Image -import os -import logging -import logging.handlers - -logging.basicConfig(level=logging.INFO, format='%(levelname)-8s %(message)s') -logger = logging.getLogger(__name__) - - -class Compress_Size: - - def __init__(self, input_image_path): - self.input_image_path = input_image_path - - def resize_image(self, target_size): - 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 \033[93m{size/1000_000:.2f}MiB") - - # 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("Invalid units. Please use either \033[1;95m'MB'\033[0m\ - or \033[1;95m'KB'\033[0m") - - # Calculate the new dimensions based on the target size - new_width, new_height = Compress_Size.calculate_new_dimensions(original_size, aspect_ratio, target_size_bytes) - print("\033[94mProcessing ..\033[0m") - resized_image = original_image.resize((new_width, new_height)) - resized_image.save(output_image_path) - t_size = os.path.getsize(output_image_path)/1000_000 - print("\033[1;92mOk\033[0m") - print(f"Image resized to \033[1;93m{t_size:.2f}\033[0m and saved to \033[1;93m{output_image_path}") - - def calculate_new_dimensions(original_size, aspect_ratio, target_size_bytes): - # 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 - - -if __name__ == "__main__": - input_image_path = input("Enter the path to the input image: ") - target_size = input("Enter the target output size (MB or KB): ") - ext = input_image_path[-3:] - output_image_path = os.path.splitext(input_image_path)[0] + f"_resized.{ext}" - - init = Compress_Size(input_image_path) - init.resize_image(target_size) diff --git a/docs/CLI_ENHANCEMENT_PLAN.md b/docs/CLI_ENHANCEMENT_PLAN.md new file mode 100644 index 0000000..27e4e0e --- /dev/null +++ b/docs/CLI_ENHANCEMENT_PLAN.md @@ -0,0 +1,342 @@ +# FileMAC CLI Enhancement Plan + +## Overview + +This document outlines the comprehensive plan to enhance FileMAC's command-line interface using Rich and pyperclip libraries to create a more robust, user-friendly experience. + +## Current State Analysis + +### Strengths +- ✅ Rich library already integrated for progress bars +- ✅ Pyperclip available in environment +- ✅ Existing color support via custom utilities +- ✅ Comprehensive functionality across 40+ commands +- ✅ Well-structured operation mapping system + +### Opportunities for Improvement +- ❌ Basic argparse interface could be more user-friendly +- ❌ Text-based help lacks visual appeal +- ❌ Limited interactive elements +- ❌ No clipboard integration +- ❌ Inconsistent progress feedback + +## Enhancement Strategy + +### Phase 1: Foundation (Week 1-2) + +**Objective**: Establish core utilities and infrastructure + +**Tasks**: +1. **Create Rich Console Wrapper** (`filemac/utils/rich_utils.py`) + - Custom theme matching existing color scheme + - Standardized message formats (info, success, error, warning) + - Console initialization and configuration + +2. **Implement Clipboard Utilities** (`filemac/utils/clipboard.py`) + - `copy_to_clipboard()` function + - `paste_from_clipboard()` function + - Error handling for clipboard operations + +3. **Basic Rich Integration** + - Replace `print()` statements with Rich console methods + - Add color consistency across modules + - Create standard message formats + +### Phase 2: Core Enhancements (Week 3-4) + +**Objective**: Enhance core CLI functionality with Rich features + +**Tasks**: +1. **Enhanced Help System** (`filemac/cli/help.py`) + - Rich-formatted command tables + - Categorized command display + - Interactive help navigation + +2. **Progress Bars for All Operations** (`filemac/utils/progress.py`) + - Standardized progress bar creation + - Consistent styling across modules + - Time estimates and completion percentages + +3. **Enhanced Error Handling** (Enhance `filemac/core/exceptions.py`) + - Rich-formatted error panels + - Contextual error information + - Suggested solutions and troubleshooting + +### Phase 3: Advanced Features (Week 5-6) + +**Objective**: Add interactive elements and workflow improvements + +**Tasks**: +1. **Interactive File Selection** (`filemac/cli/interactive.py`) + - Visual file listing with tables + - Multi-file selection interface + - File preview capabilities + +2. **Clipboard Workflow Integration** (`filemac/cli/clipboard_workflows.py`) + - Clipboard-based input workflows + - Result copying to clipboard + - Batch operation support + +3. **Operation Summary Display** (`filemac/cli/summary.py`) + - Visual operation summaries + - Success/error breakdowns + - Clipboard copy options + +### Phase 4: Integration (Week 7) + +**Objective**: Full integration with existing CLI + +**Tasks**: +1. **Enhanced CLI Entry Point** (Modify `filemac/cli/cli.py`) + - Rich welcome message + - Clipboard support flag + - Enhanced argument parsing + +2. **Operation Mapper Enhancement** (Extend `OperationMapper`) + - Rich progress display + - Clipboard integration + - Enhanced completion messages + +## Implementation Details + +### Rich Utilities Implementation + +```python +# filemac/utils/rich_utils.py +from rich.console import Console +from rich.theme import Theme + +custom_theme = Theme({ + "info": "cyan", + "warning": "yellow", + "error": "bold red", + "success": "bold green", + "debug": "magenta", + "prompt": "bold blue" +}) + +console = Console(theme=custom_theme) + +def print_info(message): + console.print(f"[info]ℹ {message}[/info]") + +def print_success(message): + console.print(f"[success]✓ {message}[/success]") + +def print_error(message): + console.print(f"[error]❌ {message}[/error]") + +def print_warning(message): + console.print(f"[warning]⚠ {message}[/warning]") +``` + +### Clipboard Utilities Implementation + +```python +# filemac/utils/clipboard.py +import pyperclip +from .rich_utils import console, print_success, print_error + +def copy_to_clipboard(text): + """Copy text to system clipboard""" + try: + pyperclip.copy(text) + print_success("Copied to clipboard!") + return True + except Exception as e: + print_error(f"Failed to copy to clipboard: {str(e)}") + return False + +def paste_from_clipboard(): + """Get text from system clipboard""" + try: + content = pyperclip.paste() + return content if content else None + except Exception as e: + print_error(f"Failed to access clipboard: {str(e)}") + return None +``` + +### Enhanced Help System + +```python +# filemac/cli/help.py +from rich.panel import Panel +from rich.table import Table +from rich.box import ROUNDED +from .rich_utils import console + +def show_main_help(): + """Display enhanced help with Rich formatting""" + table = Table( + title="📁 FileMAC Commands", + show_header=True, + header_style="bold magenta", + box=ROUNDED, + border_style="blue" + ) + + table.add_column("Command", style="cyan", no_wrap=True) + table.add_column("Description", style="white") + table.add_column("Example", style="green") + + commands = [ + ("--convert_doc", "Convert documents between formats", "filemac --convert_doc file.docx -to pdf"), + ("--convert_audio", "Convert audio files", "filemac --convert_audio file.mp3 -to wav"), + # ... more commands + ] + + for cmd, desc, example in commands: + table.add_row(cmd, desc, example) + + panel = Panel.fit( + table, + title="[bold]FileMAC Help System[/bold]", + border_style="blue", + subtitle="Advanced file conversion toolkit" + ) + + console.print(panel) +``` + +## Migration Strategy + +### Backward Compatibility +- ✅ Keep all existing command-line arguments +- ✅ Maintain current functionality +- ✅ Add new features as optional flags +- ✅ Preserve existing workflows + +### Gradual Rollout Plan +1. **Week 1-2**: Foundation utilities +2. **Week 3-4**: Core Rich enhancements +3. **Week 5-6**: Advanced interactive features +4. **Week 7**: Full integration and testing + +### Risk Assessment + +**Low Risk**: +- Rich already in dependencies +- Gradual migration approach +- Backward compatibility maintained + +**Medium Risk**: +- User adaptation to new UI +- Clipboard permissions on some systems +- Performance impact of Rich rendering + +**Mitigation**: +- Provide fallback to text mode +- Add configuration options +- Comprehensive error handling +- User education + +## Benefits Realization + +### Immediate Benefits +- ✅ Better visual feedback for users +- ✅ Professional, modern CLI appearance +- ✅ Consistent color scheme and formatting +- ✅ Enhanced error messages with context + +### Medium-Term Benefits +- ✅ Faster workflows with clipboard integration +- ✅ Better user experience with progress indicators +- ✅ Interactive file selection and processing +- ✅ Visual operation summaries + +### Long-Term Benefits +- ✅ Foundation for advanced CLI features +- ✅ Improved user adoption and satisfaction +- ✅ Competitive advantage in CLI tools +- ✅ Easier maintenance and extension + +## Testing Approach + +### Unit Testing +- Test Rich utilities in isolation +- Verify clipboard functionality +- Validate progress bar behavior + +### Integration Testing +- Test with existing CLI commands +- Verify backward compatibility +- Check error handling + +### User Testing +- Gather feedback on new UI +- Test interactive workflows +- Validate clipboard integration + +### Performance Testing +- Measure Rich rendering impact +- Test with large file operations +- Validate progress bar performance + +## Documentation Requirements + +### Updated Documentation +- ✅ README.md with Rich features +- ✅ Examples of new clipboard workflows +- ✅ Visual guides for enhanced UI +- ✅ Updated help system documentation + +### User Education +- ✅ Migration guide for existing users +- ✅ New feature tutorials +- ✅ Best practices for Rich CLI usage +- ✅ Troubleshooting guide + +## Implementation Timeline + +```mermaid +gantt + title FileMAC CLI Enhancement Timeline + dateFormat YYYY-MM-DD + section Phase 1: Foundation + Rich Utilities :a1, 2023-11-01, 5d + Clipboard Helpers :a2, 2023-11-06, 3d + Basic Integration :a3, 2023-11-09, 2d + + section Phase 2: Core Enhancements + Enhanced Help :b1, 2023-11-13, 4d + Progress Bars :b2, 2023-11-17, 3d + Error Handling :b3, 2023-11-20, 3d + + section Phase 3: Advanced Features + Interactive Selection :c1, 2023-11-24, 5d + Clipboard Workflows :c2, 2023-11-29, 4d + Operation Summaries :c3, 2023-12-03, 3d + + section Phase 4: Integration + CLI Enhancement :d1, 2023-12-06, 5d + Testing & Debugging :d2, 2023-12-11, 4d + Documentation :d3, 2023-12-15, 3d +``` + +## Success Metrics + +### Quantitative Metrics +- ✅ Reduction in user errors +- ✅ Increase in command usage +- ✅ Faster operation completion times +- ✅ Higher user satisfaction scores + +### Qualitative Metrics +- ✅ Positive user feedback +- ✅ Increased feature adoption +- ✅ Improved documentation clarity +- ✅ Enhanced professional appearance + +## Conclusion + +This enhancement plan provides a clear, low-risk path to transform FileMAC's CLI from functional to exceptional. By leveraging existing Rich integration and adding strategic pyperclip functionality, we can significantly improve user experience and productivity while maintaining all existing functionality. + +The gradual migration approach ensures minimal disruption and allows for continuous feedback and improvement throughout the process. + +**Next Steps**: +1. Implement Phase 1 foundation utilities +2. Begin gradual integration with existing modules +3. Test thoroughly and gather user feedback +4. Proceed through phases as planned +5. Document and communicate changes effectively \ No newline at end of file diff --git a/docs/index.html b/docs/index.html new file mode 100644 index 0000000..2a73f80 --- /dev/null +++ b/docs/index.html @@ -0,0 +1,137 @@ + + + + + + FileMAC - Multimedia File Operation Kit + + + + + +
+
+

FileMAC

+

+ A Comprehensive Multimedia File Operation Kit +

+
+
+ + +
+ +
+

Introduction

+

+ FileMAC is a Python-based command-line interface (CLI) utility + designed for efficient file conversion, manipulation, and analysis. It + supports various multimedia operations, including document conversion, + file analysis, and text-to-speech conversion using Google's + Text-to-Speech (gTTS) library. +

+
+ + +
+

Features

+
    +
  • Convert documents between various formats.
  • +
  • Analyze and manipulate multimedia files.
  • +
  • Generate audio files from text using gTTS.
  • +
  • + Command-line interface for easy integration into scripts and + workflows. +
  • +
  • Supports Linux operating systems.
  • +
  • + Encapsulates reputable multimedia elements for robust performance. +
  • +
+
+ + +
+

Installation

+

Install FileMAC using pip:

+
pip install filemac
+

+ Alternatively, install directly from the GitHub repository: +

+
pip install git+https://github.com/skye-cyber/FileMAC.git
+
+ + +
+

Usage

+

+ After installation, you can use FileMAC through the command line. For + help and available commands, run: +

+
filemac -h
+

or

+
Filemac -h
+

or

+
FILEMAC -h
+

+ To run the CLI app for specific operations, use the following command + structure: +

+
FileMAC [options] stdin format
+

+ Replace [options] with the desired + operation flags, stdin with the + input file, and format with the + target format or operation. +

+
+ + +
+

License

+

+ FileMAC is licensed under the GPL-3.0 License. For more details, refer + to the LICENSE file in the repository. +

+
+ + +
+

Repository

+

+ For more information, visit the GitHub repository: +

+ https://github.com/skye-cyber/FileMAC +
+
+ + + + + diff --git a/filemac.egg-info/PKG-INFO b/filemac.egg-info/PKG-INFO deleted file mode 100644 index fc84dd6..0000000 --- a/filemac.egg-info/PKG-INFO +++ /dev/null @@ -1,156 +0,0 @@ -Metadata-Version: 2.1 -Name: filemac -Version: 1.0.2 -Summary: Open source Python CLI toolkit for conversion, manipulation, Analysis -Author: wambua -Author-email: wambuamwiky2001@gmail.com -License: GPL v3 -Keywords: file-conversion,file-analysis,file-manipulation,ocr,image-conversion -Classifier: Environment :: Console -Classifier: Natural Language :: English -Classifier: Operating System :: OS Independent -Classifier: Programming Language :: Python -Classifier: Programming Language :: Python :: 3 :: Only -Classifier: Programming Language :: Python :: 3 -Classifier: Programming Language :: Python :: 3.7 -Classifier: Programming Language :: Python :: 3.8 -Classifier: Programming Language :: Python :: 3.9 -Classifier: Programming Language :: Python :: 3.10 -Classifier: Programming Language :: Python :: 3.11 -Requires-Python: >=3.6 -Description-Content-Type: text/markdown -License-File: LICENSE - -# fconverter -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). - -## Installation -1. using pip - - ```shell - pip install filemac - ``` -2. Install from github - - ```shell - pip install git+https://github.com/skye-cyber/FileMAC.git - ``` -## Usage - -To run the CLI app, use the following command: - -```shell -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 - -## Examples - -1. Example command 1: - - ```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```. -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 - -3. Extract text from images - ```shell - filemac --OCR image.jpg - ``` - - 2. 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 - ```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` - -## 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 --convert_doc help -``` -The above command displays the surported input and output formats for document conversion. -## Contributing - -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 - - -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/filemac.egg-info/SOURCES.txt b/filemac.egg-info/SOURCES.txt deleted file mode 100644 index 5d0d298..0000000 --- a/filemac.egg-info/SOURCES.txt +++ /dev/null @@ -1,38 +0,0 @@ -LICENSE -MANIFEST.ini -README.md -setup.py -version.txt -.github/workflows/python-publish.yml -__pycache__/Analyzer.cpython-311.pyc -__pycache__/AudioExtractor.cpython-311.pyc -__pycache__/OCRTextExtractor.cpython-311.pyc -__pycache__/Simple_v_Analyzer.cpython-311.pyc -__pycache__/converter.cpython-311.pyc -__pycache__/formarts.cpython-311.pyc -__pycache__/formats.cpython-311.pyc -__pycache__/show_progress.cpython-311.pyc -filemac/AudioExtractor.py -filemac/OCRTextExtractor.py -filemac/Simple_v_Analyzer.py -filemac/__init__.py -filemac/colors.py -filemac/converter.py -filemac/dd.py -filemac/fmac.py -filemac/formats.py -filemac/handle_warnings.py -filemac/image_op.py -filemac.egg-info/PKG-INFO -filemac.egg-info/SOURCES.txt -filemac.egg-info/dependency_links.txt -filemac.egg-info/entry_points.txt -filemac.egg-info/not-zip-safe -filemac.egg-info/requires.txt -filemac.egg-info/top_level.txt -filemac/__pycache__/AudioExtractor.cpython-311.pyc -filemac/__pycache__/OCRTextExtractor.cpython-311.pyc -filemac/__pycache__/Simple_v_Analyzer.cpython-311.pyc -filemac/__pycache__/colors.cpython-311.pyc -filemac/__pycache__/converter.cpython-311.pyc -filemac/__pycache__/formats.cpython-311.pyc \ No newline at end of file diff --git a/filemac.egg-info/dependency_links.txt b/filemac.egg-info/dependency_links.txt deleted file mode 100644 index 8b13789..0000000 --- a/filemac.egg-info/dependency_links.txt +++ /dev/null @@ -1 +0,0 @@ - diff --git a/filemac.egg-info/entry_points.txt b/filemac.egg-info/entry_points.txt deleted file mode 100644 index eee36a2..0000000 --- a/filemac.egg-info/entry_points.txt +++ /dev/null @@ -1,2 +0,0 @@ -[console_scripts] -filemac = filemac:main diff --git a/filemac.egg-info/not-zip-safe b/filemac.egg-info/not-zip-safe deleted file mode 100644 index 8b13789..0000000 --- a/filemac.egg-info/not-zip-safe +++ /dev/null @@ -1 +0,0 @@ - diff --git a/filemac.egg-info/requires.txt b/filemac.egg-info/requires.txt deleted file mode 100644 index 585f2a3..0000000 --- a/filemac.egg-info/requires.txt +++ /dev/null @@ -1,19 +0,0 @@ -Pillow -PyPDF2 -argparse -gTTS -moviepy -numpy -opencv-python -pandas -pdf2docx -pdf2image -pdfminer.six -pydub -pypandoc -pytesseract -python-docx -python-pptx -reportlab -requests -requests diff --git a/filemac.egg-info/top_level.txt b/filemac.egg-info/top_level.txt deleted file mode 100644 index 93e015a..0000000 --- a/filemac.egg-info/top_level.txt +++ /dev/null @@ -1,2 +0,0 @@ -build -filemac diff --git a/filemac/AudioExtractor.py b/filemac/AudioExtractor.py deleted file mode 100644 index 65172b1..0000000 --- a/filemac/AudioExtractor.py +++ /dev/null @@ -1,56 +0,0 @@ -import os -import sys -from moviepy.editor import VideoFileClip -import logging -import logging.handlers -############################################################################### -logging.basicConfig(level=logging.INFO, format='%(levelname)-8s %(message)s') -logger = logging.getLogger(__name__) - - -class ExtractAudio: - 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("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) - 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("\033[1;33mExtracting..\033[1;36m") - 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) - - -if __name__ == "__main__": - vi = ExtractAudio( - "/home/skye/Music/Melody in My Mind.mp4") - vi.moviepyextract() diff --git a/filemac/OCRTextExtractor.py b/filemac/OCRTextExtractor.py deleted file mode 100644 index 392ff6d..0000000 --- a/filemac/OCRTextExtractor.py +++ /dev/null @@ -1,101 +0,0 @@ -import os -import sys -import cv2 -import pytesseract -from PIL import Image -import logging -import logging.handlers -############################################################################### -logging.basicConfig(level=logging.INFO, format='%(levelname)-8s %(message)s') -logger = logging.getLogger(__name__) -############################################################################### -'''Do OCR text extraction from a given image file and display the extracted - text - to the screen finally save it to a text file assuming the name of the input - file''' - -############################################################################### - - -class ExtractText: - def __init__(self, input_file): - self.input_file = input_file - - 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("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 - - def OCR(self): - image_list = self.preprocess() - ls = ['png', 'jpg'] - image_list = [ - item for item in image_list if any(item.lower().endswith(ext) - for ext in ls)] - - def ocr_text_extraction(image_path): - '''Load image using OpenCV''' - img = cv2.imread(image_path) - - logger.info(f"\033[2;95mprocessing {image_path}...\033[0m") - - try: - '''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)[1] - img_pil = Image.fromarray(thresh) - - '''Perform OCR using pytesseract''' - config = ("-l eng --oem 3 --psm 6") - text = pytesseract.image_to_string((img_pil), config=config) - - '''Remove extra whitespaces and newlines - text = ' '.join(text.split()).strip()''' - logger.info("\033[36mFound:\n\033[0m") - print(text) - current_path = os.getcwd() - file_path = os.path.join(current_path, OCR_file) - ''' Save the extracted text to specified file ''' - logger.info("\033[1;92mGenerating text file for the extracted \ -text..\033[0m") - - with open(file_path, 'w') as file: - file.write(text) - logger.info( - f"File saved as \033[1;93m{OCR_file}\033[0m:") - '''If there are multiple candidate images for text extraction, - wait for key press before proceeding to the next - image otherwise don't wait - size = [i for i in enumerate(image_list)]''' - if len(image_list) >= 2: - input("\033[5;97mPress Enter to continue\033[0m") - except KeyboardInterrupt: - print("\nExiting") - sys.exit(0) - except FileNotFoundError as e: - logger.error(f"Error: {str(e)}") - except IOError as e: - logger.error( - f"Could not write to output file '{OCR_file}'. \ -Reason: {str(e)}\033[0m") - except Exception as e: - logger.error(f"Error: {type(e).__name__}: {str(e)}") - except Exception as e: - logger.error(f"Error:>>\033[31m{e}\033[0m") - return text - - for image_path in image_list: - OCR_file = image_path[:-4] + ".txt" - ocr_text_extraction(image_path) diff --git a/filemac/Simple_v_Analyzer.py b/filemac/Simple_v_Analyzer.py deleted file mode 100644 index 3b492bc..0000000 --- a/filemac/Simple_v_Analyzer.py +++ /dev/null @@ -1,60 +0,0 @@ -import sys -import cv2 -import numpy as np - - -class SA: - - def __init__(self, video): - self.video = video - - def SimpleAnalyzer(self): - try: - # Read the video file - cap = cv2.VideoCapture(self.video) - print("\033[1;33mInitializing..\033[0m") - # Initialize variables - frame_count = 0 - total_area = 0 - duration = 0 - - print("\033[1;36mWorking on it") - 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"Total Frames: \033[1;32m{frame_count}\033[0m") - print(f"Average Frame Area: \033[1;32m{total_area / frame_count}\033[0m") - print(f"Duration: \033[1;32m{duration}\033[0m seconds") - except KeyboardInterrupt: - print("\nExiting") - sys.exit(1) - except Exception as e: - print(e) - sys.exit(1) - - -if __name__ == "__main__": - vi = SA("/home/skye/Music/Melody in My Mind.mp4") - vi.SimpleAnalyzer() diff --git a/filemac/__init__.py b/filemac/__init__.py index e32c40a..7712e4c 100644 --- a/filemac/__init__.py +++ b/filemac/__init__.py @@ -1 +1,21 @@ -from .fmac import main +# FileMAC Package +# Main package initialization +from pathlib import Path +__version__ = open(Path(__file__).parent.parent / "version.txt").read().strip() + +# Import the main CLI functions +from .cli.cli import argsdev as filemac_cli +from .cli.app import enhanced_argsdev as filemac_app + +# Audiobot CLI (if available) +try: + from audiobot.cli import cli as audiobot_cli +except ImportError: + audiobot_cli = None + +# Main entry points +__all__ = ["filemac_cli", "filemac_app", "audiobot_cli"] + +# Aliases for backward compatibility +argsdev = filemac_cli +enhanced_argsdev = filemac_app diff --git a/filemac/__pycache__/AudioExtractor.cpython-311.pyc b/filemac/__pycache__/AudioExtractor.cpython-311.pyc deleted file mode 100644 index 36b350c..0000000 Binary files a/filemac/__pycache__/AudioExtractor.cpython-311.pyc and /dev/null differ diff --git a/filemac/__pycache__/OCRTextExtractor.cpython-311.pyc b/filemac/__pycache__/OCRTextExtractor.cpython-311.pyc deleted file mode 100644 index 2e0efeb..0000000 Binary files a/filemac/__pycache__/OCRTextExtractor.cpython-311.pyc and /dev/null differ diff --git a/filemac/__pycache__/Simple_v_Analyzer.cpython-311.pyc b/filemac/__pycache__/Simple_v_Analyzer.cpython-311.pyc deleted file mode 100644 index a29f114..0000000 Binary files a/filemac/__pycache__/Simple_v_Analyzer.cpython-311.pyc and /dev/null differ diff --git a/filemac/__pycache__/colors.cpython-311.pyc b/filemac/__pycache__/colors.cpython-311.pyc deleted file mode 100644 index 995bc01..0000000 Binary files a/filemac/__pycache__/colors.cpython-311.pyc and /dev/null differ diff --git a/filemac/__pycache__/converter.cpython-311.pyc b/filemac/__pycache__/converter.cpython-311.pyc deleted file mode 100644 index cbc7e1f..0000000 Binary files a/filemac/__pycache__/converter.cpython-311.pyc and /dev/null differ diff --git a/filemac/__pycache__/formats.cpython-311.pyc b/filemac/__pycache__/formats.cpython-311.pyc deleted file mode 100644 index d2b6f26..0000000 Binary files a/filemac/__pycache__/formats.cpython-311.pyc and /dev/null differ diff --git a/filemac/cli/__init__.py b/filemac/cli/__init__.py new file mode 100644 index 0000000..51747b7 --- /dev/null +++ b/filemac/cli/__init__.py @@ -0,0 +1,12 @@ +"""CLI Handling Logic-bridge between user-input and logic""" +from .converter import DirectoryConverter, Batch_Audiofy +from .cli import argsdev, OperationMapper + +__all__ = [ + "DirectoryConverter", + "Batch_Audiofy", + "MethodMappingEngine", + "argsdev", + "OperationMapper", +] + diff --git a/filemac/cli/app.py b/filemac/cli/app.py new file mode 100644 index 0000000..c0ce9cc --- /dev/null +++ b/filemac/cli/app.py @@ -0,0 +1,514 @@ +#!/usr/bin/env python3 +""" +FileMAC Enhanced CLI Application + +This module provides an enhanced CLI interface using Rich and pyperclip +for better user experience while maintaining compatibility with the +original CLI. +""" + +import argparse +import sys +import os +from pathlib import Path +from typing import List, Dict, Any, Optional, Union +from datetime import datetime +# Import existing FileMAC components +from filemac.cli.cli import OperationMapper, argsdev as original_argsdev +from filemac.utils.colors import fg, bg, rs +from filemac.core.exceptions import FileSystemError, FilemacError + +# Rich imports for enhanced UI +from rich.console import Console +from rich.panel import Panel +from rich.table import Table +from rich.box import ROUNDED +from rich.theme import Theme +from rich.progress import Progress, SpinnerColumn, BarColumn, TextColumn +from rich.prompt import Prompt, Confirm + +# Clipboard integration +try: + import pyperclip + CLIPBOARD_AVAILABLE = True +except ImportError: + CLIPBOARD_AVAILABLE = False + +# Initialize Rich console with custom theme +RESET = rs + +custom_theme = Theme({ + "info": "cyan", + "warning": "yellow", + "error": "bold red", + "success": "bold green", + "debug": "magenta", + "prompt": "bold blue", + "header": "bold white on blue", + "footer": "white on grey15" +}) + +console = Console(theme=custom_theme) + + +class RichConsoleUtils: + """Utility class for Rich console operations""" + + @staticmethod + def print_info(message: str): + """Print informational message""" + console.print(f"[info]ℹ {message}[/info]") + + @staticmethod + def print_success(message: str): + """Print success message""" + console.print(f"[success]✓ {message}[/success]") + + @staticmethod + def print_error(message: str): + """Print error message""" + console.print(f"[error]❌ {message}[/error]") + + @staticmethod + def print_warning(message: str): + """Print warning message""" + console.print(f"[warning]⚠ {message}[/warning]") + + @staticmethod + def print_debug(message: str): + """Print debug message""" + console.print(f"[debug]🐞 {message}[/debug]") + + @staticmethod + def print_header(title: str, subtitle: str = ""): + """Print formatted header""" + panel = Panel.fit( + f"[bold]{title}[/bold]\n[dim]{subtitle}[/dim]" if subtitle else f"[bold]{title}[/bold]", + border_style="blue", + title="[header]FileMAC[/header]", + subtitle="[footer]Advanced File Processing[/footer]" + ) + console.print(panel) + + +class ClipboardManager: + """Clipboard operations manager""" + + @staticmethod + def is_available() -> bool: + """Check if clipboard is available""" + return CLIPBOARD_AVAILABLE + + @staticmethod + def copy_to_clipboard(text: str) -> bool: + """Copy text to system clipboard""" + if not CLIPBOARD_AVAILABLE: + RichConsoleUtils.print_warning("Clipboard not available on this system") + return False + + try: + pyperclip.copy(text) + RichConsoleUtils.print_success("Copied to clipboard!") + return True + except Exception as e: + RichConsoleUtils.print_error(f"Failed to copy to clipboard: {str(e)}") + return False + + @staticmethod + def paste_from_clipboard() -> Optional[str]: + """Get text from system clipboard""" + if not CLIPBOARD_AVAILABLE: + RichConsoleUtils.print_warning("Clipboard not available on this system") + return None + + try: + content = pyperclip.paste() + return content if content and content.strip() else None + except Exception as e: + RichConsoleUtils.print_error(f"Failed to access clipboard: {str(e)}") + return None + + +class EnhancedHelpSystem: + """Enhanced help system with Rich formatting""" + + COMMAND_CATEGORIES = { + "Document Conversion": [ + ("--convert_doc", "Convert documents between formats", "filemac --convert_doc file.docx -to pdf"), + ("--doc2image", "Convert documents to images", "filemac --doc2image file.pdf -to png"), + ("--html2word", "Convert HTML to Word", "filemac --html2word index.html"), + ("--markdown2docx", "Convert Markdown to DOCX", "filemac --markdown2docx file.md"), + ], + "Image Processing": [ + ("--convert_image", "Convert image formats", "filemac --convert_image file.jpg -to png"), + ("--resize_image", "Resize images", "filemac --resize_image file.png -to_size 2mb"), + ("--image2pdf", "Convert images to PDF", "filemac --image2pdf image1.jpg image2.jpg"), + ("--image2word", "Convert images to Word", "filemac --image2word image1.jpg"), + ("--image2gray", "Convert to grayscale", "filemac --image2gray image.jpg"), + ], + "Audio Processing": [ + ("--convert_audio", "Convert audio formats", "filemac --convert_audio file.mp3 -to wav"), + ("--extract_audio", "Extract audio from video", "filemac -xA video.mp4"), + ("--AudioJoin", "Join audio files", "filemac --AudioJoin file1.mp3 file2.mp3"), + ], + "Video Processing": [ + ("--convert_video", "Convert video formats", "filemac --convert_video file.mp4 -to mkv"), + ("--Analyze_video", "Analyze video", "filemac --Analyze_video video.mp4"), + ], + "PDF Operations": [ + ("--pdfjoin", "Join PDF files", "filemac --pdfjoin file1.pdf file2.pdf"), + ("--extract_pages", "Extract PDF pages", "filemac --extract_pages file.pdf 1 3 5"), + ("--scan", "Scan PDF text", "filemac --scan file.pdf"), + ], + "OCR & Text": [ + ("--ocr", "Extract text from images", "filemac --ocr image.png"), + ("--scanAsImg", "Scan PDF as images", "filemac --scanAsImg file.pdf"), + ("--Richtext2word", "Advanced text to Word", "filemac --Richtext2word file.txt"), + ], + "Miscellaneous": [ + ("--voicetype", "Voice typing", "filemac --voicetype"), + ("--record", "Record audio", "filemac --record"), + ("--version", "Show version", "filemac --version"), + ] + } + + @classmethod + def show_help(cls): + """Display enhanced help with categorized commands""" + RichConsoleUtils.print_header("FileMAC Help System", "Advanced file conversion toolkit") + + for category, commands in cls.COMMAND_CATEGORIES.items(): + table = Table( + title=f"📁 {category}", + show_header=True, + header_style="bold magenta", + box=ROUNDED, + border_style="blue" + ) + + table.add_column("Command", style="cyan", no_wrap=True) + table.add_column("Description", style="white") + table.add_column("Example", style="green") + + for cmd, desc, example in commands: + table.add_row(cmd, desc, example) + + console.print(table) + console.print() # Add spacing between categories + + # Additional information + info_panel = Panel.fit( + "[bold yellow]Tip:[/bold yellow] Use [cyan]--help[/cyan] with any command for detailed usage.\n\n" + "[bold yellow]Clipboard:[/bold yellow] Use [cyan]--clipboard[/cyan] flag to enable clipboard integration.\n\n" + "[bold yellow]Examples:[/bold yellow]\n" + " filemac --convert_doc document.docx -to pdf\n" + " filemac --image2pdf *.jpg --clipboard\n" + " filemac --ocr image.png --copy-results", + title="[bold]Additional Information[/bold]", + border_style="yellow", + subtitle="Usage Tips and Examples" + ) + console.print(info_panel) + + @classmethod + def show_quick_start(cls): + """Show quick start guide""" + RichConsoleUtils.print_header("Quick Start Guide", "Get started with FileMAC") + + quick_start_content = """ +[bold]1. Basic Conversion:[/bold] + filemac --convert_doc document.docx -to pdf + filemac --convert_image photo.jpg -to png + +[bold]2. Batch Processing:[/bold] + filemac --convert_audio *.mp3 -to wav + filemac --image2pdf /path/to/images/ + +[bold]3. Advanced Features:[/bold] + filemac --resize_image large.jpg -to_size 1mb + filemac --pdfjoin file1.pdf file2.pdf -order AAB + +[bold]4. Clipboard Integration:[/bold] + filemac --convert_doc file.docx --clipboard + filemac --ocr image.png --copy-results + +[bold]5. Help and Information:[/bold] + filemac --help + filemac --version +""" + + panel = Panel.fit( + quick_start_content, + title="[bold]Quick Start[/bold]", + border_style="green", + subtitle="Common FileMAC Commands" + ) + console.print(panel) + + +class ProgressManager: + """Progress bar management for operations""" + + @staticmethod + def create_progress_bar(description: str = "Processing..."): + """Create a standardized progress bar""" + return Progress( + SpinnerColumn("dots", style="cyan"), + TextColumn("[progress.description]{task.description}", style="white"), + BarColumn(complete_style="green", finished_style="blue", pulse_style="magenta"), + TextColumn("[progress.percentage]{task.percentage:>3.0f}%", style="yellow"), + TextColumn("[blue]{task.completed}[/blue]/[green]{task.total}[/green]", justify="right"), + TextColumn("•", style="dim"), + TextColumn("[progress.elapsed]{task.elapsed:>.1f}s", style="white"), + TextColumn("•", style="dim"), + TextColumn("[progress.remaining]{task.remaining:>.1f}s remaining", style="white"), + transient=True + ) + + @staticmethod + def show_progress(operation_name: str, items: List[Any], callback: callable): + """Show progress bar for an operation""" + with ProgressManager.create_progress_bar(description=operation_name) as progress: + task = progress.add_task(operation_name, total=len(items)) + + for item in items: + callback(item) + progress.update(task, advance=1) + + +class OperationSummary: + """Operation summary and reporting""" + + @staticmethod + def show_summary(operation_name: str, results: List[Dict[str, Any]]): + """Display operation summary""" + success_count = sum(1 for r in results if r.get('success', False)) + error_count = len(results) - success_count + total_files = len(results) + + # Create summary table + summary_table = Table(show_header=True, box=ROUNDED) + summary_table.add_column("Metric", style="cyan") + summary_table.add_column("Value", style="white") + + summary_table.add_row("Operation", operation_name) + summary_table.add_row("Files Processed", str(total_files)) + summary_table.add_row("Success", f"[green]{success_count}[/green]") + summary_table.add_row("Errors", f"[red]{error_count}[/red]") + summary_table.add_row("Success Rate", + f"[green]{success_count / total_files * 100:.1f}%[/green]" if total_files > 0 else "N/A") + + # Create error details if any + error_details = "" + if error_count > 0: + error_details = "\n[bold red]Error Details:[/bold red]\n" + for i, result in enumerate(results, 1): + if not result.get('success', True): + error_details += f"{i}. [red]{result.get('file', 'Unknown')}[/red]: {result.get('error', 'Unknown error')}\n" + + # Create summary panel + panel = Panel.fit( + summary_table, + title=f"[bold]Operation Summary: {operation_name}[/bold]", + border_style="green" if error_count == 0 else "yellow", + subtitle=f"Completed at {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}" + ) + + console.print(panel) + + if error_details: + console.print(error_details) + + # Offer to copy summary to clipboard + summary_text = f"FileMAC Operation Summary - {operation_name}\n" + summary_text += f"Processed: {total_files} files\n" + summary_text += f"Success: {success_count}\n" + summary_text += f"Errors: {error_count}\n" + summary_text += f"Success Rate: {success_count / total_files * 100:.1f}%\n" + + if error_count > 0: + summary_text += "\nErrors:\n" + for result in results: + if not result.get('success', True): + summary_text += f"- {result.get('file', 'Unknown')}: {result.get('error', 'Unknown error')}\n" + + if ClipboardManager.is_available() and Confirm.ask("Copy summary to clipboard?"): + ClipboardManager.copy_to_clipboard(summary_text) + + +class EnhancedOperationMapper(OperationMapper): + """Enhanced operation mapper with Rich features""" + + def __init__(self, parser, args, remaining_args): + super().__init__(parser, args, remaining_args) + self.clipboard_enabled = getattr(args, 'clipboard', False) + self.show_progress_bars = True + + def handle_help(self): + """Enhanced help handling""" + if not self.args and not self.remaining_args: + EnhancedHelpSystem.show_help() + return True + return False + + def handle_quick_start(self): + """Handle quick start guide""" + if hasattr(self.args, 'quick_start') and self.args.quick_start: + EnhancedHelpSystem.show_quick_start() + return True + return False + + def get_file_input(self, prompt: str) -> Union[str, List[str]]: + """Get file input with optional clipboard support""" + if self.clipboard_enabled and ClipboardManager.is_available(): + RichConsoleUtils.print_info("Clipboard mode enabled - checking for file paths...") + + clipboard_content = ClipboardManager.paste_from_clipboard() + if clipboard_content: + files = [f.strip() for f in clipboard_content.split('\n') if f.strip()] + if files: + RichConsoleUtils.print_success(f"Found {len(files)} file paths from clipboard") + + # Show preview + if Confirm.ask("Show clipboard content preview?", default=True): + preview_table = Table(title="Clipboard Content Preview", box=ROUNDED) + preview_table.add_column("Index", style="cyan") + preview_table.add_column("File Path", style="white") + + for i, file in enumerate(files, 1): + preview_table.add_row(str(i), file) + + console.print(preview_table) + + return files + + # Fallback to original behavior + return super().get_file_input(prompt) + + def show_operation_start(self, operation_name: str): + """Show operation start message""" + RichConsoleUtils.print_info(f"Starting {operation_name}...") + + def show_operation_complete(self, operation_name: str, results: List[Dict[str, Any]]): + """Show operation completion message""" + OperationSummary.show_summary(operation_name, results) + + def show_progress(self, operation_name: str, items: List[Any], callback: callable): + """Show progress for operation""" + if self.show_progress_bars: + ProgressManager.show_progress(operation_name, items, callback) + else: + # Fallback to original behavior + for item in items: + callback(item) + + +def enhanced_argsdev(): + """ + Enhanced CLI entry point with Rich interface + + This function provides the main entry point for the enhanced FileMAC CLI + with Rich formatting and additional features while maintaining + compatibility with the original CLI. + """ + try: + # Initialize Rich console and display welcome message + RichConsoleUtils.print_header( + "🚀 FileMAC Enhanced CLI", + "Advanced File Processing with Rich Interface" + ) + + # Create parser with enhanced help + parser = argparse.ArgumentParser( + description="Filemac: Advanced file management tool with Rich interface", + add_help=False, + formatter_class=argparse.RawDescriptionHelpFormatter, + epilog="Use --help for detailed command information or --quick-start for examples" + ) + + # Add enhanced flags + parser.add_argument( + "--clipboard", + action="store_true", + help="Enable clipboard integration for input/output operations" + ) + + parser.add_argument( + "--quick-start", + action="store_true", + help="Show quick start guide with common examples" + ) + + parser.add_argument( + "--no-progress", + action="store_true", + help="Disable progress bars for cleaner output" + ) + + parser.add_argument( + "--copy-results", + action="store_true", + help="Copy operation results to clipboard automatically" + ) + + # Add original arguments (this would be imported or duplicated from original) + # For now, we'll handle the original arguments through the existing system + + # Parse known arguments first + args, remaining_args = parser.parse_known_args() + + # Handle quick start + if args.quick_start: + EnhancedHelpSystem.show_quick_start() + sys.exit(0) + + # Handle help + if '--help' in remaining_args or '-h' in remaining_args: + EnhancedHelpSystem.show_help() + sys.exit(0) + + # Check if user wants original CLI + if '--original' in remaining_args: + RichConsoleUtils.print_info("Switching to original CLI interface...") + original_argsdev() + return + + # Initialize enhanced operation mapper + # Note: In a real implementation, we would need to properly integrate + # with the existing argument parsing system + + RichConsoleUtils.print_info("Enhanced CLI mode activated") + RichConsoleUtils.print_info("Note: Some features are still under development") + + # For now, fall back to original CLI but with enhanced features + # This is a temporary measure until full integration is complete + + # Create a basic enhanced experience + if args.clipboard: + RichConsoleUtils.print_success("Clipboard integration enabled") + + if args.no_progress: + RichConsoleUtils.print_info("Progress bars disabled") + + # Show enhanced help if no arguments provided + if not any(vars(args).values()) and not remaining_args: + EnhancedHelpSystem.show_help() + sys.exit(0) + + # Fall back to original CLI for actual operations + # This maintains compatibility while we develop the enhanced version + RichConsoleUtils.print_info("Processing with enhanced interface...") + original_argsdev() + + except KeyboardInterrupt: + RichConsoleUtils.print_warning("Operation cancelled by user") + sys.exit(0) + except Exception as e: + RichConsoleUtils.print_error(f"Unexpected error: {str(e)}") + if Confirm.ask("Show detailed error information?", default=False): + console.print_exception() + sys.exit(1) + + +if __name__ == "__main__": + enhanced_argsdev() diff --git a/filemac/cli/cli.py b/filemac/cli/cli.py new file mode 100644 index 0000000..ccab615 --- /dev/null +++ b/filemac/cli/cli.py @@ -0,0 +1,802 @@ +#!/usr/bin/env python3 +import argparse +import os +import sys +from functools import lru_cache +from filemac.core.document import DocConverter +from filemac.core.pdf.core import PageExtractor +from filemac.core.exceptions import FileSystemError, FilemacError +from pathlib import Path +from filemac.utils.colors import fg, bg, rs +from filemac.utils.decorators import dcr +from filemac.utils.file_utils import dirbuster +from filemac.utils.simple import logger +from filemac.utils.formats import ( + SUPPORTED_VIDEO_FORMATS, + SUPPORTED_IMAGE_FORMATS, + SUPPORTED_AUDIO_FORMATS, + SUPPORTED_DOC_FORMATS +) + +try: + from audiobot.cli import cli as audiobot_cli +except ImportError: + pass + +_entry_ = PageExtractor._entry_ + +RESET = rs + + +def argsdev(): + """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 -tof pdf{RESET}", + ) + + parser.add_argument( + "--convert_audio", + nargs="+", + help=f"Convert audio file(s) to and from different format ie mp3 to wav\ + example: {fg.BYELLOW}filemac --convert_audio example.mp3 -tof wav{RESET}", + ) + + parser.add_argument( + "--convert_video", + nargs="+", + help=f"Convert video file(s) to and from different format ie mp4 to mkv.\ + example: {fg.BYELLOW}filemac --convert_video example.mp4 -to mkv{RESET}", + ) + + parser.add_argument( + "--convert_image", + nargs="+", + help=f"Convert image file(s) to and from different format ie png to jpg.\ + example: {fg.BYELLOW}filemac --convert_image example.jpg -to png{RESET}", + ) + + parser.add_argument( + "--convert_svg", + nargs="+", + help=f"Converter svg file(s) to different format ie pdf, png.\ + example: {fg.BYELLOW}filemac --convert_svg example.svg -tof pdf{RESET}", + ) + + parser.add_argument( + "--doc2image", + help=f"Convert documents to images ie png to jpg.\ + example: {fg.BYELLOW}filemac --doc2image example.pdf -to 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 -to 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( + "-to", 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 -to_size 2mb -to 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 -to 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( + "--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 filemac.core.pdf.core import PDFCombine + + if self.args.pdfjoin[0].lower().strip() == "help": + from filemac.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 filemac.utils.formats import SUPPORTED_IMAGE_FORMATS_SHOW + + print(SUPPORTED_IMAGE_FORMATS_SHOW) + return + if self.args.to is None: + self.ensure_target_format() + return + if self.args.to is None: + print( + f"{fg.RED}Please provide output format specified by{fg.CYAN} '-to'{RESET}" + ) + return + + from filemac.core.image.core import ImageConverter + + @dcr.for_loop(self.args.convert_image) + def ops(fpath): + if self.args.isolate and os.path.isdir(fpath): + if self.args.isolate not in (x.lower() for x in SUPPORTED_IMAGE_FORMATS): + sys.exit(f"Format: {self.args.isolate} not supported") + + files = dirbuster(fpath, (self.args.isolate.lower())) + + @dcr.for_loop(files) + def ops(xfpath): + ImageConverter(xfpath, self.args.to).convert_image() + ops() + else: + ImageConverter(fpath, self.args.to).convert_image() + ops() + + def doc_converter(self): + from filemac.utils.formats import SUPPORTED_AUDIO_FORMATS_DIRECT + from .converter import MethodMappingEngine, DirectoryConverter, Batch_Audiofy + + if self.args.to is None: + self.ensure_target_format() + return + + @dcr.for_loop(self.args.convert_doc) + def ops(fpath): + if self.args.use_extras: + DocConverter.word2pdf_extra(fpath) + if ( + len(fpath) <= 1 + and not os.path.isdir(fpath) + and isinstance(fpath, list) + and self.args.to in SUPPORTED_AUDIO_FORMATS_DIRECT + ): + Batch_Audiofy(fpath, self.args.no_resume, self.args.threads) + elif os.path.isdir(fpath): + DirectoryConverter( + fpath, + self.args.to, + self.args.no_resume, + self.args.threads, + self.args.isolate, + )._unbundle_dir_() + elif os.path.isfile(fpath): + MethodMappingEngine(fpath, self.args.to).document_eval() + ops() + + 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 filemac.utils.formats import SUPPORTED_DOC_FORMATS_HELP + print(SUPPORTED_DOC_FORMATS_HELP) + return + + def handle_video_conversion_help(self): + if self.args.convert_video and self.args.convert_video == "help": + from filemac.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 filemac.core.video.core import VideoConverter + + @dcr.for_loop(self.args.convert_video) + def ops(fpath): + if self.args.isolate and os.path.isdir(fpath): + if self.args.isolate not in (x.lower() for x in SUPPORTED_VIDEO_FORMATS): + sys.exit(f"Format: {self.args.isolate} not supported") + + files = dirbuster(fpath, (self.args.isolate.lower())) + + @dcr.for_loop(files) + def ops(fpath): + VideoConverter(fpath, self.args.to).CONVERT_VIDEO() + ops() + else: + VideoConverter(fpath, self.args.to).CONVERT_VIDEO() + ops() + + def handle_svg(self): + from filemac.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.to, None) + if not target: + raise FilemacError("Target format not valid for svg input.") + from filemac.utils.file_utils import generate_filename + + @dcr.for_loop(self.args.convert_svg) + def ops(fpath): + if self.args.isolate and os.path.isdir(fpath): + if self.args.isolate.lower() != 'svg': + sys.exit(f"Format: {self.args.isolate} not supported") + + files = dirbuster(fpath, (self.args.isolate.lower())) + + @dcr.for_loop(files) + def ops(xfpath): + output = generate_filename( + ext=self.args.to, basedir=Path(fpath) + ) + target( + input_svg=xfpath, + output_path=output.as_posix(), + is_string=False, + ) + print(f"Saved To:{output}") + ops() + + else: + output = generate_filename( + ext=self.args.to, basedir=Path(fpath) + ) + target( + input_svg=fpath, + output_path=output.as_posix(), + is_string=False, + ) + print(f"Saved To:{output}") + ops() + + def handle_image_resize(self): + from filemac.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): + if self.args.isolate and os.path.isdir(self.args.doc2image): + if self.args.isolate not in (x.lower() for x in SUPPORTED_DOC_FORMATS): + sys.exit(f"Format: {self.args.isolate} not supported") + + files = dirbuster(self.args.doc2image, (self.args.isolate.lower())) + + @dcr.for_loop(files) + def ops(fpath): + DocConverter(fpath).doc2image(self.args.to) + + ops() + else: + DocConverter(self.args.doc2image).doc2image(self.args.to) + + def handle_audio_conversion_help(self): + if self.args.convert_audio == "help": + from filemac.utils.formats import SUPPORTED_AUDIO_FORMATS_SHOW + print(SUPPORTED_AUDIO_FORMATS_SHOW) + return + + def handle_audio_conversion(self): + if self.args.to is None: + self.ensure_target_format() + return + from filemac.core.audio.core import AudioConverter + if self.args.isolate and os.path.isdir(self.args.convert_audio[0]): + if self.args.isolate not in (x.lower() for x in SUPPORTED_AUDIO_FORMATS): + sys.exit(f"Format: {self.args.isolate} not supported") + + files = dirbuster(self.args.convert_audio[0], (self.args.isolate.lower())) + + @dcr.for_loop(files) + def ops(fpath): + AudioConverter(fpath, self.args.to).pydub_conv() + ops() + else: + @dcr.for_loop(self.args.convert_audio) + def ops(fpath): + AudioConverter(fpath, self.args.to).pydub_conv() + ops() + + def handle_audio_extraction(self): + from filemac.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 filemac.core.pdf.core import PDF2LongImageConverter + + conv = PDF2LongImageConverter(self.args.doc_long_image) + conv.preprocess() + + def handle_ocr(self): + from filemac.core.ocr import ExtractText + + @dcr.for_loop(self.args.ocr) + def ops(fpath): + ExtractText(fpath, self.args.separator).run() + ops() + + def handle_video_analysis(self): + from filemac.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 filemac.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 filemac.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 filemac.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 filemac.core.image.core import ImageDocxConverter + + _input = self.args.image2word + if isinstance(_input, (list, tuple)): + if len(_input) > 1: + ImageDocxConverter(image_list=_input).run() + else: + ImageDocxConverter(input_dir=_input[0]).run() + + def image2grayscale(self): + from filemac.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 filemac.core.recorder import SoundRecorder + + rec = SoundRecorder() + return rec.run() + + def handle_html2word(self): + from filemac.core.html import HTML2Word + from filemac.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, + tuple(args.convert_video or ()): self.handle_video_conversion, + tuple(args.convert_image or ()): self.image_converter, + tuple(args.convert_audio or ()): self.handle_audio_conversion, + tuple(args.ocr or ()): self.handle_ocr, + tuple(args.convert_svg or ()): self.handle_svg, + args.resize_image: self.handle_image_resize, + args.doc2image: self.handle_doc_to_image_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.voicetype: self.voicetype, + 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__": + argsdev() diff --git a/filemac/cli/converter.py b/filemac/cli/converter.py new file mode 100644 index 0000000..7c97ce5 --- /dev/null +++ b/filemac/cli/converter.py @@ -0,0 +1,206 @@ +import os +import sys +from typing import List, Union +from filemac.core.warning import default_supressor +from filemac.utils.simple import logger +from filemac.utils.colors import fg, rs +from filemac.core.tts.gtts import GoogleTTS +from filemac.utils.formats import ( + SUPPORTED_AUDIO_FORMATS_DIRECT, +) +from filemac.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", "pptx", "xls", "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/colors.py b/filemac/colors.py deleted file mode 100644 index 7e03e49..0000000 --- a/filemac/colors.py +++ /dev/null @@ -1,40 +0,0 @@ -import os - -from colorama import Fore, Style, init - -init(autoreset=True) - -if os.name == "posix": - RESET = '\033[0m' - RED = '\033[91m' - DRED = '\033[1;91m' - GREEN = '\033[92m' - DGREEN = '\033[1;92m' - YELLOW = '\033[93m' - DYELLOW = '\033[1;93m' - BLUE = '\033[94m' - DBLUE = '\033[1;94m' - MAGENTA = '\033[95m' - DMAGENTA = '\033[1;95m' - CYAN = '\033[96m' - DCYAN = '\033[1;96m' - ICYAN = '\033[3;96m' - -elif os.name == "nt": - RESET = Style.RESET_ALL - RED = Fore.LIGHTRED_EX - DRED = Fore.RED - GREEN = Fore.LIGHTGREEN_EX - DGREEN = Fore.GREEN - YELLOW = Fore.LIGHTYELLOW_EX - DYELLOW = Fore.YELLOW - BLUE = Fore.LIGHTBLUE_EX - DBLUE = Fore.BLUE - MAGENTA = Fore.LIGHTMAGENTA_EX - DMAGENTA = Fore.MAGENTA - CYAN = Fore.LIGHTCYAN_EX - DCYAN = Fore.CYAN - ICYAN = Fore.WHITE - -#return RESET, RED, DRED, GREEN, DGREEN, YELLOW, DYELLOW, BLUE, DBLUE, -#MAGENTA, DMAGENTA, CYAN, DCYAN diff --git a/filemac/converter.py b/filemac/converter.py deleted file mode 100644 index a46a46f..0000000 --- a/filemac/converter.py +++ /dev/null @@ -1,1027 +0,0 @@ -############################################################################# -import logging -import logging.handlers -# import math -import os -import re -import sqlite3 -import subprocess -import sys -import time -import traceback -# import pdfminer.high_level -# from typing import Iterable -from pdf2image import convert_from_path -import cv2 -import pandas as pd -import pydub -import PyPDF2 -# import pytesseract -import requests -import speedtest -from docx import Document -# from pydub.playback import play -from gtts import gTTS -# from PyPDF2 import PdfFileReader -from moviepy.editor import VideoFileClip -from pdf2docx import parse -from PIL import Image -from pptx import Presentation -from pydub import AudioSegment -from .colors import (RESET, GREEN, DGREEN, YELLOW, DYELLOW, CYAN, BLUE, DBLUE, - MAGENTA, DMAGENTA, RED, DRED, ICYAN) -from reportlab.lib.pagesizes import letter -from reportlab.platypus import Paragraph, SimpleDocTemplate - -from .formats import (SUPPORTED_AUDIO_FORMATS, SUPPORTED_IMAGE_FORMATS, - SUPPORTED_VIDEO_FORMATS) - -# import pygame -# from aspose.words import Document as aspose_document -# from aspose.slides import Presentation as aspose_presentation -# from show_progress import progress_show -# from PIL import ImageDraw, ImageFont -############################################################################### - -PYGAME_DETECT_AVX2 = 1 -logging.basicConfig(level=logging.INFO, format='%(levelname)-8s %(message)s') -logger = logging.getLogger(__name__) - - -class MakeConversion: - - '''Initialize the class''' - - def __init__(self, input_file): - self.input_file = input_file - - '''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 sam - directory as the 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("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) - -############################################################################### -# Convert word file to pdf document (docx) -############################################################################### - def word_to_pdf(self): - word_list = self.preprocess() - ls = ["doc", "docx"] - word_list = [ - item for item in word_list if any(item.lower().endswith(ext) for ext in ls)] - for word_file in word_list: - if word_file.lower().endswith("doc"): - pdf_file = word_file[:-3] + "pdf" - elif word_file.lower().endswith("docx"): - pdf_file = word_file[:-4] + "pdf" - - try: - print( - f'{BLUE}Converting: {RESET}{word_file} {BLUE}to {RESET}{pdf_file}') - if os.name == 'posix': # Check if running on Linux - # Use subprocess to run the dpkg and grep commands - result = subprocess.run( - ['dpkg', '-l', 'libreoffice'], stdout=subprocess.PIPE, text=True) - if result.returncode != 0: - print( - "Please install libreoffice to use this functionality !") - sys.exit(1) - subprocess.run(['soffice', '--convert-to', - 'pdf', word_file, pdf_file]) - # print(f"{DMAGENTA} Successfully converted {word_file} to {pdf_file}{RESET}") - elif os.name == "nt": - try: - from docx2pdf import convert - except ImportError: - print("Run pip install docx2pdf for this function to work") - sys.exit(1) - convert(word_file, pdf_file) - print( - f"{DMAGENTA} Successfully converted {word_file} to {pdf_file}{RESET}") - - except Exception as e: - print(f"Error converting {word_file} to {pdf_file}: {e}") - -############################################################################### -# Convert pdf file to word document (docx) -############################################################################### - def pdf_to_word(self): - pdf_list = self.preprocess() - pdf_list = [item for item in pdf_list if item.lower().endswith("pdf")] - for pdf_file in pdf_list: - if pdf_file.lower().endswith("pdf"): - word_file = pdf_file[:-3] + "docx" - - try: - - parse(pdf_file, word_file, start=0, end=None) - - print(f'{GREEN}Converting to word..{RESET}', end='\r') - - logger.info(f"{DMAGENTA} Successfully converted{pdf_file} \ -to {word_file}{RESET}") - except KeyboardInterrupt: - print("\nExiting..") - sys.exit(1) - except Exception as e: - logger.info(f'{DRED}All conversion attempts have failed: \ -{e}{RESET}') - -############################################################################### -# Convert text file(s) to pdf document (docx) -############################################################################### - def txt_to_pdf(input_file, output_file): - """Convert a .txt file to a PDF.""" - - # Read the contents of the input .txt file - with open(input_file, 'r', encoding='utf-8') as file: - text_contents = file.readlines() - - # Initialize the PDF document - doc = SimpleDocTemplate(output_file, pagesize=letter) - - # Create a story to hold the elements of the PDF - story = [] - - # Iterate through each line in the input .txt file and add it to the PDF - for line in text_contents: - story.append(Paragraph(line.strip(), style="normalText")) - - # Build and write the PDF document - doc.build(story) - -############################################################################### -# Convert word file(s) to pptx document (pptx/ppt) -############################################################################### - def word_to_pptx(self): - word_list = self.preprocess() - word_list = [item for item in word_list if item.lower().endswith( - "docx") or item.lower().endswith("doc")] - - for word_file in word_list: - - if word_list is None: - print("Please provide appropriate file type") - sys.exit(1) - if word_file.lower().endswith("docx"): - pptx_file = word_file[:-4] + "pptx" - elif word_file.lower().endswith("doc"): - pptx_file = word_file[:-3] + "pptx" - try: - # Load the Word document - print(F"{DYELLOW}Load the Word document..{RESET}") - doc = Document(word_file) - - # Create a new PowerPoint presentation - print(F"{DYELLOW}Create a new PowerPoint presentation..{RESET}") - prs = Presentation() - - # Iterate through each paragraph in the Word document - print( - f"{DGREEN}Populating pptx slides with {DYELLOW}{len(doc.paragraphs)}{DGREEN} entries..{RESET}") - count = 0 - for paragraph in doc.paragraphs: - count += 1 - perc = (count/len(doc.paragraphs))*100 - print( - f"{DMAGENTA}Progress:: \033[1;36m{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) - print(f"\n{DGREEN}Done{RESET}") - except KeyboardInterrupt: - print("\nExiting") - sys.exit(1) - except KeyboardInterrupt: - print("\nExiting..") - sys.exit(1) - except Exception as e: - logger.error(e) - -############################################################################### -# Convert word file to txt file''' -############################################################################### - - def word_to_txt(self): - word_list = self.preprocess() - word_list = [item for item in word_list if item.lower().endswith( - "docx") or item.lower().endswith("doc")] - for file_path in word_list: - if file_path.lower().endswith("docx"): - txt_file = file_path[:-4] + "txt" - elif file_path.lower().endswith("doc"): - txt_file = file_path[:-3] + "txt" - try: - doc = Document(file_path) - print("INFO Processing...") - - 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:{BLUE}{Par}/{len(doc.paragraphs)}{RESET}", end='\r') - logger.info(f"{DMAGENTA}Conversion of file to txt success{RESET}") - - except KeyboardInterrupt: - print("\nExit") - sys.exit() - except Exception as e: - logger.error( - f"Dear user something went amiss while attempting the conversion:\n {e}") - with open("conversion.log", "a") as log_file: - log_file.write(f"Couldn't convert {file_path} to {txt_file}:\ -REASON->{e}") - -############################################################################### -# Convert pdf file to text file -############################################################################### - def pdf_to_txt(self): - 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: - with open(file_path, 'rb') as file: - pdf_reader = PyPDF2.PdfReader(file) - text = '' - for page_num in range(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"{DMAGENTA}Successfully converted {file_path} to \ -{txt_file}{RESET}") - except Exception as e: - logger.error( - f"Oops somethin went astray while converting {file_path} \ -to {txt_file}: {e}") - with open("conversion.log", "a") as log_file: - log_file.write( - f"Error converting {file_path} to {txt_file}: {e}\n") - -############################################################################### -# Convert ppt file to word document -############################################################################### - def ppt_to_word(self): - ppt_list = self.preprocess() - ppt_list = [item for item in ppt_list if item.lower().endswith( - "pptx") or item.lower().endswith("ppt")] - for file_path in ppt_list: - if file_path.lower().endswith("pptx"): - word_file = file_path[:-4] + "docx" - elif file_path.lower().endswith("ppt"): - word_file = file_path[:-3] + "docx" - try: - presentation = Presentation(file_path) - document = Document() - - for slide in presentation.slides: - for shape in slide.shapes: - if shape.has_text_frame: - text_frame = shape.text_frame - for paragraph in text_frame.paragraphs: - new_paragraph = document.add_paragraph() - for run in paragraph.runs: - new_run = new_paragraph.add_run(run.text) - # Preserve bold formatting - new_run.bold = run.font.bold - # Preserve italic formatting - new_run.italic = run.font.italic - # Preserve underline formatting - new_run.underline = run.font.underline - # Preserve font name - new_run.font.name = run.font.name - # Preserve font size - new_run.font.size = run.font.size - try: - # Preserve font color - new_run.font.color.rgb = run.font.color.rgb - except AttributeError: - # Ignore error and continue without - # setting the font color - pass - # Add a new paragraph after each slide - document.add_paragraph() - document.save(word_file) - logger.info(f"{DMAGENTA}Successfully converted {file_path} to \ - {word_file}{RESET}") - except Exception as e: - logger.error( - f"Oops somethin gwent awry while attempting to convert \ - {file_path} to {word_file}:\n>>>{e}") - with open("conversion.log", "a") as log_file: - log_file.write( - f"Oops something went astray while attempting \ - convert {file_path} to {word_file}:{e}\n") - -############################################################################### -# Convert text file to word -############################################################################### - def text_to_word(self): - 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 - 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 - 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"{DMAGENTA}Successfully converted {file_path} to \ - {word_file}{RESET}") - except FileExistsError as e: - logger.error(f"{str(e)}") - except Exception as e: - logger.error( - f"Oops Unable to perfom requested conversion: {e}\n") - with open("conversion.log", "a") as log_file: - log_file.write( - f"Error converting {file_path} to {word_file}: \ -{e}\n") - -############################################################################### -# Convert xlsx file(s) to word file(s) -############################################################################### - def convert_xls_to_word(self): - xls_list = self.preprocess() - ls = ["xlsx", "xls"] - xls_list = [item for item in xls_list if any( - item.lower().endswith(ext) for ext in ls)] - print(F"{DGREEN}Initializing conversion sequence{RESET}") - for xls_file in xls_list: - if xls_file.lower().endswith("xlsx"): - word_file = xls_file[:-4] + "docx" - elif xls_file.lower().endswith("xls"): - word_file = xls_file[:-3] + "docx" - 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"{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 {DYELLOW}{current_row}/{total_rows} \ -{DBLUE}{percentage:.1f}%{RESET}", end="\r") - # print(f"\033[1;36m{row}{RESET}") - - # Save the Word document - doc.save(word_file) - print(F"{DGREEN}Conversion successful!{RESET}", end="\n") - except KeyboardInterrupt: - print("\nExiting") - sys.exit(1) - except Exception as e: - print("Oops Conversion failed:", str(e)) - -############################################################################### - '''Convert xlsx/xls file/files to text file format''' -############################################################################### - - def convert_xls_to_text(self): - xls_list = self.preprocess() - ls = ["xlsx", "xls"] - xls_list = [ - item for item in xls_list if any(item.lower().endswith(ext) - for ext in ls)] - print(F"{DGREEN}Initializing conversion sequence{RESET}") - for xls_file in xls_list: - if xls_file .lower().endswith("xlsx"): - txt_file = xls_file[:-4] + "txt" - elif xls_file .lower().endswith("xls"): - txt_file = xls_file[:-3] + "txt" - 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: {DYELLOW}{chars} \033[1;30m \ -characters{DYELLOW} {words}\033[1;30m words {DYELLOW}{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"{DGREEN}Conversion successful!{RESET}", end="\n") - except KeyboardInterrupt: - print("\nExiting") - sys.exit(1) - except Exception as e: - print("Oops Conversion failed:", str(e)) - -############################################################################### - '''Convert xlsx/xls file to csv(comma seperated values) format''' -############################################################################### - - def convert_xlsx_to_csv(self): - xls_list = self.preprocess() - ls = ["xlsx", "xls"] - xls_list = [ - item for item in xls_list if any(item.lower().endswith(ext) - for ext in ls)] - for xls_file in xls_list: - if xls_file.lower().endswith("xlsx"): - csv_file = xls_file[:-4] + "csv" - elif xls_file.lower().endswith("xls"): - csv_file = xls_file[:-3] + "csv" - try: - '''Load the Excel file''' - print(F"{DGREEN}Initializing conversion sequence{RESET}") - df = pd.read_excel(xls_file) - logger.info(f"Converting {xls_file}..") - total_rows = df.shape[0] - print(f"Writing {DYELLOW}{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"{DMAGENTA} Conversion successful{RESET}") - except KeyboardInterrupt: - print("Exiting") - sys.exit(1) - except Exception as e: - print(e) - -############################################################################### -# Convert xlsx file(s) to sqlite -############################################################################### - - def convert_xlsx_to_database(self): - xlsx_list = self.preprocess() - ls = ["xlsx", "xls"] - xlsx_list = [ - item for item in xlsx_list if any(item.lower().endswith(ext) - for ext in ls)] - for xlsx_file in xlsx_list: - if xlsx_file.lower().endswith("xlsx"): - sqlfile = xlsx_file[:-4] - elif xlsx_file.lower().endswith("xls"): - sqlfile = xlsx_file[:-3] - try: - db_file = input( - F"{DBLUE}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 + "sql" - table_name = sqlfile - if not db_file.endswith(".sql"): - db_file = db_file + ".sql" - 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"{DGREEN}Initializing conversion sequence{RESET}") - print(f"{DGREEN} Connected to sqlite3 database::{RESET}") - # Create a connection to the SQLite database - conn = sqlite3.connect(db_file) - print(F"{DYELLOW} 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("\nExiting") - sys.exit(1) - except Exception as e: - logger.error(f"{e}") - -############################################################################### -# Create image objects from given files -############################################################################### - def doc2image(self, outf="png"): - outf_list = ['png', 'jpg'] - if outf not in outf_list: - outf = "png" - path_list = self.preprocess() - ls = ["pdf", "doc", "docx"] - file_list = [ - item for item in path_list if any(item.lower().endswith(ext) - for ext in ls)] - imgs = [] - for file in file_list: - if file.lower().endswith("pdf"): - # Convert the PDF to a list of PIL image objects - print("Generate image objects ..") - images = convert_from_path(file) - - # Save each image to a file - fname = file[:-4] - print(f"{YELLOW}Target images{BLUE} {len(images)}{RESET}") - for i, image in enumerate(images): - print(f"{DBLUE}{i}{RESET}", end="\r") - yd = f"{fname}_{i+1}.{outf}" - image.save(yd) - imgs.append(yd) - print(f"{GREEN}Ok{RESET}") - - return imgs - - -class Scanner: - - def __init__(self, input_file): - self.input_file = input_file - - 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): - pdf_list = self.preprocess() - pdf_list = [item for item in pdf_list if item.lower().endswith("pdf")] - - for pdf in pdf_list: - out_f = pdf[:-3] + 'txt' - print(f"{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"{DYELLOW}Progress:{RESET}", end="") - print(f"{CYAN}{pg}/{len(reader.pages)}{RESET}", end="\r") - page = reader.pages[page_num] - text += page.extract_text() - - print(f"\n{text}") - print(F"\n{YELLOW}Write text to {GREEN}{out_f}{RESET}") - with open(out_f, 'w') as f: - f.write(text) - - print(F"{DGREEN}Ok{RESET}") - - def scanAsImgs(self): - file = self.input_file - mc = MakeConversion(file) - img_objs = mc.doc2image() - # print(img_objs) - from .OCRTextExtractor import ExtractText - text = '' - for i in img_objs: - extract = ExtractText(i) - tx = extract.OCR() - if tx is not None: - text += tx - print(text) - print(f"{GREEN}Ok{RESET}") - return text - - -class FileSynthesis: - - def __init__(self, input_file): - self.input_file = input_file - # self.CHUNK_SIZE = 20_000 - - 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 - - @staticmethod - def join_audios(files, output_file): - masterfile = output_file + "_master.mp3" - print( - f"{DBLUE}Create a master file {DMAGENTA}{masterfile}{RESET}", end='\r') - # Create a list to store files - ogg_files = [] - # loop through the directory while adding the ogg files to the list - print(files) - for filename in files: - print(f"Join {DBLUE}{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"{DGREEN}Master file:Ok {RESET}") - - def Synthesise(self, text: str, output_file: str, CHUNK_SIZE: int = 20_000, ogg_folder: str = 'tempfile', retries: int = 5) -> None: - """Converts given text to speech using Google Text-to-Speech API.""" - out_ls = [] - try: - if not os.path.exists(ogg_folder): - os.mkdir(ogg_folder) - print(f"{DYELLOW}Get initial net speed..{RESET}") - st = speedtest.Speedtest() # get initial network speed - st.get_best_server() - download_speed: float = st.download() # Keep units as bytes - logger.info( - - f"{GREEN} Conversion to mp3 sequence initialized start\ -speed {CYAN}{download_speed/1_000_000:.2f}Kbps{RESET}") - - for attempt in range(retries): - try: - '''Split input text into smaller parts and generate - individual gTTS objects''' - counter = 0 - for i in range(0, len(text), CHUNK_SIZE): - chunk = text[i:i+CHUNK_SIZE] - output_filename = f"{output_file}_{counter}.ogg" - counter += 1 - # print(output_filename) - if os.path.exists(output_filename): - output_filename = f"{output_file}_{counter+1}.ogg" - # print(output_filename) - tts = gTTS(text=chunk, lang='en', slow=False) - tts.save(output_filename) - out_ls.append(output_filename) - break - # print(out_ls) - '''Handle any network related issue gracefully''' - except Exception in (ConnectionError, ConnectionAbortedError, - ConnectionRefusedError, - ConnectionResetError) as e: - logger.error(f"Sorry boss connection problem encountered: {e} in {attempt+1}/{retries}:") - time.sleep(5) # Wait 5 seconds before retrying - - # Handle connectivity/network error - except requests.exceptions.RequestException as e: - logger.error(f"{e}") - except Exception as e: - logger.error(f'{DRED} Error during conversion attempt \ -{attempt+1}/{retries}:{e}{RESET}') - tb = traceback.extract_tb(sys.exc_info()[2]) - logger.info("\n".join([f" > {line}" - for line in map(str, tb)])) - time.sleep(3) # Wait 5 seconds before retrying - pass - - if attempt >= retries: - logger.error( - f"Conversion unsuccessful after {retries} attempts.") - sys.exit(2) - - finally: - # print(out_ls) - # Combine generated gTTS objects - if len(out_ls) >= 1: - FileSynthesis.join_audios(out_ls, output_file) - - st = speedtest.Speedtest() - logger.info("Done") - print("Get final speed ...") - logger.info( - - f"{YELLOW}Final Network Speed: {st.download()/(10**6):.2f} Kbps{RESET}") - - @staticmethod - def pdf_to_text(pdf_path): - logger.info('''Processing the file...\n''') - logger.info( - F'{GREEN} Initializing pdf to text conversion sequence...{RESET}') - try: - with open(pdf_path, 'rb') as file: - pdf_reader = PyPDF2.PdfReader(file) - text = '' - for page_num in range(len(pdf_reader.pages)): - page = pdf_reader.pages[page_num] - text += page.extract_text() - print(F"{DGREEN}Ok{RESET}") - return text - except Exception as e: - logger.error( - f"{DRED}Failed to extract text from '{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"{DRED}Error converting {input_file} to text: {str(e)}\ -{RESET}") - - @staticmethod - def docx_to_text(docx_path): - try: - logger.info(f"{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"{DRED}Error converting {docx_path} to text: {e}\ -{RESET}") - - '''Handle input files based on type to initialize conversion sequence''' - - def audiofy(self): - input_list = self.preprocess() - extdoc = ["docx", "doc"] - ls = {"pdf", "docx", "doc", "txt"} - input_list = [item for item in input_list if item.lower().endswith(tuple(ls))] - for input_file in input_list: - if input_file.endswith('.pdf'): - text = FileSynthesis.pdf_to_text(input_file) - output_file = input_file[:-4] - - elif input_file.lower().endswith(tuple(extdoc)): - - text = FileSynthesis.docx_to_text(input_file) - output_file = input_file[:-5] - - elif input_file.endswith('.txt'): - text = FileSynthesis.text_file(input_file) - output_file = input_file[:-4] - - else: - logger.error('Unsupported file format. Please provide \ -a PDF, txt, or Word document.') - sys.exit(1) - try: - FileSynthesis.Synthesise(None, text, output_file) - except KeyboardInterrupt: - sys.exit(1) - - -############################################################################### -# Convert video file to from one format to another''' -############################################################################### - - -class VideoConverter: - - 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("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 - - 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"{DYELLOW}Initializing conversion..{RESET}") - - for file in input_list: - if out_f.upper() in SUPPORTED_VIDEO_FORMATS: - _, ext = os.path.splitext(file) - output_filename = _ + '.' + out_f.lower() - print(output_filename) - else: - print("Unsupported output format") - sys.exit(1) - format_codec = { - "MP4": "mpeg4", - "AVI": "rawvideo", - # "OGV": "avc", - "WEBM": "libvpx", - "MOV": "mpeg4", - "MKV": "MPEG4", - "FLV": "flv" - # "WMV": "WMV" - } - '''Load the video file''' - print(f"{DBLUE}oad file{RESET}") - video = VideoFileClip(file) - '''Export the video to a different format''' - print(f"{DMAGENTA}Converting file to {output_filename}{RESET}") - video.write_videofile( - output_filename, codec=format_codec[out_f]) - '''Close the video file''' - print(f"{DGREEN}Done{RESET}") - video.close() - except KeyboardInterrupt: - print("\nExiting..") - sys.exit(1) - except Exception as e: - print(e) - - -############################################################################### -# Convert Audio file to from one format to another''' -############################################################################### - - -class AudioConverter: - - 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("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 - - def pydub_conv(self): - 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"{DYELLOW}Initializing conversion..{RESET}") - for file in input_list: - if out_f.lower() in SUPPORTED_AUDIO_FORMATS: - _, ext = os.path.splitext(file) - output_filename = _ + '.' + out_f - else: - print("Unsupported output format") - sys.exit(1) - fmt = ext[1:] - print(fmt, out_f) - audio = pydub.AudioSegment.from_file(file, fmt) - print(f"{DMAGENTA}Converting to {output_filename}{RESET}") - audio.export(output_filename, format=out_f) - # new_audio = pydub.AudioSegment.from_file('output_audio.') - print(f"{DGREEN}Done{RESET}") - # play(new_audio) - # new_audio.close() - - -############################################################################### -# Convert images file to from one format to another -############################################################################### - - -class ImageConverter: - - def __init__(self, input_file, out_format): - self.input_file = input_file - self.out_format = out_format - - 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("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): - try: - input_list = self.preprocess() - out_f = self.out_format.upper() - - input_list = [item for item in input_list if any( - item.lower().endswith(ext) for ext in SUPPORTED_IMAGE_FORMATS[out_f])] - for file in input_list: - print(file) - if out_f.upper() in SUPPORTED_IMAGE_FORMATS: - _, ext = os.path.splitext(file) - output_filename = _ + \ - SUPPORTED_IMAGE_FORMATS[out_f].lower() - else: - print("Unsupported output format") - sys.exit(1) - '''Load the image using OpenCV: ''' - print(F"{DYELLOW}Reading input image..{RESET}") - img = cv2.imread(file) - '''Convert the OpenCV image to a PIL image: ''' - print(f"{DMAGENTA}Converting to PIL image{RESET}") - pil_img = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB)) - '''Save the PIL image to a different format: ''' - print(f"\033[1;36mSaving image as {output_filename}{RESET}") - pil_img.save(output_filename, out_f) - print(f"{DGREEN}Done{RESET}") - '''Load the image back into OpenCV: ''' - print(f"{DMAGENTA}Load and display image{RESET}") - opencv_img = cv2.imread(output_filename) - '''Display the images: ''' - cv2.imshow('OpenCV Image', opencv_img) - # pil_img.show() - '''Wait for the user to press a key and close the windows: ''' - cv2.waitKey(0) - cv2.destroyAllWindows() - except KeyboardInterrupt: - print("\nExiting..") - sys.exit(1) diff --git a/filemac/core/__init__.py b/filemac/core/__init__.py new file mode 100644 index 0000000..3375666 --- /dev/null +++ b/filemac/core/__init__.py @@ -0,0 +1,30 @@ +"""Core Logic implementation""" +from .audio.core import AudioConverter, AudioJoiner, AudioExtracter +from .svg.core import SVGConverter +from .pdf.core import PageExtractor, PDF2LongImageConverter, PDFCombine +from .video.core import VideoConverter +from .recorder import SoundRecorder +from .image.core import ( + GrayscaleConverter, + ImageCompressor, + ImageConverter, + ImageDocxConverter, + ImagePdfConverter, +) + +__all__ = [ + "AudioConverter", + "AudioJoiner", + "AudioExtracter", + "SVGConverter", + "GrayscaleConverter", + "ImageCompressor", + "ImageConverter", + "ImageDocxConverter", + "ImagePdfConverter", + "PageExtractor", + "PDF2LongImageConverter", + "PDFCombine", + "VideoConverter", + "SoundRecorder", +] diff --git a/build/lib/filemac/Simple_v_Analyzer.py b/filemac/core/audio/analyzer.py similarity index 100% rename from build/lib/filemac/Simple_v_Analyzer.py rename to filemac/core/audio/analyzer.py diff --git a/filemac/core/audio/core.py b/filemac/core/audio/core.py new file mode 100644 index 0000000..d785ff6 --- /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.YELLOW}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.') + + 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) + + print(f"{fg.GREEN}success{RESET}") + 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..208f2ab --- /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..c204d68 --- /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"{fg.GREEN}Success{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..a705599 --- /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"To: {fg.IWHITE}{output_filename}{RESET}") + video.write_videofile(output_filename, codec=Video_codecs[out_f]) + + """Close the video file""" + print(f"{fg.BGREEN}success{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/dd.py b/filemac/dd.py deleted file mode 100644 index 90fbe1f..0000000 --- a/filemac/dd.py +++ /dev/null @@ -1,10 +0,0 @@ -from OCRTextExtractor import ExtractText -img_objs = ['/home/skye/Software Engineering/Y2/SEM2/RV/SPE 2210 Client Side Programming Year II Semester II_1.png'] -text = '' -for i in img_objs: - extract = ExtractText(i) - tx = extract.OCR() - print(tx) - if tx is not None: - text += tx -print(text) diff --git a/filemac/fmac.py b/filemac/fmac.py deleted file mode 100644 index 91b28ba..0000000 --- a/filemac/fmac.py +++ /dev/null @@ -1,212 +0,0 @@ -#!/usr/bin/env python3.11.7 -# multimedia_cli/main.py -import argparse -import logging -import logging.handlers -import sys - -from . import handle_warnings -from .AudioExtractor import ExtractAudio -from .colors import (RESET, DYELLOW) -from .converter import (AudioConverter, FileSynthesis, ImageConverter, - MakeConversion, Scanner, VideoConverter) -from .formats import (SUPPORTED_AUDIO_FORMATS_SHOW, SUPPORTED_DOC_FORMATS, - SUPPORTED_IMAGE_FORMATS_SHOW, - SUPPORTED_VIDEO_FORMATS_SHOW) -from .image_op import Compress_Size -from .OCRTextExtractor import ExtractText -from .Simple_v_Analyzer import SA - -# from .formats import SUPPORTED_INPUT_FORMATS, SUPPORTED_OUTPUT_FORMATS -handle_warnings -logging.basicConfig(level=logging.INFO, format='%(levelname)-8s %(message)s') -logger = logging.getLogger(__name__) - - -class Eval: - - def __init__(self, file, outf): - self.file = file - self.outf = outf - - def document_eval(self): - ls = ["docx", "doc"] - sheetls = ["xlsx", "xls"] - try: - conv = MakeConversion(self.file) - if self.file.lower().endswith(tuple(sheetls)): - if self.outf.lower() == "csv": - conv.convert_xlsx_to_csv() - elif self.outf.lower() == "txt": - conv.convert_xls_to_text() - elif self.outf.lower() == "doc" or self.outf == "docx": - conv.convert_xls_to_word() - elif self.outf.lower() == "db": - conv.convert_xlsx_to_database() - - elif self.file.lower().endswith(tuple(ls)): - if self.outf.lower() == "txt": - conv.word_to_txt() - elif self.outf.lower() == "pdf": - conv.word_to_pdf() - elif self.outf.lower() == "pptx": - conv.word_to_pptx() - elif self.outf.lower() == "audio" or self.outf.lower() == "ogg": - conv = FileSynthesis(self.file) - conv.audiofy() - - elif self.file.endswith('txt'): - if self.outf.lower() == "pdf": - conv.txt_to_pdf() - elif self.outf.lower() == "doc" or self.outf == "docx" or self.outf == "word": - conv.text_to_word() - elif self.outf.lower() == "audio" or self.outf.lower() == "ogg": - conv = FileSynthesis(self.file) - conv.audiofy() - - elif self.file.lower().endswith('ppt') or self.file.lower().endswith('pptx'): - if self.outf.lower() == "doc" or self.outf.lower() == "docx" or self.outf == "word": - conv.ppt_to_word() - - elif self.file.lower().endswith('pdf'): - if self.outf.lower() == "doc" or self.outf.lower() == "docx" or self.outf == "word": - conv.pdf_to_word() - elif self.outf.lower() == "txt": - conv.pdf_to_txt() - elif self.outf.lower() == "audio" or self.outf.lower() == "ogg": - conv = FileSynthesis(self.file) - conv.audiofy() - - else: - print(f"{DYELLOW}Unsupported Conversion type{RESET}") - except Exception as e: - logger.error(e) - - -def main(): - parser = argparse.ArgumentParser( - description="Multimedia Element Operations") - - parser.add_argument( - "--convert_doc", help=f"Converter document file(s) to different format ie pdf_to_docx.\ - example {DYELLOW}filemac --convert_doc example.docx -t pdf{RESET}") - - parser.add_argument( - "--convert_audio", help=f"Convert audio file(s) to and from different format ie mp3 to wav\ - example {DYELLOW}filemac --convert_audio example.mp3 -t wav{RESET}") - - parser.add_argument( - "--convert_video", help=f"Convert video file(s) to and from different format ie mp4 to mkv.\ - example {DYELLOW}filemac --convert_video example.mp4 -t mkv{RESET}") - - parser.add_argument( - "--convert_image", help=f"Convert image file(s) to and from different format ie png to jpg.\ - example {DYELLOW}filemac --convert_image example.jpg -t png{RESET}") - - parser.add_argument( - - "--convert_doc2image", help=f"Convert documents to images ie png to jpg.\ - example {DYELLOW}filemac --convert_doc2image example.pdf -t png{RESET}") - - parser.add_argument("-xA", "--extract_audio", - help=f"Extract audio from a video.\ - example {DYELLOW}filemac -xA example.mp4 {RESET}") - - parser.add_argument( - "-Av", "--Analyze_video", help=f"Analyze a given video.\ - example {DYELLOW}filemac --analyze_video example.mp4 {RESET}") - - parser.add_argument("-t", "--target_format", - help="Target format for conversion (optional)") - - parser.add_argument( - "--resize_image", help=f"change size of an image compress/decompress \ - example {DYELLOW}filemac --resize_image example.png -t 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 {DYELLOW}filemac --scan example.pdf {RESET}") - - parser.add_argument( - "-SA", "--scanAsImg", help=f"Scan pdf file and extract text\ - example {DYELLOW}filemac --scanAsImg example.pdf {RESET}") - - parser.add_argument("--OCR", help=f"Extract text from an image.\ - example {DYELLOW}filemac --OCR image.png{RESET}") - - args = parser.parse_args() - - -# Call function to handle document conversion inputs before begining conversion - if args.convert_doc == 'help': - print(SUPPORTED_DOC_FORMATS) - sys.exit(1) - if args.convert_doc: - ev = Eval(args.convert_doc, args.target_format) - ev.document_eval() - - -# 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: - print(SUPPORTED_VIDEO_FORMATS_SHOW) - sys.exit(1) - ev = VideoConverter(args.convert_video, args.target_format) - ev.CONVERT_VIDEO() -# 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: - print(SUPPORTED_IMAGE_FORMATS_SHOW) - sys.exit(1) - conv = ImageConverter(args.convert_image, args.target_format) - conv.convert_image() - -# Handle image resizing - elif args.resize_image: - res = Compress_Size(args.resize_image) - res.resize_image(args.t_size) - -# Handle documents to images conversion - elif args.convert_doc2image: - conv = MakeConversion(args.convert_doc2image) - conv.doc2image(args.target_format) - -# 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: - print(SUPPORTED_AUDIO_FORMATS_SHOW) - sys.exit(1) - ev = AudioConverter(args.convert_audio, args.target_format) - ev.pydub_conv() - - -# Call module to evaluate audio files before making audio extraction from input video files conversion - elif args.extract_audio: - vi = ExtractAudio(args.extract_audio) - vi.moviepyextract() - -# Call module to scan the input and extract text - elif args.scan: - sc = Scanner(args.scan) - sc.scanPDF() - -# Call module to scan the input FILE as image object and extract text - elif args.scanAsImg: - sc = Scanner(args.scanAsImg) - tx = sc.scanAsImgs() -# Call module to handle Candidate images for text extraction inputs before begining conversion - elif args.OCR: - conv = ExtractText(args.OCR) - conv.OCR() - - elif args.Analyze_video: - analyzer = SA(args.Analyze_video) - analyzer.SimpleAnalyzer() - - -if __name__ == "__main__": - main() diff --git a/filemac/formats.py b/filemac/formats.py deleted file mode 100644 index 6490294..0000000 --- a/filemac/formats.py +++ /dev/null @@ -1,121 +0,0 @@ -# multimedia_cli/formats.py -from .colors import CYAN, DBLUE, DMAGENTA, DYELLOW, RESET - -SUPPORTED_DOC_FORMATS = f""" -|--------------------------------------------------------------------------- -|{DBLUE}Input format{RESET} |{DBLUE}Output format{RESET} | -|________________________________|__________________________________________| -| xlsx {DYELLOW}-------------------->{RESET}|csv txt doc/docx db(sql) | -| | | -| doc/docx{DYELLOW}-------------------->{RESET}|txt pdf ppt/pptx audio(ogg) | -| | | -| txt {DYELLOW}-------------------->{RESET}|pdf docx/doc audio(ogg) | -| | | -| pdf {DYELLOW}-------------------->{RESET}|doc/docx txt audio(ogg) | -| | | -| pptx/ppt{DYELLOW}-------------------->{RESET}|doc/docx | -| | -|___________________________________________________________________________| -""" - - -def p(): - print(SUPPORTED_DOC_FORMATS) - - -# 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", - "aac", # Advanced Audio Codec - "bpf", - "aiff", - "flac"] # Free Lossless Audio Codec) - -SUPPORTED_AUDIO_FORMATS_SHOW = f''' -|==============================| -| {DBLUE}Supported I/O formats {RESET} | -|==============================| -| {CYAN} wav {DYELLOW} | -| {CYAN} mp3 {DYELLOW} | -| {CYAN} ogg {DYELLOW} | -| {CYAN} flv {DYELLOW} | -| {CYAN} ogv {DYELLOW} | -| {CYAN} matroska {DYELLOW} | -| {CYAN} mov {DYELLOW} | -| {CYAN} webm {DYELLOW} | -| {CYAN} aac {DYELLOW} | -| {CYAN} bpf {DYELLOW} | --------------------------------- - -''' - -SUPPORTED_VIDEO_FORMATS = ["MP4", # MPEG-4 part 14 - "AVI", # Audio Video Interleave - "OGV", - "WEBM", - "MOV", # QuickTime Movie - "MKV", # Matroska Multimedia Container - MKV is known for its support of high-quality content. - "FLV", # - "WMV"] - -SUPPORTED_VIDEO_FORMATS_SHOW = f''' -,_______________________________________, -|x| {DBLUE}Supported I/O formats{RESET} |x| -|x|-----------------------------------{DYELLOW}|x| -|x| {DMAGENTA} MP4 {DYELLOW} |x| -|x| {DMAGENTA} AVI {DYELLOW} |x| -|x| {DMAGENTA} OGV {DYELLOW} |x| -|x| {DMAGENTA} WEBM{DYELLOW} |x| -|x| {DMAGENTA} MOV {DYELLOW} |x| -|x| {DMAGENTA} MKV {DYELLOW} |x| -|x| {DMAGENTA} FLV {DYELLOW} |x| -|x| {DMAGENTA} WMV {DYELLOW} |x| -|,|___________________________________|,|{DYELLOW} -''' - -SUPPORTED_IMAGE_FORMATS = { - "JPEG": ".jpg", # Joint Photographic Experts Group -Lossy compression - "PNG": ".png", # Joint Photographic Experts Group - not lossy - "GIF": ".gif", # Graphics Interchange Format - "BM": ".bmp", - "BMP": ".dib", - "DXF": ".dxf", # Autocad format 2D - "TIFF": ".tiff", # Tagged Image File Format A flexible and high-quality image format that supports lossless compression - "EXR": ".exr", - "pic": ".pic", - "pict": "pct", - "PDF": ".pdf", - "WebP": ".webp", - "ICNS": ".icns", - "PSD": ".psd", - "SVG": ".svg", # Scalable vector Graphics - "EPS": ".eps", - "PostSciript": ".ps", - "PS": ".ps"} - -SUPPORTED_IMAGE_FORMATS_SHOW = f''' -__________________________________________ -|x|{DBLUE}Supported I/O formats{RESET} |x| -|x|_____________________________________{DYELLOW}|x| -|x| {DMAGENTA} JPEG {DYELLOW} |x| -|x| {DMAGENTA} PNG {DYELLOW} |x| -|x| {DMAGENTA} GIF {DYELLOW} |x| -|x| {DMAGENTA} BM {DYELLOW} |x| -|x| {DMAGENTA} TIFF {DYELLOW} |x| -|x| {DMAGENTA} EXR {DYELLOW} |x| -|x| {DMAGENTA} PDF {DYELLOW} |x| -|x| {DMAGENTA} WebP{DYELLOW} |x| -|x| {DMAGENTA} ICNS {DYELLOW} |x| -|x| {DMAGENTA} PSD {DYELLOW} |x| -|x| {DMAGENTA} SVG {DYELLOW} |x| -|x| {DMAGENTA} EPS {DYELLOW} |x| -|x| {DMAGENTA} Postscript {DYELLOW} |x| -|_|_____________________________________|x| -''' - -SUPPORTED_DOCUMENT_FORMATS = ['pdf', 'doc', 'docx', 'csv', 'xlsx', 'xls', - 'ppt', 'pptx', 'txt', 'ogg', 'mp3', 'audio'] diff --git a/filemac/handle_warnings.py b/filemac/handle_warnings.py deleted file mode 100644 index 3e592d1..0000000 --- a/filemac/handle_warnings.py +++ /dev/null @@ -1,6 +0,0 @@ -import warnings - -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) diff --git a/filemac/image_op.py b/filemac/image_op.py deleted file mode 100644 index 61cfe6d..0000000 --- a/filemac/image_op.py +++ /dev/null @@ -1,64 +0,0 @@ -from PIL import Image -import os -import logging -import logging.handlers - -logging.basicConfig(level=logging.INFO, format='%(levelname)-8s %(message)s') -logger = logging.getLogger(__name__) - - -class Compress_Size: - - def __init__(self, input_image_path): - self.input_image_path = input_image_path - - def resize_image(self, target_size): - 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 \033[93m{size/1000_000:.2f}MiB") - - # 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("Invalid units. Please use either \033[1;95m'MB'\033[0m\ - or \033[1;95m'KB'\033[0m") - - # Calculate the new dimensions based on the target size - new_width, new_height = Compress_Size.calculate_new_dimensions(original_size, aspect_ratio, target_size_bytes) - print("\033[94mProcessing ..\033[0m") - resized_image = original_image.resize((new_width, new_height)) - resized_image.save(output_image_path) - t_size = os.path.getsize(output_image_path)/1000_000 - print("\033[1;92mOk\033[0m") - print(f"Image resized to \033[1;93m{t_size:.2f}\033[0m and saved to \033[1;93m{output_image_path}") - - def calculate_new_dimensions(original_size, aspect_ratio, target_size_bytes): - # 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 - - -if __name__ == "__main__": - input_image_path = input("Enter the path to the input image: ") - target_size = input("Enter the target output size (MB or KB): ") - ext = input_image_path[-3:] - output_image_path = os.path.splitext(input_image_path)[0] + f"_resized.{ext}" - - init = Compress_Size(input_image_path) - init.resize_image(target_size) 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..cf9dc7f --- /dev/null +++ b/filemac/utils/decorators.py @@ -0,0 +1,46 @@ +class Decorators: + @staticmethod + def for_loop(iterable: list | tuple | str): + """ + A for loop decorator that calls the decorated function with each element + from the provided list or tuple. + + Args: + data_list: A list, str or tuple of data to iterate over. + """ + + def decorator(func): + def wrapper(*args, **kwargs): + for item in iterable: + func(item, *args, **kwargs) + + return wrapper + + return decorator + + @staticmethod + def while_loop(iterable: list | tuple | str): + """ + A while loop decorator that calls the decorated function with each element + from the provided list or tuple. + + Args: + iterable: A list, str or tuple of data to iterate over. + """ + + def decorator(func): + def wrapper(*args, **kwargs): + index = 0 + while index <= len(iterable): + func(iterable[index], *args, **kwargs) + index += 1 + + return wrapper + + return decorator + + def threading(self): + ... + + +dcr = Decorators() diff --git a/filemac/utils/file_utils.py b/filemac/utils/file_utils.py new file mode 100644 index 0000000..5bc5481 --- /dev/null +++ b/filemac/utils/file_utils.py @@ -0,0 +1,360 @@ +""" +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, SUPPORTED_AUDIO_FORMATS, SUPPORTED_VIDEO_FORMATS +from .simple import logger + + +def map_ext_from_format(fmt: str) -> tuple: + if fmt in (x.lower() for x in SUPPORTED_AUDIO_FORMATS): + return fmt, SUPPORTED_AUDIO_FORMATS + elif fmt in (x.lower() for x in SUPPORTED_VIDEO_FORMATS): + return fmt, SUPPORTED_VIDEO_FORMATS + elif fmt in SUPPORTED_IMAGE_FORMATS.values(): + return fmt, SUPPORTED_IMAGE_FORMATS + return None, None + + +def dirbuster(_dir_, ext: list | tuple = ("pdf", "doc", "docx")) -> list: + try: + target = [] + for root, dirs, files in os.walk(_dir_): + for file in files: + fext = file.split(".")[-1] + + _path_ = os.path.join(root, file) + + if os.path.exists(_path_) and fext.lower() in ext: + 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..35e472e --- /dev/null +++ b/filemac/utils/formats.py @@ -0,0 +1,170 @@ +# multimedia_cli/formats +from .colors import fg, bg, rs + + +RESET = rs + +SUPPORTED_DOC_FORMATS = ["pdf", 'ppt', 'pptx', 'doc', 'docx', 'xls', 'xlsx', 'txt'] + +SUPPORTED_DOC_FORMATS_HELP = 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/build/lib/filemac/handle_warnings.py b/filemac/utils/handle_warnings.py similarity index 100% rename from build/lib/filemac/handle_warnings.py rename to filemac/utils/handle_warnings.py 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,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,yFAAyF,sBAAsB,CAAC,mFAAmF,kBAAkB,CAAC,2GAA2G,mBAAmB,CAAC,yFAAyF,yBAAyB,CAAC,mFAAmF,kBAAkB,CAAC,2GAA2G,sBAAsB,CAAC,yFAAyF,wBAAwB,CAAC,mFAAmF,kBAAkB,CAAC,2GAA2G,qBAAqB,CAAC,yFAAyF,yBAAyB,CAAC,mFAAmF,kBAAkB,CAAC,2GAA2G,sBAAsB,CAAC,yFAAyF,wBAAwB,CAAC,mFAAmF,kBAAkB,CAAC,2GAA2G,qBAAqB,CAAC,yFAAyF,yBAAyB,CAAC,mFAAmF,kBAAkB,CAAC,2GAA2G,sBAAsB,CAAC,yFAAyF,wBAAwB,CAAC,mFAAmF,kBAAkB,CAAC,2GAA2G,qBAAqB,CAAC,yFAAyF,yBAAyB,CAAC,mFAAmF,kBAAkB,CAAC,2GAA2G,sBAAsB,CAAC,yFAAyF,wBAAwB,CAAC,mFAAmF,kBAAkB,CAAC,2GAA2G,qBAAqB,CAAC,yFAAyF,yBAAyB,CAAC,mFAAmF,kBAAkB,CAAC,2GAA2G,sBAAsB,CAAC,yFAAyF,wBAAwB,CAAC,mFAAmF,kBAAkB,CAAC,2GAA2G,qBAAqB,CAAC,yFAAyF,yBAAyB,CAAC,mFAAmF,kBAAkB,CAAC,2GAA2G,sBAAsB,CAAC,yFAAyF,wBAAwB,CAAC,mFAAmF,kBAAkB,CAAC,2GAA2G,qBAAqB,CAAC,yFAAyF,yBAAyB,CAAC,mFAAmF,kBAAkB,CAAC,2GAA2G,sBAAsB,CAAC,yFAAyF,wBAAwB,CAAC,mFAAmF,kBAAkB,CAAC,2GAA2G,qBAAqB,CAAC,yFAAyF,yBAAyB,CAAC,mFAAmF,kBAAkB,CAAC,2GAA2G,sBAAsB,CAAC,yFAAyF,wBAAwB,CAAC,mFAAmF,kBAAkB,CAAC,2GAA2G,qBAAqB,CAAC,yFAAyF,yBAAyB,CAAC,mFAAmF,kBAAkB,CAAC,2GAA2G,sBAAsB,CAAC,yFAAyF,wBAAwB,CAAC,mFAAmF,kBAAkB,CAAC,2GAA2G,qBAAqB,CAAC,yFAAyF,yBAAyB,CAAC,mFAAmF,kBAAkB,CAAC,2GAA2G,sBAAsB,CAAC,yFAAyF,sBAAsB,CAAC,mFAAmF,kBAAkB,CAAC,2GAA2G,mBAAmB,CAAC,yFAAyF,yBAAyB,CAAC,mFAAmF,kBAAkB,CAAC,2GAA2G,sBAAsB,CAAC,yFAAyF,wBAAwB,CAAC,mFAAmF,kBAAkB,CAAC,2GAA2G,qBAAqB,CAAC,yFAAyF,yBAAyB,CAAC,mFAAmF,kBAAkB,CAAC,2GAA2G,sBAAsB,CAAC,yFAAyF,wBAAwB,CAAC,mFAAmF,kBAAkB,CAAC,2GAA2G,qBAAqB,CAAC,yFAAyF,yBAAyB,CAAC,mFAAmF,kBAAkB,CAAC,2GAA2G,sBAAsB,CAAC,yFAAyF,wBAAwB,CAAC,mFAAmF,kBAAkB,CAAC,2GAA2G,qBAAqB,CAAC,yFAAyF,yBAAyB,CAAC,mFAAmF,kBAAkB,CAAC,2GAA2G,sBAAsB,CAAC,yFAAyF,wBAAwB,CAAC,mFAAmF,kBAAkB,CAAC,2GAA2G,qBAAqB,CAAC,yFAAyF,yBAAyB,CAAC,mFAAmF,kBAAkB,CAAC,2GAA2G,sBAAsB,CAAC,yFAAyF,wBAAwB,CAAC,mFAAmF,kBAAkB,CAAC,2GAA2G,qBAAqB,CAAC,yFAAyF,yBAAyB,CAAC,mFAAmF,kBAAkB,CAAC,2GAA2G,sBAAsB,CAAC,yFAAyF,wBAAwB,CAAC,mFAAmF,kBAAkB,CAAC,2GAA2G,qBAAqB,CAAC,yFAAyF,yBAAyB,CAAC,mFAAmF,kBAAkB,CAAC,2GAA2G,sBAAsB,CAAC,yFAAyF,wBAAwB,CAAC,mFAAmF,kBAAkB,CAAC,2GAA2G,qBAAqB,CAAC,yFAAyF,yBAAyB,CAAC,mFAAmF,kBAAkB,CAAC,2GAA2G,sBAAsB,CAAC,yFAAyF,wBAAwB,CAAC,mFAAmF,kBAAkB,CAAC,2GAA2G,qBAAqB,CAAC,yFAAyF,yBAAyB,CAAC,mFAAmF,kBAAkB,CAAC,2GAA2G,sBAAsB,CAAC,yFAAyF,wBAAwB,CAAC,mFAAmF,kBAAkB,CAAC,2GAA2G,qBAAqB,CAAC,yFAAyF,yBAAyB,CAAC,mFAAmF,kBAAkB,CAAC,2GAA2G,sBAAsB,CAAC,yFAAyF,sBAAsB,CAAC,mFAAmF,kBAAkB,CAAC,2GAA2G,mBAAmB,CAAC,qFAAqF,wDAAwD,CAAC,iFAAiF,+BAA+B,CAAC,uFAAuF,kCAAkC,CAAC,yFAAyF,mCAAmC,CAAC,+FAA+F,sCAAsC,CAAC,iGAAiG,0DAA0D,CAAC,mGAAmG,4DAA4D,CAAC,yGAAyG,2DAA2D,CAAC,iGAAiG,wDAAwD,CAAC,mGAAmG,wDAAwD,CAAC,yGAAyG,yDAAyD,CAAC,iGAAiG,yDAAyD,CAAC,mGAAmG,wDAAwD,CAAC,yGAAyG,2DAA2D,CAAC,mGAAmG,yDAAyD,CAAC,qGAAqG,wDAAwD,CAAC,2GAA2G,2DAA2D,CAAC,mGAAmG,yDAAyD,CAAC,qGAAqG,wDAAwD,CAAC,2GAA2G,2DAA2D,CAAC,iCAAiC,SAAS,CAAC,qCAAqC,CAAC,6CAA6C,SAAS,CAAC,uBAAuB,CAAC,mBAAmB,gCAAgC,CAAC,qBAAqB,iCAAiC,CAAC,sBAAsB,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..97e4d12 --- /dev/null +++ b/fweb/core/static/js/utils.js @@ -0,0 +1,1003 @@ +// Additional utility functions for the new tools + +// Escape HTML to prevent XSS attacks when inserting text into innerHTML +function escapeHtml(string) { + return String(string) + .replace(/&/g, "&") + .replace(//g, ">") + .replace(/"/g, """) + .replace(/'/g, "'"); +} + +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 = ` +
+ +
+
${escapeHtml(file.name)}
+ ${isFolder ? '
' + escapeHtml(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..1f55255 --- /dev/null +++ b/fweb/core/views.py @@ -0,0 +1,284 @@ +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 +from werkzeug.utils import secure_filename +# 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: + safe_name = secure_filename(file.name) + file_path = os.path.normpath(os.path.join(temp_dir, safe_name)) + # Ensure file is stored strictly in temp_dir + if not file_path.startswith(os.path.abspath(temp_dir) + os.sep): + return JsonResponse({"error": "Invalid file name"}, status=400) + 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 0000000..7b97a28 Binary files /dev/null and b/fweb/db.sqlite3 differ 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..fc321fa --- /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.1", "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'; + + //
    + const selector_chooser = quickElement('ul', selector_div); + selector_chooser.className = 'selector-chooser'; + const add_link = quickElement('a', quickElement('li', selector_chooser), gettext('Choose'), 'title', gettext('Choose'), 'href', '#', 'id', field_id + '_add_link'); + add_link.className = 'selector-add'; + const remove_link = quickElement('a', quickElement('li', selector_chooser), gettext('Remove'), 'title', gettext('Remove'), 'href', '#', 'id', field_id + '_remove_link'); + remove_link.className = 'selector-remove'; + + //
    + const selector_chosen = quickElement('div', selector_div, '', 'id', field_id + '_selector_chosen'); + selector_chosen.className = 'selector-chosen'; + const title_chosen = quickElement('h2', selector_chosen, interpolate(gettext('Chosen %s') + ' ', [field_name])); + quickElement( + 'span', title_chosen, '', + 'class', 'help help-tooltip help-icon', + 'title', interpolate( + gettext( + 'This is the list of chosen %s. You may remove some by ' + + 'selecting them in the box below and then clicking the ' + + '"Remove" arrow between the two boxes.' + ), + [field_name] + ) + ); + + const filter_selected_p = quickElement('p', selector_chosen, '', 'id', field_id + '_filter_selected'); + filter_selected_p.className = 'selector-filter'; + + const search_filter_selected_label = quickElement('label', filter_selected_p, '', 'for', field_id + '_selected_input'); + + quickElement( + 'span', search_filter_selected_label, '', + 'class', 'help-tooltip search-label-icon', + 'title', interpolate(gettext("Type into this box to filter down the list of selected %s."), [field_name]) + ); + + filter_selected_p.appendChild(document.createTextNode(' ')); + + const filter_selected_input = quickElement('input', filter_selected_p, '', 'type', 'text', 'placeholder', gettext("Filter")); + filter_selected_input.id = field_id + '_selected_input'; + + const to_box = quickElement('select', selector_chosen, '', 'id', field_id + '_to', 'multiple', '', 'size', from_box.size, 'name', from_box.name); + to_box.className = 'filtered'; + + const warning_footer = quickElement('div', selector_chosen, '', 'class', 'list-footer-display'); + quickElement('span', warning_footer, '', 'id', field_id + '_list-footer-display-text'); + quickElement('span', warning_footer, ' (click to clear)', 'class', 'list-footer-display__clear'); + + const clear_all = quickElement('a', selector_chosen, gettext('Remove all'), 'title', interpolate(gettext('Click to remove all chosen %s at once.'), [field_name]), 'href', '#', 'id', field_id + '_remove_all_link'); + clear_all.className = 'selector-clearall'; + + from_box.name = from_box.name + '_old'; + + // Set up the JavaScript event handlers for the select box filter interface + const move_selection = function(e, elem, move_func, from, to) { + if (elem.classList.contains('active')) { + move_func(from, to); + SelectFilter.refresh_icons(field_id); + SelectFilter.refresh_filtered_selects(field_id); + SelectFilter.refresh_filtered_warning(field_id); + } + e.preventDefault(); + }; + choose_all.addEventListener('click', function(e) { + move_selection(e, this, SelectBox.move_all, field_id + '_from', field_id + '_to'); + }); + add_link.addEventListener('click', function(e) { + move_selection(e, this, SelectBox.move, field_id + '_from', field_id + '_to'); + }); + remove_link.addEventListener('click', function(e) { + move_selection(e, this, SelectBox.move, field_id + '_to', field_id + '_from'); + }); + clear_all.addEventListener('click', function(e) { + move_selection(e, this, SelectBox.move_all, field_id + '_to', field_id + '_from'); + }); + warning_footer.addEventListener('click', function(e) { + filter_selected_input.value = ''; + SelectBox.filter(field_id + '_to', ''); + SelectFilter.refresh_filtered_warning(field_id); + SelectFilter.refresh_icons(field_id); + }); + filter_input.addEventListener('keypress', function(e) { + SelectFilter.filter_key_press(e, field_id, '_from', '_to'); + }); + filter_input.addEventListener('keyup', function(e) { + SelectFilter.filter_key_up(e, field_id, '_from'); + }); + filter_input.addEventListener('keydown', function(e) { + SelectFilter.filter_key_down(e, field_id, '_from', '_to'); + }); + filter_selected_input.addEventListener('keypress', function(e) { + SelectFilter.filter_key_press(e, field_id, '_to', '_from'); + }); + filter_selected_input.addEventListener('keyup', function(e) { + SelectFilter.filter_key_up(e, field_id, '_to', '_selected_input'); + }); + filter_selected_input.addEventListener('keydown', function(e) { + SelectFilter.filter_key_down(e, field_id, '_to', '_from'); + }); + selector_div.addEventListener('change', function(e) { + if (e.target.tagName === 'SELECT') { + SelectFilter.refresh_icons(field_id); + } + }); + selector_div.addEventListener('dblclick', function(e) { + if (e.target.tagName === 'OPTION') { + if (e.target.closest('select').id === field_id + '_to') { + SelectBox.move(field_id + '_to', field_id + '_from'); + } else { + SelectBox.move(field_id + '_from', field_id + '_to'); + } + SelectFilter.refresh_icons(field_id); + } + }); + from_box.closest('form').addEventListener('submit', function() { + SelectBox.filter(field_id + '_to', ''); + SelectBox.select_all(field_id + '_to'); + }); + SelectBox.init(field_id + '_from'); + SelectBox.init(field_id + '_to'); + // Move selected from_box options to to_box + SelectBox.move(field_id + '_from', field_id + '_to'); + + // Initial icon refresh + SelectFilter.refresh_icons(field_id); + }, + any_selected: function(field) { + // Temporarily add the required attribute and check validity. + field.required = true; + const any_selected = field.checkValidity(); + field.required = false; + return any_selected; + }, + refresh_filtered_warning: function(field_id) { + const count = SelectBox.get_hidden_node_count(field_id + '_to'); + const selector = document.getElementById(field_id + '_selector_chosen'); + const warning = document.getElementById(field_id + '_list-footer-display-text'); + selector.className = selector.className.replace('selector-chosen--with-filtered', ''); + warning.textContent = interpolate(ngettext( + '%s selected option not visible', + '%s selected options not visible', + count + ), [count]); + if(count > 0) { + selector.className += ' selector-chosen--with-filtered'; + } + }, + refresh_filtered_selects: function(field_id) { + SelectBox.filter(field_id + '_from', document.getElementById(field_id + "_input").value); + SelectBox.filter(field_id + '_to', document.getElementById(field_id + "_selected_input").value); + }, + refresh_icons: function(field_id) { + const from = document.getElementById(field_id + '_from'); + const to = document.getElementById(field_id + '_to'); + // Active if at least one item is selected + document.getElementById(field_id + '_add_link').classList.toggle('active', SelectFilter.any_selected(from)); + document.getElementById(field_id + '_remove_link').classList.toggle('active', SelectFilter.any_selected(to)); + // Active if the corresponding box isn't empty + document.getElementById(field_id + '_add_all_link').classList.toggle('active', from.querySelector('option')); + document.getElementById(field_id + '_remove_all_link').classList.toggle('active', to.querySelector('option')); + SelectFilter.refresh_filtered_warning(field_id); + }, + filter_key_press: function(event, field_id, source, target) { + const source_box = document.getElementById(field_id + source); + // don't submit form if user pressed Enter + if ((event.which && event.which === 13) || (event.keyCode && event.keyCode === 13)) { + source_box.selectedIndex = 0; + SelectBox.move(field_id + source, field_id + target); + source_box.selectedIndex = 0; + event.preventDefault(); + } + }, + filter_key_up: function(event, field_id, source, filter_input) { + const input = filter_input || '_input'; + const source_box = document.getElementById(field_id + source); + const temp = source_box.selectedIndex; + SelectBox.filter(field_id + source, document.getElementById(field_id + input).value); + source_box.selectedIndex = temp; + SelectFilter.refresh_filtered_warning(field_id); + SelectFilter.refresh_icons(field_id); + }, + filter_key_down: function(event, field_id, source, target) { + const source_box = document.getElementById(field_id + source); + // right key (39) or left key (37) + const direction = source === '_from' ? 39 : 37; + // right arrow -- move across + if ((event.which && event.which === direction) || (event.keyCode && event.keyCode === direction)) { + const old_index = source_box.selectedIndex; + SelectBox.move(field_id + source, field_id + target); + SelectFilter.refresh_filtered_selects(field_id); + SelectFilter.refresh_filtered_warning(field_id); + source_box.selectedIndex = (old_index === source_box.length) ? source_box.length - 1 : old_index; + return; + } + // down arrow -- wrap around + if ((event.which && event.which === 40) || (event.keyCode && event.keyCode === 40)) { + source_box.selectedIndex = (source_box.length === source_box.selectedIndex + 1) ? 0 : source_box.selectedIndex + 1; + } + // up arrow -- wrap around + if ((event.which && event.which === 38) || (event.keyCode && event.keyCode === 38)) { + source_box.selectedIndex = (source_box.selectedIndex === 0) ? source_box.length - 1 : source_box.selectedIndex - 1; + } + } + }; + + window.addEventListener('load', function(e) { + document.querySelectorAll('select.selectfilter, select.selectfilterstacked').forEach(function(el) { + const data = el.dataset; + SelectFilter.init(el.id, data.fieldName, parseInt(data.isStacked, 10)); + }); + }); +} diff --git a/fweb/static/admin/js/actions.js b/fweb/static/admin/js/actions.js new file mode 100644 index 0000000..04b25e9 --- /dev/null +++ b/fweb/static/admin/js/actions.js @@ -0,0 +1,204 @@ +/*global gettext, interpolate, ngettext, Actions*/ +'use strict'; +{ + function show(selector) { + document.querySelectorAll(selector).forEach(function(el) { + el.classList.remove('hidden'); + }); + } + + function hide(selector) { + document.querySelectorAll(selector).forEach(function(el) { + el.classList.add('hidden'); + }); + } + + function showQuestion(options) { + hide(options.acrossClears); + show(options.acrossQuestions); + hide(options.allContainer); + } + + function showClear(options) { + show(options.acrossClears); + hide(options.acrossQuestions); + document.querySelector(options.actionContainer).classList.remove(options.selectedClass); + show(options.allContainer); + hide(options.counterContainer); + } + + function reset(options) { + hide(options.acrossClears); + hide(options.acrossQuestions); + hide(options.allContainer); + show(options.counterContainer); + } + + function clearAcross(options) { + reset(options); + const acrossInputs = document.querySelectorAll(options.acrossInput); + acrossInputs.forEach(function(acrossInput) { + acrossInput.value = 0; + }); + document.querySelector(options.actionContainer).classList.remove(options.selectedClass); + } + + function checker(actionCheckboxes, options, checked) { + if (checked) { + showQuestion(options); + } else { + reset(options); + } + actionCheckboxes.forEach(function(el) { + el.checked = checked; + el.closest('tr').classList.toggle(options.selectedClass, checked); + }); + } + + function updateCounter(actionCheckboxes, options) { + const sel = Array.from(actionCheckboxes).filter(function(el) { + return el.checked; + }).length; + const counter = document.querySelector(options.counterContainer); + // data-actions-icnt is defined in the generated HTML + // and contains the total amount of objects in the queryset + const actions_icnt = Number(counter.dataset.actionsIcnt); + counter.textContent = interpolate( + ngettext('%(sel)s of %(cnt)s selected', '%(sel)s of %(cnt)s selected', sel), { + sel: sel, + cnt: actions_icnt + }, true); + const allToggle = document.getElementById(options.allToggleId); + allToggle.checked = sel === actionCheckboxes.length; + if (allToggle.checked) { + showQuestion(options); + } else { + clearAcross(options); + } + } + + const defaults = { + actionContainer: "div.actions", + counterContainer: "span.action-counter", + allContainer: "div.actions span.all", + acrossInput: "div.actions input.select-across", + acrossQuestions: "div.actions span.question", + acrossClears: "div.actions span.clear", + allToggleId: "action-toggle", + selectedClass: "selected" + }; + + window.Actions = function(actionCheckboxes, options) { + options = Object.assign({}, defaults, options); + let list_editable_changed = false; + let lastChecked = null; + let shiftPressed = false; + + document.addEventListener('keydown', (event) => { + shiftPressed = event.shiftKey; + }); + + document.addEventListener('keyup', (event) => { + shiftPressed = event.shiftKey; + }); + + document.getElementById(options.allToggleId).addEventListener('click', function(event) { + checker(actionCheckboxes, options, this.checked); + updateCounter(actionCheckboxes, options); + }); + + document.querySelectorAll(options.acrossQuestions + " a").forEach(function(el) { + el.addEventListener('click', function(event) { + event.preventDefault(); + const acrossInputs = document.querySelectorAll(options.acrossInput); + acrossInputs.forEach(function(acrossInput) { + acrossInput.value = 1; + }); + showClear(options); + }); + }); + + document.querySelectorAll(options.acrossClears + " a").forEach(function(el) { + el.addEventListener('click', function(event) { + event.preventDefault(); + document.getElementById(options.allToggleId).checked = false; + clearAcross(options); + checker(actionCheckboxes, options, false); + updateCounter(actionCheckboxes, options); + }); + }); + + function affectedCheckboxes(target, withModifier) { + const multiSelect = (lastChecked && withModifier && lastChecked !== target); + if (!multiSelect) { + return [target]; + } + const checkboxes = Array.from(actionCheckboxes); + const targetIndex = checkboxes.findIndex(el => el === target); + const lastCheckedIndex = checkboxes.findIndex(el => el === lastChecked); + const startIndex = Math.min(targetIndex, lastCheckedIndex); + const endIndex = Math.max(targetIndex, lastCheckedIndex); + const filtered = checkboxes.filter((el, index) => (startIndex <= index) && (index <= endIndex)); + return filtered; + }; + + Array.from(document.getElementById('result_list').tBodies).forEach(function(el) { + el.addEventListener('change', function(event) { + const target = event.target; + if (target.classList.contains('action-select')) { + const checkboxes = affectedCheckboxes(target, shiftPressed); + checker(checkboxes, options, target.checked); + updateCounter(actionCheckboxes, options); + lastChecked = target; + } else { + list_editable_changed = true; + } + }); + }); + + document.querySelector('#changelist-form button[name=index]').addEventListener('click', function(event) { + if (list_editable_changed) { + const confirmed = confirm(gettext("You have unsaved changes on individual editable fields. If you run an action, your unsaved changes will be lost.")); + if (!confirmed) { + event.preventDefault(); + } + } + }); + + const el = document.querySelector('#changelist-form input[name=_save]'); + // The button does not exist if no fields are editable. + if (el) { + el.addEventListener('click', function(event) { + if (document.querySelector('[name=action]').value) { + const text = list_editable_changed + ? gettext("You have selected an action, but you haven’t saved your changes to individual fields yet. Please click OK to save. You’ll need to re-run the action.") + : gettext("You have selected an action, and you haven’t made any changes on individual fields. You’re probably looking for the Go button rather than the Save button."); + if (!confirm(text)) { + event.preventDefault(); + } + } + }); + } + // Sync counter when navigating to the page, such as through the back + // button. + window.addEventListener('pageshow', (event) => updateCounter(actionCheckboxes, options)); + }; + + // Call function fn when the DOM is loaded and ready. If it is already + // loaded, call the function now. + // http://youmightnotneedjquery.com/#ready + function ready(fn) { + if (document.readyState !== 'loading') { + fn(); + } else { + document.addEventListener('DOMContentLoaded', fn); + } + } + + ready(function() { + const actionsEls = document.querySelectorAll('tr input.action-select'); + if (actionsEls.length > 0) { + Actions(actionsEls); + } + }); +} diff --git a/fweb/static/admin/js/admin/DateTimeShortcuts.js b/fweb/static/admin/js/admin/DateTimeShortcuts.js new file mode 100644 index 0000000..aa1cae9 --- /dev/null +++ b/fweb/static/admin/js/admin/DateTimeShortcuts.js @@ -0,0 +1,408 @@ +/*global Calendar, findPosX, findPosY, get_format, gettext, gettext_noop, interpolate, ngettext, quickElement*/ +// Inserts shortcut buttons after all of the following: +// +// +'use strict'; +{ + const DateTimeShortcuts = { + calendars: [], + calendarInputs: [], + clockInputs: [], + clockHours: { + default_: [ + [gettext_noop('Now'), -1], + [gettext_noop('Midnight'), 0], + [gettext_noop('6 a.m.'), 6], + [gettext_noop('Noon'), 12], + [gettext_noop('6 p.m.'), 18] + ] + }, + dismissClockFunc: [], + dismissCalendarFunc: [], + calendarDivName1: 'calendarbox', // name of calendar
    that gets toggled + calendarDivName2: 'calendarin', // name of
    that contains calendar + calendarLinkName: 'calendarlink', // name of the link that is used to toggle + clockDivName: 'clockbox', // name of clock
    that gets toggled + clockLinkName: 'clocklink', // name of the link that is used to toggle + shortCutsClass: 'datetimeshortcuts', // class of the clock and cal shortcuts + timezoneWarningClass: 'timezonewarning', // class of the warning for timezone mismatch + timezoneOffset: 0, + init: function() { + const serverOffset = document.body.dataset.adminUtcOffset; + if (serverOffset) { + const localOffset = new Date().getTimezoneOffset() * -60; + DateTimeShortcuts.timezoneOffset = localOffset - serverOffset; + } + + for (const inp of document.getElementsByTagName('input')) { + if (inp.type === 'text' && inp.classList.contains('vTimeField')) { + DateTimeShortcuts.addClock(inp); + DateTimeShortcuts.addTimezoneWarning(inp); + } + else if (inp.type === 'text' && inp.classList.contains('vDateField')) { + DateTimeShortcuts.addCalendar(inp); + DateTimeShortcuts.addTimezoneWarning(inp); + } + } + }, + // Return the current time while accounting for the server timezone. + now: function() { + const serverOffset = document.body.dataset.adminUtcOffset; + if (serverOffset) { + const localNow = new Date(); + const localOffset = localNow.getTimezoneOffset() * -60; + localNow.setTime(localNow.getTime() + 1000 * (serverOffset - localOffset)); + return localNow; + } else { + return new Date(); + } + }, + // Add a warning when the time zone in the browser and backend do not match. + addTimezoneWarning: function(inp) { + const warningClass = DateTimeShortcuts.timezoneWarningClass; + let timezoneOffset = DateTimeShortcuts.timezoneOffset / 3600; + + // Only warn if there is a time zone mismatch. + if (!timezoneOffset) { + return; + } + + // Check if warning is already there. + if (inp.parentNode.querySelectorAll('.' + warningClass).length) { + return; + } + + let message; + if (timezoneOffset > 0) { + message = ngettext( + 'Note: You are %s hour ahead of server time.', + 'Note: You are %s hours ahead of server time.', + timezoneOffset + ); + } + else { + timezoneOffset *= -1; + message = ngettext( + 'Note: You are %s hour behind server time.', + 'Note: You are %s hours behind server time.', + timezoneOffset + ); + } + message = interpolate(message, [timezoneOffset]); + + const warning = document.createElement('div'); + warning.classList.add('help', warningClass); + warning.textContent = message; + inp.parentNode.appendChild(warning); + }, + // Add clock widget to a given field + addClock: function(inp) { + const num = DateTimeShortcuts.clockInputs.length; + DateTimeShortcuts.clockInputs[num] = inp; + DateTimeShortcuts.dismissClockFunc[num] = function() { DateTimeShortcuts.dismissClock(num); return true; }; + + // Shortcut links (clock icon and "Now" link) + const shortcuts_span = document.createElement('span'); + shortcuts_span.className = DateTimeShortcuts.shortCutsClass; + inp.parentNode.insertBefore(shortcuts_span, inp.nextSibling); + const now_link = document.createElement('a'); + now_link.href = "#"; + now_link.textContent = gettext('Now'); + now_link.addEventListener('click', function(e) { + e.preventDefault(); + DateTimeShortcuts.handleClockQuicklink(num, -1); + }); + const clock_link = document.createElement('a'); + clock_link.href = '#'; + clock_link.id = DateTimeShortcuts.clockLinkName + num; + clock_link.addEventListener('click', function(e) { + e.preventDefault(); + // avoid triggering the document click handler to dismiss the clock + e.stopPropagation(); + DateTimeShortcuts.openClock(num); + }); + + quickElement( + 'span', clock_link, '', + 'class', 'clock-icon', + 'title', gettext('Choose a Time') + ); + shortcuts_span.appendChild(document.createTextNode('\u00A0')); + shortcuts_span.appendChild(now_link); + shortcuts_span.appendChild(document.createTextNode('\u00A0|\u00A0')); + shortcuts_span.appendChild(clock_link); + + // Create clock link div + // + // Markup looks like: + //
    + //

    Choose a time

    + // + //

    Cancel

    + //
    + + const clock_box = document.createElement('div'); + clock_box.style.display = 'none'; + clock_box.style.position = 'absolute'; + clock_box.className = 'clockbox module'; + clock_box.id = DateTimeShortcuts.clockDivName + num; + document.body.appendChild(clock_box); + clock_box.addEventListener('click', function(e) { e.stopPropagation(); }); + + quickElement('h2', clock_box, gettext('Choose a time')); + const time_list = quickElement('ul', clock_box); + time_list.className = 'timelist'; + // The list of choices can be overridden in JavaScript like this: + // DateTimeShortcuts.clockHours.name = [['3 a.m.', 3]]; + // where name is the name attribute of the . + const name = typeof DateTimeShortcuts.clockHours[inp.name] === 'undefined' ? 'default_' : inp.name; + DateTimeShortcuts.clockHours[name].forEach(function(element) { + const time_link = quickElement('a', quickElement('li', time_list), gettext(element[0]), 'href', '#'); + time_link.addEventListener('click', function(e) { + e.preventDefault(); + DateTimeShortcuts.handleClockQuicklink(num, element[1]); + }); + }); + + const cancel_p = quickElement('p', clock_box); + cancel_p.className = 'calendar-cancel'; + const cancel_link = quickElement('a', cancel_p, gettext('Cancel'), 'href', '#'); + cancel_link.addEventListener('click', function(e) { + e.preventDefault(); + DateTimeShortcuts.dismissClock(num); + }); + + document.addEventListener('keyup', function(event) { + if (event.which === 27) { + // ESC key closes popup + DateTimeShortcuts.dismissClock(num); + event.preventDefault(); + } + }); + }, + openClock: function(num) { + const clock_box = document.getElementById(DateTimeShortcuts.clockDivName + num); + const clock_link = document.getElementById(DateTimeShortcuts.clockLinkName + num); + + // Recalculate the clockbox position + // is it left-to-right or right-to-left layout ? + if (window.getComputedStyle(document.body).direction !== 'rtl') { + clock_box.style.left = findPosX(clock_link) + 17 + 'px'; + } + else { + // since style's width is in em, it'd be tough to calculate + // px value of it. let's use an estimated px for now + clock_box.style.left = findPosX(clock_link) - 110 + 'px'; + } + clock_box.style.top = Math.max(0, findPosY(clock_link) - 30) + 'px'; + + // Show the clock box + clock_box.style.display = 'block'; + document.addEventListener('click', DateTimeShortcuts.dismissClockFunc[num]); + }, + dismissClock: function(num) { + document.getElementById(DateTimeShortcuts.clockDivName + num).style.display = 'none'; + document.removeEventListener('click', DateTimeShortcuts.dismissClockFunc[num]); + }, + handleClockQuicklink: function(num, val) { + let d; + if (val === -1) { + d = DateTimeShortcuts.now(); + } + else { + d = new Date(1970, 1, 1, val, 0, 0, 0); + } + DateTimeShortcuts.clockInputs[num].value = d.strftime(get_format('TIME_INPUT_FORMATS')[0]); + DateTimeShortcuts.clockInputs[num].focus(); + DateTimeShortcuts.dismissClock(num); + }, + // Add calendar widget to a given field. + addCalendar: function(inp) { + const num = DateTimeShortcuts.calendars.length; + + DateTimeShortcuts.calendarInputs[num] = inp; + DateTimeShortcuts.dismissCalendarFunc[num] = function() { DateTimeShortcuts.dismissCalendar(num); return true; }; + + // Shortcut links (calendar icon and "Today" link) + const shortcuts_span = document.createElement('span'); + shortcuts_span.className = DateTimeShortcuts.shortCutsClass; + inp.parentNode.insertBefore(shortcuts_span, inp.nextSibling); + const today_link = document.createElement('a'); + today_link.href = '#'; + today_link.appendChild(document.createTextNode(gettext('Today'))); + today_link.addEventListener('click', function(e) { + e.preventDefault(); + DateTimeShortcuts.handleCalendarQuickLink(num, 0); + }); + const cal_link = document.createElement('a'); + cal_link.href = '#'; + cal_link.id = DateTimeShortcuts.calendarLinkName + num; + cal_link.addEventListener('click', function(e) { + e.preventDefault(); + // avoid triggering the document click handler to dismiss the calendar + e.stopPropagation(); + DateTimeShortcuts.openCalendar(num); + }); + quickElement( + 'span', cal_link, '', + 'class', 'date-icon', + 'title', gettext('Choose a Date') + ); + shortcuts_span.appendChild(document.createTextNode('\u00A0')); + shortcuts_span.appendChild(today_link); + shortcuts_span.appendChild(document.createTextNode('\u00A0|\u00A0')); + shortcuts_span.appendChild(cal_link); + + // Create calendarbox div. + // + // Markup looks like: + // + //
    + //

    + // + // February 2003 + //

    + //
    + // + //
    + //
    + // Yesterday | Today | Tomorrow + //
    + //

    Cancel

    + //
    + const cal_box = document.createElement('div'); + cal_box.style.display = 'none'; + cal_box.style.position = 'absolute'; + cal_box.className = 'calendarbox module'; + cal_box.id = DateTimeShortcuts.calendarDivName1 + num; + document.body.appendChild(cal_box); + cal_box.addEventListener('click', function(e) { e.stopPropagation(); }); + + // next-prev links + const cal_nav = quickElement('div', cal_box); + const cal_nav_prev = quickElement('a', cal_nav, '<', 'href', '#'); + cal_nav_prev.className = 'calendarnav-previous'; + cal_nav_prev.addEventListener('click', function(e) { + e.preventDefault(); + DateTimeShortcuts.drawPrev(num); + }); + + const cal_nav_next = quickElement('a', cal_nav, '>', 'href', '#'); + cal_nav_next.className = 'calendarnav-next'; + cal_nav_next.addEventListener('click', function(e) { + e.preventDefault(); + DateTimeShortcuts.drawNext(num); + }); + + // main box + const cal_main = quickElement('div', cal_box, '', 'id', DateTimeShortcuts.calendarDivName2 + num); + cal_main.className = 'calendar'; + DateTimeShortcuts.calendars[num] = new Calendar(DateTimeShortcuts.calendarDivName2 + num, DateTimeShortcuts.handleCalendarCallback(num)); + DateTimeShortcuts.calendars[num].drawCurrent(); + + // calendar shortcuts + const shortcuts = quickElement('div', cal_box); + shortcuts.className = 'calendar-shortcuts'; + let day_link = quickElement('a', shortcuts, gettext('Yesterday'), 'href', '#'); + day_link.addEventListener('click', function(e) { + e.preventDefault(); + DateTimeShortcuts.handleCalendarQuickLink(num, -1); + }); + shortcuts.appendChild(document.createTextNode('\u00A0|\u00A0')); + day_link = quickElement('a', shortcuts, gettext('Today'), 'href', '#'); + day_link.addEventListener('click', function(e) { + e.preventDefault(); + DateTimeShortcuts.handleCalendarQuickLink(num, 0); + }); + shortcuts.appendChild(document.createTextNode('\u00A0|\u00A0')); + day_link = quickElement('a', shortcuts, gettext('Tomorrow'), 'href', '#'); + day_link.addEventListener('click', function(e) { + e.preventDefault(); + DateTimeShortcuts.handleCalendarQuickLink(num, +1); + }); + + // cancel bar + const cancel_p = quickElement('p', cal_box); + cancel_p.className = 'calendar-cancel'; + const cancel_link = quickElement('a', cancel_p, gettext('Cancel'), 'href', '#'); + cancel_link.addEventListener('click', function(e) { + e.preventDefault(); + DateTimeShortcuts.dismissCalendar(num); + }); + document.addEventListener('keyup', function(event) { + if (event.which === 27) { + // ESC key closes popup + DateTimeShortcuts.dismissCalendar(num); + event.preventDefault(); + } + }); + }, + openCalendar: function(num) { + const cal_box = document.getElementById(DateTimeShortcuts.calendarDivName1 + num); + const cal_link = document.getElementById(DateTimeShortcuts.calendarLinkName + num); + const inp = DateTimeShortcuts.calendarInputs[num]; + + // Determine if the current value in the input has a valid date. + // If so, draw the calendar with that date's year and month. + if (inp.value) { + const format = get_format('DATE_INPUT_FORMATS')[0]; + const selected = inp.value.strptime(format); + const year = selected.getUTCFullYear(); + const month = selected.getUTCMonth() + 1; + const re = /\d{4}/; + if (re.test(year.toString()) && month >= 1 && month <= 12) { + DateTimeShortcuts.calendars[num].drawDate(month, year, selected); + } + } + + // Recalculate the clockbox position + // is it left-to-right or right-to-left layout ? + if (window.getComputedStyle(document.body).direction !== 'rtl') { + cal_box.style.left = findPosX(cal_link) + 17 + 'px'; + } + else { + // since style's width is in em, it'd be tough to calculate + // px value of it. let's use an estimated px for now + cal_box.style.left = findPosX(cal_link) - 180 + 'px'; + } + cal_box.style.top = Math.max(0, findPosY(cal_link) - 75) + 'px'; + + cal_box.style.display = 'block'; + document.addEventListener('click', DateTimeShortcuts.dismissCalendarFunc[num]); + }, + dismissCalendar: function(num) { + document.getElementById(DateTimeShortcuts.calendarDivName1 + num).style.display = 'none'; + document.removeEventListener('click', DateTimeShortcuts.dismissCalendarFunc[num]); + }, + drawPrev: function(num) { + DateTimeShortcuts.calendars[num].drawPreviousMonth(); + }, + drawNext: function(num) { + DateTimeShortcuts.calendars[num].drawNextMonth(); + }, + handleCalendarCallback: function(num) { + const format = get_format('DATE_INPUT_FORMATS')[0]; + return function(y, m, d) { + DateTimeShortcuts.calendarInputs[num].value = new Date(y, m - 1, d).strftime(format); + DateTimeShortcuts.calendarInputs[num].focus(); + document.getElementById(DateTimeShortcuts.calendarDivName1 + num).style.display = 'none'; + }; + }, + handleCalendarQuickLink: function(num, offset) { + const d = DateTimeShortcuts.now(); + d.setDate(d.getDate() + offset); + DateTimeShortcuts.calendarInputs[num].value = d.strftime(get_format('DATE_INPUT_FORMATS')[0]); + DateTimeShortcuts.calendarInputs[num].focus(); + DateTimeShortcuts.dismissCalendar(num); + } + }; + + window.addEventListener('load', DateTimeShortcuts.init); + window.DateTimeShortcuts = DateTimeShortcuts; +} diff --git a/fweb/static/admin/js/admin/RelatedObjectLookups.js b/fweb/static/admin/js/admin/RelatedObjectLookups.js new file mode 100644 index 0000000..bc3acce --- /dev/null +++ b/fweb/static/admin/js/admin/RelatedObjectLookups.js @@ -0,0 +1,240 @@ +/*global SelectBox, interpolate*/ +// Handles related-objects functionality: lookup link for raw_id_fields +// and Add Another links. +'use strict'; +{ + const $ = django.jQuery; + let popupIndex = 0; + const relatedWindows = []; + + function dismissChildPopups() { + relatedWindows.forEach(function(win) { + if(!win.closed) { + win.dismissChildPopups(); + win.close(); + } + }); + } + + function setPopupIndex() { + if(document.getElementsByName("_popup").length > 0) { + const index = window.name.lastIndexOf("__") + 2; + popupIndex = parseInt(window.name.substring(index)); + } else { + popupIndex = 0; + } + } + + function addPopupIndex(name) { + return name + "__" + (popupIndex + 1); + } + + function removePopupIndex(name) { + return name.replace(new RegExp("__" + (popupIndex + 1) + "$"), ''); + } + + function showAdminPopup(triggeringLink, name_regexp, add_popup) { + const name = addPopupIndex(triggeringLink.id.replace(name_regexp, '')); + const href = new URL(triggeringLink.href); + if (add_popup) { + href.searchParams.set('_popup', 1); + } + const win = window.open(href, name, 'height=500,width=800,resizable=yes,scrollbars=yes'); + relatedWindows.push(win); + win.focus(); + return false; + } + + function showRelatedObjectLookupPopup(triggeringLink) { + return showAdminPopup(triggeringLink, /^lookup_/, true); + } + + function dismissRelatedLookupPopup(win, chosenId) { + const name = removePopupIndex(win.name); + const elem = document.getElementById(name); + if (elem.classList.contains('vManyToManyRawIdAdminField') && elem.value) { + elem.value += ',' + chosenId; + } else { + document.getElementById(name).value = chosenId; + } + const index = relatedWindows.indexOf(win); + if (index > -1) { + relatedWindows.splice(index, 1); + } + win.close(); + } + + function showRelatedObjectPopup(triggeringLink) { + return showAdminPopup(triggeringLink, /^(change|add|delete)_/, false); + } + + function updateRelatedObjectLinks(triggeringLink) { + const $this = $(triggeringLink); + const siblings = $this.nextAll('.view-related, .change-related, .delete-related'); + if (!siblings.length) { + return; + } + const value = $this.val(); + if (value) { + siblings.each(function() { + const elm = $(this); + elm.attr('href', elm.attr('data-href-template').replace('__fk__', value)); + elm.removeAttr('aria-disabled'); + }); + } else { + siblings.removeAttr('href'); + siblings.attr('aria-disabled', true); + } + } + + function updateRelatedSelectsOptions(currentSelect, win, objId, newRepr, newId) { + // After create/edit a model from the options next to the current + // select (+ or :pencil:) update ForeignKey PK of the rest of selects + // in the page. + + const path = win.location.pathname; + // Extract the model from the popup url '...//add/' or + // '...///change/' depending the action (add or change). + const modelName = path.split('/')[path.split('/').length - (objId ? 4 : 3)]; + // Select elements with a specific model reference and context of "available-source". + const selectsRelated = document.querySelectorAll(`[data-model-ref="${modelName}"] [data-context="available-source"]`); + + selectsRelated.forEach(function(select) { + if (currentSelect === select) { + return; + } + + let option = select.querySelector(`option[value="${objId}"]`); + + if (!option) { + option = new Option(newRepr, newId); + select.options.add(option); + return; + } + + option.textContent = newRepr; + option.value = newId; + }); + } + + function dismissAddRelatedObjectPopup(win, newId, newRepr) { + const name = removePopupIndex(win.name); + const elem = document.getElementById(name); + if (elem) { + const elemName = elem.nodeName.toUpperCase(); + if (elemName === 'SELECT') { + elem.options[elem.options.length] = new Option(newRepr, newId, true, true); + updateRelatedSelectsOptions(elem, win, null, newRepr, newId); + } else if (elemName === 'INPUT') { + if (elem.classList.contains('vManyToManyRawIdAdminField') && elem.value) { + elem.value += ',' + newId; + } else { + elem.value = newId; + } + } + // Trigger a change event to update related links if required. + $(elem).trigger('change'); + } else { + const toId = name + "_to"; + const o = new Option(newRepr, newId); + SelectBox.add_to_cache(toId, o); + SelectBox.redisplay(toId); + } + const index = relatedWindows.indexOf(win); + if (index > -1) { + relatedWindows.splice(index, 1); + } + win.close(); + } + + function dismissChangeRelatedObjectPopup(win, objId, newRepr, newId) { + const id = removePopupIndex(win.name.replace(/^edit_/, '')); + const selectsSelector = interpolate('#%s, #%s_from, #%s_to', [id, id, id]); + const selects = $(selectsSelector); + selects.find('option').each(function() { + if (this.value === objId) { + this.textContent = newRepr; + this.value = newId; + } + }).trigger('change'); + updateRelatedSelectsOptions(selects[0], win, objId, newRepr, newId); + selects.next().find('.select2-selection__rendered').each(function() { + // The element can have a clear button as a child. + // Use the lastChild to modify only the displayed value. + this.lastChild.textContent = newRepr; + this.title = newRepr; + }); + const index = relatedWindows.indexOf(win); + if (index > -1) { + relatedWindows.splice(index, 1); + } + win.close(); + } + + function dismissDeleteRelatedObjectPopup(win, objId) { + const id = removePopupIndex(win.name.replace(/^delete_/, '')); + const selectsSelector = interpolate('#%s, #%s_from, #%s_to', [id, id, id]); + const selects = $(selectsSelector); + selects.find('option').each(function() { + if (this.value === objId) { + $(this).remove(); + } + }).trigger('change'); + const index = relatedWindows.indexOf(win); + if (index > -1) { + relatedWindows.splice(index, 1); + } + win.close(); + } + + window.showRelatedObjectLookupPopup = showRelatedObjectLookupPopup; + window.dismissRelatedLookupPopup = dismissRelatedLookupPopup; + window.showRelatedObjectPopup = showRelatedObjectPopup; + window.updateRelatedObjectLinks = updateRelatedObjectLinks; + window.dismissAddRelatedObjectPopup = dismissAddRelatedObjectPopup; + window.dismissChangeRelatedObjectPopup = dismissChangeRelatedObjectPopup; + window.dismissDeleteRelatedObjectPopup = dismissDeleteRelatedObjectPopup; + window.dismissChildPopups = dismissChildPopups; + + // Kept for backward compatibility + window.showAddAnotherPopup = showRelatedObjectPopup; + window.dismissAddAnotherPopup = dismissAddRelatedObjectPopup; + + window.addEventListener('unload', function(evt) { + window.dismissChildPopups(); + }); + + $(document).ready(function() { + setPopupIndex(); + $("a[data-popup-opener]").on('click', function(event) { + event.preventDefault(); + opener.dismissRelatedLookupPopup(window, $(this).data("popup-opener")); + }); + $('body').on('click', '.related-widget-wrapper-link[data-popup="yes"]', function(e) { + e.preventDefault(); + if (this.href) { + const event = $.Event('django:show-related', {href: this.href}); + $(this).trigger(event); + if (!event.isDefaultPrevented()) { + showRelatedObjectPopup(this); + } + } + }); + $('body').on('change', '.related-widget-wrapper select', function(e) { + const event = $.Event('django:update-related'); + $(this).trigger(event); + if (!event.isDefaultPrevented()) { + updateRelatedObjectLinks(this); + } + }); + $('.related-widget-wrapper select').trigger('change'); + $('body').on('click', '.related-lookup', function(e) { + e.preventDefault(); + const event = $.Event('django:lookup-related'); + $(this).trigger(event); + if (!event.isDefaultPrevented()) { + showRelatedObjectLookupPopup(this); + } + }); + }); +} diff --git a/fweb/static/admin/js/autocomplete.js b/fweb/static/admin/js/autocomplete.js new file mode 100644 index 0000000..d3daeab --- /dev/null +++ b/fweb/static/admin/js/autocomplete.js @@ -0,0 +1,33 @@ +'use strict'; +{ + const $ = django.jQuery; + + $.fn.djangoAdminSelect2 = function() { + $.each(this, function(i, element) { + $(element).select2({ + ajax: { + data: (params) => { + return { + term: params.term, + page: params.page, + app_label: element.dataset.appLabel, + model_name: element.dataset.modelName, + field_name: element.dataset.fieldName + }; + } + } + }); + }); + return this; + }; + + $(function() { + // Initialize all autocomplete widgets except the one in the template + // form used when a new formset is added. + $('.admin-autocomplete').not('[name*=__prefix__]').djangoAdminSelect2(); + }); + + document.addEventListener('formset:added', (event) => { + $(event.target).find('.admin-autocomplete').djangoAdminSelect2(); + }); +} diff --git a/fweb/static/admin/js/calendar.js b/fweb/static/admin/js/calendar.js new file mode 100644 index 0000000..776310f --- /dev/null +++ b/fweb/static/admin/js/calendar.js @@ -0,0 +1,239 @@ +/*global gettext, pgettext, get_format, quickElement, removeChildren*/ +/* +calendar.js - Calendar functions by Adrian Holovaty +depends on core.js for utility functions like removeChildren or quickElement +*/ +'use strict'; +{ + // CalendarNamespace -- Provides a collection of HTML calendar-related helper functions + const CalendarNamespace = { + monthsOfYear: [ + gettext('January'), + gettext('February'), + gettext('March'), + gettext('April'), + gettext('May'), + gettext('June'), + gettext('July'), + gettext('August'), + gettext('September'), + gettext('October'), + gettext('November'), + gettext('December') + ], + monthsOfYearAbbrev: [ + pgettext('abbrev. month January', 'Jan'), + pgettext('abbrev. month February', 'Feb'), + pgettext('abbrev. month March', 'Mar'), + pgettext('abbrev. month April', 'Apr'), + pgettext('abbrev. month May', 'May'), + pgettext('abbrev. month June', 'Jun'), + pgettext('abbrev. month July', 'Jul'), + pgettext('abbrev. month August', 'Aug'), + pgettext('abbrev. month September', 'Sep'), + pgettext('abbrev. month October', 'Oct'), + pgettext('abbrev. month November', 'Nov'), + pgettext('abbrev. month December', 'Dec') + ], + daysOfWeek: [ + gettext('Sunday'), + gettext('Monday'), + gettext('Tuesday'), + gettext('Wednesday'), + gettext('Thursday'), + gettext('Friday'), + gettext('Saturday') + ], + daysOfWeekAbbrev: [ + pgettext('abbrev. day Sunday', 'Sun'), + pgettext('abbrev. day Monday', 'Mon'), + pgettext('abbrev. day Tuesday', 'Tue'), + pgettext('abbrev. day Wednesday', 'Wed'), + pgettext('abbrev. day Thursday', 'Thur'), + pgettext('abbrev. day Friday', 'Fri'), + pgettext('abbrev. day Saturday', 'Sat') + ], + daysOfWeekInitial: [ + pgettext('one letter Sunday', 'S'), + pgettext('one letter Monday', 'M'), + pgettext('one letter Tuesday', 'T'), + pgettext('one letter Wednesday', 'W'), + pgettext('one letter Thursday', 'T'), + pgettext('one letter Friday', 'F'), + pgettext('one letter Saturday', 'S') + ], + firstDayOfWeek: parseInt(get_format('FIRST_DAY_OF_WEEK')), + isLeapYear: function(year) { + return (((year % 4) === 0) && ((year % 100) !== 0 ) || ((year % 400) === 0)); + }, + getDaysInMonth: function(month, year) { + let days; + if (month === 1 || month === 3 || month === 5 || month === 7 || month === 8 || month === 10 || month === 12) { + days = 31; + } + else if (month === 4 || month === 6 || month === 9 || month === 11) { + days = 30; + } + else if (month === 2 && CalendarNamespace.isLeapYear(year)) { + days = 29; + } + else { + days = 28; + } + return days; + }, + draw: function(month, year, div_id, callback, selected) { // month = 1-12, year = 1-9999 + const today = new Date(); + const todayDay = today.getDate(); + const todayMonth = today.getMonth() + 1; + const todayYear = today.getFullYear(); + let todayClass = ''; + + // Use UTC functions here because the date field does not contain time + // and using the UTC function variants prevent the local time offset + // from altering the date, specifically the day field. For example: + // + // ``` + // var x = new Date('2013-10-02'); + // var day = x.getDate(); + // ``` + // + // The day variable above will be 1 instead of 2 in, say, US Pacific time + // zone. + let isSelectedMonth = false; + if (typeof selected !== 'undefined') { + isSelectedMonth = (selected.getUTCFullYear() === year && (selected.getUTCMonth() + 1) === month); + } + + month = parseInt(month); + year = parseInt(year); + const calDiv = document.getElementById(div_id); + removeChildren(calDiv); + const calTable = document.createElement('table'); + quickElement('caption', calTable, CalendarNamespace.monthsOfYear[month - 1] + ' ' + year); + const tableBody = quickElement('tbody', calTable); + + // Draw days-of-week header + let tableRow = quickElement('tr', tableBody); + for (let i = 0; i < 7; i++) { + quickElement('th', tableRow, CalendarNamespace.daysOfWeekInitial[(i + CalendarNamespace.firstDayOfWeek) % 7]); + } + + const startingPos = new Date(year, month - 1, 1 - CalendarNamespace.firstDayOfWeek).getDay(); + const days = CalendarNamespace.getDaysInMonth(month, year); + + let nonDayCell; + + // Draw blanks before first of month + tableRow = quickElement('tr', tableBody); + for (let i = 0; i < startingPos; i++) { + nonDayCell = quickElement('td', tableRow, ' '); + nonDayCell.className = "nonday"; + } + + function calendarMonth(y, m) { + function onClick(e) { + e.preventDefault(); + callback(y, m, this.textContent); + } + return onClick; + } + + // Draw days of month + let currentDay = 1; + for (let i = startingPos; currentDay <= days; i++) { + if (i % 7 === 0 && currentDay !== 1) { + tableRow = quickElement('tr', tableBody); + } + if ((currentDay === todayDay) && (month === todayMonth) && (year === todayYear)) { + todayClass = 'today'; + } else { + todayClass = ''; + } + + // use UTC function; see above for explanation. + if (isSelectedMonth && currentDay === selected.getUTCDate()) { + if (todayClass !== '') { + todayClass += " "; + } + todayClass += "selected"; + } + + const cell = quickElement('td', tableRow, '', 'class', todayClass); + const link = quickElement('a', cell, currentDay, 'href', '#'); + link.addEventListener('click', calendarMonth(year, month)); + currentDay++; + } + + // Draw blanks after end of month (optional, but makes for valid code) + while (tableRow.childNodes.length < 7) { + nonDayCell = quickElement('td', tableRow, ' '); + nonDayCell.className = "nonday"; + } + + calDiv.appendChild(calTable); + } + }; + + // Calendar -- A calendar instance + function Calendar(div_id, callback, selected) { + // div_id (string) is the ID of the element in which the calendar will + // be displayed + // callback (string) is the name of a JavaScript function that will be + // called with the parameters (year, month, day) when a day in the + // calendar is clicked + this.div_id = div_id; + this.callback = callback; + this.today = new Date(); + this.currentMonth = this.today.getMonth() + 1; + this.currentYear = this.today.getFullYear(); + if (typeof selected !== 'undefined') { + this.selected = selected; + } + } + Calendar.prototype = { + drawCurrent: function() { + CalendarNamespace.draw(this.currentMonth, this.currentYear, this.div_id, this.callback, this.selected); + }, + drawDate: function(month, year, selected) { + this.currentMonth = month; + this.currentYear = year; + + if(selected) { + this.selected = selected; + } + + this.drawCurrent(); + }, + drawPreviousMonth: function() { + if (this.currentMonth === 1) { + this.currentMonth = 12; + this.currentYear--; + } + else { + this.currentMonth--; + } + this.drawCurrent(); + }, + drawNextMonth: function() { + if (this.currentMonth === 12) { + this.currentMonth = 1; + this.currentYear++; + } + else { + this.currentMonth++; + } + this.drawCurrent(); + }, + drawPreviousYear: function() { + this.currentYear--; + this.drawCurrent(); + }, + drawNextYear: function() { + this.currentYear++; + this.drawCurrent(); + } + }; + window.Calendar = Calendar; + window.CalendarNamespace = CalendarNamespace; +} diff --git a/fweb/static/admin/js/cancel.js b/fweb/static/admin/js/cancel.js new file mode 100644 index 0000000..3069c6f --- /dev/null +++ b/fweb/static/admin/js/cancel.js @@ -0,0 +1,29 @@ +'use strict'; +{ + // Call function fn when the DOM is loaded and ready. If it is already + // loaded, call the function now. + // http://youmightnotneedjquery.com/#ready + function ready(fn) { + if (document.readyState !== 'loading') { + fn(); + } else { + document.addEventListener('DOMContentLoaded', fn); + } + } + + ready(function() { + function handleClick(event) { + event.preventDefault(); + const params = new URLSearchParams(window.location.search); + if (params.has('_popup')) { + window.close(); // Close the popup. + } else { + window.history.back(); // Otherwise, go back. + } + } + + document.querySelectorAll('.cancel-link').forEach(function(el) { + el.addEventListener('click', handleClick); + }); + }); +} diff --git a/fweb/static/admin/js/change_form.js b/fweb/static/admin/js/change_form.js new file mode 100644 index 0000000..96a4c62 --- /dev/null +++ b/fweb/static/admin/js/change_form.js @@ -0,0 +1,16 @@ +'use strict'; +{ + const inputTags = ['BUTTON', 'INPUT', 'SELECT', 'TEXTAREA']; + const modelName = document.getElementById('django-admin-form-add-constants').dataset.modelName; + if (modelName) { + const form = document.getElementById(modelName + '_form'); + for (const element of form.elements) { + // HTMLElement.offsetParent returns null when the element is not + // rendered. + if (inputTags.includes(element.tagName) && !element.disabled && element.offsetParent) { + element.focus(); + break; + } + } + } +} diff --git a/fweb/static/admin/js/core.js b/fweb/static/admin/js/core.js new file mode 100644 index 0000000..10504d4 --- /dev/null +++ b/fweb/static/admin/js/core.js @@ -0,0 +1,184 @@ +// Core JavaScript helper functions +'use strict'; + +// quickElement(tagType, parentReference [, textInChildNode, attribute, attributeValue ...]); +function quickElement() { + const obj = document.createElement(arguments[0]); + if (arguments[2]) { + const textNode = document.createTextNode(arguments[2]); + obj.appendChild(textNode); + } + const len = arguments.length; + for (let i = 3; i < len; i += 2) { + obj.setAttribute(arguments[i], arguments[i + 1]); + } + arguments[1].appendChild(obj); + return obj; +} + +// "a" is reference to an object +function removeChildren(a) { + while (a.hasChildNodes()) { + a.removeChild(a.lastChild); + } +} + +// ---------------------------------------------------------------------------- +// Find-position functions by PPK +// See https://www.quirksmode.org/js/findpos.html +// ---------------------------------------------------------------------------- +function findPosX(obj) { + let curleft = 0; + if (obj.offsetParent) { + while (obj.offsetParent) { + curleft += obj.offsetLeft - obj.scrollLeft; + obj = obj.offsetParent; + } + } else if (obj.x) { + curleft += obj.x; + } + return curleft; +} + +function findPosY(obj) { + let curtop = 0; + if (obj.offsetParent) { + while (obj.offsetParent) { + curtop += obj.offsetTop - obj.scrollTop; + obj = obj.offsetParent; + } + } else if (obj.y) { + curtop += obj.y; + } + return curtop; +} + +//----------------------------------------------------------------------------- +// Date object extensions +// ---------------------------------------------------------------------------- +{ + Date.prototype.getTwelveHours = function() { + return this.getHours() % 12 || 12; + }; + + Date.prototype.getTwoDigitMonth = function() { + return (this.getMonth() < 9) ? '0' + (this.getMonth() + 1) : (this.getMonth() + 1); + }; + + Date.prototype.getTwoDigitDate = function() { + return (this.getDate() < 10) ? '0' + this.getDate() : this.getDate(); + }; + + Date.prototype.getTwoDigitTwelveHour = function() { + return (this.getTwelveHours() < 10) ? '0' + this.getTwelveHours() : this.getTwelveHours(); + }; + + Date.prototype.getTwoDigitHour = function() { + return (this.getHours() < 10) ? '0' + this.getHours() : this.getHours(); + }; + + Date.prototype.getTwoDigitMinute = function() { + return (this.getMinutes() < 10) ? '0' + this.getMinutes() : this.getMinutes(); + }; + + Date.prototype.getTwoDigitSecond = function() { + return (this.getSeconds() < 10) ? '0' + this.getSeconds() : this.getSeconds(); + }; + + Date.prototype.getAbbrevDayName = function() { + return typeof window.CalendarNamespace === "undefined" + ? '0' + this.getDay() + : window.CalendarNamespace.daysOfWeekAbbrev[this.getDay()]; + }; + + Date.prototype.getFullDayName = function() { + return typeof window.CalendarNamespace === "undefined" + ? '0' + this.getDay() + : window.CalendarNamespace.daysOfWeek[this.getDay()]; + }; + + Date.prototype.getAbbrevMonthName = function() { + return typeof window.CalendarNamespace === "undefined" + ? this.getTwoDigitMonth() + : window.CalendarNamespace.monthsOfYearAbbrev[this.getMonth()]; + }; + + Date.prototype.getFullMonthName = function() { + return typeof window.CalendarNamespace === "undefined" + ? this.getTwoDigitMonth() + : window.CalendarNamespace.monthsOfYear[this.getMonth()]; + }; + + Date.prototype.strftime = function(format) { + const fields = { + a: this.getAbbrevDayName(), + A: this.getFullDayName(), + b: this.getAbbrevMonthName(), + B: this.getFullMonthName(), + c: this.toString(), + d: this.getTwoDigitDate(), + H: this.getTwoDigitHour(), + I: this.getTwoDigitTwelveHour(), + m: this.getTwoDigitMonth(), + M: this.getTwoDigitMinute(), + p: (this.getHours() >= 12) ? 'PM' : 'AM', + S: this.getTwoDigitSecond(), + w: '0' + this.getDay(), + x: this.toLocaleDateString(), + X: this.toLocaleTimeString(), + y: ('' + this.getFullYear()).substr(2, 4), + Y: '' + this.getFullYear(), + '%': '%' + }; + let result = '', i = 0; + while (i < format.length) { + if (format.charAt(i) === '%') { + result += fields[format.charAt(i + 1)]; + ++i; + } + else { + result += format.charAt(i); + } + ++i; + } + return result; + }; + + // ---------------------------------------------------------------------------- + // String object extensions + // ---------------------------------------------------------------------------- + String.prototype.strptime = function(format) { + const split_format = format.split(/[.\-/]/); + const date = this.split(/[.\-/]/); + let i = 0; + let day, month, year; + while (i < split_format.length) { + switch (split_format[i]) { + case "%d": + day = date[i]; + break; + case "%m": + month = date[i] - 1; + break; + case "%Y": + year = date[i]; + break; + case "%y": + // A %y value in the range of [00, 68] is in the current + // century, while [69, 99] is in the previous century, + // according to the Open Group Specification. + if (parseInt(date[i], 10) >= 69) { + year = date[i]; + } else { + year = (new Date(Date.UTC(date[i], 0))).getUTCFullYear() + 100; + } + break; + } + ++i; + } + // Create Date object from UTC since the parsed value is supposed to be + // in UTC, not local time. Also, the calendar uses UTC functions for + // date extraction. + return new Date(Date.UTC(year, month, day)); + }; +} diff --git a/fweb/static/admin/js/filters.js b/fweb/static/admin/js/filters.js new file mode 100644 index 0000000..f5536eb --- /dev/null +++ b/fweb/static/admin/js/filters.js @@ -0,0 +1,30 @@ +/** + * Persist changelist filters state (collapsed/expanded). + */ +'use strict'; +{ + // Init filters. + let filters = JSON.parse(sessionStorage.getItem('django.admin.filtersState')); + + if (!filters) { + filters = {}; + } + + Object.entries(filters).forEach(([key, value]) => { + const detailElement = document.querySelector(`[data-filter-title='${CSS.escape(key)}']`); + + // Check if the filter is present, it could be from other view. + if (detailElement) { + value ? detailElement.setAttribute('open', '') : detailElement.removeAttribute('open'); + } + }); + + // Save filter state when clicks. + const details = document.querySelectorAll('details'); + details.forEach(detail => { + detail.addEventListener('toggle', event => { + filters[`${event.target.dataset.filterTitle}`] = detail.open; + sessionStorage.setItem('django.admin.filtersState', JSON.stringify(filters)); + }); + }); +} diff --git a/fweb/static/admin/js/inlines.js b/fweb/static/admin/js/inlines.js new file mode 100644 index 0000000..e9a1dfe --- /dev/null +++ b/fweb/static/admin/js/inlines.js @@ -0,0 +1,359 @@ +/*global DateTimeShortcuts, SelectFilter*/ +/** + * Django admin inlines + * + * Based on jQuery Formset 1.1 + * @author Stanislaus Madueke (stan DOT madueke AT gmail DOT com) + * @requires jQuery 1.2.6 or later + * + * Copyright (c) 2009, Stanislaus Madueke + * All rights reserved. + * + * Spiced up with Code from Zain Memon's GSoC project 2009 + * and modified for Django by Jannis Leidel, Travis Swicegood and Julien Phalip. + * + * Licensed under the New BSD License + * See: https://opensource.org/licenses/bsd-license.php + */ +'use strict'; +{ + const $ = django.jQuery; + $.fn.formset = function(opts) { + const options = $.extend({}, $.fn.formset.defaults, opts); + const $this = $(this); + const $parent = $this.parent(); + const updateElementIndex = function(el, prefix, ndx) { + const id_regex = new RegExp("(" + prefix + "-(\\d+|__prefix__))"); + const replacement = prefix + "-" + ndx; + if ($(el).prop("for")) { + $(el).prop("for", $(el).prop("for").replace(id_regex, replacement)); + } + if (el.id) { + el.id = el.id.replace(id_regex, replacement); + } + if (el.name) { + el.name = el.name.replace(id_regex, replacement); + } + }; + const totalForms = $("#id_" + options.prefix + "-TOTAL_FORMS").prop("autocomplete", "off"); + let nextIndex = parseInt(totalForms.val(), 10); + const maxForms = $("#id_" + options.prefix + "-MAX_NUM_FORMS").prop("autocomplete", "off"); + const minForms = $("#id_" + options.prefix + "-MIN_NUM_FORMS").prop("autocomplete", "off"); + let addButton; + + /** + * The "Add another MyModel" button below the inline forms. + */ + const addInlineAddButton = function() { + if (addButton === null) { + if ($this.prop("tagName") === "TR") { + // If forms are laid out as table rows, insert the + // "add" button in a new table row: + const numCols = $this.eq(-1).children().length; + $parent.append('' + options.addText + ""); + addButton = $parent.find("tr:last a"); + } else { + // Otherwise, insert it immediately after the last form: + $this.filter(":last").after('"); + addButton = $this.filter(":last").next().find("a"); + } + } + addButton.on('click', addInlineClickHandler); + }; + + const addInlineClickHandler = function(e) { + e.preventDefault(); + const template = $("#" + options.prefix + "-empty"); + const row = template.clone(true); + row.removeClass(options.emptyCssClass) + .addClass(options.formCssClass) + .attr("id", options.prefix + "-" + nextIndex); + addInlineDeleteButton(row); + row.find("*").each(function() { + updateElementIndex(this, options.prefix, totalForms.val()); + }); + // Insert the new form when it has been fully edited. + row.insertBefore($(template)); + // Update number of total forms. + $(totalForms).val(parseInt(totalForms.val(), 10) + 1); + nextIndex += 1; + // Hide the add button if there's a limit and it's been reached. + if ((maxForms.val() !== '') && (maxForms.val() - totalForms.val()) <= 0) { + addButton.parent().hide(); + } + // Show the remove buttons if there are more than min_num. + toggleDeleteButtonVisibility(row.closest('.inline-group')); + + // Pass the new form to the post-add callback, if provided. + if (options.added) { + options.added(row); + } + row.get(0).dispatchEvent(new CustomEvent("formset:added", { + bubbles: true, + detail: { + formsetName: options.prefix + } + })); + }; + + /** + * The "X" button that is part of every unsaved inline. + * (When saved, it is replaced with a "Delete" checkbox.) + */ + const addInlineDeleteButton = function(row) { + if (row.is("tr")) { + // If the forms are laid out in table rows, insert + // the remove button into the last table cell: + row.children(":last").append('"); + } else if (row.is("ul") || row.is("ol")) { + // If they're laid out as an ordered/unordered list, + // insert an
  • after the last list item: + row.append('
  • ' + options.deleteText + "
  • "); + } else { + // Otherwise, just insert the remove button as the + // last child element of the form's container: + row.children(":first").append('' + options.deleteText + ""); + } + // Add delete handler for each row. + row.find("a." + options.deleteCssClass).on('click', inlineDeleteHandler.bind(this)); + }; + + const inlineDeleteHandler = function(e1) { + e1.preventDefault(); + const deleteButton = $(e1.target); + const row = deleteButton.closest('.' + options.formCssClass); + const inlineGroup = row.closest('.inline-group'); + // Remove the parent form containing this button, + // and also remove the relevant row with non-field errors: + const prevRow = row.prev(); + if (prevRow.length && prevRow.hasClass('row-form-errors')) { + prevRow.remove(); + } + row.remove(); + nextIndex -= 1; + // Pass the deleted form to the post-delete callback, if provided. + if (options.removed) { + options.removed(row); + } + document.dispatchEvent(new CustomEvent("formset:removed", { + detail: { + formsetName: options.prefix + } + })); + // Update the TOTAL_FORMS form count. + const forms = $("." + options.formCssClass); + $("#id_" + options.prefix + "-TOTAL_FORMS").val(forms.length); + // Show add button again once below maximum number. + if ((maxForms.val() === '') || (maxForms.val() - forms.length) > 0) { + addButton.parent().show(); + } + // Hide the remove buttons if at min_num. + toggleDeleteButtonVisibility(inlineGroup); + // Also, update names and ids for all remaining form controls so + // they remain in sequence: + let i, formCount; + const updateElementCallback = function() { + updateElementIndex(this, options.prefix, i); + }; + for (i = 0, formCount = forms.length; i < formCount; i++) { + updateElementIndex($(forms).get(i), options.prefix, i); + $(forms.get(i)).find("*").each(updateElementCallback); + } + }; + + const toggleDeleteButtonVisibility = function(inlineGroup) { + if ((minForms.val() !== '') && (minForms.val() - totalForms.val()) >= 0) { + inlineGroup.find('.inline-deletelink').hide(); + } else { + inlineGroup.find('.inline-deletelink').show(); + } + }; + + $this.each(function(i) { + $(this).not("." + options.emptyCssClass).addClass(options.formCssClass); + }); + + // Create the delete buttons for all unsaved inlines: + $this.filter('.' + options.formCssClass + ':not(.has_original):not(.' + options.emptyCssClass + ')').each(function() { + addInlineDeleteButton($(this)); + }); + toggleDeleteButtonVisibility($this); + + // Create the add button, initially hidden. + addButton = options.addButton; + addInlineAddButton(); + + // Show the add button if allowed to add more items. + // Note that max_num = None translates to a blank string. + const showAddButton = maxForms.val() === '' || (maxForms.val() - totalForms.val()) > 0; + if ($this.length && showAddButton) { + addButton.parent().show(); + } else { + addButton.parent().hide(); + } + + return this; + }; + + /* Setup plugin defaults */ + $.fn.formset.defaults = { + prefix: "form", // The form prefix for your django formset + addText: "add another", // Text for the add link + deleteText: "remove", // Text for the delete link + addCssClass: "add-row", // CSS class applied to the add link + deleteCssClass: "delete-row", // CSS class applied to the delete link + emptyCssClass: "empty-row", // CSS class applied to the empty row + formCssClass: "dynamic-form", // CSS class applied to each form in a formset + added: null, // Function called each time a new form is added + removed: null, // Function called each time a form is deleted + addButton: null // Existing add button to use + }; + + + // Tabular inlines --------------------------------------------------------- + $.fn.tabularFormset = function(selector, options) { + const $rows = $(this); + + const reinitDateTimeShortCuts = function() { + // Reinitialize the calendar and clock widgets by force + if (typeof DateTimeShortcuts !== "undefined") { + $(".datetimeshortcuts").remove(); + DateTimeShortcuts.init(); + } + }; + + const updateSelectFilter = function() { + // If any SelectFilter widgets are a part of the new form, + // instantiate a new SelectFilter instance for it. + if (typeof SelectFilter !== 'undefined') { + $('.selectfilter').each(function(index, value) { + SelectFilter.init(value.id, this.dataset.fieldName, false); + }); + $('.selectfilterstacked').each(function(index, value) { + SelectFilter.init(value.id, this.dataset.fieldName, true); + }); + } + }; + + const initPrepopulatedFields = function(row) { + row.find('.prepopulated_field').each(function() { + const field = $(this), + input = field.find('input, select, textarea'), + dependency_list = input.data('dependency_list') || [], + dependencies = []; + $.each(dependency_list, function(i, field_name) { + dependencies.push('#' + row.find('.field-' + field_name).find('input, select, textarea').attr('id')); + }); + if (dependencies.length) { + input.prepopulate(dependencies, input.attr('maxlength')); + } + }); + }; + + $rows.formset({ + prefix: options.prefix, + addText: options.addText, + formCssClass: "dynamic-" + options.prefix, + deleteCssClass: "inline-deletelink", + deleteText: options.deleteText, + emptyCssClass: "empty-form", + added: function(row) { + initPrepopulatedFields(row); + reinitDateTimeShortCuts(); + updateSelectFilter(); + }, + addButton: options.addButton + }); + + return $rows; + }; + + // Stacked inlines --------------------------------------------------------- + $.fn.stackedFormset = function(selector, options) { + const $rows = $(this); + const updateInlineLabel = function(row) { + $(selector).find(".inline_label").each(function(i) { + const count = i + 1; + $(this).html($(this).html().replace(/(#\d+)/g, "#" + count)); + }); + }; + + const reinitDateTimeShortCuts = function() { + // Reinitialize the calendar and clock widgets by force, yuck. + if (typeof DateTimeShortcuts !== "undefined") { + $(".datetimeshortcuts").remove(); + DateTimeShortcuts.init(); + } + }; + + const updateSelectFilter = function() { + // If any SelectFilter widgets were added, instantiate a new instance. + if (typeof SelectFilter !== "undefined") { + $(".selectfilter").each(function(index, value) { + SelectFilter.init(value.id, this.dataset.fieldName, false); + }); + $(".selectfilterstacked").each(function(index, value) { + SelectFilter.init(value.id, this.dataset.fieldName, true); + }); + } + }; + + const initPrepopulatedFields = function(row) { + row.find('.prepopulated_field').each(function() { + const field = $(this), + input = field.find('input, select, textarea'), + dependency_list = input.data('dependency_list') || [], + dependencies = []; + $.each(dependency_list, function(i, field_name) { + // Dependency in a fieldset. + let field_element = row.find('.form-row .field-' + field_name); + // Dependency without a fieldset. + if (!field_element.length) { + field_element = row.find('.form-row.field-' + field_name); + } + dependencies.push('#' + field_element.find('input, select, textarea').attr('id')); + }); + if (dependencies.length) { + input.prepopulate(dependencies, input.attr('maxlength')); + } + }); + }; + + $rows.formset({ + prefix: options.prefix, + addText: options.addText, + formCssClass: "dynamic-" + options.prefix, + deleteCssClass: "inline-deletelink", + deleteText: options.deleteText, + emptyCssClass: "empty-form", + removed: updateInlineLabel, + added: function(row) { + initPrepopulatedFields(row); + reinitDateTimeShortCuts(); + updateSelectFilter(); + updateInlineLabel(row); + }, + addButton: options.addButton + }); + + return $rows; + }; + + $(document).ready(function() { + $(".js-inline-admin-formset").each(function() { + const data = $(this).data(), + inlineOptions = data.inlineFormset; + let selector; + switch(data.inlineType) { + case "stacked": + selector = inlineOptions.name + "-group .inline-related"; + $(selector).stackedFormset(selector, inlineOptions.options); + break; + case "tabular": + selector = inlineOptions.name + "-group .tabular.inline-related tbody:first > tr.form-row"; + $(selector).tabularFormset(selector, inlineOptions.options); + break; + } + }); + }); +} diff --git a/fweb/static/admin/js/jquery.init.js b/fweb/static/admin/js/jquery.init.js new file mode 100644 index 0000000..f40b27f --- /dev/null +++ b/fweb/static/admin/js/jquery.init.js @@ -0,0 +1,8 @@ +/*global jQuery:false*/ +'use strict'; +/* Puts the included jQuery into our own namespace using noConflict and passing + * it 'true'. This ensures that the included jQuery doesn't pollute the global + * namespace (i.e. this preserves pre-existing values for both window.$ and + * window.jQuery). + */ +window.django = {jQuery: jQuery.noConflict(true)}; diff --git a/fweb/static/admin/js/nav_sidebar.js b/fweb/static/admin/js/nav_sidebar.js new file mode 100644 index 0000000..7e735db --- /dev/null +++ b/fweb/static/admin/js/nav_sidebar.js @@ -0,0 +1,79 @@ +'use strict'; +{ + const toggleNavSidebar = document.getElementById('toggle-nav-sidebar'); + if (toggleNavSidebar !== null) { + const navSidebar = document.getElementById('nav-sidebar'); + const main = document.getElementById('main'); + let navSidebarIsOpen = localStorage.getItem('django.admin.navSidebarIsOpen'); + if (navSidebarIsOpen === null) { + navSidebarIsOpen = 'true'; + } + main.classList.toggle('shifted', navSidebarIsOpen === 'true'); + navSidebar.setAttribute('aria-expanded', navSidebarIsOpen); + + toggleNavSidebar.addEventListener('click', function() { + if (navSidebarIsOpen === 'true') { + navSidebarIsOpen = 'false'; + } else { + navSidebarIsOpen = 'true'; + } + localStorage.setItem('django.admin.navSidebarIsOpen', navSidebarIsOpen); + main.classList.toggle('shifted'); + navSidebar.setAttribute('aria-expanded', navSidebarIsOpen); + }); + } + + function initSidebarQuickFilter() { + const options = []; + const navSidebar = document.getElementById('nav-sidebar'); + if (!navSidebar) { + return; + } + navSidebar.querySelectorAll('th[scope=row] a').forEach((container) => { + options.push({title: container.innerHTML, node: container}); + }); + + function checkValue(event) { + let filterValue = event.target.value; + if (filterValue) { + filterValue = filterValue.toLowerCase(); + } + if (event.key === 'Escape') { + filterValue = ''; + event.target.value = ''; // clear input + } + let matches = false; + for (const o of options) { + let displayValue = ''; + if (filterValue) { + if (o.title.toLowerCase().indexOf(filterValue) === -1) { + displayValue = 'none'; + } else { + matches = true; + } + } + // show/hide parent + o.node.parentNode.parentNode.style.display = displayValue; + } + if (!filterValue || matches) { + event.target.classList.remove('no-results'); + } else { + event.target.classList.add('no-results'); + } + sessionStorage.setItem('django.admin.navSidebarFilterValue', filterValue); + } + + const nav = document.getElementById('nav-filter'); + nav.addEventListener('change', checkValue, false); + nav.addEventListener('input', checkValue, false); + nav.addEventListener('keyup', checkValue, false); + + const storedValue = sessionStorage.getItem('django.admin.navSidebarFilterValue'); + if (storedValue) { + nav.value = storedValue; + checkValue({target: nav, key: ''}); + } + } + window.initSidebarQuickFilter = initSidebarQuickFilter; + initSidebarQuickFilter(); +} diff --git a/fweb/static/admin/js/popup_response.js b/fweb/static/admin/js/popup_response.js new file mode 100644 index 0000000..fecf0f4 --- /dev/null +++ b/fweb/static/admin/js/popup_response.js @@ -0,0 +1,15 @@ +'use strict'; +{ + const initData = JSON.parse(document.getElementById('django-admin-popup-response-constants').dataset.popupResponse); + switch(initData.action) { + case 'change': + opener.dismissChangeRelatedObjectPopup(window, initData.value, initData.obj, initData.new_value); + break; + case 'delete': + opener.dismissDeleteRelatedObjectPopup(window, initData.value); + break; + default: + opener.dismissAddRelatedObjectPopup(window, initData.value, initData.obj); + break; + } +} diff --git a/fweb/static/admin/js/prepopulate.js b/fweb/static/admin/js/prepopulate.js new file mode 100644 index 0000000..89e95ab --- /dev/null +++ b/fweb/static/admin/js/prepopulate.js @@ -0,0 +1,43 @@ +/*global URLify*/ +'use strict'; +{ + const $ = django.jQuery; + $.fn.prepopulate = function(dependencies, maxLength, allowUnicode) { + /* + Depends on urlify.js + Populates a selected field with the values of the dependent fields, + URLifies and shortens the string. + dependencies - array of dependent fields ids + maxLength - maximum length of the URLify'd string + allowUnicode - Unicode support of the URLify'd string + */ + return this.each(function() { + const prepopulatedField = $(this); + + const populate = function() { + // Bail if the field's value has been changed by the user + if (prepopulatedField.data('_changed')) { + return; + } + + const values = []; + $.each(dependencies, function(i, field) { + field = $(field); + if (field.val().length > 0) { + values.push(field.val()); + } + }); + prepopulatedField.val(URLify(values.join(' '), maxLength, allowUnicode)); + }; + + prepopulatedField.data('_changed', false); + prepopulatedField.on('change', function() { + prepopulatedField.data('_changed', true); + }); + + if (!prepopulatedField.val()) { + $(dependencies.join(',')).on('keyup change focus', populate); + } + }); + }; +} diff --git a/fweb/static/admin/js/prepopulate_init.js b/fweb/static/admin/js/prepopulate_init.js new file mode 100644 index 0000000..a58841f --- /dev/null +++ b/fweb/static/admin/js/prepopulate_init.js @@ -0,0 +1,15 @@ +'use strict'; +{ + const $ = django.jQuery; + const fields = $('#django-admin-prepopulated-fields-constants').data('prepopulatedFields'); + $.each(fields, function(index, field) { + $( + '.empty-form .form-row .field-' + field.name + + ', .empty-form.form-row .field-' + field.name + + ', .empty-form .form-row.field-' + field.name + ).addClass('prepopulated_field'); + $(field.id).data('dependency_list', field.dependency_list).prepopulate( + field.dependency_ids, field.maxLength, field.allowUnicode + ); + }); +} diff --git a/fweb/static/admin/js/theme.js b/fweb/static/admin/js/theme.js new file mode 100644 index 0000000..e79d375 --- /dev/null +++ b/fweb/static/admin/js/theme.js @@ -0,0 +1,51 @@ +'use strict'; +{ + function setTheme(mode) { + if (mode !== "light" && mode !== "dark" && mode !== "auto") { + console.error(`Got invalid theme mode: ${mode}. Resetting to auto.`); + mode = "auto"; + } + document.documentElement.dataset.theme = mode; + localStorage.setItem("theme", mode); + } + + function cycleTheme() { + const currentTheme = localStorage.getItem("theme") || "auto"; + const prefersDark = window.matchMedia("(prefers-color-scheme: dark)").matches; + + if (prefersDark) { + // Auto (dark) -> Light -> Dark + if (currentTheme === "auto") { + setTheme("light"); + } else if (currentTheme === "light") { + setTheme("dark"); + } else { + setTheme("auto"); + } + } else { + // Auto (light) -> Dark -> Light + if (currentTheme === "auto") { + setTheme("dark"); + } else if (currentTheme === "dark") { + setTheme("light"); + } else { + setTheme("auto"); + } + } + } + + function initTheme() { + // set theme defined in localStorage if there is one, or fallback to auto mode + const currentTheme = localStorage.getItem("theme"); + currentTheme ? setTheme(currentTheme) : setTheme("auto"); + } + + window.addEventListener('load', function(_) { + const buttons = document.getElementsByClassName("theme-toggle"); + Array.from(buttons).forEach((btn) => { + btn.addEventListener("click", cycleTheme); + }); + }); + + initTheme(); +} diff --git a/fweb/static/admin/js/unusable_password_field.js b/fweb/static/admin/js/unusable_password_field.js new file mode 100644 index 0000000..ec26238 --- /dev/null +++ b/fweb/static/admin/js/unusable_password_field.js @@ -0,0 +1,29 @@ +"use strict"; +// Fallback JS for browsers which do not support :has selector used in +// admin/css/unusable_password_fields.css +// Remove file once all supported browsers support :has selector +try { + // If browser does not support :has selector this will raise an error + document.querySelector("form:has(input)"); +} catch (error) { + console.log("Defaulting to javascript for usable password form management: " + error); + // JS replacement for unsupported :has selector + document.querySelectorAll('input[name="usable_password"]').forEach(option => { + option.addEventListener('change', function() { + const usablePassword = (this.value === "true" ? this.checked : !this.checked); + const submit1 = document.querySelector('input[type="submit"].set-password'); + const submit2 = document.querySelector('input[type="submit"].unset-password'); + const messages = document.querySelector('#id_unusable_warning'); + document.getElementById('id_password1').closest('.form-row').hidden = !usablePassword; + document.getElementById('id_password2').closest('.form-row').hidden = !usablePassword; + if (messages) { + messages.hidden = usablePassword; + } + if (submit1 && submit2) { + submit1.hidden = !usablePassword; + submit2.hidden = usablePassword; + } + }); + option.dispatchEvent(new Event('change')); + }); +} diff --git a/fweb/static/admin/js/urlify.js b/fweb/static/admin/js/urlify.js new file mode 100644 index 0000000..9fc0409 --- /dev/null +++ b/fweb/static/admin/js/urlify.js @@ -0,0 +1,169 @@ +/*global XRegExp*/ +'use strict'; +{ + const LATIN_MAP = { + 'À': 'A', 'Á': 'A', 'Â': 'A', 'Ã': 'A', 'Ä': 'A', 'Å': 'A', 'Æ': 'AE', + 'Ç': 'C', 'È': 'E', 'É': 'E', 'Ê': 'E', 'Ë': 'E', 'Ì': 'I', 'Í': 'I', + 'Î': 'I', 'Ï': 'I', 'Ð': 'D', 'Ñ': 'N', 'Ò': 'O', 'Ó': 'O', 'Ô': 'O', + 'Õ': 'O', 'Ö': 'O', 'Ő': 'O', 'Ø': 'O', 'Ù': 'U', 'Ú': 'U', 'Û': 'U', + 'Ü': 'U', 'Ű': 'U', 'Ý': 'Y', 'Þ': 'TH', 'Ÿ': 'Y', 'ß': 'ss', 'à': 'a', + 'á': 'a', 'â': 'a', 'ã': 'a', 'ä': 'a', 'å': 'a', 'æ': 'ae', 'ç': 'c', + 'è': 'e', 'é': 'e', 'ê': 'e', 'ë': 'e', 'ì': 'i', 'í': 'i', 'î': 'i', + 'ï': 'i', 'ð': 'd', 'ñ': 'n', 'ò': 'o', 'ó': 'o', 'ô': 'o', 'õ': 'o', + 'ö': 'o', 'ő': 'o', 'ø': 'o', 'ù': 'u', 'ú': 'u', 'û': 'u', 'ü': 'u', + 'ű': 'u', 'ý': 'y', 'þ': 'th', 'ÿ': 'y' + }; + const LATIN_SYMBOLS_MAP = { + '©': '(c)' + }; + const GREEK_MAP = { + 'α': 'a', 'β': 'b', 'γ': 'g', 'δ': 'd', 'ε': 'e', 'ζ': 'z', 'η': 'h', + 'θ': '8', 'ι': 'i', 'κ': 'k', 'λ': 'l', 'μ': 'm', 'ν': 'n', 'ξ': '3', + 'ο': 'o', 'π': 'p', 'ρ': 'r', 'σ': 's', 'τ': 't', 'υ': 'y', 'φ': 'f', + 'χ': 'x', 'ψ': 'ps', 'ω': 'w', 'ά': 'a', 'έ': 'e', 'ί': 'i', 'ό': 'o', + 'ύ': 'y', 'ή': 'h', 'ώ': 'w', 'ς': 's', 'ϊ': 'i', 'ΰ': 'y', 'ϋ': 'y', + 'ΐ': 'i', 'Α': 'A', 'Β': 'B', 'Γ': 'G', 'Δ': 'D', 'Ε': 'E', 'Ζ': 'Z', + 'Η': 'H', 'Θ': '8', 'Ι': 'I', 'Κ': 'K', 'Λ': 'L', 'Μ': 'M', 'Ν': 'N', + 'Ξ': '3', 'Ο': 'O', 'Π': 'P', 'Ρ': 'R', 'Σ': 'S', 'Τ': 'T', 'Υ': 'Y', + 'Φ': 'F', 'Χ': 'X', 'Ψ': 'PS', 'Ω': 'W', 'Ά': 'A', 'Έ': 'E', 'Ί': 'I', + 'Ό': 'O', 'Ύ': 'Y', 'Ή': 'H', 'Ώ': 'W', 'Ϊ': 'I', 'Ϋ': 'Y' + }; + const TURKISH_MAP = { + 'ş': 's', 'Ş': 'S', 'ı': 'i', 'İ': 'I', 'ç': 'c', 'Ç': 'C', 'ü': 'u', + 'Ü': 'U', 'ö': 'o', 'Ö': 'O', 'ğ': 'g', 'Ğ': 'G' + }; + const ROMANIAN_MAP = { + 'ă': 'a', 'î': 'i', 'ș': 's', 'ț': 't', 'â': 'a', + 'Ă': 'A', 'Î': 'I', 'Ș': 'S', 'Ț': 'T', 'Â': 'A' + }; + const RUSSIAN_MAP = { + 'а': 'a', 'б': 'b', 'в': 'v', 'г': 'g', 'д': 'd', 'е': 'e', 'ё': 'yo', + 'ж': 'zh', 'з': 'z', 'и': 'i', 'й': 'j', 'к': 'k', 'л': 'l', 'м': 'm', + 'н': 'n', 'о': 'o', 'п': 'p', 'р': 'r', 'с': 's', 'т': 't', 'у': 'u', + 'ф': 'f', 'х': 'h', 'ц': 'c', 'ч': 'ch', 'ш': 'sh', 'щ': 'sh', 'ъ': '', + 'ы': 'y', 'ь': '', 'э': 'e', 'ю': 'yu', 'я': 'ya', + 'А': 'A', 'Б': 'B', 'В': 'V', 'Г': 'G', 'Д': 'D', 'Е': 'E', 'Ё': 'Yo', + 'Ж': 'Zh', 'З': 'Z', 'И': 'I', 'Й': 'J', 'К': 'K', 'Л': 'L', 'М': 'M', + 'Н': 'N', 'О': 'O', 'П': 'P', 'Р': 'R', 'С': 'S', 'Т': 'T', 'У': 'U', + 'Ф': 'F', 'Х': 'H', 'Ц': 'C', 'Ч': 'Ch', 'Ш': 'Sh', 'Щ': 'Sh', 'Ъ': '', + 'Ы': 'Y', 'Ь': '', 'Э': 'E', 'Ю': 'Yu', 'Я': 'Ya' + }; + const UKRAINIAN_MAP = { + 'Є': 'Ye', 'І': 'I', 'Ї': 'Yi', 'Ґ': 'G', 'є': 'ye', 'і': 'i', + 'ї': 'yi', 'ґ': 'g' + }; + const CZECH_MAP = { + 'č': 'c', 'ď': 'd', 'ě': 'e', 'ň': 'n', 'ř': 'r', 'š': 's', 'ť': 't', + 'ů': 'u', 'ž': 'z', 'Č': 'C', 'Ď': 'D', 'Ě': 'E', 'Ň': 'N', 'Ř': 'R', + 'Š': 'S', 'Ť': 'T', 'Ů': 'U', 'Ž': 'Z' + }; + const SLOVAK_MAP = { + 'á': 'a', 'ä': 'a', 'č': 'c', 'ď': 'd', 'é': 'e', 'í': 'i', 'ľ': 'l', + 'ĺ': 'l', 'ň': 'n', 'ó': 'o', 'ô': 'o', 'ŕ': 'r', 'š': 's', 'ť': 't', + 'ú': 'u', 'ý': 'y', 'ž': 'z', + 'Á': 'a', 'Ä': 'A', 'Č': 'C', 'Ď': 'D', 'É': 'E', 'Í': 'I', 'Ľ': 'L', + 'Ĺ': 'L', 'Ň': 'N', 'Ó': 'O', 'Ô': 'O', 'Ŕ': 'R', 'Š': 'S', 'Ť': 'T', + 'Ú': 'U', 'Ý': 'Y', 'Ž': 'Z' + }; + const POLISH_MAP = { + 'ą': 'a', 'ć': 'c', 'ę': 'e', 'ł': 'l', 'ń': 'n', 'ó': 'o', 'ś': 's', + 'ź': 'z', 'ż': 'z', + 'Ą': 'A', 'Ć': 'C', 'Ę': 'E', 'Ł': 'L', 'Ń': 'N', 'Ó': 'O', 'Ś': 'S', + 'Ź': 'Z', 'Ż': 'Z' + }; + const LATVIAN_MAP = { + 'ā': 'a', 'č': 'c', 'ē': 'e', 'ģ': 'g', 'ī': 'i', 'ķ': 'k', 'ļ': 'l', + 'ņ': 'n', 'š': 's', 'ū': 'u', 'ž': 'z', + 'Ā': 'A', 'Č': 'C', 'Ē': 'E', 'Ģ': 'G', 'Ī': 'I', 'Ķ': 'K', 'Ļ': 'L', + 'Ņ': 'N', 'Š': 'S', 'Ū': 'U', 'Ž': 'Z' + }; + const ARABIC_MAP = { + 'أ': 'a', 'ب': 'b', 'ت': 't', 'ث': 'th', 'ج': 'g', 'ح': 'h', 'خ': 'kh', 'د': 'd', + 'ذ': 'th', 'ر': 'r', 'ز': 'z', 'س': 's', 'ش': 'sh', 'ص': 's', 'ض': 'd', 'ط': 't', + 'ظ': 'th', 'ع': 'aa', 'غ': 'gh', 'ف': 'f', 'ق': 'k', 'ك': 'k', 'ل': 'l', 'م': 'm', + 'ن': 'n', 'ه': 'h', 'و': 'o', 'ي': 'y' + }; + const LITHUANIAN_MAP = { + 'ą': 'a', 'č': 'c', 'ę': 'e', 'ė': 'e', 'į': 'i', 'š': 's', 'ų': 'u', + 'ū': 'u', 'ž': 'z', + 'Ą': 'A', 'Č': 'C', 'Ę': 'E', 'Ė': 'E', 'Į': 'I', 'Š': 'S', 'Ų': 'U', + 'Ū': 'U', 'Ž': 'Z' + }; + const SERBIAN_MAP = { + 'ђ': 'dj', 'ј': 'j', 'љ': 'lj', 'њ': 'nj', 'ћ': 'c', 'џ': 'dz', + 'đ': 'dj', 'Ђ': 'Dj', 'Ј': 'j', 'Љ': 'Lj', 'Њ': 'Nj', 'Ћ': 'C', + 'Џ': 'Dz', 'Đ': 'Dj' + }; + const AZERBAIJANI_MAP = { + 'ç': 'c', 'ə': 'e', 'ğ': 'g', 'ı': 'i', 'ö': 'o', 'ş': 's', 'ü': 'u', + 'Ç': 'C', 'Ə': 'E', 'Ğ': 'G', 'İ': 'I', 'Ö': 'O', 'Ş': 'S', 'Ü': 'U' + }; + const GEORGIAN_MAP = { + 'ა': 'a', 'ბ': 'b', 'გ': 'g', 'დ': 'd', 'ე': 'e', 'ვ': 'v', 'ზ': 'z', + 'თ': 't', 'ი': 'i', 'კ': 'k', 'ლ': 'l', 'მ': 'm', 'ნ': 'n', 'ო': 'o', + 'პ': 'p', 'ჟ': 'j', 'რ': 'r', 'ს': 's', 'ტ': 't', 'უ': 'u', 'ფ': 'f', + 'ქ': 'q', 'ღ': 'g', 'ყ': 'y', 'შ': 'sh', 'ჩ': 'ch', 'ც': 'c', 'ძ': 'dz', + 'წ': 'w', 'ჭ': 'ch', 'ხ': 'x', 'ჯ': 'j', 'ჰ': 'h' + }; + + const ALL_DOWNCODE_MAPS = [ + LATIN_MAP, + LATIN_SYMBOLS_MAP, + GREEK_MAP, + TURKISH_MAP, + ROMANIAN_MAP, + RUSSIAN_MAP, + UKRAINIAN_MAP, + CZECH_MAP, + SLOVAK_MAP, + POLISH_MAP, + LATVIAN_MAP, + ARABIC_MAP, + LITHUANIAN_MAP, + SERBIAN_MAP, + AZERBAIJANI_MAP, + GEORGIAN_MAP + ]; + + const Downcoder = { + 'Initialize': function() { + if (Downcoder.map) { // already made + return; + } + Downcoder.map = {}; + for (const lookup of ALL_DOWNCODE_MAPS) { + Object.assign(Downcoder.map, lookup); + } + Downcoder.regex = new RegExp(Object.keys(Downcoder.map).join('|'), 'g'); + } + }; + + function downcode(slug) { + Downcoder.Initialize(); + return slug.replace(Downcoder.regex, function(m) { + return Downcoder.map[m]; + }); + } + + + function URLify(s, num_chars, allowUnicode) { + // changes, e.g., "Petty theft" to "petty-theft" + if (!allowUnicode) { + s = downcode(s); + } + s = s.toLowerCase(); // convert to lowercase + // if downcode doesn't hit, the char will be stripped here + if (allowUnicode) { + // Keep Unicode letters including both lowercase and uppercase + // characters, whitespace, and dash; remove other characters. + s = XRegExp.replace(s, XRegExp('[^-_\\p{L}\\p{N}\\s]', 'g'), ''); + } else { + s = s.replace(/[^-\w\s]/g, ''); // remove unneeded chars + } + s = s.replace(/^\s+|\s+$/g, ''); // trim leading/trailing spaces + s = s.replace(/[-\s]+/g, '-'); // convert spaces to hyphens + s = s.substring(0, num_chars); // trim to first num_chars chars + return s.replace(/-+$/g, ''); // trim any trailing hyphens + } + window.URLify = URLify; +} diff --git a/fweb/static/admin/js/vendor/jquery/LICENSE.txt b/fweb/static/admin/js/vendor/jquery/LICENSE.txt new file mode 100644 index 0000000..f642c3f --- /dev/null +++ b/fweb/static/admin/js/vendor/jquery/LICENSE.txt @@ -0,0 +1,20 @@ +Copyright OpenJS Foundation and other contributors, https://openjsf.org/ + +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/js/vendor/jquery/jquery.js b/fweb/static/admin/js/vendor/jquery/jquery.js new file mode 100644 index 0000000..1a86433 --- /dev/null +++ b/fweb/static/admin/js/vendor/jquery/jquery.js @@ -0,0 +1,10716 @@ +/*! + * jQuery JavaScript Library v3.7.1 + * https://jquery.com/ + * + * Copyright OpenJS Foundation and other contributors + * Released under the MIT license + * https://jquery.org/license + * + * Date: 2023-08-28T13:37Z + */ +( function( global, factory ) { + + "use strict"; + + if ( typeof module === "object" && typeof module.exports === "object" ) { + + // For CommonJS and CommonJS-like environments where a proper `window` + // is present, execute the factory and get jQuery. + // For environments that do not have a `window` with a `document` + // (such as Node.js), expose a factory as module.exports. + // This accentuates the need for the creation of a real `window`. + // e.g. var jQuery = require("jquery")(window); + // See ticket trac-14549 for more info. + module.exports = global.document ? + factory( global, true ) : + function( w ) { + if ( !w.document ) { + throw new Error( "jQuery requires a window with a document" ); + } + return factory( w ); + }; + } else { + factory( global ); + } + +// Pass this if window is not defined yet +} )( typeof window !== "undefined" ? window : this, function( window, noGlobal ) { + +// Edge <= 12 - 13+, Firefox <=18 - 45+, IE 10 - 11, Safari 5.1 - 9+, iOS 6 - 9.1 +// throw exceptions when non-strict code (e.g., ASP.NET 4.5) accesses strict mode +// arguments.callee.caller (trac-13335). But as of jQuery 3.0 (2016), strict mode should be common +// enough that all such attempts are guarded in a try block. +"use strict"; + +var arr = []; + +var getProto = Object.getPrototypeOf; + +var slice = arr.slice; + +var flat = arr.flat ? function( array ) { + return arr.flat.call( array ); +} : function( array ) { + return arr.concat.apply( [], array ); +}; + + +var push = arr.push; + +var indexOf = arr.indexOf; + +var class2type = {}; + +var toString = class2type.toString; + +var hasOwn = class2type.hasOwnProperty; + +var fnToString = hasOwn.toString; + +var ObjectFunctionString = fnToString.call( Object ); + +var support = {}; + +var isFunction = function isFunction( obj ) { + + // Support: Chrome <=57, Firefox <=52 + // In some browsers, typeof returns "function" for HTML elements + // (i.e., `typeof document.createElement( "object" ) === "function"`). + // We don't want to classify *any* DOM node as a function. + // Support: QtWeb <=3.8.5, WebKit <=534.34, wkhtmltopdf tool <=0.12.5 + // Plus for old WebKit, typeof returns "function" for HTML collections + // (e.g., `typeof document.getElementsByTagName("div") === "function"`). (gh-4756) + return typeof obj === "function" && typeof obj.nodeType !== "number" && + typeof obj.item !== "function"; + }; + + +var isWindow = function isWindow( obj ) { + return obj != null && obj === obj.window; + }; + + +var document = window.document; + + + + var preservedScriptAttributes = { + type: true, + src: true, + nonce: true, + noModule: true + }; + + function DOMEval( code, node, doc ) { + doc = doc || document; + + var i, val, + script = doc.createElement( "script" ); + + script.text = code; + if ( node ) { + for ( i in preservedScriptAttributes ) { + + // Support: Firefox 64+, Edge 18+ + // Some browsers don't support the "nonce" property on scripts. + // On the other hand, just using `getAttribute` is not enough as + // the `nonce` attribute is reset to an empty string whenever it + // becomes browsing-context connected. + // See https://github.com/whatwg/html/issues/2369 + // See https://html.spec.whatwg.org/#nonce-attributes + // The `node.getAttribute` check was added for the sake of + // `jQuery.globalEval` so that it can fake a nonce-containing node + // via an object. + val = node[ i ] || node.getAttribute && node.getAttribute( i ); + if ( val ) { + script.setAttribute( i, val ); + } + } + } + doc.head.appendChild( script ).parentNode.removeChild( script ); + } + + +function toType( obj ) { + if ( obj == null ) { + return obj + ""; + } + + // Support: Android <=2.3 only (functionish RegExp) + return typeof obj === "object" || typeof obj === "function" ? + class2type[ toString.call( obj ) ] || "object" : + typeof obj; +} +/* global Symbol */ +// Defining this global in .eslintrc.json would create a danger of using the global +// unguarded in another place, it seems safer to define global only for this module + + + +var version = "3.7.1", + + rhtmlSuffix = /HTML$/i, + + // Define a local copy of jQuery + jQuery = function( selector, context ) { + + // The jQuery object is actually just the init constructor 'enhanced' + // Need init if jQuery is called (just allow error to be thrown if not included) + return new jQuery.fn.init( selector, context ); + }; + +jQuery.fn = jQuery.prototype = { + + // The current version of jQuery being used + jquery: version, + + constructor: jQuery, + + // The default length of a jQuery object is 0 + length: 0, + + toArray: function() { + return slice.call( this ); + }, + + // Get the Nth element in the matched element set OR + // Get the whole matched element set as a clean array + get: function( num ) { + + // Return all the elements in a clean array + if ( num == null ) { + return slice.call( this ); + } + + // Return just the one element from the set + return num < 0 ? this[ num + this.length ] : this[ num ]; + }, + + // Take an array of elements and push it onto the stack + // (returning the new matched element set) + pushStack: function( elems ) { + + // Build a new jQuery matched element set + var ret = jQuery.merge( this.constructor(), elems ); + + // Add the old object onto the stack (as a reference) + ret.prevObject = this; + + // Return the newly-formed element set + return ret; + }, + + // Execute a callback for every element in the matched set. + each: function( callback ) { + return jQuery.each( this, callback ); + }, + + map: function( callback ) { + return this.pushStack( jQuery.map( this, function( elem, i ) { + return callback.call( elem, i, elem ); + } ) ); + }, + + slice: function() { + return this.pushStack( slice.apply( this, arguments ) ); + }, + + first: function() { + return this.eq( 0 ); + }, + + last: function() { + return this.eq( -1 ); + }, + + even: function() { + return this.pushStack( jQuery.grep( this, function( _elem, i ) { + return ( i + 1 ) % 2; + } ) ); + }, + + odd: function() { + return this.pushStack( jQuery.grep( this, function( _elem, i ) { + return i % 2; + } ) ); + }, + + eq: function( i ) { + var len = this.length, + j = +i + ( i < 0 ? len : 0 ); + return this.pushStack( j >= 0 && j < len ? [ this[ j ] ] : [] ); + }, + + end: function() { + return this.prevObject || this.constructor(); + }, + + // For internal use only. + // Behaves like an Array's method, not like a jQuery method. + push: push, + sort: arr.sort, + splice: arr.splice +}; + +jQuery.extend = jQuery.fn.extend = function() { + var options, name, src, copy, copyIsArray, clone, + target = arguments[ 0 ] || {}, + i = 1, + length = arguments.length, + deep = false; + + // Handle a deep copy situation + if ( typeof target === "boolean" ) { + deep = target; + + // Skip the boolean and the target + target = arguments[ i ] || {}; + i++; + } + + // Handle case when target is a string or something (possible in deep copy) + if ( typeof target !== "object" && !isFunction( target ) ) { + target = {}; + } + + // Extend jQuery itself if only one argument is passed + if ( i === length ) { + target = this; + i--; + } + + for ( ; i < length; i++ ) { + + // Only deal with non-null/undefined values + if ( ( options = arguments[ i ] ) != null ) { + + // Extend the base object + for ( name in options ) { + copy = options[ name ]; + + // Prevent Object.prototype pollution + // Prevent never-ending loop + if ( name === "__proto__" || target === copy ) { + continue; + } + + // Recurse if we're merging plain objects or arrays + if ( deep && copy && ( jQuery.isPlainObject( copy ) || + ( copyIsArray = Array.isArray( copy ) ) ) ) { + src = target[ name ]; + + // Ensure proper type for the source value + if ( copyIsArray && !Array.isArray( src ) ) { + clone = []; + } else if ( !copyIsArray && !jQuery.isPlainObject( src ) ) { + clone = {}; + } else { + clone = src; + } + copyIsArray = false; + + // Never move original objects, clone them + target[ name ] = jQuery.extend( deep, clone, copy ); + + // Don't bring in undefined values + } else if ( copy !== undefined ) { + target[ name ] = copy; + } + } + } + } + + // Return the modified object + return target; +}; + +jQuery.extend( { + + // Unique for each copy of jQuery on the page + expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ), + + // Assume jQuery is ready without the ready module + isReady: true, + + error: function( msg ) { + throw new Error( msg ); + }, + + noop: function() {}, + + isPlainObject: function( obj ) { + var proto, Ctor; + + // Detect obvious negatives + // Use toString instead of jQuery.type to catch host objects + if ( !obj || toString.call( obj ) !== "[object Object]" ) { + return false; + } + + proto = getProto( obj ); + + // Objects with no prototype (e.g., `Object.create( null )`) are plain + if ( !proto ) { + return true; + } + + // Objects with prototype are plain iff they were constructed by a global Object function + Ctor = hasOwn.call( proto, "constructor" ) && proto.constructor; + return typeof Ctor === "function" && fnToString.call( Ctor ) === ObjectFunctionString; + }, + + isEmptyObject: function( obj ) { + var name; + + for ( name in obj ) { + return false; + } + return true; + }, + + // Evaluates a script in a provided context; falls back to the global one + // if not specified. + globalEval: function( code, options, doc ) { + DOMEval( code, { nonce: options && options.nonce }, doc ); + }, + + each: function( obj, callback ) { + var length, i = 0; + + if ( isArrayLike( obj ) ) { + length = obj.length; + for ( ; i < length; i++ ) { + if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) { + break; + } + } + } else { + for ( i in obj ) { + if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) { + break; + } + } + } + + return obj; + }, + + + // Retrieve the text value of an array of DOM nodes + text: function( elem ) { + var node, + ret = "", + i = 0, + nodeType = elem.nodeType; + + if ( !nodeType ) { + + // If no nodeType, this is expected to be an array + while ( ( node = elem[ i++ ] ) ) { + + // Do not traverse comment nodes + ret += jQuery.text( node ); + } + } + if ( nodeType === 1 || nodeType === 11 ) { + return elem.textContent; + } + if ( nodeType === 9 ) { + return elem.documentElement.textContent; + } + if ( nodeType === 3 || nodeType === 4 ) { + return elem.nodeValue; + } + + // Do not include comment or processing instruction nodes + + return ret; + }, + + // results is for internal usage only + makeArray: function( arr, results ) { + var ret = results || []; + + if ( arr != null ) { + if ( isArrayLike( Object( arr ) ) ) { + jQuery.merge( ret, + typeof arr === "string" ? + [ arr ] : arr + ); + } else { + push.call( ret, arr ); + } + } + + return ret; + }, + + inArray: function( elem, arr, i ) { + return arr == null ? -1 : indexOf.call( arr, elem, i ); + }, + + isXMLDoc: function( elem ) { + var namespace = elem && elem.namespaceURI, + docElem = elem && ( elem.ownerDocument || elem ).documentElement; + + // Assume HTML when documentElement doesn't yet exist, such as inside + // document fragments. + return !rhtmlSuffix.test( namespace || docElem && docElem.nodeName || "HTML" ); + }, + + // Support: Android <=4.0 only, PhantomJS 1 only + // push.apply(_, arraylike) throws on ancient WebKit + merge: function( first, second ) { + var len = +second.length, + j = 0, + i = first.length; + + for ( ; j < len; j++ ) { + first[ i++ ] = second[ j ]; + } + + first.length = i; + + return first; + }, + + grep: function( elems, callback, invert ) { + var callbackInverse, + matches = [], + i = 0, + length = elems.length, + callbackExpect = !invert; + + // Go through the array, only saving the items + // that pass the validator function + for ( ; i < length; i++ ) { + callbackInverse = !callback( elems[ i ], i ); + if ( callbackInverse !== callbackExpect ) { + matches.push( elems[ i ] ); + } + } + + return matches; + }, + + // arg is for internal usage only + map: function( elems, callback, arg ) { + var length, value, + i = 0, + ret = []; + + // Go through the array, translating each of the items to their new values + if ( isArrayLike( elems ) ) { + length = elems.length; + for ( ; i < length; i++ ) { + value = callback( elems[ i ], i, arg ); + + if ( value != null ) { + ret.push( value ); + } + } + + // Go through every key on the object, + } else { + for ( i in elems ) { + value = callback( elems[ i ], i, arg ); + + if ( value != null ) { + ret.push( value ); + } + } + } + + // Flatten any nested arrays + return flat( ret ); + }, + + // A global GUID counter for objects + guid: 1, + + // jQuery.support is not used in Core but other projects attach their + // properties to it so it needs to exist. + support: support +} ); + +if ( typeof Symbol === "function" ) { + jQuery.fn[ Symbol.iterator ] = arr[ Symbol.iterator ]; +} + +// Populate the class2type map +jQuery.each( "Boolean Number String Function Array Date RegExp Object Error Symbol".split( " " ), + function( _i, name ) { + class2type[ "[object " + name + "]" ] = name.toLowerCase(); + } ); + +function isArrayLike( obj ) { + + // Support: real iOS 8.2 only (not reproducible in simulator) + // `in` check used to prevent JIT error (gh-2145) + // hasOwn isn't used here due to false negatives + // regarding Nodelist length in IE + var length = !!obj && "length" in obj && obj.length, + type = toType( obj ); + + if ( isFunction( obj ) || isWindow( obj ) ) { + return false; + } + + return type === "array" || length === 0 || + typeof length === "number" && length > 0 && ( length - 1 ) in obj; +} + + +function nodeName( elem, name ) { + + return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); + +} +var pop = arr.pop; + + +var sort = arr.sort; + + +var splice = arr.splice; + + +var whitespace = "[\\x20\\t\\r\\n\\f]"; + + +var rtrimCSS = new RegExp( + "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", + "g" +); + + + + +// Note: an element does not contain itself +jQuery.contains = function( a, b ) { + var bup = b && b.parentNode; + + return a === bup || !!( bup && bup.nodeType === 1 && ( + + // Support: IE 9 - 11+ + // IE doesn't have `contains` on SVG. + a.contains ? + a.contains( bup ) : + a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 + ) ); +}; + + + + +// CSS string/identifier serialization +// https://drafts.csswg.org/cssom/#common-serializing-idioms +var rcssescape = /([\0-\x1f\x7f]|^-?\d)|^-$|[^\x80-\uFFFF\w-]/g; + +function fcssescape( ch, asCodePoint ) { + if ( asCodePoint ) { + + // U+0000 NULL becomes U+FFFD REPLACEMENT CHARACTER + if ( ch === "\0" ) { + return "\uFFFD"; + } + + // Control characters and (dependent upon position) numbers get escaped as code points + return ch.slice( 0, -1 ) + "\\" + ch.charCodeAt( ch.length - 1 ).toString( 16 ) + " "; + } + + // Other potentially-special ASCII characters get backslash-escaped + return "\\" + ch; +} + +jQuery.escapeSelector = function( sel ) { + return ( sel + "" ).replace( rcssescape, fcssescape ); +}; + + + + +var preferredDoc = document, + pushNative = push; + +( function() { + +var i, + Expr, + outermostContext, + sortInput, + hasDuplicate, + push = pushNative, + + // Local document vars + document, + documentElement, + documentIsHTML, + rbuggyQSA, + matches, + + // Instance-specific data + expando = jQuery.expando, + dirruns = 0, + done = 0, + classCache = createCache(), + tokenCache = createCache(), + compilerCache = createCache(), + nonnativeSelectorCache = createCache(), + sortOrder = function( a, b ) { + if ( a === b ) { + hasDuplicate = true; + } + return 0; + }, + + booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|" + + "loop|multiple|open|readonly|required|scoped", + + // Regular expressions + + // https://www.w3.org/TR/css-syntax-3/#ident-token-diagram + identifier = "(?:\\\\[\\da-fA-F]{1,6}" + whitespace + + "?|\\\\[^\\r\\n\\f]|[\\w-]|[^\0-\\x7f])+", + + // Attribute selectors: https://www.w3.org/TR/selectors/#attribute-selectors + attributes = "\\[" + whitespace + "*(" + identifier + ")(?:" + whitespace + + + // Operator (capture 2) + "*([*^$|!~]?=)" + whitespace + + + // "Attribute values must be CSS identifiers [capture 5] or strings [capture 3 or capture 4]" + "*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + + whitespace + "*\\]", + + pseudos = ":(" + identifier + ")(?:\\((" + + + // To reduce the number of selectors needing tokenize in the preFilter, prefer arguments: + // 1. quoted (capture 3; capture 4 or capture 5) + "('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" + + + // 2. simple (capture 6) + "((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" + + + // 3. anything else (capture 2) + ".*" + + ")\\)|)", + + // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter + rwhitespace = new RegExp( whitespace + "+", "g" ), + + rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), + rleadingCombinator = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + + whitespace + "*" ), + rdescend = new RegExp( whitespace + "|>" ), + + rpseudo = new RegExp( pseudos ), + ridentifier = new RegExp( "^" + identifier + "$" ), + + matchExpr = { + ID: new RegExp( "^#(" + identifier + ")" ), + CLASS: new RegExp( "^\\.(" + identifier + ")" ), + TAG: new RegExp( "^(" + identifier + "|[*])" ), + ATTR: new RegExp( "^" + attributes ), + PSEUDO: new RegExp( "^" + pseudos ), + CHILD: new RegExp( + "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), + bool: new RegExp( "^(?:" + booleans + ")$", "i" ), + + // For use in libraries implementing .is() + // We use this for POS matching in `select` + needsContext: new RegExp( "^" + whitespace + + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) + }, + + rinputs = /^(?:input|select|textarea|button)$/i, + rheader = /^h\d$/i, + + // Easily-parseable/retrievable ID or TAG or CLASS selectors + rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, + + rsibling = /[+~]/, + + // CSS escapes + // https://www.w3.org/TR/CSS21/syndata.html#escaped-characters + runescape = new RegExp( "\\\\[\\da-fA-F]{1,6}" + whitespace + + "?|\\\\([^\\r\\n\\f])", "g" ), + funescape = function( escape, nonHex ) { + var high = "0x" + escape.slice( 1 ) - 0x10000; + + if ( nonHex ) { + + // Strip the backslash prefix from a non-hex escape sequence + return nonHex; + } + + // Replace a hexadecimal escape sequence with the encoded Unicode code point + // Support: IE <=11+ + // For values outside the Basic Multilingual Plane (BMP), manually construct a + // surrogate pair + return high < 0 ? + String.fromCharCode( high + 0x10000 ) : + String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); + }, + + // Used for iframes; see `setDocument`. + // Support: IE 9 - 11+, Edge 12 - 18+ + // Removing the function wrapper causes a "Permission Denied" + // error in IE/Edge. + unloadHandler = function() { + setDocument(); + }, + + inDisabledFieldset = addCombinator( + function( elem ) { + return elem.disabled === true && nodeName( elem, "fieldset" ); + }, + { dir: "parentNode", next: "legend" } + ); + +// Support: IE <=9 only +// Accessing document.activeElement can throw unexpectedly +// https://bugs.jquery.com/ticket/13393 +function safeActiveElement() { + try { + return document.activeElement; + } catch ( err ) { } +} + +// Optimize for push.apply( _, NodeList ) +try { + push.apply( + ( arr = slice.call( preferredDoc.childNodes ) ), + preferredDoc.childNodes + ); + + // Support: Android <=4.0 + // Detect silently failing push.apply + // eslint-disable-next-line no-unused-expressions + arr[ preferredDoc.childNodes.length ].nodeType; +} catch ( e ) { + push = { + apply: function( target, els ) { + pushNative.apply( target, slice.call( els ) ); + }, + call: function( target ) { + pushNative.apply( target, slice.call( arguments, 1 ) ); + } + }; +} + +function find( selector, context, results, seed ) { + var m, i, elem, nid, match, groups, newSelector, + newContext = context && context.ownerDocument, + + // nodeType defaults to 9, since context defaults to document + nodeType = context ? context.nodeType : 9; + + results = results || []; + + // Return early from calls with invalid selector or context + if ( typeof selector !== "string" || !selector || + nodeType !== 1 && nodeType !== 9 && nodeType !== 11 ) { + + return results; + } + + // Try to shortcut find operations (as opposed to filters) in HTML documents + if ( !seed ) { + setDocument( context ); + context = context || document; + + if ( documentIsHTML ) { + + // If the selector is sufficiently simple, try using a "get*By*" DOM method + // (excepting DocumentFragment context, where the methods don't exist) + if ( nodeType !== 11 && ( match = rquickExpr.exec( selector ) ) ) { + + // ID selector + if ( ( m = match[ 1 ] ) ) { + + // Document context + if ( nodeType === 9 ) { + if ( ( elem = context.getElementById( m ) ) ) { + + // Support: IE 9 only + // getElementById can match elements by name instead of ID + if ( elem.id === m ) { + push.call( results, elem ); + return results; + } + } else { + return results; + } + + // Element context + } else { + + // Support: IE 9 only + // getElementById can match elements by name instead of ID + if ( newContext && ( elem = newContext.getElementById( m ) ) && + find.contains( context, elem ) && + elem.id === m ) { + + push.call( results, elem ); + return results; + } + } + + // Type selector + } else if ( match[ 2 ] ) { + push.apply( results, context.getElementsByTagName( selector ) ); + return results; + + // Class selector + } else if ( ( m = match[ 3 ] ) && context.getElementsByClassName ) { + push.apply( results, context.getElementsByClassName( m ) ); + return results; + } + } + + // Take advantage of querySelectorAll + if ( !nonnativeSelectorCache[ selector + " " ] && + ( !rbuggyQSA || !rbuggyQSA.test( selector ) ) ) { + + newSelector = selector; + newContext = context; + + // qSA considers elements outside a scoping root when evaluating child or + // descendant combinators, which is not what we want. + // In such cases, we work around the behavior by prefixing every selector in the + // list with an ID selector referencing the scope context. + // The technique has to be used as well when a leading combinator is used + // as such selectors are not recognized by querySelectorAll. + // Thanks to Andrew Dupont for this technique. + if ( nodeType === 1 && + ( rdescend.test( selector ) || rleadingCombinator.test( selector ) ) ) { + + // Expand context for sibling selectors + newContext = rsibling.test( selector ) && testContext( context.parentNode ) || + context; + + // We can use :scope instead of the ID hack if the browser + // supports it & if we're not changing the context. + // Support: IE 11+, Edge 17 - 18+ + // IE/Edge sometimes throw a "Permission denied" error when + // strict-comparing two documents; shallow comparisons work. + // eslint-disable-next-line eqeqeq + if ( newContext != context || !support.scope ) { + + // Capture the context ID, setting it first if necessary + if ( ( nid = context.getAttribute( "id" ) ) ) { + nid = jQuery.escapeSelector( nid ); + } else { + context.setAttribute( "id", ( nid = expando ) ); + } + } + + // Prefix every selector in the list + groups = tokenize( selector ); + i = groups.length; + while ( i-- ) { + groups[ i ] = ( nid ? "#" + nid : ":scope" ) + " " + + toSelector( groups[ i ] ); + } + newSelector = groups.join( "," ); + } + + try { + push.apply( results, + newContext.querySelectorAll( newSelector ) + ); + return results; + } catch ( qsaError ) { + nonnativeSelectorCache( selector, true ); + } finally { + if ( nid === expando ) { + context.removeAttribute( "id" ); + } + } + } + } + } + + // All others + return select( selector.replace( rtrimCSS, "$1" ), context, results, seed ); +} + +/** + * Create key-value caches of limited size + * @returns {function(string, object)} Returns the Object data after storing it on itself with + * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) + * deleting the oldest entry + */ +function createCache() { + var keys = []; + + function cache( key, value ) { + + // Use (key + " ") to avoid collision with native prototype properties + // (see https://github.com/jquery/sizzle/issues/157) + if ( keys.push( key + " " ) > Expr.cacheLength ) { + + // Only keep the most recent entries + delete cache[ keys.shift() ]; + } + return ( cache[ key + " " ] = value ); + } + return cache; +} + +/** + * Mark a function for special use by jQuery selector module + * @param {Function} fn The function to mark + */ +function markFunction( fn ) { + fn[ expando ] = true; + return fn; +} + +/** + * Support testing using an element + * @param {Function} fn Passed the created element and returns a boolean result + */ +function assert( fn ) { + var el = document.createElement( "fieldset" ); + + try { + return !!fn( el ); + } catch ( e ) { + return false; + } finally { + + // Remove from its parent by default + if ( el.parentNode ) { + el.parentNode.removeChild( el ); + } + + // release memory in IE + el = null; + } +} + +/** + * Returns a function to use in pseudos for input types + * @param {String} type + */ +function createInputPseudo( type ) { + return function( elem ) { + return nodeName( elem, "input" ) && elem.type === type; + }; +} + +/** + * Returns a function to use in pseudos for buttons + * @param {String} type + */ +function createButtonPseudo( type ) { + return function( elem ) { + return ( nodeName( elem, "input" ) || nodeName( elem, "button" ) ) && + elem.type === type; + }; +} + +/** + * Returns a function to use in pseudos for :enabled/:disabled + * @param {Boolean} disabled true for :disabled; false for :enabled + */ +function createDisabledPseudo( disabled ) { + + // Known :disabled false positives: fieldset[disabled] > legend:nth-of-type(n+2) :can-disable + return function( elem ) { + + // Only certain elements can match :enabled or :disabled + // https://html.spec.whatwg.org/multipage/scripting.html#selector-enabled + // https://html.spec.whatwg.org/multipage/scripting.html#selector-disabled + if ( "form" in elem ) { + + // Check for inherited disabledness on relevant non-disabled elements: + // * listed form-associated elements in a disabled fieldset + // https://html.spec.whatwg.org/multipage/forms.html#category-listed + // https://html.spec.whatwg.org/multipage/forms.html#concept-fe-disabled + // * option elements in a disabled optgroup + // https://html.spec.whatwg.org/multipage/forms.html#concept-option-disabled + // All such elements have a "form" property. + if ( elem.parentNode && elem.disabled === false ) { + + // Option elements defer to a parent optgroup if present + if ( "label" in elem ) { + if ( "label" in elem.parentNode ) { + return elem.parentNode.disabled === disabled; + } else { + return elem.disabled === disabled; + } + } + + // Support: IE 6 - 11+ + // Use the isDisabled shortcut property to check for disabled fieldset ancestors + return elem.isDisabled === disabled || + + // Where there is no isDisabled, check manually + elem.isDisabled !== !disabled && + inDisabledFieldset( elem ) === disabled; + } + + return elem.disabled === disabled; + + // Try to winnow out elements that can't be disabled before trusting the disabled property. + // Some victims get caught in our net (label, legend, menu, track), but it shouldn't + // even exist on them, let alone have a boolean value. + } else if ( "label" in elem ) { + return elem.disabled === disabled; + } + + // Remaining elements are neither :enabled nor :disabled + return false; + }; +} + +/** + * Returns a function to use in pseudos for positionals + * @param {Function} fn + */ +function createPositionalPseudo( fn ) { + return markFunction( function( argument ) { + argument = +argument; + return markFunction( function( seed, matches ) { + var j, + matchIndexes = fn( [], seed.length, argument ), + i = matchIndexes.length; + + // Match elements found at the specified indexes + while ( i-- ) { + if ( seed[ ( j = matchIndexes[ i ] ) ] ) { + seed[ j ] = !( matches[ j ] = seed[ j ] ); + } + } + } ); + } ); +} + +/** + * Checks a node for validity as a jQuery selector context + * @param {Element|Object=} context + * @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value + */ +function testContext( context ) { + return context && typeof context.getElementsByTagName !== "undefined" && context; +} + +/** + * Sets document-related variables once based on the current document + * @param {Element|Object} [node] An element or document object to use to set the document + * @returns {Object} Returns the current document + */ +function setDocument( node ) { + var subWindow, + doc = node ? node.ownerDocument || node : preferredDoc; + + // Return early if doc is invalid or already selected + // Support: IE 11+, Edge 17 - 18+ + // IE/Edge sometimes throw a "Permission denied" error when strict-comparing + // two documents; shallow comparisons work. + // eslint-disable-next-line eqeqeq + if ( doc == document || doc.nodeType !== 9 || !doc.documentElement ) { + return document; + } + + // Update global variables + document = doc; + documentElement = document.documentElement; + documentIsHTML = !jQuery.isXMLDoc( document ); + + // Support: iOS 7 only, IE 9 - 11+ + // Older browsers didn't support unprefixed `matches`. + matches = documentElement.matches || + documentElement.webkitMatchesSelector || + documentElement.msMatchesSelector; + + // Support: IE 9 - 11+, Edge 12 - 18+ + // Accessing iframe documents after unload throws "permission denied" errors + // (see trac-13936). + // Limit the fix to IE & Edge Legacy; despite Edge 15+ implementing `matches`, + // all IE 9+ and Edge Legacy versions implement `msMatchesSelector` as well. + if ( documentElement.msMatchesSelector && + + // Support: IE 11+, Edge 17 - 18+ + // IE/Edge sometimes throw a "Permission denied" error when strict-comparing + // two documents; shallow comparisons work. + // eslint-disable-next-line eqeqeq + preferredDoc != document && + ( subWindow = document.defaultView ) && subWindow.top !== subWindow ) { + + // Support: IE 9 - 11+, Edge 12 - 18+ + subWindow.addEventListener( "unload", unloadHandler ); + } + + // Support: IE <10 + // Check if getElementById returns elements by name + // The broken getElementById methods don't pick up programmatically-set names, + // so use a roundabout getElementsByName test + support.getById = assert( function( el ) { + documentElement.appendChild( el ).id = jQuery.expando; + return !document.getElementsByName || + !document.getElementsByName( jQuery.expando ).length; + } ); + + // Support: IE 9 only + // Check to see if it's possible to do matchesSelector + // on a disconnected node. + support.disconnectedMatch = assert( function( el ) { + return matches.call( el, "*" ); + } ); + + // Support: IE 9 - 11+, Edge 12 - 18+ + // IE/Edge don't support the :scope pseudo-class. + support.scope = assert( function() { + return document.querySelectorAll( ":scope" ); + } ); + + // Support: Chrome 105 - 111 only, Safari 15.4 - 16.3 only + // Make sure the `:has()` argument is parsed unforgivingly. + // We include `*` in the test to detect buggy implementations that are + // _selectively_ forgiving (specifically when the list includes at least + // one valid selector). + // Note that we treat complete lack of support for `:has()` as if it were + // spec-compliant support, which is fine because use of `:has()` in such + // environments will fail in the qSA path and fall back to jQuery traversal + // anyway. + support.cssHas = assert( function() { + try { + document.querySelector( ":has(*,:jqfake)" ); + return false; + } catch ( e ) { + return true; + } + } ); + + // ID filter and find + if ( support.getById ) { + Expr.filter.ID = function( id ) { + var attrId = id.replace( runescape, funescape ); + return function( elem ) { + return elem.getAttribute( "id" ) === attrId; + }; + }; + Expr.find.ID = function( id, context ) { + if ( typeof context.getElementById !== "undefined" && documentIsHTML ) { + var elem = context.getElementById( id ); + return elem ? [ elem ] : []; + } + }; + } else { + Expr.filter.ID = function( id ) { + var attrId = id.replace( runescape, funescape ); + return function( elem ) { + var node = typeof elem.getAttributeNode !== "undefined" && + elem.getAttributeNode( "id" ); + return node && node.value === attrId; + }; + }; + + // Support: IE 6 - 7 only + // getElementById is not reliable as a find shortcut + Expr.find.ID = function( id, context ) { + if ( typeof context.getElementById !== "undefined" && documentIsHTML ) { + var node, i, elems, + elem = context.getElementById( id ); + + if ( elem ) { + + // Verify the id attribute + node = elem.getAttributeNode( "id" ); + if ( node && node.value === id ) { + return [ elem ]; + } + + // Fall back on getElementsByName + elems = context.getElementsByName( id ); + i = 0; + while ( ( elem = elems[ i++ ] ) ) { + node = elem.getAttributeNode( "id" ); + if ( node && node.value === id ) { + return [ elem ]; + } + } + } + + return []; + } + }; + } + + // Tag + Expr.find.TAG = function( tag, context ) { + if ( typeof context.getElementsByTagName !== "undefined" ) { + return context.getElementsByTagName( tag ); + + // DocumentFragment nodes don't have gEBTN + } else { + return context.querySelectorAll( tag ); + } + }; + + // Class + Expr.find.CLASS = function( className, context ) { + if ( typeof context.getElementsByClassName !== "undefined" && documentIsHTML ) { + return context.getElementsByClassName( className ); + } + }; + + /* QSA/matchesSelector + ---------------------------------------------------------------------- */ + + // QSA and matchesSelector support + + rbuggyQSA = []; + + // Build QSA regex + // Regex strategy adopted from Diego Perini + assert( function( el ) { + + var input; + + documentElement.appendChild( el ).innerHTML = + "" + + ""; + + // Support: iOS <=7 - 8 only + // Boolean attributes and "value" are not treated correctly in some XML documents + if ( !el.querySelectorAll( "[selected]" ).length ) { + rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" ); + } + + // Support: iOS <=7 - 8 only + if ( !el.querySelectorAll( "[id~=" + expando + "-]" ).length ) { + rbuggyQSA.push( "~=" ); + } + + // Support: iOS 8 only + // https://bugs.webkit.org/show_bug.cgi?id=136851 + // In-page `selector#id sibling-combinator selector` fails + if ( !el.querySelectorAll( "a#" + expando + "+*" ).length ) { + rbuggyQSA.push( ".#.+[+~]" ); + } + + // Support: Chrome <=105+, Firefox <=104+, Safari <=15.4+ + // In some of the document kinds, these selectors wouldn't work natively. + // This is probably OK but for backwards compatibility we want to maintain + // handling them through jQuery traversal in jQuery 3.x. + if ( !el.querySelectorAll( ":checked" ).length ) { + rbuggyQSA.push( ":checked" ); + } + + // Support: Windows 8 Native Apps + // The type and name attributes are restricted during .innerHTML assignment + input = document.createElement( "input" ); + input.setAttribute( "type", "hidden" ); + el.appendChild( input ).setAttribute( "name", "D" ); + + // Support: IE 9 - 11+ + // IE's :disabled selector does not pick up the children of disabled fieldsets + // Support: Chrome <=105+, Firefox <=104+, Safari <=15.4+ + // In some of the document kinds, these selectors wouldn't work natively. + // This is probably OK but for backwards compatibility we want to maintain + // handling them through jQuery traversal in jQuery 3.x. + documentElement.appendChild( el ).disabled = true; + if ( el.querySelectorAll( ":disabled" ).length !== 2 ) { + rbuggyQSA.push( ":enabled", ":disabled" ); + } + + // Support: IE 11+, Edge 15 - 18+ + // IE 11/Edge don't find elements on a `[name='']` query in some cases. + // Adding a temporary attribute to the document before the selection works + // around the issue. + // Interestingly, IE 10 & older don't seem to have the issue. + input = document.createElement( "input" ); + input.setAttribute( "name", "" ); + el.appendChild( input ); + if ( !el.querySelectorAll( "[name='']" ).length ) { + rbuggyQSA.push( "\\[" + whitespace + "*name" + whitespace + "*=" + + whitespace + "*(?:''|\"\")" ); + } + } ); + + if ( !support.cssHas ) { + + // Support: Chrome 105 - 110+, Safari 15.4 - 16.3+ + // Our regular `try-catch` mechanism fails to detect natively-unsupported + // pseudo-classes inside `:has()` (such as `:has(:contains("Foo"))`) + // in browsers that parse the `:has()` argument as a forgiving selector list. + // https://drafts.csswg.org/selectors/#relational now requires the argument + // to be parsed unforgivingly, but browsers have not yet fully adjusted. + rbuggyQSA.push( ":has" ); + } + + rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join( "|" ) ); + + /* Sorting + ---------------------------------------------------------------------- */ + + // Document order sorting + sortOrder = function( a, b ) { + + // Flag for duplicate removal + if ( a === b ) { + hasDuplicate = true; + return 0; + } + + // Sort on method existence if only one input has compareDocumentPosition + var compare = !a.compareDocumentPosition - !b.compareDocumentPosition; + if ( compare ) { + return compare; + } + + // Calculate position if both inputs belong to the same document + // Support: IE 11+, Edge 17 - 18+ + // IE/Edge sometimes throw a "Permission denied" error when strict-comparing + // two documents; shallow comparisons work. + // eslint-disable-next-line eqeqeq + compare = ( a.ownerDocument || a ) == ( b.ownerDocument || b ) ? + a.compareDocumentPosition( b ) : + + // Otherwise we know they are disconnected + 1; + + // Disconnected nodes + if ( compare & 1 || + ( !support.sortDetached && b.compareDocumentPosition( a ) === compare ) ) { + + // Choose the first element that is related to our preferred document + // Support: IE 11+, Edge 17 - 18+ + // IE/Edge sometimes throw a "Permission denied" error when strict-comparing + // two documents; shallow comparisons work. + // eslint-disable-next-line eqeqeq + if ( a === document || a.ownerDocument == preferredDoc && + find.contains( preferredDoc, a ) ) { + return -1; + } + + // Support: IE 11+, Edge 17 - 18+ + // IE/Edge sometimes throw a "Permission denied" error when strict-comparing + // two documents; shallow comparisons work. + // eslint-disable-next-line eqeqeq + if ( b === document || b.ownerDocument == preferredDoc && + find.contains( preferredDoc, b ) ) { + return 1; + } + + // Maintain original order + return sortInput ? + ( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) : + 0; + } + + return compare & 4 ? -1 : 1; + }; + + return document; +} + +find.matches = function( expr, elements ) { + return find( expr, null, null, elements ); +}; + +find.matchesSelector = function( elem, expr ) { + setDocument( elem ); + + if ( documentIsHTML && + !nonnativeSelectorCache[ expr + " " ] && + ( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) { + + try { + var ret = matches.call( elem, expr ); + + // IE 9's matchesSelector returns false on disconnected nodes + if ( ret || support.disconnectedMatch || + + // As well, disconnected nodes are said to be in a document + // fragment in IE 9 + elem.document && elem.document.nodeType !== 11 ) { + return ret; + } + } catch ( e ) { + nonnativeSelectorCache( expr, true ); + } + } + + return find( expr, document, null, [ elem ] ).length > 0; +}; + +find.contains = function( context, elem ) { + + // Set document vars if needed + // Support: IE 11+, Edge 17 - 18+ + // IE/Edge sometimes throw a "Permission denied" error when strict-comparing + // two documents; shallow comparisons work. + // eslint-disable-next-line eqeqeq + if ( ( context.ownerDocument || context ) != document ) { + setDocument( context ); + } + return jQuery.contains( context, elem ); +}; + + +find.attr = function( elem, name ) { + + // Set document vars if needed + // Support: IE 11+, Edge 17 - 18+ + // IE/Edge sometimes throw a "Permission denied" error when strict-comparing + // two documents; shallow comparisons work. + // eslint-disable-next-line eqeqeq + if ( ( elem.ownerDocument || elem ) != document ) { + setDocument( elem ); + } + + var fn = Expr.attrHandle[ name.toLowerCase() ], + + // Don't get fooled by Object.prototype properties (see trac-13807) + val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ? + fn( elem, name, !documentIsHTML ) : + undefined; + + if ( val !== undefined ) { + return val; + } + + return elem.getAttribute( name ); +}; + +find.error = function( msg ) { + throw new Error( "Syntax error, unrecognized expression: " + msg ); +}; + +/** + * Document sorting and removing duplicates + * @param {ArrayLike} results + */ +jQuery.uniqueSort = function( results ) { + var elem, + duplicates = [], + j = 0, + i = 0; + + // Unless we *know* we can detect duplicates, assume their presence + // + // Support: Android <=4.0+ + // Testing for detecting duplicates is unpredictable so instead assume we can't + // depend on duplicate detection in all browsers without a stable sort. + hasDuplicate = !support.sortStable; + sortInput = !support.sortStable && slice.call( results, 0 ); + sort.call( results, sortOrder ); + + if ( hasDuplicate ) { + while ( ( elem = results[ i++ ] ) ) { + if ( elem === results[ i ] ) { + j = duplicates.push( i ); + } + } + while ( j-- ) { + splice.call( results, duplicates[ j ], 1 ); + } + } + + // Clear input after sorting to release objects + // See https://github.com/jquery/sizzle/pull/225 + sortInput = null; + + return results; +}; + +jQuery.fn.uniqueSort = function() { + return this.pushStack( jQuery.uniqueSort( slice.apply( this ) ) ); +}; + +Expr = jQuery.expr = { + + // Can be adjusted by the user + cacheLength: 50, + + createPseudo: markFunction, + + match: matchExpr, + + attrHandle: {}, + + find: {}, + + relative: { + ">": { dir: "parentNode", first: true }, + " ": { dir: "parentNode" }, + "+": { dir: "previousSibling", first: true }, + "~": { dir: "previousSibling" } + }, + + preFilter: { + ATTR: function( match ) { + match[ 1 ] = match[ 1 ].replace( runescape, funescape ); + + // Move the given value to match[3] whether quoted or unquoted + match[ 3 ] = ( match[ 3 ] || match[ 4 ] || match[ 5 ] || "" ) + .replace( runescape, funescape ); + + if ( match[ 2 ] === "~=" ) { + match[ 3 ] = " " + match[ 3 ] + " "; + } + + return match.slice( 0, 4 ); + }, + + CHILD: function( match ) { + + /* matches from matchExpr["CHILD"] + 1 type (only|nth|...) + 2 what (child|of-type) + 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) + 4 xn-component of xn+y argument ([+-]?\d*n|) + 5 sign of xn-component + 6 x of xn-component + 7 sign of y-component + 8 y of y-component + */ + match[ 1 ] = match[ 1 ].toLowerCase(); + + if ( match[ 1 ].slice( 0, 3 ) === "nth" ) { + + // nth-* requires argument + if ( !match[ 3 ] ) { + find.error( match[ 0 ] ); + } + + // numeric x and y parameters for Expr.filter.CHILD + // remember that false/true cast respectively to 0/1 + match[ 4 ] = +( match[ 4 ] ? + match[ 5 ] + ( match[ 6 ] || 1 ) : + 2 * ( match[ 3 ] === "even" || match[ 3 ] === "odd" ) + ); + match[ 5 ] = +( ( match[ 7 ] + match[ 8 ] ) || match[ 3 ] === "odd" ); + + // other types prohibit arguments + } else if ( match[ 3 ] ) { + find.error( match[ 0 ] ); + } + + return match; + }, + + PSEUDO: function( match ) { + var excess, + unquoted = !match[ 6 ] && match[ 2 ]; + + if ( matchExpr.CHILD.test( match[ 0 ] ) ) { + return null; + } + + // Accept quoted arguments as-is + if ( match[ 3 ] ) { + match[ 2 ] = match[ 4 ] || match[ 5 ] || ""; + + // Strip excess characters from unquoted arguments + } else if ( unquoted && rpseudo.test( unquoted ) && + + // Get excess from tokenize (recursively) + ( excess = tokenize( unquoted, true ) ) && + + // advance to the next closing parenthesis + ( excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length ) ) { + + // excess is a negative index + match[ 0 ] = match[ 0 ].slice( 0, excess ); + match[ 2 ] = unquoted.slice( 0, excess ); + } + + // Return only captures needed by the pseudo filter method (type and argument) + return match.slice( 0, 3 ); + } + }, + + filter: { + + TAG: function( nodeNameSelector ) { + var expectedNodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase(); + return nodeNameSelector === "*" ? + function() { + return true; + } : + function( elem ) { + return nodeName( elem, expectedNodeName ); + }; + }, + + CLASS: function( className ) { + var pattern = classCache[ className + " " ]; + + return pattern || + ( pattern = new RegExp( "(^|" + whitespace + ")" + className + + "(" + whitespace + "|$)" ) ) && + classCache( className, function( elem ) { + return pattern.test( + typeof elem.className === "string" && elem.className || + typeof elem.getAttribute !== "undefined" && + elem.getAttribute( "class" ) || + "" + ); + } ); + }, + + ATTR: function( name, operator, check ) { + return function( elem ) { + var result = find.attr( elem, name ); + + if ( result == null ) { + return operator === "!="; + } + if ( !operator ) { + return true; + } + + result += ""; + + if ( operator === "=" ) { + return result === check; + } + if ( operator === "!=" ) { + return result !== check; + } + if ( operator === "^=" ) { + return check && result.indexOf( check ) === 0; + } + if ( operator === "*=" ) { + return check && result.indexOf( check ) > -1; + } + if ( operator === "$=" ) { + return check && result.slice( -check.length ) === check; + } + if ( operator === "~=" ) { + return ( " " + result.replace( rwhitespace, " " ) + " " ) + .indexOf( check ) > -1; + } + if ( operator === "|=" ) { + return result === check || result.slice( 0, check.length + 1 ) === check + "-"; + } + + return false; + }; + }, + + CHILD: function( type, what, _argument, first, last ) { + var simple = type.slice( 0, 3 ) !== "nth", + forward = type.slice( -4 ) !== "last", + ofType = what === "of-type"; + + return first === 1 && last === 0 ? + + // Shortcut for :nth-*(n) + function( elem ) { + return !!elem.parentNode; + } : + + function( elem, _context, xml ) { + var cache, outerCache, node, nodeIndex, start, + dir = simple !== forward ? "nextSibling" : "previousSibling", + parent = elem.parentNode, + name = ofType && elem.nodeName.toLowerCase(), + useCache = !xml && !ofType, + diff = false; + + if ( parent ) { + + // :(first|last|only)-(child|of-type) + if ( simple ) { + while ( dir ) { + node = elem; + while ( ( node = node[ dir ] ) ) { + if ( ofType ? + nodeName( node, name ) : + node.nodeType === 1 ) { + + return false; + } + } + + // Reverse direction for :only-* (if we haven't yet done so) + start = dir = type === "only" && !start && "nextSibling"; + } + return true; + } + + start = [ forward ? parent.firstChild : parent.lastChild ]; + + // non-xml :nth-child(...) stores cache data on `parent` + if ( forward && useCache ) { + + // Seek `elem` from a previously-cached index + outerCache = parent[ expando ] || ( parent[ expando ] = {} ); + cache = outerCache[ type ] || []; + nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ]; + diff = nodeIndex && cache[ 2 ]; + node = nodeIndex && parent.childNodes[ nodeIndex ]; + + while ( ( node = ++nodeIndex && node && node[ dir ] || + + // Fallback to seeking `elem` from the start + ( diff = nodeIndex = 0 ) || start.pop() ) ) { + + // When found, cache indexes on `parent` and break + if ( node.nodeType === 1 && ++diff && node === elem ) { + outerCache[ type ] = [ dirruns, nodeIndex, diff ]; + break; + } + } + + } else { + + // Use previously-cached element index if available + if ( useCache ) { + outerCache = elem[ expando ] || ( elem[ expando ] = {} ); + cache = outerCache[ type ] || []; + nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ]; + diff = nodeIndex; + } + + // xml :nth-child(...) + // or :nth-last-child(...) or :nth(-last)?-of-type(...) + if ( diff === false ) { + + // Use the same loop as above to seek `elem` from the start + while ( ( node = ++nodeIndex && node && node[ dir ] || + ( diff = nodeIndex = 0 ) || start.pop() ) ) { + + if ( ( ofType ? + nodeName( node, name ) : + node.nodeType === 1 ) && + ++diff ) { + + // Cache the index of each encountered element + if ( useCache ) { + outerCache = node[ expando ] || + ( node[ expando ] = {} ); + outerCache[ type ] = [ dirruns, diff ]; + } + + if ( node === elem ) { + break; + } + } + } + } + } + + // Incorporate the offset, then check against cycle size + diff -= last; + return diff === first || ( diff % first === 0 && diff / first >= 0 ); + } + }; + }, + + PSEUDO: function( pseudo, argument ) { + + // pseudo-class names are case-insensitive + // https://www.w3.org/TR/selectors/#pseudo-classes + // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters + // Remember that setFilters inherits from pseudos + var args, + fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || + find.error( "unsupported pseudo: " + pseudo ); + + // The user may use createPseudo to indicate that + // arguments are needed to create the filter function + // just as jQuery does + if ( fn[ expando ] ) { + return fn( argument ); + } + + // But maintain support for old signatures + if ( fn.length > 1 ) { + args = [ pseudo, pseudo, "", argument ]; + return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? + markFunction( function( seed, matches ) { + var idx, + matched = fn( seed, argument ), + i = matched.length; + while ( i-- ) { + idx = indexOf.call( seed, matched[ i ] ); + seed[ idx ] = !( matches[ idx ] = matched[ i ] ); + } + } ) : + function( elem ) { + return fn( elem, 0, args ); + }; + } + + return fn; + } + }, + + pseudos: { + + // Potentially complex pseudos + not: markFunction( function( selector ) { + + // Trim the selector passed to compile + // to avoid treating leading and trailing + // spaces as combinators + var input = [], + results = [], + matcher = compile( selector.replace( rtrimCSS, "$1" ) ); + + return matcher[ expando ] ? + markFunction( function( seed, matches, _context, xml ) { + var elem, + unmatched = matcher( seed, null, xml, [] ), + i = seed.length; + + // Match elements unmatched by `matcher` + while ( i-- ) { + if ( ( elem = unmatched[ i ] ) ) { + seed[ i ] = !( matches[ i ] = elem ); + } + } + } ) : + function( elem, _context, xml ) { + input[ 0 ] = elem; + matcher( input, null, xml, results ); + + // Don't keep the element + // (see https://github.com/jquery/sizzle/issues/299) + input[ 0 ] = null; + return !results.pop(); + }; + } ), + + has: markFunction( function( selector ) { + return function( elem ) { + return find( selector, elem ).length > 0; + }; + } ), + + contains: markFunction( function( text ) { + text = text.replace( runescape, funescape ); + return function( elem ) { + return ( elem.textContent || jQuery.text( elem ) ).indexOf( text ) > -1; + }; + } ), + + // "Whether an element is represented by a :lang() selector + // is based solely on the element's language value + // being equal to the identifier C, + // or beginning with the identifier C immediately followed by "-". + // The matching of C against the element's language value is performed case-insensitively. + // The identifier C does not have to be a valid language name." + // https://www.w3.org/TR/selectors/#lang-pseudo + lang: markFunction( function( lang ) { + + // lang value must be a valid identifier + if ( !ridentifier.test( lang || "" ) ) { + find.error( "unsupported lang: " + lang ); + } + lang = lang.replace( runescape, funescape ).toLowerCase(); + return function( elem ) { + var elemLang; + do { + if ( ( elemLang = documentIsHTML ? + elem.lang : + elem.getAttribute( "xml:lang" ) || elem.getAttribute( "lang" ) ) ) { + + elemLang = elemLang.toLowerCase(); + return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; + } + } while ( ( elem = elem.parentNode ) && elem.nodeType === 1 ); + return false; + }; + } ), + + // Miscellaneous + target: function( elem ) { + var hash = window.location && window.location.hash; + return hash && hash.slice( 1 ) === elem.id; + }, + + root: function( elem ) { + return elem === documentElement; + }, + + focus: function( elem ) { + return elem === safeActiveElement() && + document.hasFocus() && + !!( elem.type || elem.href || ~elem.tabIndex ); + }, + + // Boolean properties + enabled: createDisabledPseudo( false ), + disabled: createDisabledPseudo( true ), + + checked: function( elem ) { + + // In CSS3, :checked should return both checked and selected elements + // https://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked + return ( nodeName( elem, "input" ) && !!elem.checked ) || + ( nodeName( elem, "option" ) && !!elem.selected ); + }, + + selected: function( elem ) { + + // Support: IE <=11+ + // Accessing the selectedIndex property + // forces the browser to treat the default option as + // selected when in an optgroup. + if ( elem.parentNode ) { + // eslint-disable-next-line no-unused-expressions + elem.parentNode.selectedIndex; + } + + return elem.selected === true; + }, + + // Contents + empty: function( elem ) { + + // https://www.w3.org/TR/selectors/#empty-pseudo + // :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5), + // but not by others (comment: 8; processing instruction: 7; etc.) + // nodeType < 6 works because attributes (2) do not appear as children + for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { + if ( elem.nodeType < 6 ) { + return false; + } + } + return true; + }, + + parent: function( elem ) { + return !Expr.pseudos.empty( elem ); + }, + + // Element/input types + header: function( elem ) { + return rheader.test( elem.nodeName ); + }, + + input: function( elem ) { + return rinputs.test( elem.nodeName ); + }, + + button: function( elem ) { + return nodeName( elem, "input" ) && elem.type === "button" || + nodeName( elem, "button" ); + }, + + text: function( elem ) { + var attr; + return nodeName( elem, "input" ) && elem.type === "text" && + + // Support: IE <10 only + // New HTML5 attribute values (e.g., "search") appear + // with elem.type === "text" + ( ( attr = elem.getAttribute( "type" ) ) == null || + attr.toLowerCase() === "text" ); + }, + + // Position-in-collection + first: createPositionalPseudo( function() { + return [ 0 ]; + } ), + + last: createPositionalPseudo( function( _matchIndexes, length ) { + return [ length - 1 ]; + } ), + + eq: createPositionalPseudo( function( _matchIndexes, length, argument ) { + return [ argument < 0 ? argument + length : argument ]; + } ), + + even: createPositionalPseudo( function( matchIndexes, length ) { + var i = 0; + for ( ; i < length; i += 2 ) { + matchIndexes.push( i ); + } + return matchIndexes; + } ), + + odd: createPositionalPseudo( function( matchIndexes, length ) { + var i = 1; + for ( ; i < length; i += 2 ) { + matchIndexes.push( i ); + } + return matchIndexes; + } ), + + lt: createPositionalPseudo( function( matchIndexes, length, argument ) { + var i; + + if ( argument < 0 ) { + i = argument + length; + } else if ( argument > length ) { + i = length; + } else { + i = argument; + } + + for ( ; --i >= 0; ) { + matchIndexes.push( i ); + } + return matchIndexes; + } ), + + gt: createPositionalPseudo( function( matchIndexes, length, argument ) { + var i = argument < 0 ? argument + length : argument; + for ( ; ++i < length; ) { + matchIndexes.push( i ); + } + return matchIndexes; + } ) + } +}; + +Expr.pseudos.nth = Expr.pseudos.eq; + +// Add button/input type pseudos +for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) { + Expr.pseudos[ i ] = createInputPseudo( i ); +} +for ( i in { submit: true, reset: true } ) { + Expr.pseudos[ i ] = createButtonPseudo( i ); +} + +// Easy API for creating new setFilters +function setFilters() {} +setFilters.prototype = Expr.filters = Expr.pseudos; +Expr.setFilters = new setFilters(); + +function tokenize( selector, parseOnly ) { + var matched, match, tokens, type, + soFar, groups, preFilters, + cached = tokenCache[ selector + " " ]; + + if ( cached ) { + return parseOnly ? 0 : cached.slice( 0 ); + } + + soFar = selector; + groups = []; + preFilters = Expr.preFilter; + + while ( soFar ) { + + // Comma and first run + if ( !matched || ( match = rcomma.exec( soFar ) ) ) { + if ( match ) { + + // Don't consume trailing commas as valid + soFar = soFar.slice( match[ 0 ].length ) || soFar; + } + groups.push( ( tokens = [] ) ); + } + + matched = false; + + // Combinators + if ( ( match = rleadingCombinator.exec( soFar ) ) ) { + matched = match.shift(); + tokens.push( { + value: matched, + + // Cast descendant combinators to space + type: match[ 0 ].replace( rtrimCSS, " " ) + } ); + soFar = soFar.slice( matched.length ); + } + + // Filters + for ( type in Expr.filter ) { + if ( ( match = matchExpr[ type ].exec( soFar ) ) && ( !preFilters[ type ] || + ( match = preFilters[ type ]( match ) ) ) ) { + matched = match.shift(); + tokens.push( { + value: matched, + type: type, + matches: match + } ); + soFar = soFar.slice( matched.length ); + } + } + + if ( !matched ) { + break; + } + } + + // Return the length of the invalid excess + // if we're just parsing + // Otherwise, throw an error or return tokens + if ( parseOnly ) { + return soFar.length; + } + + return soFar ? + find.error( selector ) : + + // Cache the tokens + tokenCache( selector, groups ).slice( 0 ); +} + +function toSelector( tokens ) { + var i = 0, + len = tokens.length, + selector = ""; + for ( ; i < len; i++ ) { + selector += tokens[ i ].value; + } + return selector; +} + +function addCombinator( matcher, combinator, base ) { + var dir = combinator.dir, + skip = combinator.next, + key = skip || dir, + checkNonElements = base && key === "parentNode", + doneName = done++; + + return combinator.first ? + + // Check against closest ancestor/preceding element + function( elem, context, xml ) { + while ( ( elem = elem[ dir ] ) ) { + if ( elem.nodeType === 1 || checkNonElements ) { + return matcher( elem, context, xml ); + } + } + return false; + } : + + // Check against all ancestor/preceding elements + function( elem, context, xml ) { + var oldCache, outerCache, + newCache = [ dirruns, doneName ]; + + // We can't set arbitrary data on XML nodes, so they don't benefit from combinator caching + if ( xml ) { + while ( ( elem = elem[ dir ] ) ) { + if ( elem.nodeType === 1 || checkNonElements ) { + if ( matcher( elem, context, xml ) ) { + return true; + } + } + } + } else { + while ( ( elem = elem[ dir ] ) ) { + if ( elem.nodeType === 1 || checkNonElements ) { + outerCache = elem[ expando ] || ( elem[ expando ] = {} ); + + if ( skip && nodeName( elem, skip ) ) { + elem = elem[ dir ] || elem; + } else if ( ( oldCache = outerCache[ key ] ) && + oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) { + + // Assign to newCache so results back-propagate to previous elements + return ( newCache[ 2 ] = oldCache[ 2 ] ); + } else { + + // Reuse newcache so results back-propagate to previous elements + outerCache[ key ] = newCache; + + // A match means we're done; a fail means we have to keep checking + if ( ( newCache[ 2 ] = matcher( elem, context, xml ) ) ) { + return true; + } + } + } + } + } + return false; + }; +} + +function elementMatcher( matchers ) { + return matchers.length > 1 ? + function( elem, context, xml ) { + var i = matchers.length; + while ( i-- ) { + if ( !matchers[ i ]( elem, context, xml ) ) { + return false; + } + } + return true; + } : + matchers[ 0 ]; +} + +function multipleContexts( selector, contexts, results ) { + var i = 0, + len = contexts.length; + for ( ; i < len; i++ ) { + find( selector, contexts[ i ], results ); + } + return results; +} + +function condense( unmatched, map, filter, context, xml ) { + var elem, + newUnmatched = [], + i = 0, + len = unmatched.length, + mapped = map != null; + + for ( ; i < len; i++ ) { + if ( ( elem = unmatched[ i ] ) ) { + if ( !filter || filter( elem, context, xml ) ) { + newUnmatched.push( elem ); + if ( mapped ) { + map.push( i ); + } + } + } + } + + return newUnmatched; +} + +function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { + if ( postFilter && !postFilter[ expando ] ) { + postFilter = setMatcher( postFilter ); + } + if ( postFinder && !postFinder[ expando ] ) { + postFinder = setMatcher( postFinder, postSelector ); + } + return markFunction( function( seed, results, context, xml ) { + var temp, i, elem, matcherOut, + preMap = [], + postMap = [], + preexisting = results.length, + + // Get initial elements from seed or context + elems = seed || + multipleContexts( selector || "*", + context.nodeType ? [ context ] : context, [] ), + + // Prefilter to get matcher input, preserving a map for seed-results synchronization + matcherIn = preFilter && ( seed || !selector ) ? + condense( elems, preMap, preFilter, context, xml ) : + elems; + + if ( matcher ) { + + // If we have a postFinder, or filtered seed, or non-seed postFilter + // or preexisting results, + matcherOut = postFinder || ( seed ? preFilter : preexisting || postFilter ) ? + + // ...intermediate processing is necessary + [] : + + // ...otherwise use results directly + results; + + // Find primary matches + matcher( matcherIn, matcherOut, context, xml ); + } else { + matcherOut = matcherIn; + } + + // Apply postFilter + if ( postFilter ) { + temp = condense( matcherOut, postMap ); + postFilter( temp, [], context, xml ); + + // Un-match failing elements by moving them back to matcherIn + i = temp.length; + while ( i-- ) { + if ( ( elem = temp[ i ] ) ) { + matcherOut[ postMap[ i ] ] = !( matcherIn[ postMap[ i ] ] = elem ); + } + } + } + + if ( seed ) { + if ( postFinder || preFilter ) { + if ( postFinder ) { + + // Get the final matcherOut by condensing this intermediate into postFinder contexts + temp = []; + i = matcherOut.length; + while ( i-- ) { + if ( ( elem = matcherOut[ i ] ) ) { + + // Restore matcherIn since elem is not yet a final match + temp.push( ( matcherIn[ i ] = elem ) ); + } + } + postFinder( null, ( matcherOut = [] ), temp, xml ); + } + + // Move matched elements from seed to results to keep them synchronized + i = matcherOut.length; + while ( i-- ) { + if ( ( elem = matcherOut[ i ] ) && + ( temp = postFinder ? indexOf.call( seed, elem ) : preMap[ i ] ) > -1 ) { + + seed[ temp ] = !( results[ temp ] = elem ); + } + } + } + + // Add elements to results, through postFinder if defined + } else { + matcherOut = condense( + matcherOut === results ? + matcherOut.splice( preexisting, matcherOut.length ) : + matcherOut + ); + if ( postFinder ) { + postFinder( null, results, matcherOut, xml ); + } else { + push.apply( results, matcherOut ); + } + } + } ); +} + +function matcherFromTokens( tokens ) { + var checkContext, matcher, j, + len = tokens.length, + leadingRelative = Expr.relative[ tokens[ 0 ].type ], + implicitRelative = leadingRelative || Expr.relative[ " " ], + i = leadingRelative ? 1 : 0, + + // The foundational matcher ensures that elements are reachable from top-level context(s) + matchContext = addCombinator( function( elem ) { + return elem === checkContext; + }, implicitRelative, true ), + matchAnyContext = addCombinator( function( elem ) { + return indexOf.call( checkContext, elem ) > -1; + }, implicitRelative, true ), + matchers = [ function( elem, context, xml ) { + + // Support: IE 11+, Edge 17 - 18+ + // IE/Edge sometimes throw a "Permission denied" error when strict-comparing + // two documents; shallow comparisons work. + // eslint-disable-next-line eqeqeq + var ret = ( !leadingRelative && ( xml || context != outermostContext ) ) || ( + ( checkContext = context ).nodeType ? + matchContext( elem, context, xml ) : + matchAnyContext( elem, context, xml ) ); + + // Avoid hanging onto element + // (see https://github.com/jquery/sizzle/issues/299) + checkContext = null; + return ret; + } ]; + + for ( ; i < len; i++ ) { + if ( ( matcher = Expr.relative[ tokens[ i ].type ] ) ) { + matchers = [ addCombinator( elementMatcher( matchers ), matcher ) ]; + } else { + matcher = Expr.filter[ tokens[ i ].type ].apply( null, tokens[ i ].matches ); + + // Return special upon seeing a positional matcher + if ( matcher[ expando ] ) { + + // Find the next relative operator (if any) for proper handling + j = ++i; + for ( ; j < len; j++ ) { + if ( Expr.relative[ tokens[ j ].type ] ) { + break; + } + } + return setMatcher( + i > 1 && elementMatcher( matchers ), + i > 1 && toSelector( + + // If the preceding token was a descendant combinator, insert an implicit any-element `*` + tokens.slice( 0, i - 1 ) + .concat( { value: tokens[ i - 2 ].type === " " ? "*" : "" } ) + ).replace( rtrimCSS, "$1" ), + matcher, + i < j && matcherFromTokens( tokens.slice( i, j ) ), + j < len && matcherFromTokens( ( tokens = tokens.slice( j ) ) ), + j < len && toSelector( tokens ) + ); + } + matchers.push( matcher ); + } + } + + return elementMatcher( matchers ); +} + +function matcherFromGroupMatchers( elementMatchers, setMatchers ) { + var bySet = setMatchers.length > 0, + byElement = elementMatchers.length > 0, + superMatcher = function( seed, context, xml, results, outermost ) { + var elem, j, matcher, + matchedCount = 0, + i = "0", + unmatched = seed && [], + setMatched = [], + contextBackup = outermostContext, + + // We must always have either seed elements or outermost context + elems = seed || byElement && Expr.find.TAG( "*", outermost ), + + // Use integer dirruns iff this is the outermost matcher + dirrunsUnique = ( dirruns += contextBackup == null ? 1 : Math.random() || 0.1 ), + len = elems.length; + + if ( outermost ) { + + // Support: IE 11+, Edge 17 - 18+ + // IE/Edge sometimes throw a "Permission denied" error when strict-comparing + // two documents; shallow comparisons work. + // eslint-disable-next-line eqeqeq + outermostContext = context == document || context || outermost; + } + + // Add elements passing elementMatchers directly to results + // Support: iOS <=7 - 9 only + // Tolerate NodeList properties (IE: "length"; Safari: ) matching + // elements by id. (see trac-14142) + for ( ; i !== len && ( elem = elems[ i ] ) != null; i++ ) { + if ( byElement && elem ) { + j = 0; + + // Support: IE 11+, Edge 17 - 18+ + // IE/Edge sometimes throw a "Permission denied" error when strict-comparing + // two documents; shallow comparisons work. + // eslint-disable-next-line eqeqeq + if ( !context && elem.ownerDocument != document ) { + setDocument( elem ); + xml = !documentIsHTML; + } + while ( ( matcher = elementMatchers[ j++ ] ) ) { + if ( matcher( elem, context || document, xml ) ) { + push.call( results, elem ); + break; + } + } + if ( outermost ) { + dirruns = dirrunsUnique; + } + } + + // Track unmatched elements for set filters + if ( bySet ) { + + // They will have gone through all possible matchers + if ( ( elem = !matcher && elem ) ) { + matchedCount--; + } + + // Lengthen the array for every element, matched or not + if ( seed ) { + unmatched.push( elem ); + } + } + } + + // `i` is now the count of elements visited above, and adding it to `matchedCount` + // makes the latter nonnegative. + matchedCount += i; + + // Apply set filters to unmatched elements + // NOTE: This can be skipped if there are no unmatched elements (i.e., `matchedCount` + // equals `i`), unless we didn't visit _any_ elements in the above loop because we have + // no element matchers and no seed. + // Incrementing an initially-string "0" `i` allows `i` to remain a string only in that + // case, which will result in a "00" `matchedCount` that differs from `i` but is also + // numerically zero. + if ( bySet && i !== matchedCount ) { + j = 0; + while ( ( matcher = setMatchers[ j++ ] ) ) { + matcher( unmatched, setMatched, context, xml ); + } + + if ( seed ) { + + // Reintegrate element matches to eliminate the need for sorting + if ( matchedCount > 0 ) { + while ( i-- ) { + if ( !( unmatched[ i ] || setMatched[ i ] ) ) { + setMatched[ i ] = pop.call( results ); + } + } + } + + // Discard index placeholder values to get only actual matches + setMatched = condense( setMatched ); + } + + // Add matches to results + push.apply( results, setMatched ); + + // Seedless set matches succeeding multiple successful matchers stipulate sorting + if ( outermost && !seed && setMatched.length > 0 && + ( matchedCount + setMatchers.length ) > 1 ) { + + jQuery.uniqueSort( results ); + } + } + + // Override manipulation of globals by nested matchers + if ( outermost ) { + dirruns = dirrunsUnique; + outermostContext = contextBackup; + } + + return unmatched; + }; + + return bySet ? + markFunction( superMatcher ) : + superMatcher; +} + +function compile( selector, match /* Internal Use Only */ ) { + var i, + setMatchers = [], + elementMatchers = [], + cached = compilerCache[ selector + " " ]; + + if ( !cached ) { + + // Generate a function of recursive functions that can be used to check each element + if ( !match ) { + match = tokenize( selector ); + } + i = match.length; + while ( i-- ) { + cached = matcherFromTokens( match[ i ] ); + if ( cached[ expando ] ) { + setMatchers.push( cached ); + } else { + elementMatchers.push( cached ); + } + } + + // Cache the compiled function + cached = compilerCache( selector, + matcherFromGroupMatchers( elementMatchers, setMatchers ) ); + + // Save selector and tokenization + cached.selector = selector; + } + return cached; +} + +/** + * A low-level selection function that works with jQuery's compiled + * selector functions + * @param {String|Function} selector A selector or a pre-compiled + * selector function built with jQuery selector compile + * @param {Element} context + * @param {Array} [results] + * @param {Array} [seed] A set of elements to match against + */ +function select( selector, context, results, seed ) { + var i, tokens, token, type, find, + compiled = typeof selector === "function" && selector, + match = !seed && tokenize( ( selector = compiled.selector || selector ) ); + + results = results || []; + + // Try to minimize operations if there is only one selector in the list and no seed + // (the latter of which guarantees us context) + if ( match.length === 1 ) { + + // Reduce context if the leading compound selector is an ID + tokens = match[ 0 ] = match[ 0 ].slice( 0 ); + if ( tokens.length > 2 && ( token = tokens[ 0 ] ).type === "ID" && + context.nodeType === 9 && documentIsHTML && Expr.relative[ tokens[ 1 ].type ] ) { + + context = ( Expr.find.ID( + token.matches[ 0 ].replace( runescape, funescape ), + context + ) || [] )[ 0 ]; + if ( !context ) { + return results; + + // Precompiled matchers will still verify ancestry, so step up a level + } else if ( compiled ) { + context = context.parentNode; + } + + selector = selector.slice( tokens.shift().value.length ); + } + + // Fetch a seed set for right-to-left matching + i = matchExpr.needsContext.test( selector ) ? 0 : tokens.length; + while ( i-- ) { + token = tokens[ i ]; + + // Abort if we hit a combinator + if ( Expr.relative[ ( type = token.type ) ] ) { + break; + } + if ( ( find = Expr.find[ type ] ) ) { + + // Search, expanding context for leading sibling combinators + if ( ( seed = find( + token.matches[ 0 ].replace( runescape, funescape ), + rsibling.test( tokens[ 0 ].type ) && + testContext( context.parentNode ) || context + ) ) ) { + + // If seed is empty or no tokens remain, we can return early + tokens.splice( i, 1 ); + selector = seed.length && toSelector( tokens ); + if ( !selector ) { + push.apply( results, seed ); + return results; + } + + break; + } + } + } + } + + // Compile and execute a filtering function if one is not provided + // Provide `match` to avoid retokenization if we modified the selector above + ( compiled || compile( selector, match ) )( + seed, + context, + !documentIsHTML, + results, + !context || rsibling.test( selector ) && testContext( context.parentNode ) || context + ); + return results; +} + +// One-time assignments + +// Support: Android <=4.0 - 4.1+ +// Sort stability +support.sortStable = expando.split( "" ).sort( sortOrder ).join( "" ) === expando; + +// Initialize against the default document +setDocument(); + +// Support: Android <=4.0 - 4.1+ +// Detached nodes confoundingly follow *each other* +support.sortDetached = assert( function( el ) { + + // Should return 1, but returns 4 (following) + return el.compareDocumentPosition( document.createElement( "fieldset" ) ) & 1; +} ); + +jQuery.find = find; + +// Deprecated +jQuery.expr[ ":" ] = jQuery.expr.pseudos; +jQuery.unique = jQuery.uniqueSort; + +// These have always been private, but they used to be documented as part of +// Sizzle so let's maintain them for now for backwards compatibility purposes. +find.compile = compile; +find.select = select; +find.setDocument = setDocument; +find.tokenize = tokenize; + +find.escape = jQuery.escapeSelector; +find.getText = jQuery.text; +find.isXML = jQuery.isXMLDoc; +find.selectors = jQuery.expr; +find.support = jQuery.support; +find.uniqueSort = jQuery.uniqueSort; + + /* eslint-enable */ + +} )(); + + +var dir = function( elem, dir, until ) { + var matched = [], + truncate = until !== undefined; + + while ( ( elem = elem[ dir ] ) && elem.nodeType !== 9 ) { + if ( elem.nodeType === 1 ) { + if ( truncate && jQuery( elem ).is( until ) ) { + break; + } + matched.push( elem ); + } + } + return matched; +}; + + +var siblings = function( n, elem ) { + var matched = []; + + for ( ; n; n = n.nextSibling ) { + if ( n.nodeType === 1 && n !== elem ) { + matched.push( n ); + } + } + + return matched; +}; + + +var rneedsContext = jQuery.expr.match.needsContext; + +var rsingleTag = ( /^<([a-z][^\/\0>:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i ); + + + +// Implement the identical functionality for filter and not +function winnow( elements, qualifier, not ) { + if ( isFunction( qualifier ) ) { + return jQuery.grep( elements, function( elem, i ) { + return !!qualifier.call( elem, i, elem ) !== not; + } ); + } + + // Single element + if ( qualifier.nodeType ) { + return jQuery.grep( elements, function( elem ) { + return ( elem === qualifier ) !== not; + } ); + } + + // Arraylike of elements (jQuery, arguments, Array) + if ( typeof qualifier !== "string" ) { + return jQuery.grep( elements, function( elem ) { + return ( indexOf.call( qualifier, elem ) > -1 ) !== not; + } ); + } + + // Filtered directly for both simple and complex selectors + return jQuery.filter( qualifier, elements, not ); +} + +jQuery.filter = function( expr, elems, not ) { + var elem = elems[ 0 ]; + + if ( not ) { + expr = ":not(" + expr + ")"; + } + + if ( elems.length === 1 && elem.nodeType === 1 ) { + return jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : []; + } + + return jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) { + return elem.nodeType === 1; + } ) ); +}; + +jQuery.fn.extend( { + find: function( selector ) { + var i, ret, + len = this.length, + self = this; + + if ( typeof selector !== "string" ) { + return this.pushStack( jQuery( selector ).filter( function() { + for ( i = 0; i < len; i++ ) { + if ( jQuery.contains( self[ i ], this ) ) { + return true; + } + } + } ) ); + } + + ret = this.pushStack( [] ); + + for ( i = 0; i < len; i++ ) { + jQuery.find( selector, self[ i ], ret ); + } + + return len > 1 ? jQuery.uniqueSort( ret ) : ret; + }, + filter: function( selector ) { + return this.pushStack( winnow( this, selector || [], false ) ); + }, + not: function( selector ) { + return this.pushStack( winnow( this, selector || [], true ) ); + }, + is: function( selector ) { + return !!winnow( + this, + + // If this is a positional/relative selector, check membership in the returned set + // so $("p:first").is("p:last") won't return true for a doc with two "p". + typeof selector === "string" && rneedsContext.test( selector ) ? + jQuery( selector ) : + selector || [], + false + ).length; + } +} ); + + +// Initialize a jQuery object + + +// A central reference to the root jQuery(document) +var rootjQuery, + + // A simple way to check for HTML strings + // Prioritize #id over to avoid XSS via location.hash (trac-9521) + // Strict HTML recognition (trac-11290: must start with <) + // Shortcut simple #id case for speed + rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]+))$/, + + init = jQuery.fn.init = function( selector, context, root ) { + var match, elem; + + // HANDLE: $(""), $(null), $(undefined), $(false) + if ( !selector ) { + return this; + } + + // Method init() accepts an alternate rootjQuery + // so migrate can support jQuery.sub (gh-2101) + root = root || rootjQuery; + + // Handle HTML strings + if ( typeof selector === "string" ) { + if ( selector[ 0 ] === "<" && + selector[ selector.length - 1 ] === ">" && + selector.length >= 3 ) { + + // Assume that strings that start and end with <> are HTML and skip the regex check + match = [ null, selector, null ]; + + } else { + match = rquickExpr.exec( selector ); + } + + // Match html or make sure no context is specified for #id + if ( match && ( match[ 1 ] || !context ) ) { + + // HANDLE: $(html) -> $(array) + if ( match[ 1 ] ) { + context = context instanceof jQuery ? context[ 0 ] : context; + + // Option to run scripts is true for back-compat + // Intentionally let the error be thrown if parseHTML is not present + jQuery.merge( this, jQuery.parseHTML( + match[ 1 ], + context && context.nodeType ? context.ownerDocument || context : document, + true + ) ); + + // HANDLE: $(html, props) + if ( rsingleTag.test( match[ 1 ] ) && jQuery.isPlainObject( context ) ) { + for ( match in context ) { + + // Properties of context are called as methods if possible + if ( isFunction( this[ match ] ) ) { + this[ match ]( context[ match ] ); + + // ...and otherwise set as attributes + } else { + this.attr( match, context[ match ] ); + } + } + } + + return this; + + // HANDLE: $(#id) + } else { + elem = document.getElementById( match[ 2 ] ); + + if ( elem ) { + + // Inject the element directly into the jQuery object + this[ 0 ] = elem; + this.length = 1; + } + return this; + } + + // HANDLE: $(expr, $(...)) + } else if ( !context || context.jquery ) { + return ( context || root ).find( selector ); + + // HANDLE: $(expr, context) + // (which is just equivalent to: $(context).find(expr) + } else { + return this.constructor( context ).find( selector ); + } + + // HANDLE: $(DOMElement) + } else if ( selector.nodeType ) { + this[ 0 ] = selector; + this.length = 1; + return this; + + // HANDLE: $(function) + // Shortcut for document ready + } else if ( isFunction( selector ) ) { + return root.ready !== undefined ? + root.ready( selector ) : + + // Execute immediately if ready is not present + selector( jQuery ); + } + + return jQuery.makeArray( selector, this ); + }; + +// Give the init function the jQuery prototype for later instantiation +init.prototype = jQuery.fn; + +// Initialize central reference +rootjQuery = jQuery( document ); + + +var rparentsprev = /^(?:parents|prev(?:Until|All))/, + + // Methods guaranteed to produce a unique set when starting from a unique set + guaranteedUnique = { + children: true, + contents: true, + next: true, + prev: true + }; + +jQuery.fn.extend( { + has: function( target ) { + var targets = jQuery( target, this ), + l = targets.length; + + return this.filter( function() { + var i = 0; + for ( ; i < l; i++ ) { + if ( jQuery.contains( this, targets[ i ] ) ) { + return true; + } + } + } ); + }, + + closest: function( selectors, context ) { + var cur, + i = 0, + l = this.length, + matched = [], + targets = typeof selectors !== "string" && jQuery( selectors ); + + // Positional selectors never match, since there's no _selection_ context + if ( !rneedsContext.test( selectors ) ) { + for ( ; i < l; i++ ) { + for ( cur = this[ i ]; cur && cur !== context; cur = cur.parentNode ) { + + // Always skip document fragments + if ( cur.nodeType < 11 && ( targets ? + targets.index( cur ) > -1 : + + // Don't pass non-elements to jQuery#find + cur.nodeType === 1 && + jQuery.find.matchesSelector( cur, selectors ) ) ) { + + matched.push( cur ); + break; + } + } + } + } + + return this.pushStack( matched.length > 1 ? jQuery.uniqueSort( matched ) : matched ); + }, + + // Determine the position of an element within the set + index: function( elem ) { + + // No argument, return index in parent + if ( !elem ) { + return ( this[ 0 ] && this[ 0 ].parentNode ) ? this.first().prevAll().length : -1; + } + + // Index in selector + if ( typeof elem === "string" ) { + return indexOf.call( jQuery( elem ), this[ 0 ] ); + } + + // Locate the position of the desired element + return indexOf.call( this, + + // If it receives a jQuery object, the first element is used + elem.jquery ? elem[ 0 ] : elem + ); + }, + + add: function( selector, context ) { + return this.pushStack( + jQuery.uniqueSort( + jQuery.merge( this.get(), jQuery( selector, context ) ) + ) + ); + }, + + addBack: function( selector ) { + return this.add( selector == null ? + this.prevObject : this.prevObject.filter( selector ) + ); + } +} ); + +function sibling( cur, dir ) { + while ( ( cur = cur[ dir ] ) && cur.nodeType !== 1 ) {} + return cur; +} + +jQuery.each( { + parent: function( elem ) { + var parent = elem.parentNode; + return parent && parent.nodeType !== 11 ? parent : null; + }, + parents: function( elem ) { + return dir( elem, "parentNode" ); + }, + parentsUntil: function( elem, _i, until ) { + return dir( elem, "parentNode", until ); + }, + next: function( elem ) { + return sibling( elem, "nextSibling" ); + }, + prev: function( elem ) { + return sibling( elem, "previousSibling" ); + }, + nextAll: function( elem ) { + return dir( elem, "nextSibling" ); + }, + prevAll: function( elem ) { + return dir( elem, "previousSibling" ); + }, + nextUntil: function( elem, _i, until ) { + return dir( elem, "nextSibling", until ); + }, + prevUntil: function( elem, _i, until ) { + return dir( elem, "previousSibling", until ); + }, + siblings: function( elem ) { + return siblings( ( elem.parentNode || {} ).firstChild, elem ); + }, + children: function( elem ) { + return siblings( elem.firstChild ); + }, + contents: function( elem ) { + if ( elem.contentDocument != null && + + // Support: IE 11+ + // elements with no `data` attribute has an object + // `contentDocument` with a `null` prototype. + getProto( elem.contentDocument ) ) { + + return elem.contentDocument; + } + + // Support: IE 9 - 11 only, iOS 7 only, Android Browser <=4.3 only + // Treat the template element as a regular one in browsers that + // don't support it. + if ( nodeName( elem, "template" ) ) { + elem = elem.content || elem; + } + + return jQuery.merge( [], elem.childNodes ); + } +}, function( name, fn ) { + jQuery.fn[ name ] = function( until, selector ) { + var matched = jQuery.map( this, fn, until ); + + if ( name.slice( -5 ) !== "Until" ) { + selector = until; + } + + if ( selector && typeof selector === "string" ) { + matched = jQuery.filter( selector, matched ); + } + + if ( this.length > 1 ) { + + // Remove duplicates + if ( !guaranteedUnique[ name ] ) { + jQuery.uniqueSort( matched ); + } + + // Reverse order for parents* and prev-derivatives + if ( rparentsprev.test( name ) ) { + matched.reverse(); + } + } + + return this.pushStack( matched ); + }; +} ); +var rnothtmlwhite = ( /[^\x20\t\r\n\f]+/g ); + + + +// Convert String-formatted options into Object-formatted ones +function createOptions( options ) { + var object = {}; + jQuery.each( options.match( rnothtmlwhite ) || [], function( _, flag ) { + object[ flag ] = true; + } ); + return object; +} + +/* + * Create a callback list using the following parameters: + * + * options: an optional list of space-separated options that will change how + * the callback list behaves or a more traditional option object + * + * By default a callback list will act like an event callback list and can be + * "fired" multiple times. + * + * Possible options: + * + * once: will ensure the callback list can only be fired once (like a Deferred) + * + * memory: will keep track of previous values and will call any callback added + * after the list has been fired right away with the latest "memorized" + * values (like a Deferred) + * + * unique: will ensure a callback can only be added once (no duplicate in the list) + * + * stopOnFalse: interrupt callings when a callback returns false + * + */ +jQuery.Callbacks = function( options ) { + + // Convert options from String-formatted to Object-formatted if needed + // (we check in cache first) + options = typeof options === "string" ? + createOptions( options ) : + jQuery.extend( {}, options ); + + var // Flag to know if list is currently firing + firing, + + // Last fire value for non-forgettable lists + memory, + + // Flag to know if list was already fired + fired, + + // Flag to prevent firing + locked, + + // Actual callback list + list = [], + + // Queue of execution data for repeatable lists + queue = [], + + // Index of currently firing callback (modified by add/remove as needed) + firingIndex = -1, + + // Fire callbacks + fire = function() { + + // Enforce single-firing + locked = locked || options.once; + + // Execute callbacks for all pending executions, + // respecting firingIndex overrides and runtime changes + fired = firing = true; + for ( ; queue.length; firingIndex = -1 ) { + memory = queue.shift(); + while ( ++firingIndex < list.length ) { + + // Run callback and check for early termination + if ( list[ firingIndex ].apply( memory[ 0 ], memory[ 1 ] ) === false && + options.stopOnFalse ) { + + // Jump to end and forget the data so .add doesn't re-fire + firingIndex = list.length; + memory = false; + } + } + } + + // Forget the data if we're done with it + if ( !options.memory ) { + memory = false; + } + + firing = false; + + // Clean up if we're done firing for good + if ( locked ) { + + // Keep an empty list if we have data for future add calls + if ( memory ) { + list = []; + + // Otherwise, this object is spent + } else { + list = ""; + } + } + }, + + // Actual Callbacks object + self = { + + // Add a callback or a collection of callbacks to the list + add: function() { + if ( list ) { + + // If we have memory from a past run, we should fire after adding + if ( memory && !firing ) { + firingIndex = list.length - 1; + queue.push( memory ); + } + + ( function add( args ) { + jQuery.each( args, function( _, arg ) { + if ( isFunction( arg ) ) { + if ( !options.unique || !self.has( arg ) ) { + list.push( arg ); + } + } else if ( arg && arg.length && toType( arg ) !== "string" ) { + + // Inspect recursively + add( arg ); + } + } ); + } )( arguments ); + + if ( memory && !firing ) { + fire(); + } + } + return this; + }, + + // Remove a callback from the list + remove: function() { + jQuery.each( arguments, function( _, arg ) { + var index; + while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { + list.splice( index, 1 ); + + // Handle firing indexes + if ( index <= firingIndex ) { + firingIndex--; + } + } + } ); + return this; + }, + + // Check if a given callback is in the list. + // If no argument is given, return whether or not list has callbacks attached. + has: function( fn ) { + return fn ? + jQuery.inArray( fn, list ) > -1 : + list.length > 0; + }, + + // Remove all callbacks from the list + empty: function() { + if ( list ) { + list = []; + } + return this; + }, + + // Disable .fire and .add + // Abort any current/pending executions + // Clear all callbacks and values + disable: function() { + locked = queue = []; + list = memory = ""; + return this; + }, + disabled: function() { + return !list; + }, + + // Disable .fire + // Also disable .add unless we have memory (since it would have no effect) + // Abort any pending executions + lock: function() { + locked = queue = []; + if ( !memory && !firing ) { + list = memory = ""; + } + return this; + }, + locked: function() { + return !!locked; + }, + + // Call all callbacks with the given context and arguments + fireWith: function( context, args ) { + if ( !locked ) { + args = args || []; + args = [ context, args.slice ? args.slice() : args ]; + queue.push( args ); + if ( !firing ) { + fire(); + } + } + return this; + }, + + // Call all the callbacks with the given arguments + fire: function() { + self.fireWith( this, arguments ); + return this; + }, + + // To know if the callbacks have already been called at least once + fired: function() { + return !!fired; + } + }; + + return self; +}; + + +function Identity( v ) { + return v; +} +function Thrower( ex ) { + throw ex; +} + +function adoptValue( value, resolve, reject, noValue ) { + var method; + + try { + + // Check for promise aspect first to privilege synchronous behavior + if ( value && isFunction( ( method = value.promise ) ) ) { + method.call( value ).done( resolve ).fail( reject ); + + // Other thenables + } else if ( value && isFunction( ( method = value.then ) ) ) { + method.call( value, resolve, reject ); + + // Other non-thenables + } else { + + // Control `resolve` arguments by letting Array#slice cast boolean `noValue` to integer: + // * false: [ value ].slice( 0 ) => resolve( value ) + // * true: [ value ].slice( 1 ) => resolve() + resolve.apply( undefined, [ value ].slice( noValue ) ); + } + + // For Promises/A+, convert exceptions into rejections + // Since jQuery.when doesn't unwrap thenables, we can skip the extra checks appearing in + // Deferred#then to conditionally suppress rejection. + } catch ( value ) { + + // Support: Android 4.0 only + // Strict mode functions invoked without .call/.apply get global-object context + reject.apply( undefined, [ value ] ); + } +} + +jQuery.extend( { + + Deferred: function( func ) { + var tuples = [ + + // action, add listener, callbacks, + // ... .then handlers, argument index, [final state] + [ "notify", "progress", jQuery.Callbacks( "memory" ), + jQuery.Callbacks( "memory" ), 2 ], + [ "resolve", "done", jQuery.Callbacks( "once memory" ), + jQuery.Callbacks( "once memory" ), 0, "resolved" ], + [ "reject", "fail", jQuery.Callbacks( "once memory" ), + jQuery.Callbacks( "once memory" ), 1, "rejected" ] + ], + state = "pending", + promise = { + state: function() { + return state; + }, + always: function() { + deferred.done( arguments ).fail( arguments ); + return this; + }, + "catch": function( fn ) { + return promise.then( null, fn ); + }, + + // Keep pipe for back-compat + pipe: function( /* fnDone, fnFail, fnProgress */ ) { + var fns = arguments; + + return jQuery.Deferred( function( newDefer ) { + jQuery.each( tuples, function( _i, tuple ) { + + // Map tuples (progress, done, fail) to arguments (done, fail, progress) + var fn = isFunction( fns[ tuple[ 4 ] ] ) && fns[ tuple[ 4 ] ]; + + // deferred.progress(function() { bind to newDefer or newDefer.notify }) + // deferred.done(function() { bind to newDefer or newDefer.resolve }) + // deferred.fail(function() { bind to newDefer or newDefer.reject }) + deferred[ tuple[ 1 ] ]( function() { + var returned = fn && fn.apply( this, arguments ); + if ( returned && isFunction( returned.promise ) ) { + returned.promise() + .progress( newDefer.notify ) + .done( newDefer.resolve ) + .fail( newDefer.reject ); + } else { + newDefer[ tuple[ 0 ] + "With" ]( + this, + fn ? [ returned ] : arguments + ); + } + } ); + } ); + fns = null; + } ).promise(); + }, + then: function( onFulfilled, onRejected, onProgress ) { + var maxDepth = 0; + function resolve( depth, deferred, handler, special ) { + return function() { + var that = this, + args = arguments, + mightThrow = function() { + var returned, then; + + // Support: Promises/A+ section 2.3.3.3.3 + // https://promisesaplus.com/#point-59 + // Ignore double-resolution attempts + if ( depth < maxDepth ) { + return; + } + + returned = handler.apply( that, args ); + + // Support: Promises/A+ section 2.3.1 + // https://promisesaplus.com/#point-48 + if ( returned === deferred.promise() ) { + throw new TypeError( "Thenable self-resolution" ); + } + + // Support: Promises/A+ sections 2.3.3.1, 3.5 + // https://promisesaplus.com/#point-54 + // https://promisesaplus.com/#point-75 + // Retrieve `then` only once + then = returned && + + // Support: Promises/A+ section 2.3.4 + // https://promisesaplus.com/#point-64 + // Only check objects and functions for thenability + ( typeof returned === "object" || + typeof returned === "function" ) && + returned.then; + + // Handle a returned thenable + if ( isFunction( then ) ) { + + // Special processors (notify) just wait for resolution + if ( special ) { + then.call( + returned, + resolve( maxDepth, deferred, Identity, special ), + resolve( maxDepth, deferred, Thrower, special ) + ); + + // Normal processors (resolve) also hook into progress + } else { + + // ...and disregard older resolution values + maxDepth++; + + then.call( + returned, + resolve( maxDepth, deferred, Identity, special ), + resolve( maxDepth, deferred, Thrower, special ), + resolve( maxDepth, deferred, Identity, + deferred.notifyWith ) + ); + } + + // Handle all other returned values + } else { + + // Only substitute handlers pass on context + // and multiple values (non-spec behavior) + if ( handler !== Identity ) { + that = undefined; + args = [ returned ]; + } + + // Process the value(s) + // Default process is resolve + ( special || deferred.resolveWith )( that, args ); + } + }, + + // Only normal processors (resolve) catch and reject exceptions + process = special ? + mightThrow : + function() { + try { + mightThrow(); + } catch ( e ) { + + if ( jQuery.Deferred.exceptionHook ) { + jQuery.Deferred.exceptionHook( e, + process.error ); + } + + // Support: Promises/A+ section 2.3.3.3.4.1 + // https://promisesaplus.com/#point-61 + // Ignore post-resolution exceptions + if ( depth + 1 >= maxDepth ) { + + // Only substitute handlers pass on context + // and multiple values (non-spec behavior) + if ( handler !== Thrower ) { + that = undefined; + args = [ e ]; + } + + deferred.rejectWith( that, args ); + } + } + }; + + // Support: Promises/A+ section 2.3.3.3.1 + // https://promisesaplus.com/#point-57 + // Re-resolve promises immediately to dodge false rejection from + // subsequent errors + if ( depth ) { + process(); + } else { + + // Call an optional hook to record the error, in case of exception + // since it's otherwise lost when execution goes async + if ( jQuery.Deferred.getErrorHook ) { + process.error = jQuery.Deferred.getErrorHook(); + + // The deprecated alias of the above. While the name suggests + // returning the stack, not an error instance, jQuery just passes + // it directly to `console.warn` so both will work; an instance + // just better cooperates with source maps. + } else if ( jQuery.Deferred.getStackHook ) { + process.error = jQuery.Deferred.getStackHook(); + } + window.setTimeout( process ); + } + }; + } + + return jQuery.Deferred( function( newDefer ) { + + // progress_handlers.add( ... ) + tuples[ 0 ][ 3 ].add( + resolve( + 0, + newDefer, + isFunction( onProgress ) ? + onProgress : + Identity, + newDefer.notifyWith + ) + ); + + // fulfilled_handlers.add( ... ) + tuples[ 1 ][ 3 ].add( + resolve( + 0, + newDefer, + isFunction( onFulfilled ) ? + onFulfilled : + Identity + ) + ); + + // rejected_handlers.add( ... ) + tuples[ 2 ][ 3 ].add( + resolve( + 0, + newDefer, + isFunction( onRejected ) ? + onRejected : + Thrower + ) + ); + } ).promise(); + }, + + // Get a promise for this deferred + // If obj is provided, the promise aspect is added to the object + promise: function( obj ) { + return obj != null ? jQuery.extend( obj, promise ) : promise; + } + }, + deferred = {}; + + // Add list-specific methods + jQuery.each( tuples, function( i, tuple ) { + var list = tuple[ 2 ], + stateString = tuple[ 5 ]; + + // promise.progress = list.add + // promise.done = list.add + // promise.fail = list.add + promise[ tuple[ 1 ] ] = list.add; + + // Handle state + if ( stateString ) { + list.add( + function() { + + // state = "resolved" (i.e., fulfilled) + // state = "rejected" + state = stateString; + }, + + // rejected_callbacks.disable + // fulfilled_callbacks.disable + tuples[ 3 - i ][ 2 ].disable, + + // rejected_handlers.disable + // fulfilled_handlers.disable + tuples[ 3 - i ][ 3 ].disable, + + // progress_callbacks.lock + tuples[ 0 ][ 2 ].lock, + + // progress_handlers.lock + tuples[ 0 ][ 3 ].lock + ); + } + + // progress_handlers.fire + // fulfilled_handlers.fire + // rejected_handlers.fire + list.add( tuple[ 3 ].fire ); + + // deferred.notify = function() { deferred.notifyWith(...) } + // deferred.resolve = function() { deferred.resolveWith(...) } + // deferred.reject = function() { deferred.rejectWith(...) } + deferred[ tuple[ 0 ] ] = function() { + deferred[ tuple[ 0 ] + "With" ]( this === deferred ? undefined : this, arguments ); + return this; + }; + + // deferred.notifyWith = list.fireWith + // deferred.resolveWith = list.fireWith + // deferred.rejectWith = list.fireWith + deferred[ tuple[ 0 ] + "With" ] = list.fireWith; + } ); + + // Make the deferred a promise + promise.promise( deferred ); + + // Call given func if any + if ( func ) { + func.call( deferred, deferred ); + } + + // All done! + return deferred; + }, + + // Deferred helper + when: function( singleValue ) { + var + + // count of uncompleted subordinates + remaining = arguments.length, + + // count of unprocessed arguments + i = remaining, + + // subordinate fulfillment data + resolveContexts = Array( i ), + resolveValues = slice.call( arguments ), + + // the primary Deferred + primary = jQuery.Deferred(), + + // subordinate callback factory + updateFunc = function( i ) { + return function( value ) { + resolveContexts[ i ] = this; + resolveValues[ i ] = arguments.length > 1 ? slice.call( arguments ) : value; + if ( !( --remaining ) ) { + primary.resolveWith( resolveContexts, resolveValues ); + } + }; + }; + + // Single- and empty arguments are adopted like Promise.resolve + if ( remaining <= 1 ) { + adoptValue( singleValue, primary.done( updateFunc( i ) ).resolve, primary.reject, + !remaining ); + + // Use .then() to unwrap secondary thenables (cf. gh-3000) + if ( primary.state() === "pending" || + isFunction( resolveValues[ i ] && resolveValues[ i ].then ) ) { + + return primary.then(); + } + } + + // Multiple arguments are aggregated like Promise.all array elements + while ( i-- ) { + adoptValue( resolveValues[ i ], updateFunc( i ), primary.reject ); + } + + return primary.promise(); + } +} ); + + +// These usually indicate a programmer mistake during development, +// warn about them ASAP rather than swallowing them by default. +var rerrorNames = /^(Eval|Internal|Range|Reference|Syntax|Type|URI)Error$/; + +// If `jQuery.Deferred.getErrorHook` is defined, `asyncError` is an error +// captured before the async barrier to get the original error cause +// which may otherwise be hidden. +jQuery.Deferred.exceptionHook = function( error, asyncError ) { + + // Support: IE 8 - 9 only + // Console exists when dev tools are open, which can happen at any time + if ( window.console && window.console.warn && error && rerrorNames.test( error.name ) ) { + window.console.warn( "jQuery.Deferred exception: " + error.message, + error.stack, asyncError ); + } +}; + + + + +jQuery.readyException = function( error ) { + window.setTimeout( function() { + throw error; + } ); +}; + + + + +// The deferred used on DOM ready +var readyList = jQuery.Deferred(); + +jQuery.fn.ready = function( fn ) { + + readyList + .then( fn ) + + // Wrap jQuery.readyException in a function so that the lookup + // happens at the time of error handling instead of callback + // registration. + .catch( function( error ) { + jQuery.readyException( error ); + } ); + + return this; +}; + +jQuery.extend( { + + // Is the DOM ready to be used? Set to true once it occurs. + isReady: false, + + // A counter to track how many items to wait for before + // the ready event fires. See trac-6781 + readyWait: 1, + + // Handle when the DOM is ready + ready: function( wait ) { + + // Abort if there are pending holds or we're already ready + if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { + return; + } + + // Remember that the DOM is ready + jQuery.isReady = true; + + // If a normal DOM Ready event fired, decrement, and wait if need be + if ( wait !== true && --jQuery.readyWait > 0 ) { + return; + } + + // If there are functions bound, to execute + readyList.resolveWith( document, [ jQuery ] ); + } +} ); + +jQuery.ready.then = readyList.then; + +// The ready event handler and self cleanup method +function completed() { + document.removeEventListener( "DOMContentLoaded", completed ); + window.removeEventListener( "load", completed ); + jQuery.ready(); +} + +// Catch cases where $(document).ready() is called +// after the browser event has already occurred. +// Support: IE <=9 - 10 only +// Older IE sometimes signals "interactive" too soon +if ( document.readyState === "complete" || + ( document.readyState !== "loading" && !document.documentElement.doScroll ) ) { + + // Handle it asynchronously to allow scripts the opportunity to delay ready + window.setTimeout( jQuery.ready ); + +} else { + + // Use the handy event callback + document.addEventListener( "DOMContentLoaded", completed ); + + // A fallback to window.onload, that will always work + window.addEventListener( "load", completed ); +} + + + + +// Multifunctional method to get and set values of a collection +// The value/s can optionally be executed if it's a function +var access = function( elems, fn, key, value, chainable, emptyGet, raw ) { + var i = 0, + len = elems.length, + bulk = key == null; + + // Sets many values + if ( toType( key ) === "object" ) { + chainable = true; + for ( i in key ) { + access( elems, fn, i, key[ i ], true, emptyGet, raw ); + } + + // Sets one value + } else if ( value !== undefined ) { + chainable = true; + + if ( !isFunction( value ) ) { + raw = true; + } + + if ( bulk ) { + + // Bulk operations run against the entire set + if ( raw ) { + fn.call( elems, value ); + fn = null; + + // ...except when executing function values + } else { + bulk = fn; + fn = function( elem, _key, value ) { + return bulk.call( jQuery( elem ), value ); + }; + } + } + + if ( fn ) { + for ( ; i < len; i++ ) { + fn( + elems[ i ], key, raw ? + value : + value.call( elems[ i ], i, fn( elems[ i ], key ) ) + ); + } + } + } + + if ( chainable ) { + return elems; + } + + // Gets + if ( bulk ) { + return fn.call( elems ); + } + + return len ? fn( elems[ 0 ], key ) : emptyGet; +}; + + +// Matches dashed string for camelizing +var rmsPrefix = /^-ms-/, + rdashAlpha = /-([a-z])/g; + +// Used by camelCase as callback to replace() +function fcamelCase( _all, letter ) { + return letter.toUpperCase(); +} + +// Convert dashed to camelCase; used by the css and data modules +// Support: IE <=9 - 11, Edge 12 - 15 +// Microsoft forgot to hump their vendor prefix (trac-9572) +function camelCase( string ) { + return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); +} +var acceptData = function( owner ) { + + // Accepts only: + // - Node + // - Node.ELEMENT_NODE + // - Node.DOCUMENT_NODE + // - Object + // - Any + return owner.nodeType === 1 || owner.nodeType === 9 || !( +owner.nodeType ); +}; + + + + +function Data() { + this.expando = jQuery.expando + Data.uid++; +} + +Data.uid = 1; + +Data.prototype = { + + cache: function( owner ) { + + // Check if the owner object already has a cache + var value = owner[ this.expando ]; + + // If not, create one + if ( !value ) { + value = {}; + + // We can accept data for non-element nodes in modern browsers, + // but we should not, see trac-8335. + // Always return an empty object. + if ( acceptData( owner ) ) { + + // If it is a node unlikely to be stringify-ed or looped over + // use plain assignment + if ( owner.nodeType ) { + owner[ this.expando ] = value; + + // Otherwise secure it in a non-enumerable property + // configurable must be true to allow the property to be + // deleted when data is removed + } else { + Object.defineProperty( owner, this.expando, { + value: value, + configurable: true + } ); + } + } + } + + return value; + }, + set: function( owner, data, value ) { + var prop, + cache = this.cache( owner ); + + // Handle: [ owner, key, value ] args + // Always use camelCase key (gh-2257) + if ( typeof data === "string" ) { + cache[ camelCase( data ) ] = value; + + // Handle: [ owner, { properties } ] args + } else { + + // Copy the properties one-by-one to the cache object + for ( prop in data ) { + cache[ camelCase( prop ) ] = data[ prop ]; + } + } + return cache; + }, + get: function( owner, key ) { + return key === undefined ? + this.cache( owner ) : + + // Always use camelCase key (gh-2257) + owner[ this.expando ] && owner[ this.expando ][ camelCase( key ) ]; + }, + access: function( owner, key, value ) { + + // In cases where either: + // + // 1. No key was specified + // 2. A string key was specified, but no value provided + // + // Take the "read" path and allow the get method to determine + // which value to return, respectively either: + // + // 1. The entire cache object + // 2. The data stored at the key + // + if ( key === undefined || + ( ( key && typeof key === "string" ) && value === undefined ) ) { + + return this.get( owner, key ); + } + + // When the key is not a string, or both a key and value + // are specified, set or extend (existing objects) with either: + // + // 1. An object of properties + // 2. A key and value + // + this.set( owner, key, value ); + + // Since the "set" path can have two possible entry points + // return the expected data based on which path was taken[*] + return value !== undefined ? value : key; + }, + remove: function( owner, key ) { + var i, + cache = owner[ this.expando ]; + + if ( cache === undefined ) { + return; + } + + if ( key !== undefined ) { + + // Support array or space separated string of keys + if ( Array.isArray( key ) ) { + + // If key is an array of keys... + // We always set camelCase keys, so remove that. + key = key.map( camelCase ); + } else { + key = camelCase( key ); + + // If a key with the spaces exists, use it. + // Otherwise, create an array by matching non-whitespace + key = key in cache ? + [ key ] : + ( key.match( rnothtmlwhite ) || [] ); + } + + i = key.length; + + while ( i-- ) { + delete cache[ key[ i ] ]; + } + } + + // Remove the expando if there's no more data + if ( key === undefined || jQuery.isEmptyObject( cache ) ) { + + // Support: Chrome <=35 - 45 + // Webkit & Blink performance suffers when deleting properties + // from DOM nodes, so set to undefined instead + // https://bugs.chromium.org/p/chromium/issues/detail?id=378607 (bug restricted) + if ( owner.nodeType ) { + owner[ this.expando ] = undefined; + } else { + delete owner[ this.expando ]; + } + } + }, + hasData: function( owner ) { + var cache = owner[ this.expando ]; + return cache !== undefined && !jQuery.isEmptyObject( cache ); + } +}; +var dataPriv = new Data(); + +var dataUser = new Data(); + + + +// Implementation Summary +// +// 1. Enforce API surface and semantic compatibility with 1.9.x branch +// 2. Improve the module's maintainability by reducing the storage +// paths to a single mechanism. +// 3. Use the same single mechanism to support "private" and "user" data. +// 4. _Never_ expose "private" data to user code (TODO: Drop _data, _removeData) +// 5. Avoid exposing implementation details on user objects (eg. expando properties) +// 6. Provide a clear path for implementation upgrade to WeakMap in 2014 + +var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/, + rmultiDash = /[A-Z]/g; + +function getData( data ) { + if ( data === "true" ) { + return true; + } + + if ( data === "false" ) { + return false; + } + + if ( data === "null" ) { + return null; + } + + // Only convert to a number if it doesn't change the string + if ( data === +data + "" ) { + return +data; + } + + if ( rbrace.test( data ) ) { + return JSON.parse( data ); + } + + return data; +} + +function dataAttr( elem, key, data ) { + var name; + + // If nothing was found internally, try to fetch any + // data from the HTML5 data-* attribute + if ( data === undefined && elem.nodeType === 1 ) { + name = "data-" + key.replace( rmultiDash, "-$&" ).toLowerCase(); + data = elem.getAttribute( name ); + + if ( typeof data === "string" ) { + try { + data = getData( data ); + } catch ( e ) {} + + // Make sure we set the data so it isn't changed later + dataUser.set( elem, key, data ); + } else { + data = undefined; + } + } + return data; +} + +jQuery.extend( { + hasData: function( elem ) { + return dataUser.hasData( elem ) || dataPriv.hasData( elem ); + }, + + data: function( elem, name, data ) { + return dataUser.access( elem, name, data ); + }, + + removeData: function( elem, name ) { + dataUser.remove( elem, name ); + }, + + // TODO: Now that all calls to _data and _removeData have been replaced + // with direct calls to dataPriv methods, these can be deprecated. + _data: function( elem, name, data ) { + return dataPriv.access( elem, name, data ); + }, + + _removeData: function( elem, name ) { + dataPriv.remove( elem, name ); + } +} ); + +jQuery.fn.extend( { + data: function( key, value ) { + var i, name, data, + elem = this[ 0 ], + attrs = elem && elem.attributes; + + // Gets all values + if ( key === undefined ) { + if ( this.length ) { + data = dataUser.get( elem ); + + if ( elem.nodeType === 1 && !dataPriv.get( elem, "hasDataAttrs" ) ) { + i = attrs.length; + while ( i-- ) { + + // Support: IE 11 only + // The attrs elements can be null (trac-14894) + if ( attrs[ i ] ) { + name = attrs[ i ].name; + if ( name.indexOf( "data-" ) === 0 ) { + name = camelCase( name.slice( 5 ) ); + dataAttr( elem, name, data[ name ] ); + } + } + } + dataPriv.set( elem, "hasDataAttrs", true ); + } + } + + return data; + } + + // Sets multiple values + if ( typeof key === "object" ) { + return this.each( function() { + dataUser.set( this, key ); + } ); + } + + return access( this, function( value ) { + var data; + + // The calling jQuery object (element matches) is not empty + // (and therefore has an element appears at this[ 0 ]) and the + // `value` parameter was not undefined. An empty jQuery object + // will result in `undefined` for elem = this[ 0 ] which will + // throw an exception if an attempt to read a data cache is made. + if ( elem && value === undefined ) { + + // Attempt to get data from the cache + // The key will always be camelCased in Data + data = dataUser.get( elem, key ); + if ( data !== undefined ) { + return data; + } + + // Attempt to "discover" the data in + // HTML5 custom data-* attrs + data = dataAttr( elem, key ); + if ( data !== undefined ) { + return data; + } + + // We tried really hard, but the data doesn't exist. + return; + } + + // Set the data... + this.each( function() { + + // We always store the camelCased key + dataUser.set( this, key, value ); + } ); + }, null, value, arguments.length > 1, null, true ); + }, + + removeData: function( key ) { + return this.each( function() { + dataUser.remove( this, key ); + } ); + } +} ); + + +jQuery.extend( { + queue: function( elem, type, data ) { + var queue; + + if ( elem ) { + type = ( type || "fx" ) + "queue"; + queue = dataPriv.get( elem, type ); + + // Speed up dequeue by getting out quickly if this is just a lookup + if ( data ) { + if ( !queue || Array.isArray( data ) ) { + queue = dataPriv.access( elem, type, jQuery.makeArray( data ) ); + } else { + queue.push( data ); + } + } + return queue || []; + } + }, + + dequeue: function( elem, type ) { + type = type || "fx"; + + var queue = jQuery.queue( elem, type ), + startLength = queue.length, + fn = queue.shift(), + hooks = jQuery._queueHooks( elem, type ), + next = function() { + jQuery.dequeue( elem, type ); + }; + + // If the fx queue is dequeued, always remove the progress sentinel + if ( fn === "inprogress" ) { + fn = queue.shift(); + startLength--; + } + + if ( fn ) { + + // Add a progress sentinel to prevent the fx queue from being + // automatically dequeued + if ( type === "fx" ) { + queue.unshift( "inprogress" ); + } + + // Clear up the last queue stop function + delete hooks.stop; + fn.call( elem, next, hooks ); + } + + if ( !startLength && hooks ) { + hooks.empty.fire(); + } + }, + + // Not public - generate a queueHooks object, or return the current one + _queueHooks: function( elem, type ) { + var key = type + "queueHooks"; + return dataPriv.get( elem, key ) || dataPriv.access( elem, key, { + empty: jQuery.Callbacks( "once memory" ).add( function() { + dataPriv.remove( elem, [ type + "queue", key ] ); + } ) + } ); + } +} ); + +jQuery.fn.extend( { + queue: function( type, data ) { + var setter = 2; + + if ( typeof type !== "string" ) { + data = type; + type = "fx"; + setter--; + } + + if ( arguments.length < setter ) { + return jQuery.queue( this[ 0 ], type ); + } + + return data === undefined ? + this : + this.each( function() { + var queue = jQuery.queue( this, type, data ); + + // Ensure a hooks for this queue + jQuery._queueHooks( this, type ); + + if ( type === "fx" && queue[ 0 ] !== "inprogress" ) { + jQuery.dequeue( this, type ); + } + } ); + }, + dequeue: function( type ) { + return this.each( function() { + jQuery.dequeue( this, type ); + } ); + }, + clearQueue: function( type ) { + return this.queue( type || "fx", [] ); + }, + + // Get a promise resolved when queues of a certain type + // are emptied (fx is the type by default) + promise: function( type, obj ) { + var tmp, + count = 1, + defer = jQuery.Deferred(), + elements = this, + i = this.length, + resolve = function() { + if ( !( --count ) ) { + defer.resolveWith( elements, [ elements ] ); + } + }; + + if ( typeof type !== "string" ) { + obj = type; + type = undefined; + } + type = type || "fx"; + + while ( i-- ) { + tmp = dataPriv.get( elements[ i ], type + "queueHooks" ); + if ( tmp && tmp.empty ) { + count++; + tmp.empty.add( resolve ); + } + } + resolve(); + return defer.promise( obj ); + } +} ); +var pnum = ( /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/ ).source; + +var rcssNum = new RegExp( "^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i" ); + + +var cssExpand = [ "Top", "Right", "Bottom", "Left" ]; + +var documentElement = document.documentElement; + + + + var isAttached = function( elem ) { + return jQuery.contains( elem.ownerDocument, elem ); + }, + composed = { composed: true }; + + // Support: IE 9 - 11+, Edge 12 - 18+, iOS 10.0 - 10.2 only + // Check attachment across shadow DOM boundaries when possible (gh-3504) + // Support: iOS 10.0-10.2 only + // Early iOS 10 versions support `attachShadow` but not `getRootNode`, + // leading to errors. We need to check for `getRootNode`. + if ( documentElement.getRootNode ) { + isAttached = function( elem ) { + return jQuery.contains( elem.ownerDocument, elem ) || + elem.getRootNode( composed ) === elem.ownerDocument; + }; + } +var isHiddenWithinTree = function( elem, el ) { + + // isHiddenWithinTree might be called from jQuery#filter function; + // in that case, element will be second argument + elem = el || elem; + + // Inline style trumps all + return elem.style.display === "none" || + elem.style.display === "" && + + // Otherwise, check computed style + // Support: Firefox <=43 - 45 + // Disconnected elements can have computed display: none, so first confirm that elem is + // in the document. + isAttached( elem ) && + + jQuery.css( elem, "display" ) === "none"; + }; + + + +function adjustCSS( elem, prop, valueParts, tween ) { + var adjusted, scale, + maxIterations = 20, + currentValue = tween ? + function() { + return tween.cur(); + } : + function() { + return jQuery.css( elem, prop, "" ); + }, + initial = currentValue(), + unit = valueParts && valueParts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ), + + // Starting value computation is required for potential unit mismatches + initialInUnit = elem.nodeType && + ( jQuery.cssNumber[ prop ] || unit !== "px" && +initial ) && + rcssNum.exec( jQuery.css( elem, prop ) ); + + if ( initialInUnit && initialInUnit[ 3 ] !== unit ) { + + // Support: Firefox <=54 + // Halve the iteration target value to prevent interference from CSS upper bounds (gh-2144) + initial = initial / 2; + + // Trust units reported by jQuery.css + unit = unit || initialInUnit[ 3 ]; + + // Iteratively approximate from a nonzero starting point + initialInUnit = +initial || 1; + + while ( maxIterations-- ) { + + // Evaluate and update our best guess (doubling guesses that zero out). + // Finish if the scale equals or crosses 1 (making the old*new product non-positive). + jQuery.style( elem, prop, initialInUnit + unit ); + if ( ( 1 - scale ) * ( 1 - ( scale = currentValue() / initial || 0.5 ) ) <= 0 ) { + maxIterations = 0; + } + initialInUnit = initialInUnit / scale; + + } + + initialInUnit = initialInUnit * 2; + jQuery.style( elem, prop, initialInUnit + unit ); + + // Make sure we update the tween properties later on + valueParts = valueParts || []; + } + + if ( valueParts ) { + initialInUnit = +initialInUnit || +initial || 0; + + // Apply relative offset (+=/-=) if specified + adjusted = valueParts[ 1 ] ? + initialInUnit + ( valueParts[ 1 ] + 1 ) * valueParts[ 2 ] : + +valueParts[ 2 ]; + if ( tween ) { + tween.unit = unit; + tween.start = initialInUnit; + tween.end = adjusted; + } + } + return adjusted; +} + + +var defaultDisplayMap = {}; + +function getDefaultDisplay( elem ) { + var temp, + doc = elem.ownerDocument, + nodeName = elem.nodeName, + display = defaultDisplayMap[ nodeName ]; + + if ( display ) { + return display; + } + + temp = doc.body.appendChild( doc.createElement( nodeName ) ); + display = jQuery.css( temp, "display" ); + + temp.parentNode.removeChild( temp ); + + if ( display === "none" ) { + display = "block"; + } + defaultDisplayMap[ nodeName ] = display; + + return display; +} + +function showHide( elements, show ) { + var display, elem, + values = [], + index = 0, + length = elements.length; + + // Determine new display value for elements that need to change + for ( ; index < length; index++ ) { + elem = elements[ index ]; + if ( !elem.style ) { + continue; + } + + display = elem.style.display; + if ( show ) { + + // Since we force visibility upon cascade-hidden elements, an immediate (and slow) + // check is required in this first loop unless we have a nonempty display value (either + // inline or about-to-be-restored) + if ( display === "none" ) { + values[ index ] = dataPriv.get( elem, "display" ) || null; + if ( !values[ index ] ) { + elem.style.display = ""; + } + } + if ( elem.style.display === "" && isHiddenWithinTree( elem ) ) { + values[ index ] = getDefaultDisplay( elem ); + } + } else { + if ( display !== "none" ) { + values[ index ] = "none"; + + // Remember what we're overwriting + dataPriv.set( elem, "display", display ); + } + } + } + + // Set the display of the elements in a second loop to avoid constant reflow + for ( index = 0; index < length; index++ ) { + if ( values[ index ] != null ) { + elements[ index ].style.display = values[ index ]; + } + } + + return elements; +} + +jQuery.fn.extend( { + show: function() { + return showHide( this, true ); + }, + hide: function() { + return showHide( this ); + }, + toggle: function( state ) { + if ( typeof state === "boolean" ) { + return state ? this.show() : this.hide(); + } + + return this.each( function() { + if ( isHiddenWithinTree( this ) ) { + jQuery( this ).show(); + } else { + jQuery( this ).hide(); + } + } ); + } +} ); +var rcheckableType = ( /^(?:checkbox|radio)$/i ); + +var rtagName = ( /<([a-z][^\/\0>\x20\t\r\n\f]*)/i ); + +var rscriptType = ( /^$|^module$|\/(?:java|ecma)script/i ); + + + +( function() { + var fragment = document.createDocumentFragment(), + div = fragment.appendChild( document.createElement( "div" ) ), + input = document.createElement( "input" ); + + // Support: Android 4.0 - 4.3 only + // Check state lost if the name is set (trac-11217) + // Support: Windows Web Apps (WWA) + // `name` and `type` must use .setAttribute for WWA (trac-14901) + input.setAttribute( "type", "radio" ); + input.setAttribute( "checked", "checked" ); + input.setAttribute( "name", "t" ); + + div.appendChild( input ); + + // Support: Android <=4.1 only + // Older WebKit doesn't clone checked state correctly in fragments + support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked; + + // Support: IE <=11 only + // Make sure textarea (and checkbox) defaultValue is properly cloned + div.innerHTML = ""; + support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue; + + // Support: IE <=9 only + // IE <=9 replaces "; + support.option = !!div.lastChild; +} )(); + + +// We have to close these tags to support XHTML (trac-13200) +var wrapMap = { + + // XHTML parsers do not magically insert elements in the + // same way that tag soup parsers do. So we cannot shorten + // this by omitting or other required elements. + thead: [ 1, "", "
    " ], + col: [ 2, "", "
    " ], + tr: [ 2, "", "
    " ], + td: [ 3, "", "
    " ], + + _default: [ 0, "", "" ] +}; + +wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; +wrapMap.th = wrapMap.td; + +// Support: IE <=9 only +if ( !support.option ) { + wrapMap.optgroup = wrapMap.option = [ 1, "" ]; +} + + +function getAll( context, tag ) { + + // Support: IE <=9 - 11 only + // Use typeof to avoid zero-argument method invocation on host objects (trac-15151) + var ret; + + if ( typeof context.getElementsByTagName !== "undefined" ) { + ret = context.getElementsByTagName( tag || "*" ); + + } else if ( typeof context.querySelectorAll !== "undefined" ) { + ret = context.querySelectorAll( tag || "*" ); + + } else { + ret = []; + } + + if ( tag === undefined || tag && nodeName( context, tag ) ) { + return jQuery.merge( [ context ], ret ); + } + + return ret; +} + + +// Mark scripts as having already been evaluated +function setGlobalEval( elems, refElements ) { + var i = 0, + l = elems.length; + + for ( ; i < l; i++ ) { + dataPriv.set( + elems[ i ], + "globalEval", + !refElements || dataPriv.get( refElements[ i ], "globalEval" ) + ); + } +} + + +var rhtml = /<|&#?\w+;/; + +function buildFragment( elems, context, scripts, selection, ignored ) { + var elem, tmp, tag, wrap, attached, j, + fragment = context.createDocumentFragment(), + nodes = [], + i = 0, + l = elems.length; + + for ( ; i < l; i++ ) { + elem = elems[ i ]; + + if ( elem || elem === 0 ) { + + // Add nodes directly + if ( toType( elem ) === "object" ) { + + // Support: Android <=4.0 only, PhantomJS 1 only + // push.apply(_, arraylike) throws on ancient WebKit + jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); + + // Convert non-html into a text node + } else if ( !rhtml.test( elem ) ) { + nodes.push( context.createTextNode( elem ) ); + + // Convert html into DOM nodes + } else { + tmp = tmp || fragment.appendChild( context.createElement( "div" ) ); + + // Deserialize a standard representation + tag = ( rtagName.exec( elem ) || [ "", "" ] )[ 1 ].toLowerCase(); + wrap = wrapMap[ tag ] || wrapMap._default; + tmp.innerHTML = wrap[ 1 ] + jQuery.htmlPrefilter( elem ) + wrap[ 2 ]; + + // Descend through wrappers to the right content + j = wrap[ 0 ]; + while ( j-- ) { + tmp = tmp.lastChild; + } + + // Support: Android <=4.0 only, PhantomJS 1 only + // push.apply(_, arraylike) throws on ancient WebKit + jQuery.merge( nodes, tmp.childNodes ); + + // Remember the top-level container + tmp = fragment.firstChild; + + // Ensure the created nodes are orphaned (trac-12392) + tmp.textContent = ""; + } + } + } + + // Remove wrapper from fragment + fragment.textContent = ""; + + i = 0; + while ( ( elem = nodes[ i++ ] ) ) { + + // Skip elements already in the context collection (trac-4087) + if ( selection && jQuery.inArray( elem, selection ) > -1 ) { + if ( ignored ) { + ignored.push( elem ); + } + continue; + } + + attached = isAttached( elem ); + + // Append to fragment + tmp = getAll( fragment.appendChild( elem ), "script" ); + + // Preserve script evaluation history + if ( attached ) { + setGlobalEval( tmp ); + } + + // Capture executables + if ( scripts ) { + j = 0; + while ( ( elem = tmp[ j++ ] ) ) { + if ( rscriptType.test( elem.type || "" ) ) { + scripts.push( elem ); + } + } + } + } + + return fragment; +} + + +var rtypenamespace = /^([^.]*)(?:\.(.+)|)/; + +function returnTrue() { + return true; +} + +function returnFalse() { + return false; +} + +function on( elem, types, selector, data, fn, one ) { + var origFn, type; + + // Types can be a map of types/handlers + if ( typeof types === "object" ) { + + // ( types-Object, selector, data ) + if ( typeof selector !== "string" ) { + + // ( types-Object, data ) + data = data || selector; + selector = undefined; + } + for ( type in types ) { + on( elem, type, selector, data, types[ type ], one ); + } + return elem; + } + + if ( data == null && fn == null ) { + + // ( types, fn ) + fn = selector; + data = selector = undefined; + } else if ( fn == null ) { + if ( typeof selector === "string" ) { + + // ( types, selector, fn ) + fn = data; + data = undefined; + } else { + + // ( types, data, fn ) + fn = data; + data = selector; + selector = undefined; + } + } + if ( fn === false ) { + fn = returnFalse; + } else if ( !fn ) { + return elem; + } + + if ( one === 1 ) { + origFn = fn; + fn = function( event ) { + + // Can use an empty set, since event contains the info + jQuery().off( event ); + return origFn.apply( this, arguments ); + }; + + // Use same guid so caller can remove using origFn + fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); + } + return elem.each( function() { + jQuery.event.add( this, types, fn, data, selector ); + } ); +} + +/* + * Helper functions for managing events -- not part of the public interface. + * Props to Dean Edwards' addEvent library for many of the ideas. + */ +jQuery.event = { + + global: {}, + + add: function( elem, types, handler, data, selector ) { + + var handleObjIn, eventHandle, tmp, + events, t, handleObj, + special, handlers, type, namespaces, origType, + elemData = dataPriv.get( elem ); + + // Only attach events to objects that accept data + if ( !acceptData( elem ) ) { + return; + } + + // Caller can pass in an object of custom data in lieu of the handler + if ( handler.handler ) { + handleObjIn = handler; + handler = handleObjIn.handler; + selector = handleObjIn.selector; + } + + // Ensure that invalid selectors throw exceptions at attach time + // Evaluate against documentElement in case elem is a non-element node (e.g., document) + if ( selector ) { + jQuery.find.matchesSelector( documentElement, selector ); + } + + // Make sure that the handler has a unique ID, used to find/remove it later + if ( !handler.guid ) { + handler.guid = jQuery.guid++; + } + + // Init the element's event structure and main handler, if this is the first + if ( !( events = elemData.events ) ) { + events = elemData.events = Object.create( null ); + } + if ( !( eventHandle = elemData.handle ) ) { + eventHandle = elemData.handle = function( e ) { + + // Discard the second event of a jQuery.event.trigger() and + // when an event is called after a page has unloaded + return typeof jQuery !== "undefined" && jQuery.event.triggered !== e.type ? + jQuery.event.dispatch.apply( elem, arguments ) : undefined; + }; + } + + // Handle multiple events separated by a space + types = ( types || "" ).match( rnothtmlwhite ) || [ "" ]; + t = types.length; + while ( t-- ) { + tmp = rtypenamespace.exec( types[ t ] ) || []; + type = origType = tmp[ 1 ]; + namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort(); + + // There *must* be a type, no attaching namespace-only handlers + if ( !type ) { + continue; + } + + // If event changes its type, use the special event handlers for the changed type + special = jQuery.event.special[ type ] || {}; + + // If selector defined, determine special event api type, otherwise given type + type = ( selector ? special.delegateType : special.bindType ) || type; + + // Update special based on newly reset type + special = jQuery.event.special[ type ] || {}; + + // handleObj is passed to all event handlers + handleObj = jQuery.extend( { + type: type, + origType: origType, + data: data, + handler: handler, + guid: handler.guid, + selector: selector, + needsContext: selector && jQuery.expr.match.needsContext.test( selector ), + namespace: namespaces.join( "." ) + }, handleObjIn ); + + // Init the event handler queue if we're the first + if ( !( handlers = events[ type ] ) ) { + handlers = events[ type ] = []; + handlers.delegateCount = 0; + + // Only use addEventListener if the special events handler returns false + if ( !special.setup || + special.setup.call( elem, data, namespaces, eventHandle ) === false ) { + + if ( elem.addEventListener ) { + elem.addEventListener( type, eventHandle ); + } + } + } + + if ( special.add ) { + special.add.call( elem, handleObj ); + + if ( !handleObj.handler.guid ) { + handleObj.handler.guid = handler.guid; + } + } + + // Add to the element's handler list, delegates in front + if ( selector ) { + handlers.splice( handlers.delegateCount++, 0, handleObj ); + } else { + handlers.push( handleObj ); + } + + // Keep track of which events have ever been used, for event optimization + jQuery.event.global[ type ] = true; + } + + }, + + // Detach an event or set of events from an element + remove: function( elem, types, handler, selector, mappedTypes ) { + + var j, origCount, tmp, + events, t, handleObj, + special, handlers, type, namespaces, origType, + elemData = dataPriv.hasData( elem ) && dataPriv.get( elem ); + + if ( !elemData || !( events = elemData.events ) ) { + return; + } + + // Once for each type.namespace in types; type may be omitted + types = ( types || "" ).match( rnothtmlwhite ) || [ "" ]; + t = types.length; + while ( t-- ) { + tmp = rtypenamespace.exec( types[ t ] ) || []; + type = origType = tmp[ 1 ]; + namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort(); + + // Unbind all events (on this namespace, if provided) for the element + if ( !type ) { + for ( type in events ) { + jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); + } + continue; + } + + special = jQuery.event.special[ type ] || {}; + type = ( selector ? special.delegateType : special.bindType ) || type; + handlers = events[ type ] || []; + tmp = tmp[ 2 ] && + new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.|)" ) + "(\\.|$)" ); + + // Remove matching events + origCount = j = handlers.length; + while ( j-- ) { + handleObj = handlers[ j ]; + + if ( ( mappedTypes || origType === handleObj.origType ) && + ( !handler || handler.guid === handleObj.guid ) && + ( !tmp || tmp.test( handleObj.namespace ) ) && + ( !selector || selector === handleObj.selector || + selector === "**" && handleObj.selector ) ) { + handlers.splice( j, 1 ); + + if ( handleObj.selector ) { + handlers.delegateCount--; + } + if ( special.remove ) { + special.remove.call( elem, handleObj ); + } + } + } + + // Remove generic event handler if we removed something and no more handlers exist + // (avoids potential for endless recursion during removal of special event handlers) + if ( origCount && !handlers.length ) { + if ( !special.teardown || + special.teardown.call( elem, namespaces, elemData.handle ) === false ) { + + jQuery.removeEvent( elem, type, elemData.handle ); + } + + delete events[ type ]; + } + } + + // Remove data and the expando if it's no longer used + if ( jQuery.isEmptyObject( events ) ) { + dataPriv.remove( elem, "handle events" ); + } + }, + + dispatch: function( nativeEvent ) { + + var i, j, ret, matched, handleObj, handlerQueue, + args = new Array( arguments.length ), + + // Make a writable jQuery.Event from the native event object + event = jQuery.event.fix( nativeEvent ), + + handlers = ( + dataPriv.get( this, "events" ) || Object.create( null ) + )[ event.type ] || [], + special = jQuery.event.special[ event.type ] || {}; + + // Use the fix-ed jQuery.Event rather than the (read-only) native event + args[ 0 ] = event; + + for ( i = 1; i < arguments.length; i++ ) { + args[ i ] = arguments[ i ]; + } + + event.delegateTarget = this; + + // Call the preDispatch hook for the mapped type, and let it bail if desired + if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { + return; + } + + // Determine handlers + handlerQueue = jQuery.event.handlers.call( this, event, handlers ); + + // Run delegates first; they may want to stop propagation beneath us + i = 0; + while ( ( matched = handlerQueue[ i++ ] ) && !event.isPropagationStopped() ) { + event.currentTarget = matched.elem; + + j = 0; + while ( ( handleObj = matched.handlers[ j++ ] ) && + !event.isImmediatePropagationStopped() ) { + + // If the event is namespaced, then each handler is only invoked if it is + // specially universal or its namespaces are a superset of the event's. + if ( !event.rnamespace || handleObj.namespace === false || + event.rnamespace.test( handleObj.namespace ) ) { + + event.handleObj = handleObj; + event.data = handleObj.data; + + ret = ( ( jQuery.event.special[ handleObj.origType ] || {} ).handle || + handleObj.handler ).apply( matched.elem, args ); + + if ( ret !== undefined ) { + if ( ( event.result = ret ) === false ) { + event.preventDefault(); + event.stopPropagation(); + } + } + } + } + } + + // Call the postDispatch hook for the mapped type + if ( special.postDispatch ) { + special.postDispatch.call( this, event ); + } + + return event.result; + }, + + handlers: function( event, handlers ) { + var i, handleObj, sel, matchedHandlers, matchedSelectors, + handlerQueue = [], + delegateCount = handlers.delegateCount, + cur = event.target; + + // Find delegate handlers + if ( delegateCount && + + // Support: IE <=9 + // Black-hole SVG instance trees (trac-13180) + cur.nodeType && + + // Support: Firefox <=42 + // Suppress spec-violating clicks indicating a non-primary pointer button (trac-3861) + // https://www.w3.org/TR/DOM-Level-3-Events/#event-type-click + // Support: IE 11 only + // ...but not arrow key "clicks" of radio inputs, which can have `button` -1 (gh-2343) + !( event.type === "click" && event.button >= 1 ) ) { + + for ( ; cur !== this; cur = cur.parentNode || this ) { + + // Don't check non-elements (trac-13208) + // Don't process clicks on disabled elements (trac-6911, trac-8165, trac-11382, trac-11764) + if ( cur.nodeType === 1 && !( event.type === "click" && cur.disabled === true ) ) { + matchedHandlers = []; + matchedSelectors = {}; + for ( i = 0; i < delegateCount; i++ ) { + handleObj = handlers[ i ]; + + // Don't conflict with Object.prototype properties (trac-13203) + sel = handleObj.selector + " "; + + if ( matchedSelectors[ sel ] === undefined ) { + matchedSelectors[ sel ] = handleObj.needsContext ? + jQuery( sel, this ).index( cur ) > -1 : + jQuery.find( sel, this, null, [ cur ] ).length; + } + if ( matchedSelectors[ sel ] ) { + matchedHandlers.push( handleObj ); + } + } + if ( matchedHandlers.length ) { + handlerQueue.push( { elem: cur, handlers: matchedHandlers } ); + } + } + } + } + + // Add the remaining (directly-bound) handlers + cur = this; + if ( delegateCount < handlers.length ) { + handlerQueue.push( { elem: cur, handlers: handlers.slice( delegateCount ) } ); + } + + return handlerQueue; + }, + + addProp: function( name, hook ) { + Object.defineProperty( jQuery.Event.prototype, name, { + enumerable: true, + configurable: true, + + get: isFunction( hook ) ? + function() { + if ( this.originalEvent ) { + return hook( this.originalEvent ); + } + } : + function() { + if ( this.originalEvent ) { + return this.originalEvent[ name ]; + } + }, + + set: function( value ) { + Object.defineProperty( this, name, { + enumerable: true, + configurable: true, + writable: true, + value: value + } ); + } + } ); + }, + + fix: function( originalEvent ) { + return originalEvent[ jQuery.expando ] ? + originalEvent : + new jQuery.Event( originalEvent ); + }, + + special: { + load: { + + // Prevent triggered image.load events from bubbling to window.load + noBubble: true + }, + click: { + + // Utilize native event to ensure correct state for checkable inputs + setup: function( data ) { + + // For mutual compressibility with _default, replace `this` access with a local var. + // `|| data` is dead code meant only to preserve the variable through minification. + var el = this || data; + + // Claim the first handler + if ( rcheckableType.test( el.type ) && + el.click && nodeName( el, "input" ) ) { + + // dataPriv.set( el, "click", ... ) + leverageNative( el, "click", true ); + } + + // Return false to allow normal processing in the caller + return false; + }, + trigger: function( data ) { + + // For mutual compressibility with _default, replace `this` access with a local var. + // `|| data` is dead code meant only to preserve the variable through minification. + var el = this || data; + + // Force setup before triggering a click + if ( rcheckableType.test( el.type ) && + el.click && nodeName( el, "input" ) ) { + + leverageNative( el, "click" ); + } + + // Return non-false to allow normal event-path propagation + return true; + }, + + // For cross-browser consistency, suppress native .click() on links + // Also prevent it if we're currently inside a leveraged native-event stack + _default: function( event ) { + var target = event.target; + return rcheckableType.test( target.type ) && + target.click && nodeName( target, "input" ) && + dataPriv.get( target, "click" ) || + nodeName( target, "a" ); + } + }, + + beforeunload: { + postDispatch: function( event ) { + + // Support: Firefox 20+ + // Firefox doesn't alert if the returnValue field is not set. + if ( event.result !== undefined && event.originalEvent ) { + event.originalEvent.returnValue = event.result; + } + } + } + } +}; + +// Ensure the presence of an event listener that handles manually-triggered +// synthetic events by interrupting progress until reinvoked in response to +// *native* events that it fires directly, ensuring that state changes have +// already occurred before other listeners are invoked. +function leverageNative( el, type, isSetup ) { + + // Missing `isSetup` indicates a trigger call, which must force setup through jQuery.event.add + if ( !isSetup ) { + if ( dataPriv.get( el, type ) === undefined ) { + jQuery.event.add( el, type, returnTrue ); + } + return; + } + + // Register the controller as a special universal handler for all event namespaces + dataPriv.set( el, type, false ); + jQuery.event.add( el, type, { + namespace: false, + handler: function( event ) { + var result, + saved = dataPriv.get( this, type ); + + if ( ( event.isTrigger & 1 ) && this[ type ] ) { + + // Interrupt processing of the outer synthetic .trigger()ed event + if ( !saved ) { + + // Store arguments for use when handling the inner native event + // There will always be at least one argument (an event object), so this array + // will not be confused with a leftover capture object. + saved = slice.call( arguments ); + dataPriv.set( this, type, saved ); + + // Trigger the native event and capture its result + this[ type ](); + result = dataPriv.get( this, type ); + dataPriv.set( this, type, false ); + + if ( saved !== result ) { + + // Cancel the outer synthetic event + event.stopImmediatePropagation(); + event.preventDefault(); + + return result; + } + + // If this is an inner synthetic event for an event with a bubbling surrogate + // (focus or blur), assume that the surrogate already propagated from triggering + // the native event and prevent that from happening again here. + // This technically gets the ordering wrong w.r.t. to `.trigger()` (in which the + // bubbling surrogate propagates *after* the non-bubbling base), but that seems + // less bad than duplication. + } else if ( ( jQuery.event.special[ type ] || {} ).delegateType ) { + event.stopPropagation(); + } + + // If this is a native event triggered above, everything is now in order + // Fire an inner synthetic event with the original arguments + } else if ( saved ) { + + // ...and capture the result + dataPriv.set( this, type, jQuery.event.trigger( + saved[ 0 ], + saved.slice( 1 ), + this + ) ); + + // Abort handling of the native event by all jQuery handlers while allowing + // native handlers on the same element to run. On target, this is achieved + // by stopping immediate propagation just on the jQuery event. However, + // the native event is re-wrapped by a jQuery one on each level of the + // propagation so the only way to stop it for jQuery is to stop it for + // everyone via native `stopPropagation()`. This is not a problem for + // focus/blur which don't bubble, but it does also stop click on checkboxes + // and radios. We accept this limitation. + event.stopPropagation(); + event.isImmediatePropagationStopped = returnTrue; + } + } + } ); +} + +jQuery.removeEvent = function( elem, type, handle ) { + + // This "if" is needed for plain objects + if ( elem.removeEventListener ) { + elem.removeEventListener( type, handle ); + } +}; + +jQuery.Event = function( src, props ) { + + // Allow instantiation without the 'new' keyword + if ( !( this instanceof jQuery.Event ) ) { + return new jQuery.Event( src, props ); + } + + // Event object + if ( src && src.type ) { + this.originalEvent = src; + this.type = src.type; + + // Events bubbling up the document may have been marked as prevented + // by a handler lower down the tree; reflect the correct value. + this.isDefaultPrevented = src.defaultPrevented || + src.defaultPrevented === undefined && + + // Support: Android <=2.3 only + src.returnValue === false ? + returnTrue : + returnFalse; + + // Create target properties + // Support: Safari <=6 - 7 only + // Target should not be a text node (trac-504, trac-13143) + this.target = ( src.target && src.target.nodeType === 3 ) ? + src.target.parentNode : + src.target; + + this.currentTarget = src.currentTarget; + this.relatedTarget = src.relatedTarget; + + // Event type + } else { + this.type = src; + } + + // Put explicitly provided properties onto the event object + if ( props ) { + jQuery.extend( this, props ); + } + + // Create a timestamp if incoming event doesn't have one + this.timeStamp = src && src.timeStamp || Date.now(); + + // Mark it as fixed + this[ jQuery.expando ] = true; +}; + +// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding +// https://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html +jQuery.Event.prototype = { + constructor: jQuery.Event, + isDefaultPrevented: returnFalse, + isPropagationStopped: returnFalse, + isImmediatePropagationStopped: returnFalse, + isSimulated: false, + + preventDefault: function() { + var e = this.originalEvent; + + this.isDefaultPrevented = returnTrue; + + if ( e && !this.isSimulated ) { + e.preventDefault(); + } + }, + stopPropagation: function() { + var e = this.originalEvent; + + this.isPropagationStopped = returnTrue; + + if ( e && !this.isSimulated ) { + e.stopPropagation(); + } + }, + stopImmediatePropagation: function() { + var e = this.originalEvent; + + this.isImmediatePropagationStopped = returnTrue; + + if ( e && !this.isSimulated ) { + e.stopImmediatePropagation(); + } + + this.stopPropagation(); + } +}; + +// Includes all common event props including KeyEvent and MouseEvent specific props +jQuery.each( { + altKey: true, + bubbles: true, + cancelable: true, + changedTouches: true, + ctrlKey: true, + detail: true, + eventPhase: true, + metaKey: true, + pageX: true, + pageY: true, + shiftKey: true, + view: true, + "char": true, + code: true, + charCode: true, + key: true, + keyCode: true, + button: true, + buttons: true, + clientX: true, + clientY: true, + offsetX: true, + offsetY: true, + pointerId: true, + pointerType: true, + screenX: true, + screenY: true, + targetTouches: true, + toElement: true, + touches: true, + which: true +}, jQuery.event.addProp ); + +jQuery.each( { focus: "focusin", blur: "focusout" }, function( type, delegateType ) { + + function focusMappedHandler( nativeEvent ) { + if ( document.documentMode ) { + + // Support: IE 11+ + // Attach a single focusin/focusout handler on the document while someone wants + // focus/blur. This is because the former are synchronous in IE while the latter + // are async. In other browsers, all those handlers are invoked synchronously. + + // `handle` from private data would already wrap the event, but we need + // to change the `type` here. + var handle = dataPriv.get( this, "handle" ), + event = jQuery.event.fix( nativeEvent ); + event.type = nativeEvent.type === "focusin" ? "focus" : "blur"; + event.isSimulated = true; + + // First, handle focusin/focusout + handle( nativeEvent ); + + // ...then, handle focus/blur + // + // focus/blur don't bubble while focusin/focusout do; simulate the former by only + // invoking the handler at the lower level. + if ( event.target === event.currentTarget ) { + + // The setup part calls `leverageNative`, which, in turn, calls + // `jQuery.event.add`, so event handle will already have been set + // by this point. + handle( event ); + } + } else { + + // For non-IE browsers, attach a single capturing handler on the document + // while someone wants focusin/focusout. + jQuery.event.simulate( delegateType, nativeEvent.target, + jQuery.event.fix( nativeEvent ) ); + } + } + + jQuery.event.special[ type ] = { + + // Utilize native event if possible so blur/focus sequence is correct + setup: function() { + + var attaches; + + // Claim the first handler + // dataPriv.set( this, "focus", ... ) + // dataPriv.set( this, "blur", ... ) + leverageNative( this, type, true ); + + if ( document.documentMode ) { + + // Support: IE 9 - 11+ + // We use the same native handler for focusin & focus (and focusout & blur) + // so we need to coordinate setup & teardown parts between those events. + // Use `delegateType` as the key as `type` is already used by `leverageNative`. + attaches = dataPriv.get( this, delegateType ); + if ( !attaches ) { + this.addEventListener( delegateType, focusMappedHandler ); + } + dataPriv.set( this, delegateType, ( attaches || 0 ) + 1 ); + } else { + + // Return false to allow normal processing in the caller + return false; + } + }, + trigger: function() { + + // Force setup before trigger + leverageNative( this, type ); + + // Return non-false to allow normal event-path propagation + return true; + }, + + teardown: function() { + var attaches; + + if ( document.documentMode ) { + attaches = dataPriv.get( this, delegateType ) - 1; + if ( !attaches ) { + this.removeEventListener( delegateType, focusMappedHandler ); + dataPriv.remove( this, delegateType ); + } else { + dataPriv.set( this, delegateType, attaches ); + } + } else { + + // Return false to indicate standard teardown should be applied + return false; + } + }, + + // Suppress native focus or blur if we're currently inside + // a leveraged native-event stack + _default: function( event ) { + return dataPriv.get( event.target, type ); + }, + + delegateType: delegateType + }; + + // Support: Firefox <=44 + // Firefox doesn't have focus(in | out) events + // Related ticket - https://bugzilla.mozilla.org/show_bug.cgi?id=687787 + // + // Support: Chrome <=48 - 49, Safari <=9.0 - 9.1 + // focus(in | out) events fire after focus & blur events, + // which is spec violation - http://www.w3.org/TR/DOM-Level-3-Events/#events-focusevent-event-order + // Related ticket - https://bugs.chromium.org/p/chromium/issues/detail?id=449857 + // + // Support: IE 9 - 11+ + // To preserve relative focusin/focus & focusout/blur event order guaranteed on the 3.x branch, + // attach a single handler for both events in IE. + jQuery.event.special[ delegateType ] = { + setup: function() { + + // Handle: regular nodes (via `this.ownerDocument`), window + // (via `this.document`) & document (via `this`). + var doc = this.ownerDocument || this.document || this, + dataHolder = document.documentMode ? this : doc, + attaches = dataPriv.get( dataHolder, delegateType ); + + // Support: IE 9 - 11+ + // We use the same native handler for focusin & focus (and focusout & blur) + // so we need to coordinate setup & teardown parts between those events. + // Use `delegateType` as the key as `type` is already used by `leverageNative`. + if ( !attaches ) { + if ( document.documentMode ) { + this.addEventListener( delegateType, focusMappedHandler ); + } else { + doc.addEventListener( type, focusMappedHandler, true ); + } + } + dataPriv.set( dataHolder, delegateType, ( attaches || 0 ) + 1 ); + }, + teardown: function() { + var doc = this.ownerDocument || this.document || this, + dataHolder = document.documentMode ? this : doc, + attaches = dataPriv.get( dataHolder, delegateType ) - 1; + + if ( !attaches ) { + if ( document.documentMode ) { + this.removeEventListener( delegateType, focusMappedHandler ); + } else { + doc.removeEventListener( type, focusMappedHandler, true ); + } + dataPriv.remove( dataHolder, delegateType ); + } else { + dataPriv.set( dataHolder, delegateType, attaches ); + } + } + }; +} ); + +// Create mouseenter/leave events using mouseover/out and event-time checks +// so that event delegation works in jQuery. +// Do the same for pointerenter/pointerleave and pointerover/pointerout +// +// Support: Safari 7 only +// Safari sends mouseenter too often; see: +// https://bugs.chromium.org/p/chromium/issues/detail?id=470258 +// for the description of the bug (it existed in older Chrome versions as well). +jQuery.each( { + mouseenter: "mouseover", + mouseleave: "mouseout", + pointerenter: "pointerover", + pointerleave: "pointerout" +}, function( orig, fix ) { + jQuery.event.special[ orig ] = { + delegateType: fix, + bindType: fix, + + handle: function( event ) { + var ret, + target = this, + related = event.relatedTarget, + handleObj = event.handleObj; + + // For mouseenter/leave call the handler if related is outside the target. + // NB: No relatedTarget if the mouse left/entered the browser window + if ( !related || ( related !== target && !jQuery.contains( target, related ) ) ) { + event.type = handleObj.origType; + ret = handleObj.handler.apply( this, arguments ); + event.type = fix; + } + return ret; + } + }; +} ); + +jQuery.fn.extend( { + + on: function( types, selector, data, fn ) { + return on( this, types, selector, data, fn ); + }, + one: function( types, selector, data, fn ) { + return on( this, types, selector, data, fn, 1 ); + }, + off: function( types, selector, fn ) { + var handleObj, type; + if ( types && types.preventDefault && types.handleObj ) { + + // ( event ) dispatched jQuery.Event + handleObj = types.handleObj; + jQuery( types.delegateTarget ).off( + handleObj.namespace ? + handleObj.origType + "." + handleObj.namespace : + handleObj.origType, + handleObj.selector, + handleObj.handler + ); + return this; + } + if ( typeof types === "object" ) { + + // ( types-object [, selector] ) + for ( type in types ) { + this.off( type, selector, types[ type ] ); + } + return this; + } + if ( selector === false || typeof selector === "function" ) { + + // ( types [, fn] ) + fn = selector; + selector = undefined; + } + if ( fn === false ) { + fn = returnFalse; + } + return this.each( function() { + jQuery.event.remove( this, types, fn, selector ); + } ); + } +} ); + + +var + + // Support: IE <=10 - 11, Edge 12 - 13 only + // In IE/Edge using regex groups here causes severe slowdowns. + // See https://connect.microsoft.com/IE/feedback/details/1736512/ + rnoInnerhtml = /\s*$/g; + +// Prefer a tbody over its parent table for containing new rows +function manipulationTarget( elem, content ) { + if ( nodeName( elem, "table" ) && + nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ) { + + return jQuery( elem ).children( "tbody" )[ 0 ] || elem; + } + + return elem; +} + +// Replace/restore the type attribute of script elements for safe DOM manipulation +function disableScript( elem ) { + elem.type = ( elem.getAttribute( "type" ) !== null ) + "/" + elem.type; + return elem; +} +function restoreScript( elem ) { + if ( ( elem.type || "" ).slice( 0, 5 ) === "true/" ) { + elem.type = elem.type.slice( 5 ); + } else { + elem.removeAttribute( "type" ); + } + + return elem; +} + +function cloneCopyEvent( src, dest ) { + var i, l, type, pdataOld, udataOld, udataCur, events; + + if ( dest.nodeType !== 1 ) { + return; + } + + // 1. Copy private data: events, handlers, etc. + if ( dataPriv.hasData( src ) ) { + pdataOld = dataPriv.get( src ); + events = pdataOld.events; + + if ( events ) { + dataPriv.remove( dest, "handle events" ); + + for ( type in events ) { + for ( i = 0, l = events[ type ].length; i < l; i++ ) { + jQuery.event.add( dest, type, events[ type ][ i ] ); + } + } + } + } + + // 2. Copy user data + if ( dataUser.hasData( src ) ) { + udataOld = dataUser.access( src ); + udataCur = jQuery.extend( {}, udataOld ); + + dataUser.set( dest, udataCur ); + } +} + +// Fix IE bugs, see support tests +function fixInput( src, dest ) { + var nodeName = dest.nodeName.toLowerCase(); + + // Fails to persist the checked state of a cloned checkbox or radio button. + if ( nodeName === "input" && rcheckableType.test( src.type ) ) { + dest.checked = src.checked; + + // Fails to return the selected option to the default selected state when cloning options + } else if ( nodeName === "input" || nodeName === "textarea" ) { + dest.defaultValue = src.defaultValue; + } +} + +function domManip( collection, args, callback, ignored ) { + + // Flatten any nested arrays + args = flat( args ); + + var fragment, first, scripts, hasScripts, node, doc, + i = 0, + l = collection.length, + iNoClone = l - 1, + value = args[ 0 ], + valueIsFunction = isFunction( value ); + + // We can't cloneNode fragments that contain checked, in WebKit + if ( valueIsFunction || + ( l > 1 && typeof value === "string" && + !support.checkClone && rchecked.test( value ) ) ) { + return collection.each( function( index ) { + var self = collection.eq( index ); + if ( valueIsFunction ) { + args[ 0 ] = value.call( this, index, self.html() ); + } + domManip( self, args, callback, ignored ); + } ); + } + + if ( l ) { + fragment = buildFragment( args, collection[ 0 ].ownerDocument, false, collection, ignored ); + first = fragment.firstChild; + + if ( fragment.childNodes.length === 1 ) { + fragment = first; + } + + // Require either new content or an interest in ignored elements to invoke the callback + if ( first || ignored ) { + scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); + hasScripts = scripts.length; + + // Use the original fragment for the last item + // instead of the first because it can end up + // being emptied incorrectly in certain situations (trac-8070). + for ( ; i < l; i++ ) { + node = fragment; + + if ( i !== iNoClone ) { + node = jQuery.clone( node, true, true ); + + // Keep references to cloned scripts for later restoration + if ( hasScripts ) { + + // Support: Android <=4.0 only, PhantomJS 1 only + // push.apply(_, arraylike) throws on ancient WebKit + jQuery.merge( scripts, getAll( node, "script" ) ); + } + } + + callback.call( collection[ i ], node, i ); + } + + if ( hasScripts ) { + doc = scripts[ scripts.length - 1 ].ownerDocument; + + // Re-enable scripts + jQuery.map( scripts, restoreScript ); + + // Evaluate executable scripts on first document insertion + for ( i = 0; i < hasScripts; i++ ) { + node = scripts[ i ]; + if ( rscriptType.test( node.type || "" ) && + !dataPriv.access( node, "globalEval" ) && + jQuery.contains( doc, node ) ) { + + if ( node.src && ( node.type || "" ).toLowerCase() !== "module" ) { + + // Optional AJAX dependency, but won't run scripts if not present + if ( jQuery._evalUrl && !node.noModule ) { + jQuery._evalUrl( node.src, { + nonce: node.nonce || node.getAttribute( "nonce" ) + }, doc ); + } + } else { + + // Unwrap a CDATA section containing script contents. This shouldn't be + // needed as in XML documents they're already not visible when + // inspecting element contents and in HTML documents they have no + // meaning but we're preserving that logic for backwards compatibility. + // This will be removed completely in 4.0. See gh-4904. + DOMEval( node.textContent.replace( rcleanScript, "" ), node, doc ); + } + } + } + } + } + } + + return collection; +} + +function remove( elem, selector, keepData ) { + var node, + nodes = selector ? jQuery.filter( selector, elem ) : elem, + i = 0; + + for ( ; ( node = nodes[ i ] ) != null; i++ ) { + if ( !keepData && node.nodeType === 1 ) { + jQuery.cleanData( getAll( node ) ); + } + + if ( node.parentNode ) { + if ( keepData && isAttached( node ) ) { + setGlobalEval( getAll( node, "script" ) ); + } + node.parentNode.removeChild( node ); + } + } + + return elem; +} + +jQuery.extend( { + htmlPrefilter: function( html ) { + return html; + }, + + clone: function( elem, dataAndEvents, deepDataAndEvents ) { + var i, l, srcElements, destElements, + clone = elem.cloneNode( true ), + inPage = isAttached( elem ); + + // Fix IE cloning issues + if ( !support.noCloneChecked && ( elem.nodeType === 1 || elem.nodeType === 11 ) && + !jQuery.isXMLDoc( elem ) ) { + + // We eschew jQuery#find here for performance reasons: + // https://jsperf.com/getall-vs-sizzle/2 + destElements = getAll( clone ); + srcElements = getAll( elem ); + + for ( i = 0, l = srcElements.length; i < l; i++ ) { + fixInput( srcElements[ i ], destElements[ i ] ); + } + } + + // Copy the events from the original to the clone + if ( dataAndEvents ) { + if ( deepDataAndEvents ) { + srcElements = srcElements || getAll( elem ); + destElements = destElements || getAll( clone ); + + for ( i = 0, l = srcElements.length; i < l; i++ ) { + cloneCopyEvent( srcElements[ i ], destElements[ i ] ); + } + } else { + cloneCopyEvent( elem, clone ); + } + } + + // Preserve script evaluation history + destElements = getAll( clone, "script" ); + if ( destElements.length > 0 ) { + setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); + } + + // Return the cloned set + return clone; + }, + + cleanData: function( elems ) { + var data, elem, type, + special = jQuery.event.special, + i = 0; + + for ( ; ( elem = elems[ i ] ) !== undefined; i++ ) { + if ( acceptData( elem ) ) { + if ( ( data = elem[ dataPriv.expando ] ) ) { + if ( data.events ) { + for ( type in data.events ) { + if ( special[ type ] ) { + jQuery.event.remove( elem, type ); + + // This is a shortcut to avoid jQuery.event.remove's overhead + } else { + jQuery.removeEvent( elem, type, data.handle ); + } + } + } + + // Support: Chrome <=35 - 45+ + // Assign undefined instead of using delete, see Data#remove + elem[ dataPriv.expando ] = undefined; + } + if ( elem[ dataUser.expando ] ) { + + // Support: Chrome <=35 - 45+ + // Assign undefined instead of using delete, see Data#remove + elem[ dataUser.expando ] = undefined; + } + } + } + } +} ); + +jQuery.fn.extend( { + detach: function( selector ) { + return remove( this, selector, true ); + }, + + remove: function( selector ) { + return remove( this, selector ); + }, + + text: function( value ) { + return access( this, function( value ) { + return value === undefined ? + jQuery.text( this ) : + this.empty().each( function() { + if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { + this.textContent = value; + } + } ); + }, null, value, arguments.length ); + }, + + append: function() { + return domManip( this, arguments, function( elem ) { + if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { + var target = manipulationTarget( this, elem ); + target.appendChild( elem ); + } + } ); + }, + + prepend: function() { + return domManip( this, arguments, function( elem ) { + if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { + var target = manipulationTarget( this, elem ); + target.insertBefore( elem, target.firstChild ); + } + } ); + }, + + before: function() { + return domManip( this, arguments, function( elem ) { + if ( this.parentNode ) { + this.parentNode.insertBefore( elem, this ); + } + } ); + }, + + after: function() { + return domManip( this, arguments, function( elem ) { + if ( this.parentNode ) { + this.parentNode.insertBefore( elem, this.nextSibling ); + } + } ); + }, + + empty: function() { + var elem, + i = 0; + + for ( ; ( elem = this[ i ] ) != null; i++ ) { + if ( elem.nodeType === 1 ) { + + // Prevent memory leaks + jQuery.cleanData( getAll( elem, false ) ); + + // Remove any remaining nodes + elem.textContent = ""; + } + } + + return this; + }, + + clone: function( dataAndEvents, deepDataAndEvents ) { + dataAndEvents = dataAndEvents == null ? false : dataAndEvents; + deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; + + return this.map( function() { + return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); + } ); + }, + + html: function( value ) { + return access( this, function( value ) { + var elem = this[ 0 ] || {}, + i = 0, + l = this.length; + + if ( value === undefined && elem.nodeType === 1 ) { + return elem.innerHTML; + } + + // See if we can take a shortcut and just use innerHTML + if ( typeof value === "string" && !rnoInnerhtml.test( value ) && + !wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) { + + value = jQuery.htmlPrefilter( value ); + + try { + for ( ; i < l; i++ ) { + elem = this[ i ] || {}; + + // Remove element nodes and prevent memory leaks + if ( elem.nodeType === 1 ) { + jQuery.cleanData( getAll( elem, false ) ); + elem.innerHTML = value; + } + } + + elem = 0; + + // If using innerHTML throws an exception, use the fallback method + } catch ( e ) {} + } + + if ( elem ) { + this.empty().append( value ); + } + }, null, value, arguments.length ); + }, + + replaceWith: function() { + var ignored = []; + + // Make the changes, replacing each non-ignored context element with the new content + return domManip( this, arguments, function( elem ) { + var parent = this.parentNode; + + if ( jQuery.inArray( this, ignored ) < 0 ) { + jQuery.cleanData( getAll( this ) ); + if ( parent ) { + parent.replaceChild( elem, this ); + } + } + + // Force callback invocation + }, ignored ); + } +} ); + +jQuery.each( { + appendTo: "append", + prependTo: "prepend", + insertBefore: "before", + insertAfter: "after", + replaceAll: "replaceWith" +}, function( name, original ) { + jQuery.fn[ name ] = function( selector ) { + var elems, + ret = [], + insert = jQuery( selector ), + last = insert.length - 1, + i = 0; + + for ( ; i <= last; i++ ) { + elems = i === last ? this : this.clone( true ); + jQuery( insert[ i ] )[ original ]( elems ); + + // Support: Android <=4.0 only, PhantomJS 1 only + // .get() because push.apply(_, arraylike) throws on ancient WebKit + push.apply( ret, elems.get() ); + } + + return this.pushStack( ret ); + }; +} ); +var rnumnonpx = new RegExp( "^(" + pnum + ")(?!px)[a-z%]+$", "i" ); + +var rcustomProp = /^--/; + + +var getStyles = function( elem ) { + + // Support: IE <=11 only, Firefox <=30 (trac-15098, trac-14150) + // IE throws on elements created in popups + // FF meanwhile throws on frame elements through "defaultView.getComputedStyle" + var view = elem.ownerDocument.defaultView; + + if ( !view || !view.opener ) { + view = window; + } + + return view.getComputedStyle( elem ); + }; + +var swap = function( elem, options, callback ) { + var ret, name, + old = {}; + + // Remember the old values, and insert the new ones + for ( name in options ) { + old[ name ] = elem.style[ name ]; + elem.style[ name ] = options[ name ]; + } + + ret = callback.call( elem ); + + // Revert the old values + for ( name in options ) { + elem.style[ name ] = old[ name ]; + } + + return ret; +}; + + +var rboxStyle = new RegExp( cssExpand.join( "|" ), "i" ); + + + +( function() { + + // Executing both pixelPosition & boxSizingReliable tests require only one layout + // so they're executed at the same time to save the second computation. + function computeStyleTests() { + + // This is a singleton, we need to execute it only once + if ( !div ) { + return; + } + + container.style.cssText = "position:absolute;left:-11111px;width:60px;" + + "margin-top:1px;padding:0;border:0"; + div.style.cssText = + "position:relative;display:block;box-sizing:border-box;overflow:scroll;" + + "margin:auto;border:1px;padding:1px;" + + "width:60%;top:1%"; + documentElement.appendChild( container ).appendChild( div ); + + var divStyle = window.getComputedStyle( div ); + pixelPositionVal = divStyle.top !== "1%"; + + // Support: Android 4.0 - 4.3 only, Firefox <=3 - 44 + reliableMarginLeftVal = roundPixelMeasures( divStyle.marginLeft ) === 12; + + // Support: Android 4.0 - 4.3 only, Safari <=9.1 - 10.1, iOS <=7.0 - 9.3 + // Some styles come back with percentage values, even though they shouldn't + div.style.right = "60%"; + pixelBoxStylesVal = roundPixelMeasures( divStyle.right ) === 36; + + // Support: IE 9 - 11 only + // Detect misreporting of content dimensions for box-sizing:border-box elements + boxSizingReliableVal = roundPixelMeasures( divStyle.width ) === 36; + + // Support: IE 9 only + // Detect overflow:scroll screwiness (gh-3699) + // Support: Chrome <=64 + // Don't get tricked when zoom affects offsetWidth (gh-4029) + div.style.position = "absolute"; + scrollboxSizeVal = roundPixelMeasures( div.offsetWidth / 3 ) === 12; + + documentElement.removeChild( container ); + + // Nullify the div so it wouldn't be stored in the memory and + // it will also be a sign that checks already performed + div = null; + } + + function roundPixelMeasures( measure ) { + return Math.round( parseFloat( measure ) ); + } + + var pixelPositionVal, boxSizingReliableVal, scrollboxSizeVal, pixelBoxStylesVal, + reliableTrDimensionsVal, reliableMarginLeftVal, + container = document.createElement( "div" ), + div = document.createElement( "div" ); + + // Finish early in limited (non-browser) environments + if ( !div.style ) { + return; + } + + // Support: IE <=9 - 11 only + // Style of cloned element affects source element cloned (trac-8908) + div.style.backgroundClip = "content-box"; + div.cloneNode( true ).style.backgroundClip = ""; + support.clearCloneStyle = div.style.backgroundClip === "content-box"; + + jQuery.extend( support, { + boxSizingReliable: function() { + computeStyleTests(); + return boxSizingReliableVal; + }, + pixelBoxStyles: function() { + computeStyleTests(); + return pixelBoxStylesVal; + }, + pixelPosition: function() { + computeStyleTests(); + return pixelPositionVal; + }, + reliableMarginLeft: function() { + computeStyleTests(); + return reliableMarginLeftVal; + }, + scrollboxSize: function() { + computeStyleTests(); + return scrollboxSizeVal; + }, + + // Support: IE 9 - 11+, Edge 15 - 18+ + // IE/Edge misreport `getComputedStyle` of table rows with width/height + // set in CSS while `offset*` properties report correct values. + // Behavior in IE 9 is more subtle than in newer versions & it passes + // some versions of this test; make sure not to make it pass there! + // + // Support: Firefox 70+ + // Only Firefox includes border widths + // in computed dimensions. (gh-4529) + reliableTrDimensions: function() { + var table, tr, trChild, trStyle; + if ( reliableTrDimensionsVal == null ) { + table = document.createElement( "table" ); + tr = document.createElement( "tr" ); + trChild = document.createElement( "div" ); + + table.style.cssText = "position:absolute;left:-11111px;border-collapse:separate"; + tr.style.cssText = "box-sizing:content-box;border:1px solid"; + + // Support: Chrome 86+ + // Height set through cssText does not get applied. + // Computed height then comes back as 0. + tr.style.height = "1px"; + trChild.style.height = "9px"; + + // Support: Android 8 Chrome 86+ + // In our bodyBackground.html iframe, + // display for all div elements is set to "inline", + // which causes a problem only in Android 8 Chrome 86. + // Ensuring the div is `display: block` + // gets around this issue. + trChild.style.display = "block"; + + documentElement + .appendChild( table ) + .appendChild( tr ) + .appendChild( trChild ); + + trStyle = window.getComputedStyle( tr ); + reliableTrDimensionsVal = ( parseInt( trStyle.height, 10 ) + + parseInt( trStyle.borderTopWidth, 10 ) + + parseInt( trStyle.borderBottomWidth, 10 ) ) === tr.offsetHeight; + + documentElement.removeChild( table ); + } + return reliableTrDimensionsVal; + } + } ); +} )(); + + +function curCSS( elem, name, computed ) { + var width, minWidth, maxWidth, ret, + isCustomProp = rcustomProp.test( name ), + + // Support: Firefox 51+ + // Retrieving style before computed somehow + // fixes an issue with getting wrong values + // on detached elements + style = elem.style; + + computed = computed || getStyles( elem ); + + // getPropertyValue is needed for: + // .css('filter') (IE 9 only, trac-12537) + // .css('--customProperty) (gh-3144) + if ( computed ) { + + // Support: IE <=9 - 11+ + // IE only supports `"float"` in `getPropertyValue`; in computed styles + // it's only available as `"cssFloat"`. We no longer modify properties + // sent to `.css()` apart from camelCasing, so we need to check both. + // Normally, this would create difference in behavior: if + // `getPropertyValue` returns an empty string, the value returned + // by `.css()` would be `undefined`. This is usually the case for + // disconnected elements. However, in IE even disconnected elements + // with no styles return `"none"` for `getPropertyValue( "float" )` + ret = computed.getPropertyValue( name ) || computed[ name ]; + + if ( isCustomProp && ret ) { + + // Support: Firefox 105+, Chrome <=105+ + // Spec requires trimming whitespace for custom properties (gh-4926). + // Firefox only trims leading whitespace. Chrome just collapses + // both leading & trailing whitespace to a single space. + // + // Fall back to `undefined` if empty string returned. + // This collapses a missing definition with property defined + // and set to an empty string but there's no standard API + // allowing us to differentiate them without a performance penalty + // and returning `undefined` aligns with older jQuery. + // + // rtrimCSS treats U+000D CARRIAGE RETURN and U+000C FORM FEED + // as whitespace while CSS does not, but this is not a problem + // because CSS preprocessing replaces them with U+000A LINE FEED + // (which *is* CSS whitespace) + // https://www.w3.org/TR/css-syntax-3/#input-preprocessing + ret = ret.replace( rtrimCSS, "$1" ) || undefined; + } + + if ( ret === "" && !isAttached( elem ) ) { + ret = jQuery.style( elem, name ); + } + + // A tribute to the "awesome hack by Dean Edwards" + // Android Browser returns percentage for some values, + // but width seems to be reliably pixels. + // This is against the CSSOM draft spec: + // https://drafts.csswg.org/cssom/#resolved-values + if ( !support.pixelBoxStyles() && rnumnonpx.test( ret ) && rboxStyle.test( name ) ) { + + // Remember the original values + width = style.width; + minWidth = style.minWidth; + maxWidth = style.maxWidth; + + // Put in the new values to get a computed value out + style.minWidth = style.maxWidth = style.width = ret; + ret = computed.width; + + // Revert the changed values + style.width = width; + style.minWidth = minWidth; + style.maxWidth = maxWidth; + } + } + + return ret !== undefined ? + + // Support: IE <=9 - 11 only + // IE returns zIndex value as an integer. + ret + "" : + ret; +} + + +function addGetHookIf( conditionFn, hookFn ) { + + // Define the hook, we'll check on the first run if it's really needed. + return { + get: function() { + if ( conditionFn() ) { + + // Hook not needed (or it's not possible to use it due + // to missing dependency), remove it. + delete this.get; + return; + } + + // Hook needed; redefine it so that the support test is not executed again. + return ( this.get = hookFn ).apply( this, arguments ); + } + }; +} + + +var cssPrefixes = [ "Webkit", "Moz", "ms" ], + emptyStyle = document.createElement( "div" ).style, + vendorProps = {}; + +// Return a vendor-prefixed property or undefined +function vendorPropName( name ) { + + // Check for vendor prefixed names + var capName = name[ 0 ].toUpperCase() + name.slice( 1 ), + i = cssPrefixes.length; + + while ( i-- ) { + name = cssPrefixes[ i ] + capName; + if ( name in emptyStyle ) { + return name; + } + } +} + +// Return a potentially-mapped jQuery.cssProps or vendor prefixed property +function finalPropName( name ) { + var final = jQuery.cssProps[ name ] || vendorProps[ name ]; + + if ( final ) { + return final; + } + if ( name in emptyStyle ) { + return name; + } + return vendorProps[ name ] = vendorPropName( name ) || name; +} + + +var + + // Swappable if display is none or starts with table + // except "table", "table-cell", or "table-caption" + // See here for display values: https://developer.mozilla.org/en-US/docs/CSS/display + rdisplayswap = /^(none|table(?!-c[ea]).+)/, + cssShow = { position: "absolute", visibility: "hidden", display: "block" }, + cssNormalTransform = { + letterSpacing: "0", + fontWeight: "400" + }; + +function setPositiveNumber( _elem, value, subtract ) { + + // Any relative (+/-) values have already been + // normalized at this point + var matches = rcssNum.exec( value ); + return matches ? + + // Guard against undefined "subtract", e.g., when used as in cssHooks + Math.max( 0, matches[ 2 ] - ( subtract || 0 ) ) + ( matches[ 3 ] || "px" ) : + value; +} + +function boxModelAdjustment( elem, dimension, box, isBorderBox, styles, computedVal ) { + var i = dimension === "width" ? 1 : 0, + extra = 0, + delta = 0, + marginDelta = 0; + + // Adjustment may not be necessary + if ( box === ( isBorderBox ? "border" : "content" ) ) { + return 0; + } + + for ( ; i < 4; i += 2 ) { + + // Both box models exclude margin + // Count margin delta separately to only add it after scroll gutter adjustment. + // This is needed to make negative margins work with `outerHeight( true )` (gh-3982). + if ( box === "margin" ) { + marginDelta += jQuery.css( elem, box + cssExpand[ i ], true, styles ); + } + + // If we get here with a content-box, we're seeking "padding" or "border" or "margin" + if ( !isBorderBox ) { + + // Add padding + delta += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); + + // For "border" or "margin", add border + if ( box !== "padding" ) { + delta += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); + + // But still keep track of it otherwise + } else { + extra += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); + } + + // If we get here with a border-box (content + padding + border), we're seeking "content" or + // "padding" or "margin" + } else { + + // For "content", subtract padding + if ( box === "content" ) { + delta -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); + } + + // For "content" or "padding", subtract border + if ( box !== "margin" ) { + delta -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); + } + } + } + + // Account for positive content-box scroll gutter when requested by providing computedVal + if ( !isBorderBox && computedVal >= 0 ) { + + // offsetWidth/offsetHeight is a rounded sum of content, padding, scroll gutter, and border + // Assuming integer scroll gutter, subtract the rest and round down + delta += Math.max( 0, Math.ceil( + elem[ "offset" + dimension[ 0 ].toUpperCase() + dimension.slice( 1 ) ] - + computedVal - + delta - + extra - + 0.5 + + // If offsetWidth/offsetHeight is unknown, then we can't determine content-box scroll gutter + // Use an explicit zero to avoid NaN (gh-3964) + ) ) || 0; + } + + return delta + marginDelta; +} + +function getWidthOrHeight( elem, dimension, extra ) { + + // Start with computed style + var styles = getStyles( elem ), + + // To avoid forcing a reflow, only fetch boxSizing if we need it (gh-4322). + // Fake content-box until we know it's needed to know the true value. + boxSizingNeeded = !support.boxSizingReliable() || extra, + isBorderBox = boxSizingNeeded && + jQuery.css( elem, "boxSizing", false, styles ) === "border-box", + valueIsBorderBox = isBorderBox, + + val = curCSS( elem, dimension, styles ), + offsetProp = "offset" + dimension[ 0 ].toUpperCase() + dimension.slice( 1 ); + + // Support: Firefox <=54 + // Return a confounding non-pixel value or feign ignorance, as appropriate. + if ( rnumnonpx.test( val ) ) { + if ( !extra ) { + return val; + } + val = "auto"; + } + + + // Support: IE 9 - 11 only + // Use offsetWidth/offsetHeight for when box sizing is unreliable. + // In those cases, the computed value can be trusted to be border-box. + if ( ( !support.boxSizingReliable() && isBorderBox || + + // Support: IE 10 - 11+, Edge 15 - 18+ + // IE/Edge misreport `getComputedStyle` of table rows with width/height + // set in CSS while `offset*` properties report correct values. + // Interestingly, in some cases IE 9 doesn't suffer from this issue. + !support.reliableTrDimensions() && nodeName( elem, "tr" ) || + + // Fall back to offsetWidth/offsetHeight when value is "auto" + // This happens for inline elements with no explicit setting (gh-3571) + val === "auto" || + + // Support: Android <=4.1 - 4.3 only + // Also use offsetWidth/offsetHeight for misreported inline dimensions (gh-3602) + !parseFloat( val ) && jQuery.css( elem, "display", false, styles ) === "inline" ) && + + // Make sure the element is visible & connected + elem.getClientRects().length ) { + + isBorderBox = jQuery.css( elem, "boxSizing", false, styles ) === "border-box"; + + // Where available, offsetWidth/offsetHeight approximate border box dimensions. + // Where not available (e.g., SVG), assume unreliable box-sizing and interpret the + // retrieved value as a content box dimension. + valueIsBorderBox = offsetProp in elem; + if ( valueIsBorderBox ) { + val = elem[ offsetProp ]; + } + } + + // Normalize "" and auto + val = parseFloat( val ) || 0; + + // Adjust for the element's box model + return ( val + + boxModelAdjustment( + elem, + dimension, + extra || ( isBorderBox ? "border" : "content" ), + valueIsBorderBox, + styles, + + // Provide the current computed size to request scroll gutter calculation (gh-3589) + val + ) + ) + "px"; +} + +jQuery.extend( { + + // Add in style property hooks for overriding the default + // behavior of getting and setting a style property + cssHooks: { + opacity: { + get: function( elem, computed ) { + if ( computed ) { + + // We should always get a number back from opacity + var ret = curCSS( elem, "opacity" ); + return ret === "" ? "1" : ret; + } + } + } + }, + + // Don't automatically add "px" to these possibly-unitless properties + cssNumber: { + animationIterationCount: true, + aspectRatio: true, + borderImageSlice: true, + columnCount: true, + flexGrow: true, + flexShrink: true, + fontWeight: true, + gridArea: true, + gridColumn: true, + gridColumnEnd: true, + gridColumnStart: true, + gridRow: true, + gridRowEnd: true, + gridRowStart: true, + lineHeight: true, + opacity: true, + order: true, + orphans: true, + scale: true, + widows: true, + zIndex: true, + zoom: true, + + // SVG-related + fillOpacity: true, + floodOpacity: true, + stopOpacity: true, + strokeMiterlimit: true, + strokeOpacity: true + }, + + // Add in properties whose names you wish to fix before + // setting or getting the value + cssProps: {}, + + // Get and set the style property on a DOM Node + style: function( elem, name, value, extra ) { + + // Don't set styles on text and comment nodes + if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { + return; + } + + // Make sure that we're working with the right name + var ret, type, hooks, + origName = camelCase( name ), + isCustomProp = rcustomProp.test( name ), + style = elem.style; + + // Make sure that we're working with the right name. We don't + // want to query the value if it is a CSS custom property + // since they are user-defined. + if ( !isCustomProp ) { + name = finalPropName( origName ); + } + + // Gets hook for the prefixed version, then unprefixed version + hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; + + // Check if we're setting a value + if ( value !== undefined ) { + type = typeof value; + + // Convert "+=" or "-=" to relative numbers (trac-7345) + if ( type === "string" && ( ret = rcssNum.exec( value ) ) && ret[ 1 ] ) { + value = adjustCSS( elem, name, ret ); + + // Fixes bug trac-9237 + type = "number"; + } + + // Make sure that null and NaN values aren't set (trac-7116) + if ( value == null || value !== value ) { + return; + } + + // If a number was passed in, add the unit (except for certain CSS properties) + // The isCustomProp check can be removed in jQuery 4.0 when we only auto-append + // "px" to a few hardcoded values. + if ( type === "number" && !isCustomProp ) { + value += ret && ret[ 3 ] || ( jQuery.cssNumber[ origName ] ? "" : "px" ); + } + + // background-* props affect original clone's values + if ( !support.clearCloneStyle && value === "" && name.indexOf( "background" ) === 0 ) { + style[ name ] = "inherit"; + } + + // If a hook was provided, use that value, otherwise just set the specified value + if ( !hooks || !( "set" in hooks ) || + ( value = hooks.set( elem, value, extra ) ) !== undefined ) { + + if ( isCustomProp ) { + style.setProperty( name, value ); + } else { + style[ name ] = value; + } + } + + } else { + + // If a hook was provided get the non-computed value from there + if ( hooks && "get" in hooks && + ( ret = hooks.get( elem, false, extra ) ) !== undefined ) { + + return ret; + } + + // Otherwise just get the value from the style object + return style[ name ]; + } + }, + + css: function( elem, name, extra, styles ) { + var val, num, hooks, + origName = camelCase( name ), + isCustomProp = rcustomProp.test( name ); + + // Make sure that we're working with the right name. We don't + // want to modify the value if it is a CSS custom property + // since they are user-defined. + if ( !isCustomProp ) { + name = finalPropName( origName ); + } + + // Try prefixed name followed by the unprefixed name + hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; + + // If a hook was provided get the computed value from there + if ( hooks && "get" in hooks ) { + val = hooks.get( elem, true, extra ); + } + + // Otherwise, if a way to get the computed value exists, use that + if ( val === undefined ) { + val = curCSS( elem, name, styles ); + } + + // Convert "normal" to computed value + if ( val === "normal" && name in cssNormalTransform ) { + val = cssNormalTransform[ name ]; + } + + // Make numeric if forced or a qualifier was provided and val looks numeric + if ( extra === "" || extra ) { + num = parseFloat( val ); + return extra === true || isFinite( num ) ? num || 0 : val; + } + + return val; + } +} ); + +jQuery.each( [ "height", "width" ], function( _i, dimension ) { + jQuery.cssHooks[ dimension ] = { + get: function( elem, computed, extra ) { + if ( computed ) { + + // Certain elements can have dimension info if we invisibly show them + // but it must have a current display style that would benefit + return rdisplayswap.test( jQuery.css( elem, "display" ) ) && + + // Support: Safari 8+ + // Table columns in Safari have non-zero offsetWidth & zero + // getBoundingClientRect().width unless display is changed. + // Support: IE <=11 only + // Running getBoundingClientRect on a disconnected node + // in IE throws an error. + ( !elem.getClientRects().length || !elem.getBoundingClientRect().width ) ? + swap( elem, cssShow, function() { + return getWidthOrHeight( elem, dimension, extra ); + } ) : + getWidthOrHeight( elem, dimension, extra ); + } + }, + + set: function( elem, value, extra ) { + var matches, + styles = getStyles( elem ), + + // Only read styles.position if the test has a chance to fail + // to avoid forcing a reflow. + scrollboxSizeBuggy = !support.scrollboxSize() && + styles.position === "absolute", + + // To avoid forcing a reflow, only fetch boxSizing if we need it (gh-3991) + boxSizingNeeded = scrollboxSizeBuggy || extra, + isBorderBox = boxSizingNeeded && + jQuery.css( elem, "boxSizing", false, styles ) === "border-box", + subtract = extra ? + boxModelAdjustment( + elem, + dimension, + extra, + isBorderBox, + styles + ) : + 0; + + // Account for unreliable border-box dimensions by comparing offset* to computed and + // faking a content-box to get border and padding (gh-3699) + if ( isBorderBox && scrollboxSizeBuggy ) { + subtract -= Math.ceil( + elem[ "offset" + dimension[ 0 ].toUpperCase() + dimension.slice( 1 ) ] - + parseFloat( styles[ dimension ] ) - + boxModelAdjustment( elem, dimension, "border", false, styles ) - + 0.5 + ); + } + + // Convert to pixels if value adjustment is needed + if ( subtract && ( matches = rcssNum.exec( value ) ) && + ( matches[ 3 ] || "px" ) !== "px" ) { + + elem.style[ dimension ] = value; + value = jQuery.css( elem, dimension ); + } + + return setPositiveNumber( elem, value, subtract ); + } + }; +} ); + +jQuery.cssHooks.marginLeft = addGetHookIf( support.reliableMarginLeft, + function( elem, computed ) { + if ( computed ) { + return ( parseFloat( curCSS( elem, "marginLeft" ) ) || + elem.getBoundingClientRect().left - + swap( elem, { marginLeft: 0 }, function() { + return elem.getBoundingClientRect().left; + } ) + ) + "px"; + } + } +); + +// These hooks are used by animate to expand properties +jQuery.each( { + margin: "", + padding: "", + border: "Width" +}, function( prefix, suffix ) { + jQuery.cssHooks[ prefix + suffix ] = { + expand: function( value ) { + var i = 0, + expanded = {}, + + // Assumes a single number if not a string + parts = typeof value === "string" ? value.split( " " ) : [ value ]; + + for ( ; i < 4; i++ ) { + expanded[ prefix + cssExpand[ i ] + suffix ] = + parts[ i ] || parts[ i - 2 ] || parts[ 0 ]; + } + + return expanded; + } + }; + + if ( prefix !== "margin" ) { + jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber; + } +} ); + +jQuery.fn.extend( { + css: function( name, value ) { + return access( this, function( elem, name, value ) { + var styles, len, + map = {}, + i = 0; + + if ( Array.isArray( name ) ) { + styles = getStyles( elem ); + len = name.length; + + for ( ; i < len; i++ ) { + map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles ); + } + + return map; + } + + return value !== undefined ? + jQuery.style( elem, name, value ) : + jQuery.css( elem, name ); + }, name, value, arguments.length > 1 ); + } +} ); + + +function Tween( elem, options, prop, end, easing ) { + return new Tween.prototype.init( elem, options, prop, end, easing ); +} +jQuery.Tween = Tween; + +Tween.prototype = { + constructor: Tween, + init: function( elem, options, prop, end, easing, unit ) { + this.elem = elem; + this.prop = prop; + this.easing = easing || jQuery.easing._default; + this.options = options; + this.start = this.now = this.cur(); + this.end = end; + this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" ); + }, + cur: function() { + var hooks = Tween.propHooks[ this.prop ]; + + return hooks && hooks.get ? + hooks.get( this ) : + Tween.propHooks._default.get( this ); + }, + run: function( percent ) { + var eased, + hooks = Tween.propHooks[ this.prop ]; + + if ( this.options.duration ) { + this.pos = eased = jQuery.easing[ this.easing ]( + percent, this.options.duration * percent, 0, 1, this.options.duration + ); + } else { + this.pos = eased = percent; + } + this.now = ( this.end - this.start ) * eased + this.start; + + if ( this.options.step ) { + this.options.step.call( this.elem, this.now, this ); + } + + if ( hooks && hooks.set ) { + hooks.set( this ); + } else { + Tween.propHooks._default.set( this ); + } + return this; + } +}; + +Tween.prototype.init.prototype = Tween.prototype; + +Tween.propHooks = { + _default: { + get: function( tween ) { + var result; + + // Use a property on the element directly when it is not a DOM element, + // or when there is no matching style property that exists. + if ( tween.elem.nodeType !== 1 || + tween.elem[ tween.prop ] != null && tween.elem.style[ tween.prop ] == null ) { + return tween.elem[ tween.prop ]; + } + + // Passing an empty string as a 3rd parameter to .css will automatically + // attempt a parseFloat and fallback to a string if the parse fails. + // Simple values such as "10px" are parsed to Float; + // complex values such as "rotate(1rad)" are returned as-is. + result = jQuery.css( tween.elem, tween.prop, "" ); + + // Empty strings, null, undefined and "auto" are converted to 0. + return !result || result === "auto" ? 0 : result; + }, + set: function( tween ) { + + // Use step hook for back compat. + // Use cssHook if its there. + // Use .style if available and use plain properties where available. + if ( jQuery.fx.step[ tween.prop ] ) { + jQuery.fx.step[ tween.prop ]( tween ); + } else if ( tween.elem.nodeType === 1 && ( + jQuery.cssHooks[ tween.prop ] || + tween.elem.style[ finalPropName( tween.prop ) ] != null ) ) { + jQuery.style( tween.elem, tween.prop, tween.now + tween.unit ); + } else { + tween.elem[ tween.prop ] = tween.now; + } + } + } +}; + +// Support: IE <=9 only +// Panic based approach to setting things on disconnected nodes +Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = { + set: function( tween ) { + if ( tween.elem.nodeType && tween.elem.parentNode ) { + tween.elem[ tween.prop ] = tween.now; + } + } +}; + +jQuery.easing = { + linear: function( p ) { + return p; + }, + swing: function( p ) { + return 0.5 - Math.cos( p * Math.PI ) / 2; + }, + _default: "swing" +}; + +jQuery.fx = Tween.prototype.init; + +// Back compat <1.8 extension point +jQuery.fx.step = {}; + + + + +var + fxNow, inProgress, + rfxtypes = /^(?:toggle|show|hide)$/, + rrun = /queueHooks$/; + +function schedule() { + if ( inProgress ) { + if ( document.hidden === false && window.requestAnimationFrame ) { + window.requestAnimationFrame( schedule ); + } else { + window.setTimeout( schedule, jQuery.fx.interval ); + } + + jQuery.fx.tick(); + } +} + +// Animations created synchronously will run synchronously +function createFxNow() { + window.setTimeout( function() { + fxNow = undefined; + } ); + return ( fxNow = Date.now() ); +} + +// Generate parameters to create a standard animation +function genFx( type, includeWidth ) { + var which, + i = 0, + attrs = { height: type }; + + // If we include width, step value is 1 to do all cssExpand values, + // otherwise step value is 2 to skip over Left and Right + includeWidth = includeWidth ? 1 : 0; + for ( ; i < 4; i += 2 - includeWidth ) { + which = cssExpand[ i ]; + attrs[ "margin" + which ] = attrs[ "padding" + which ] = type; + } + + if ( includeWidth ) { + attrs.opacity = attrs.width = type; + } + + return attrs; +} + +function createTween( value, prop, animation ) { + var tween, + collection = ( Animation.tweeners[ prop ] || [] ).concat( Animation.tweeners[ "*" ] ), + index = 0, + length = collection.length; + for ( ; index < length; index++ ) { + if ( ( tween = collection[ index ].call( animation, prop, value ) ) ) { + + // We're done with this property + return tween; + } + } +} + +function defaultPrefilter( elem, props, opts ) { + var prop, value, toggle, hooks, oldfire, propTween, restoreDisplay, display, + isBox = "width" in props || "height" in props, + anim = this, + orig = {}, + style = elem.style, + hidden = elem.nodeType && isHiddenWithinTree( elem ), + dataShow = dataPriv.get( elem, "fxshow" ); + + // Queue-skipping animations hijack the fx hooks + if ( !opts.queue ) { + hooks = jQuery._queueHooks( elem, "fx" ); + if ( hooks.unqueued == null ) { + hooks.unqueued = 0; + oldfire = hooks.empty.fire; + hooks.empty.fire = function() { + if ( !hooks.unqueued ) { + oldfire(); + } + }; + } + hooks.unqueued++; + + anim.always( function() { + + // Ensure the complete handler is called before this completes + anim.always( function() { + hooks.unqueued--; + if ( !jQuery.queue( elem, "fx" ).length ) { + hooks.empty.fire(); + } + } ); + } ); + } + + // Detect show/hide animations + for ( prop in props ) { + value = props[ prop ]; + if ( rfxtypes.test( value ) ) { + delete props[ prop ]; + toggle = toggle || value === "toggle"; + if ( value === ( hidden ? "hide" : "show" ) ) { + + // Pretend to be hidden if this is a "show" and + // there is still data from a stopped show/hide + if ( value === "show" && dataShow && dataShow[ prop ] !== undefined ) { + hidden = true; + + // Ignore all other no-op show/hide data + } else { + continue; + } + } + orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop ); + } + } + + // Bail out if this is a no-op like .hide().hide() + propTween = !jQuery.isEmptyObject( props ); + if ( !propTween && jQuery.isEmptyObject( orig ) ) { + return; + } + + // Restrict "overflow" and "display" styles during box animations + if ( isBox && elem.nodeType === 1 ) { + + // Support: IE <=9 - 11, Edge 12 - 15 + // Record all 3 overflow attributes because IE does not infer the shorthand + // from identically-valued overflowX and overflowY and Edge just mirrors + // the overflowX value there. + opts.overflow = [ style.overflow, style.overflowX, style.overflowY ]; + + // Identify a display type, preferring old show/hide data over the CSS cascade + restoreDisplay = dataShow && dataShow.display; + if ( restoreDisplay == null ) { + restoreDisplay = dataPriv.get( elem, "display" ); + } + display = jQuery.css( elem, "display" ); + if ( display === "none" ) { + if ( restoreDisplay ) { + display = restoreDisplay; + } else { + + // Get nonempty value(s) by temporarily forcing visibility + showHide( [ elem ], true ); + restoreDisplay = elem.style.display || restoreDisplay; + display = jQuery.css( elem, "display" ); + showHide( [ elem ] ); + } + } + + // Animate inline elements as inline-block + if ( display === "inline" || display === "inline-block" && restoreDisplay != null ) { + if ( jQuery.css( elem, "float" ) === "none" ) { + + // Restore the original display value at the end of pure show/hide animations + if ( !propTween ) { + anim.done( function() { + style.display = restoreDisplay; + } ); + if ( restoreDisplay == null ) { + display = style.display; + restoreDisplay = display === "none" ? "" : display; + } + } + style.display = "inline-block"; + } + } + } + + if ( opts.overflow ) { + style.overflow = "hidden"; + anim.always( function() { + style.overflow = opts.overflow[ 0 ]; + style.overflowX = opts.overflow[ 1 ]; + style.overflowY = opts.overflow[ 2 ]; + } ); + } + + // Implement show/hide animations + propTween = false; + for ( prop in orig ) { + + // General show/hide setup for this element animation + if ( !propTween ) { + if ( dataShow ) { + if ( "hidden" in dataShow ) { + hidden = dataShow.hidden; + } + } else { + dataShow = dataPriv.access( elem, "fxshow", { display: restoreDisplay } ); + } + + // Store hidden/visible for toggle so `.stop().toggle()` "reverses" + if ( toggle ) { + dataShow.hidden = !hidden; + } + + // Show elements before animating them + if ( hidden ) { + showHide( [ elem ], true ); + } + + /* eslint-disable no-loop-func */ + + anim.done( function() { + + /* eslint-enable no-loop-func */ + + // The final step of a "hide" animation is actually hiding the element + if ( !hidden ) { + showHide( [ elem ] ); + } + dataPriv.remove( elem, "fxshow" ); + for ( prop in orig ) { + jQuery.style( elem, prop, orig[ prop ] ); + } + } ); + } + + // Per-property setup + propTween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim ); + if ( !( prop in dataShow ) ) { + dataShow[ prop ] = propTween.start; + if ( hidden ) { + propTween.end = propTween.start; + propTween.start = 0; + } + } + } +} + +function propFilter( props, specialEasing ) { + var index, name, easing, value, hooks; + + // camelCase, specialEasing and expand cssHook pass + for ( index in props ) { + name = camelCase( index ); + easing = specialEasing[ name ]; + value = props[ index ]; + if ( Array.isArray( value ) ) { + easing = value[ 1 ]; + value = props[ index ] = value[ 0 ]; + } + + if ( index !== name ) { + props[ name ] = value; + delete props[ index ]; + } + + hooks = jQuery.cssHooks[ name ]; + if ( hooks && "expand" in hooks ) { + value = hooks.expand( value ); + delete props[ name ]; + + // Not quite $.extend, this won't overwrite existing keys. + // Reusing 'index' because we have the correct "name" + for ( index in value ) { + if ( !( index in props ) ) { + props[ index ] = value[ index ]; + specialEasing[ index ] = easing; + } + } + } else { + specialEasing[ name ] = easing; + } + } +} + +function Animation( elem, properties, options ) { + var result, + stopped, + index = 0, + length = Animation.prefilters.length, + deferred = jQuery.Deferred().always( function() { + + // Don't match elem in the :animated selector + delete tick.elem; + } ), + tick = function() { + if ( stopped ) { + return false; + } + var currentTime = fxNow || createFxNow(), + remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ), + + // Support: Android 2.3 only + // Archaic crash bug won't allow us to use `1 - ( 0.5 || 0 )` (trac-12497) + temp = remaining / animation.duration || 0, + percent = 1 - temp, + index = 0, + length = animation.tweens.length; + + for ( ; index < length; index++ ) { + animation.tweens[ index ].run( percent ); + } + + deferred.notifyWith( elem, [ animation, percent, remaining ] ); + + // If there's more to do, yield + if ( percent < 1 && length ) { + return remaining; + } + + // If this was an empty animation, synthesize a final progress notification + if ( !length ) { + deferred.notifyWith( elem, [ animation, 1, 0 ] ); + } + + // Resolve the animation and report its conclusion + deferred.resolveWith( elem, [ animation ] ); + return false; + }, + animation = deferred.promise( { + elem: elem, + props: jQuery.extend( {}, properties ), + opts: jQuery.extend( true, { + specialEasing: {}, + easing: jQuery.easing._default + }, options ), + originalProperties: properties, + originalOptions: options, + startTime: fxNow || createFxNow(), + duration: options.duration, + tweens: [], + createTween: function( prop, end ) { + var tween = jQuery.Tween( elem, animation.opts, prop, end, + animation.opts.specialEasing[ prop ] || animation.opts.easing ); + animation.tweens.push( tween ); + return tween; + }, + stop: function( gotoEnd ) { + var index = 0, + + // If we are going to the end, we want to run all the tweens + // otherwise we skip this part + length = gotoEnd ? animation.tweens.length : 0; + if ( stopped ) { + return this; + } + stopped = true; + for ( ; index < length; index++ ) { + animation.tweens[ index ].run( 1 ); + } + + // Resolve when we played the last frame; otherwise, reject + if ( gotoEnd ) { + deferred.notifyWith( elem, [ animation, 1, 0 ] ); + deferred.resolveWith( elem, [ animation, gotoEnd ] ); + } else { + deferred.rejectWith( elem, [ animation, gotoEnd ] ); + } + return this; + } + } ), + props = animation.props; + + propFilter( props, animation.opts.specialEasing ); + + for ( ; index < length; index++ ) { + result = Animation.prefilters[ index ].call( animation, elem, props, animation.opts ); + if ( result ) { + if ( isFunction( result.stop ) ) { + jQuery._queueHooks( animation.elem, animation.opts.queue ).stop = + result.stop.bind( result ); + } + return result; + } + } + + jQuery.map( props, createTween, animation ); + + if ( isFunction( animation.opts.start ) ) { + animation.opts.start.call( elem, animation ); + } + + // Attach callbacks from options + animation + .progress( animation.opts.progress ) + .done( animation.opts.done, animation.opts.complete ) + .fail( animation.opts.fail ) + .always( animation.opts.always ); + + jQuery.fx.timer( + jQuery.extend( tick, { + elem: elem, + anim: animation, + queue: animation.opts.queue + } ) + ); + + return animation; +} + +jQuery.Animation = jQuery.extend( Animation, { + + tweeners: { + "*": [ function( prop, value ) { + var tween = this.createTween( prop, value ); + adjustCSS( tween.elem, prop, rcssNum.exec( value ), tween ); + return tween; + } ] + }, + + tweener: function( props, callback ) { + if ( isFunction( props ) ) { + callback = props; + props = [ "*" ]; + } else { + props = props.match( rnothtmlwhite ); + } + + var prop, + index = 0, + length = props.length; + + for ( ; index < length; index++ ) { + prop = props[ index ]; + Animation.tweeners[ prop ] = Animation.tweeners[ prop ] || []; + Animation.tweeners[ prop ].unshift( callback ); + } + }, + + prefilters: [ defaultPrefilter ], + + prefilter: function( callback, prepend ) { + if ( prepend ) { + Animation.prefilters.unshift( callback ); + } else { + Animation.prefilters.push( callback ); + } + } +} ); + +jQuery.speed = function( speed, easing, fn ) { + var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : { + complete: fn || !fn && easing || + isFunction( speed ) && speed, + duration: speed, + easing: fn && easing || easing && !isFunction( easing ) && easing + }; + + // Go to the end state if fx are off + if ( jQuery.fx.off ) { + opt.duration = 0; + + } else { + if ( typeof opt.duration !== "number" ) { + if ( opt.duration in jQuery.fx.speeds ) { + opt.duration = jQuery.fx.speeds[ opt.duration ]; + + } else { + opt.duration = jQuery.fx.speeds._default; + } + } + } + + // Normalize opt.queue - true/undefined/null -> "fx" + if ( opt.queue == null || opt.queue === true ) { + opt.queue = "fx"; + } + + // Queueing + opt.old = opt.complete; + + opt.complete = function() { + if ( isFunction( opt.old ) ) { + opt.old.call( this ); + } + + if ( opt.queue ) { + jQuery.dequeue( this, opt.queue ); + } + }; + + return opt; +}; + +jQuery.fn.extend( { + fadeTo: function( speed, to, easing, callback ) { + + // Show any hidden elements after setting opacity to 0 + return this.filter( isHiddenWithinTree ).css( "opacity", 0 ).show() + + // Animate to the value specified + .end().animate( { opacity: to }, speed, easing, callback ); + }, + animate: function( prop, speed, easing, callback ) { + var empty = jQuery.isEmptyObject( prop ), + optall = jQuery.speed( speed, easing, callback ), + doAnimation = function() { + + // Operate on a copy of prop so per-property easing won't be lost + var anim = Animation( this, jQuery.extend( {}, prop ), optall ); + + // Empty animations, or finishing resolves immediately + if ( empty || dataPriv.get( this, "finish" ) ) { + anim.stop( true ); + } + }; + + doAnimation.finish = doAnimation; + + return empty || optall.queue === false ? + this.each( doAnimation ) : + this.queue( optall.queue, doAnimation ); + }, + stop: function( type, clearQueue, gotoEnd ) { + var stopQueue = function( hooks ) { + var stop = hooks.stop; + delete hooks.stop; + stop( gotoEnd ); + }; + + if ( typeof type !== "string" ) { + gotoEnd = clearQueue; + clearQueue = type; + type = undefined; + } + if ( clearQueue ) { + this.queue( type || "fx", [] ); + } + + return this.each( function() { + var dequeue = true, + index = type != null && type + "queueHooks", + timers = jQuery.timers, + data = dataPriv.get( this ); + + if ( index ) { + if ( data[ index ] && data[ index ].stop ) { + stopQueue( data[ index ] ); + } + } else { + for ( index in data ) { + if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) { + stopQueue( data[ index ] ); + } + } + } + + for ( index = timers.length; index--; ) { + if ( timers[ index ].elem === this && + ( type == null || timers[ index ].queue === type ) ) { + + timers[ index ].anim.stop( gotoEnd ); + dequeue = false; + timers.splice( index, 1 ); + } + } + + // Start the next in the queue if the last step wasn't forced. + // Timers currently will call their complete callbacks, which + // will dequeue but only if they were gotoEnd. + if ( dequeue || !gotoEnd ) { + jQuery.dequeue( this, type ); + } + } ); + }, + finish: function( type ) { + if ( type !== false ) { + type = type || "fx"; + } + return this.each( function() { + var index, + data = dataPriv.get( this ), + queue = data[ type + "queue" ], + hooks = data[ type + "queueHooks" ], + timers = jQuery.timers, + length = queue ? queue.length : 0; + + // Enable finishing flag on private data + data.finish = true; + + // Empty the queue first + jQuery.queue( this, type, [] ); + + if ( hooks && hooks.stop ) { + hooks.stop.call( this, true ); + } + + // Look for any active animations, and finish them + for ( index = timers.length; index--; ) { + if ( timers[ index ].elem === this && timers[ index ].queue === type ) { + timers[ index ].anim.stop( true ); + timers.splice( index, 1 ); + } + } + + // Look for any animations in the old queue and finish them + for ( index = 0; index < length; index++ ) { + if ( queue[ index ] && queue[ index ].finish ) { + queue[ index ].finish.call( this ); + } + } + + // Turn off finishing flag + delete data.finish; + } ); + } +} ); + +jQuery.each( [ "toggle", "show", "hide" ], function( _i, name ) { + var cssFn = jQuery.fn[ name ]; + jQuery.fn[ name ] = function( speed, easing, callback ) { + return speed == null || typeof speed === "boolean" ? + cssFn.apply( this, arguments ) : + this.animate( genFx( name, true ), speed, easing, callback ); + }; +} ); + +// Generate shortcuts for custom animations +jQuery.each( { + slideDown: genFx( "show" ), + slideUp: genFx( "hide" ), + slideToggle: genFx( "toggle" ), + fadeIn: { opacity: "show" }, + fadeOut: { opacity: "hide" }, + fadeToggle: { opacity: "toggle" } +}, function( name, props ) { + jQuery.fn[ name ] = function( speed, easing, callback ) { + return this.animate( props, speed, easing, callback ); + }; +} ); + +jQuery.timers = []; +jQuery.fx.tick = function() { + var timer, + i = 0, + timers = jQuery.timers; + + fxNow = Date.now(); + + for ( ; i < timers.length; i++ ) { + timer = timers[ i ]; + + // Run the timer and safely remove it when done (allowing for external removal) + if ( !timer() && timers[ i ] === timer ) { + timers.splice( i--, 1 ); + } + } + + if ( !timers.length ) { + jQuery.fx.stop(); + } + fxNow = undefined; +}; + +jQuery.fx.timer = function( timer ) { + jQuery.timers.push( timer ); + jQuery.fx.start(); +}; + +jQuery.fx.interval = 13; +jQuery.fx.start = function() { + if ( inProgress ) { + return; + } + + inProgress = true; + schedule(); +}; + +jQuery.fx.stop = function() { + inProgress = null; +}; + +jQuery.fx.speeds = { + slow: 600, + fast: 200, + + // Default speed + _default: 400 +}; + + +// Based off of the plugin by Clint Helfers, with permission. +jQuery.fn.delay = function( time, type ) { + time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; + type = type || "fx"; + + return this.queue( type, function( next, hooks ) { + var timeout = window.setTimeout( next, time ); + hooks.stop = function() { + window.clearTimeout( timeout ); + }; + } ); +}; + + +( function() { + var input = document.createElement( "input" ), + select = document.createElement( "select" ), + opt = select.appendChild( document.createElement( "option" ) ); + + input.type = "checkbox"; + + // Support: Android <=4.3 only + // Default value for a checkbox should be "on" + support.checkOn = input.value !== ""; + + // Support: IE <=11 only + // Must access selectedIndex to make default options select + support.optSelected = opt.selected; + + // Support: IE <=11 only + // An input loses its value after becoming a radio + input = document.createElement( "input" ); + input.value = "t"; + input.type = "radio"; + support.radioValue = input.value === "t"; +} )(); + + +var boolHook, + attrHandle = jQuery.expr.attrHandle; + +jQuery.fn.extend( { + attr: function( name, value ) { + return access( this, jQuery.attr, name, value, arguments.length > 1 ); + }, + + removeAttr: function( name ) { + return this.each( function() { + jQuery.removeAttr( this, name ); + } ); + } +} ); + +jQuery.extend( { + attr: function( elem, name, value ) { + var ret, hooks, + nType = elem.nodeType; + + // Don't get/set attributes on text, comment and attribute nodes + if ( nType === 3 || nType === 8 || nType === 2 ) { + return; + } + + // Fallback to prop when attributes are not supported + if ( typeof elem.getAttribute === "undefined" ) { + return jQuery.prop( elem, name, value ); + } + + // Attribute hooks are determined by the lowercase version + // Grab necessary hook if one is defined + if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { + hooks = jQuery.attrHooks[ name.toLowerCase() ] || + ( jQuery.expr.match.bool.test( name ) ? boolHook : undefined ); + } + + if ( value !== undefined ) { + if ( value === null ) { + jQuery.removeAttr( elem, name ); + return; + } + + if ( hooks && "set" in hooks && + ( ret = hooks.set( elem, value, name ) ) !== undefined ) { + return ret; + } + + elem.setAttribute( name, value + "" ); + return value; + } + + if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) { + return ret; + } + + ret = jQuery.find.attr( elem, name ); + + // Non-existent attributes return null, we normalize to undefined + return ret == null ? undefined : ret; + }, + + attrHooks: { + type: { + set: function( elem, value ) { + if ( !support.radioValue && value === "radio" && + nodeName( elem, "input" ) ) { + var val = elem.value; + elem.setAttribute( "type", value ); + if ( val ) { + elem.value = val; + } + return value; + } + } + } + }, + + removeAttr: function( elem, value ) { + var name, + i = 0, + + // Attribute names can contain non-HTML whitespace characters + // https://html.spec.whatwg.org/multipage/syntax.html#attributes-2 + attrNames = value && value.match( rnothtmlwhite ); + + if ( attrNames && elem.nodeType === 1 ) { + while ( ( name = attrNames[ i++ ] ) ) { + elem.removeAttribute( name ); + } + } + } +} ); + +// Hooks for boolean attributes +boolHook = { + set: function( elem, value, name ) { + if ( value === false ) { + + // Remove boolean attributes when set to false + jQuery.removeAttr( elem, name ); + } else { + elem.setAttribute( name, name ); + } + return name; + } +}; + +jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( _i, name ) { + var getter = attrHandle[ name ] || jQuery.find.attr; + + attrHandle[ name ] = function( elem, name, isXML ) { + var ret, handle, + lowercaseName = name.toLowerCase(); + + if ( !isXML ) { + + // Avoid an infinite loop by temporarily removing this function from the getter + handle = attrHandle[ lowercaseName ]; + attrHandle[ lowercaseName ] = ret; + ret = getter( elem, name, isXML ) != null ? + lowercaseName : + null; + attrHandle[ lowercaseName ] = handle; + } + return ret; + }; +} ); + + + + +var rfocusable = /^(?:input|select|textarea|button)$/i, + rclickable = /^(?:a|area)$/i; + +jQuery.fn.extend( { + prop: function( name, value ) { + return access( this, jQuery.prop, name, value, arguments.length > 1 ); + }, + + removeProp: function( name ) { + return this.each( function() { + delete this[ jQuery.propFix[ name ] || name ]; + } ); + } +} ); + +jQuery.extend( { + prop: function( elem, name, value ) { + var ret, hooks, + nType = elem.nodeType; + + // Don't get/set properties on text, comment and attribute nodes + if ( nType === 3 || nType === 8 || nType === 2 ) { + return; + } + + if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { + + // Fix name and attach hooks + name = jQuery.propFix[ name ] || name; + hooks = jQuery.propHooks[ name ]; + } + + if ( value !== undefined ) { + if ( hooks && "set" in hooks && + ( ret = hooks.set( elem, value, name ) ) !== undefined ) { + return ret; + } + + return ( elem[ name ] = value ); + } + + if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) { + return ret; + } + + return elem[ name ]; + }, + + propHooks: { + tabIndex: { + get: function( elem ) { + + // Support: IE <=9 - 11 only + // elem.tabIndex doesn't always return the + // correct value when it hasn't been explicitly set + // Use proper attribute retrieval (trac-12072) + var tabindex = jQuery.find.attr( elem, "tabindex" ); + + if ( tabindex ) { + return parseInt( tabindex, 10 ); + } + + if ( + rfocusable.test( elem.nodeName ) || + rclickable.test( elem.nodeName ) && + elem.href + ) { + return 0; + } + + return -1; + } + } + }, + + propFix: { + "for": "htmlFor", + "class": "className" + } +} ); + +// Support: IE <=11 only +// Accessing the selectedIndex property +// forces the browser to respect setting selected +// on the option +// The getter ensures a default option is selected +// when in an optgroup +// eslint rule "no-unused-expressions" is disabled for this code +// since it considers such accessions noop +if ( !support.optSelected ) { + jQuery.propHooks.selected = { + get: function( elem ) { + + /* eslint no-unused-expressions: "off" */ + + var parent = elem.parentNode; + if ( parent && parent.parentNode ) { + parent.parentNode.selectedIndex; + } + return null; + }, + set: function( elem ) { + + /* eslint no-unused-expressions: "off" */ + + var parent = elem.parentNode; + if ( parent ) { + parent.selectedIndex; + + if ( parent.parentNode ) { + parent.parentNode.selectedIndex; + } + } + } + }; +} + +jQuery.each( [ + "tabIndex", + "readOnly", + "maxLength", + "cellSpacing", + "cellPadding", + "rowSpan", + "colSpan", + "useMap", + "frameBorder", + "contentEditable" +], function() { + jQuery.propFix[ this.toLowerCase() ] = this; +} ); + + + + + // Strip and collapse whitespace according to HTML spec + // https://infra.spec.whatwg.org/#strip-and-collapse-ascii-whitespace + function stripAndCollapse( value ) { + var tokens = value.match( rnothtmlwhite ) || []; + return tokens.join( " " ); + } + + +function getClass( elem ) { + return elem.getAttribute && elem.getAttribute( "class" ) || ""; +} + +function classesToArray( value ) { + if ( Array.isArray( value ) ) { + return value; + } + if ( typeof value === "string" ) { + return value.match( rnothtmlwhite ) || []; + } + return []; +} + +jQuery.fn.extend( { + addClass: function( value ) { + var classNames, cur, curValue, className, i, finalValue; + + if ( isFunction( value ) ) { + return this.each( function( j ) { + jQuery( this ).addClass( value.call( this, j, getClass( this ) ) ); + } ); + } + + classNames = classesToArray( value ); + + if ( classNames.length ) { + return this.each( function() { + curValue = getClass( this ); + cur = this.nodeType === 1 && ( " " + stripAndCollapse( curValue ) + " " ); + + if ( cur ) { + for ( i = 0; i < classNames.length; i++ ) { + className = classNames[ i ]; + if ( cur.indexOf( " " + className + " " ) < 0 ) { + cur += className + " "; + } + } + + // Only assign if different to avoid unneeded rendering. + finalValue = stripAndCollapse( cur ); + if ( curValue !== finalValue ) { + this.setAttribute( "class", finalValue ); + } + } + } ); + } + + return this; + }, + + removeClass: function( value ) { + var classNames, cur, curValue, className, i, finalValue; + + if ( isFunction( value ) ) { + return this.each( function( j ) { + jQuery( this ).removeClass( value.call( this, j, getClass( this ) ) ); + } ); + } + + if ( !arguments.length ) { + return this.attr( "class", "" ); + } + + classNames = classesToArray( value ); + + if ( classNames.length ) { + return this.each( function() { + curValue = getClass( this ); + + // This expression is here for better compressibility (see addClass) + cur = this.nodeType === 1 && ( " " + stripAndCollapse( curValue ) + " " ); + + if ( cur ) { + for ( i = 0; i < classNames.length; i++ ) { + className = classNames[ i ]; + + // Remove *all* instances + while ( cur.indexOf( " " + className + " " ) > -1 ) { + cur = cur.replace( " " + className + " ", " " ); + } + } + + // Only assign if different to avoid unneeded rendering. + finalValue = stripAndCollapse( cur ); + if ( curValue !== finalValue ) { + this.setAttribute( "class", finalValue ); + } + } + } ); + } + + return this; + }, + + toggleClass: function( value, stateVal ) { + var classNames, className, i, self, + type = typeof value, + isValidValue = type === "string" || Array.isArray( value ); + + if ( isFunction( value ) ) { + return this.each( function( i ) { + jQuery( this ).toggleClass( + value.call( this, i, getClass( this ), stateVal ), + stateVal + ); + } ); + } + + if ( typeof stateVal === "boolean" && isValidValue ) { + return stateVal ? this.addClass( value ) : this.removeClass( value ); + } + + classNames = classesToArray( value ); + + return this.each( function() { + if ( isValidValue ) { + + // Toggle individual class names + self = jQuery( this ); + + for ( i = 0; i < classNames.length; i++ ) { + className = classNames[ i ]; + + // Check each className given, space separated list + if ( self.hasClass( className ) ) { + self.removeClass( className ); + } else { + self.addClass( className ); + } + } + + // Toggle whole class name + } else if ( value === undefined || type === "boolean" ) { + className = getClass( this ); + if ( className ) { + + // Store className if set + dataPriv.set( this, "__className__", className ); + } + + // If the element has a class name or if we're passed `false`, + // then remove the whole classname (if there was one, the above saved it). + // Otherwise bring back whatever was previously saved (if anything), + // falling back to the empty string if nothing was stored. + if ( this.setAttribute ) { + this.setAttribute( "class", + className || value === false ? + "" : + dataPriv.get( this, "__className__" ) || "" + ); + } + } + } ); + }, + + hasClass: function( selector ) { + var className, elem, + i = 0; + + className = " " + selector + " "; + while ( ( elem = this[ i++ ] ) ) { + if ( elem.nodeType === 1 && + ( " " + stripAndCollapse( getClass( elem ) ) + " " ).indexOf( className ) > -1 ) { + return true; + } + } + + return false; + } +} ); + + + + +var rreturn = /\r/g; + +jQuery.fn.extend( { + val: function( value ) { + var hooks, ret, valueIsFunction, + elem = this[ 0 ]; + + if ( !arguments.length ) { + if ( elem ) { + hooks = jQuery.valHooks[ elem.type ] || + jQuery.valHooks[ elem.nodeName.toLowerCase() ]; + + if ( hooks && + "get" in hooks && + ( ret = hooks.get( elem, "value" ) ) !== undefined + ) { + return ret; + } + + ret = elem.value; + + // Handle most common string cases + if ( typeof ret === "string" ) { + return ret.replace( rreturn, "" ); + } + + // Handle cases where value is null/undef or number + return ret == null ? "" : ret; + } + + return; + } + + valueIsFunction = isFunction( value ); + + return this.each( function( i ) { + var val; + + if ( this.nodeType !== 1 ) { + return; + } + + if ( valueIsFunction ) { + val = value.call( this, i, jQuery( this ).val() ); + } else { + val = value; + } + + // Treat null/undefined as ""; convert numbers to string + if ( val == null ) { + val = ""; + + } else if ( typeof val === "number" ) { + val += ""; + + } else if ( Array.isArray( val ) ) { + val = jQuery.map( val, function( value ) { + return value == null ? "" : value + ""; + } ); + } + + hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; + + // If set returns undefined, fall back to normal setting + if ( !hooks || !( "set" in hooks ) || hooks.set( this, val, "value" ) === undefined ) { + this.value = val; + } + } ); + } +} ); + +jQuery.extend( { + valHooks: { + option: { + get: function( elem ) { + + var val = jQuery.find.attr( elem, "value" ); + return val != null ? + val : + + // Support: IE <=10 - 11 only + // option.text throws exceptions (trac-14686, trac-14858) + // Strip and collapse whitespace + // https://html.spec.whatwg.org/#strip-and-collapse-whitespace + stripAndCollapse( jQuery.text( elem ) ); + } + }, + select: { + get: function( elem ) { + var value, option, i, + options = elem.options, + index = elem.selectedIndex, + one = elem.type === "select-one", + values = one ? null : [], + max = one ? index + 1 : options.length; + + if ( index < 0 ) { + i = max; + + } else { + i = one ? index : 0; + } + + // Loop through all the selected options + for ( ; i < max; i++ ) { + option = options[ i ]; + + // Support: IE <=9 only + // IE8-9 doesn't update selected after form reset (trac-2551) + if ( ( option.selected || i === index ) && + + // Don't return options that are disabled or in a disabled optgroup + !option.disabled && + ( !option.parentNode.disabled || + !nodeName( option.parentNode, "optgroup" ) ) ) { + + // Get the specific value for the option + value = jQuery( option ).val(); + + // We don't need an array for one selects + if ( one ) { + return value; + } + + // Multi-Selects return an array + values.push( value ); + } + } + + return values; + }, + + set: function( elem, value ) { + var optionSet, option, + options = elem.options, + values = jQuery.makeArray( value ), + i = options.length; + + while ( i-- ) { + option = options[ i ]; + + /* eslint-disable no-cond-assign */ + + if ( option.selected = + jQuery.inArray( jQuery.valHooks.option.get( option ), values ) > -1 + ) { + optionSet = true; + } + + /* eslint-enable no-cond-assign */ + } + + // Force browsers to behave consistently when non-matching value is set + if ( !optionSet ) { + elem.selectedIndex = -1; + } + return values; + } + } + } +} ); + +// Radios and checkboxes getter/setter +jQuery.each( [ "radio", "checkbox" ], function() { + jQuery.valHooks[ this ] = { + set: function( elem, value ) { + if ( Array.isArray( value ) ) { + return ( elem.checked = jQuery.inArray( jQuery( elem ).val(), value ) > -1 ); + } + } + }; + if ( !support.checkOn ) { + jQuery.valHooks[ this ].get = function( elem ) { + return elem.getAttribute( "value" ) === null ? "on" : elem.value; + }; + } +} ); + + + + +// Return jQuery for attributes-only inclusion +var location = window.location; + +var nonce = { guid: Date.now() }; + +var rquery = ( /\?/ ); + + + +// Cross-browser xml parsing +jQuery.parseXML = function( data ) { + var xml, parserErrorElem; + if ( !data || typeof data !== "string" ) { + return null; + } + + // Support: IE 9 - 11 only + // IE throws on parseFromString with invalid input. + try { + xml = ( new window.DOMParser() ).parseFromString( data, "text/xml" ); + } catch ( e ) {} + + parserErrorElem = xml && xml.getElementsByTagName( "parsererror" )[ 0 ]; + if ( !xml || parserErrorElem ) { + jQuery.error( "Invalid XML: " + ( + parserErrorElem ? + jQuery.map( parserErrorElem.childNodes, function( el ) { + return el.textContent; + } ).join( "\n" ) : + data + ) ); + } + return xml; +}; + + +var rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, + stopPropagationCallback = function( e ) { + e.stopPropagation(); + }; + +jQuery.extend( jQuery.event, { + + trigger: function( event, data, elem, onlyHandlers ) { + + var i, cur, tmp, bubbleType, ontype, handle, special, lastElement, + eventPath = [ elem || document ], + type = hasOwn.call( event, "type" ) ? event.type : event, + namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split( "." ) : []; + + cur = lastElement = tmp = elem = elem || document; + + // Don't do events on text and comment nodes + if ( elem.nodeType === 3 || elem.nodeType === 8 ) { + return; + } + + // focus/blur morphs to focusin/out; ensure we're not firing them right now + if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { + return; + } + + if ( type.indexOf( "." ) > -1 ) { + + // Namespaced trigger; create a regexp to match event type in handle() + namespaces = type.split( "." ); + type = namespaces.shift(); + namespaces.sort(); + } + ontype = type.indexOf( ":" ) < 0 && "on" + type; + + // Caller can pass in a jQuery.Event object, Object, or just an event type string + event = event[ jQuery.expando ] ? + event : + new jQuery.Event( type, typeof event === "object" && event ); + + // Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true) + event.isTrigger = onlyHandlers ? 2 : 3; + event.namespace = namespaces.join( "." ); + event.rnamespace = event.namespace ? + new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.|)" ) + "(\\.|$)" ) : + null; + + // Clean up the event in case it is being reused + event.result = undefined; + if ( !event.target ) { + event.target = elem; + } + + // Clone any incoming data and prepend the event, creating the handler arg list + data = data == null ? + [ event ] : + jQuery.makeArray( data, [ event ] ); + + // Allow special events to draw outside the lines + special = jQuery.event.special[ type ] || {}; + if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) { + return; + } + + // Determine event propagation path in advance, per W3C events spec (trac-9951) + // Bubble up to document, then to window; watch for a global ownerDocument var (trac-9724) + if ( !onlyHandlers && !special.noBubble && !isWindow( elem ) ) { + + bubbleType = special.delegateType || type; + if ( !rfocusMorph.test( bubbleType + type ) ) { + cur = cur.parentNode; + } + for ( ; cur; cur = cur.parentNode ) { + eventPath.push( cur ); + tmp = cur; + } + + // Only add window if we got to document (e.g., not plain obj or detached DOM) + if ( tmp === ( elem.ownerDocument || document ) ) { + eventPath.push( tmp.defaultView || tmp.parentWindow || window ); + } + } + + // Fire handlers on the event path + i = 0; + while ( ( cur = eventPath[ i++ ] ) && !event.isPropagationStopped() ) { + lastElement = cur; + event.type = i > 1 ? + bubbleType : + special.bindType || type; + + // jQuery handler + handle = ( dataPriv.get( cur, "events" ) || Object.create( null ) )[ event.type ] && + dataPriv.get( cur, "handle" ); + if ( handle ) { + handle.apply( cur, data ); + } + + // Native handler + handle = ontype && cur[ ontype ]; + if ( handle && handle.apply && acceptData( cur ) ) { + event.result = handle.apply( cur, data ); + if ( event.result === false ) { + event.preventDefault(); + } + } + } + event.type = type; + + // If nobody prevented the default action, do it now + if ( !onlyHandlers && !event.isDefaultPrevented() ) { + + if ( ( !special._default || + special._default.apply( eventPath.pop(), data ) === false ) && + acceptData( elem ) ) { + + // Call a native DOM method on the target with the same name as the event. + // Don't do default actions on window, that's where global variables be (trac-6170) + if ( ontype && isFunction( elem[ type ] ) && !isWindow( elem ) ) { + + // Don't re-trigger an onFOO event when we call its FOO() method + tmp = elem[ ontype ]; + + if ( tmp ) { + elem[ ontype ] = null; + } + + // Prevent re-triggering of the same event, since we already bubbled it above + jQuery.event.triggered = type; + + if ( event.isPropagationStopped() ) { + lastElement.addEventListener( type, stopPropagationCallback ); + } + + elem[ type ](); + + if ( event.isPropagationStopped() ) { + lastElement.removeEventListener( type, stopPropagationCallback ); + } + + jQuery.event.triggered = undefined; + + if ( tmp ) { + elem[ ontype ] = tmp; + } + } + } + } + + return event.result; + }, + + // Piggyback on a donor event to simulate a different one + // Used only for `focus(in | out)` events + simulate: function( type, elem, event ) { + var e = jQuery.extend( + new jQuery.Event(), + event, + { + type: type, + isSimulated: true + } + ); + + jQuery.event.trigger( e, null, elem ); + } + +} ); + +jQuery.fn.extend( { + + trigger: function( type, data ) { + return this.each( function() { + jQuery.event.trigger( type, data, this ); + } ); + }, + triggerHandler: function( type, data ) { + var elem = this[ 0 ]; + if ( elem ) { + return jQuery.event.trigger( type, data, elem, true ); + } + } +} ); + + +var + rbracket = /\[\]$/, + rCRLF = /\r?\n/g, + rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i, + rsubmittable = /^(?:input|select|textarea|keygen)/i; + +function buildParams( prefix, obj, traditional, add ) { + var name; + + if ( Array.isArray( obj ) ) { + + // Serialize array item. + jQuery.each( obj, function( i, v ) { + if ( traditional || rbracket.test( prefix ) ) { + + // Treat each array item as a scalar. + add( prefix, v ); + + } else { + + // Item is non-scalar (array or object), encode its numeric index. + buildParams( + prefix + "[" + ( typeof v === "object" && v != null ? i : "" ) + "]", + v, + traditional, + add + ); + } + } ); + + } else if ( !traditional && toType( obj ) === "object" ) { + + // Serialize object item. + for ( name in obj ) { + buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); + } + + } else { + + // Serialize scalar item. + add( prefix, obj ); + } +} + +// Serialize an array of form elements or a set of +// key/values into a query string +jQuery.param = function( a, traditional ) { + var prefix, + s = [], + add = function( key, valueOrFunction ) { + + // If value is a function, invoke it and use its return value + var value = isFunction( valueOrFunction ) ? + valueOrFunction() : + valueOrFunction; + + s[ s.length ] = encodeURIComponent( key ) + "=" + + encodeURIComponent( value == null ? "" : value ); + }; + + if ( a == null ) { + return ""; + } + + // If an array was passed in, assume that it is an array of form elements. + if ( Array.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { + + // Serialize the form elements + jQuery.each( a, function() { + add( this.name, this.value ); + } ); + + } else { + + // If traditional, encode the "old" way (the way 1.3.2 or older + // did it), otherwise encode params recursively. + for ( prefix in a ) { + buildParams( prefix, a[ prefix ], traditional, add ); + } + } + + // Return the resulting serialization + return s.join( "&" ); +}; + +jQuery.fn.extend( { + serialize: function() { + return jQuery.param( this.serializeArray() ); + }, + serializeArray: function() { + return this.map( function() { + + // Can add propHook for "elements" to filter or add form elements + var elements = jQuery.prop( this, "elements" ); + return elements ? jQuery.makeArray( elements ) : this; + } ).filter( function() { + var type = this.type; + + // Use .is( ":disabled" ) so that fieldset[disabled] works + return this.name && !jQuery( this ).is( ":disabled" ) && + rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) && + ( this.checked || !rcheckableType.test( type ) ); + } ).map( function( _i, elem ) { + var val = jQuery( this ).val(); + + if ( val == null ) { + return null; + } + + if ( Array.isArray( val ) ) { + return jQuery.map( val, function( val ) { + return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; + } ); + } + + return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; + } ).get(); + } +} ); + + +var + r20 = /%20/g, + rhash = /#.*$/, + rantiCache = /([?&])_=[^&]*/, + rheaders = /^(.*?):[ \t]*([^\r\n]*)$/mg, + + // trac-7653, trac-8125, trac-8152: local protocol detection + rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/, + rnoContent = /^(?:GET|HEAD)$/, + rprotocol = /^\/\//, + + /* Prefilters + * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example) + * 2) These are called: + * - BEFORE asking for a transport + * - AFTER param serialization (s.data is a string if s.processData is true) + * 3) key is the dataType + * 4) the catchall symbol "*" can be used + * 5) execution will start with transport dataType and THEN continue down to "*" if needed + */ + prefilters = {}, + + /* Transports bindings + * 1) key is the dataType + * 2) the catchall symbol "*" can be used + * 3) selection will start with transport dataType and THEN go to "*" if needed + */ + transports = {}, + + // Avoid comment-prolog char sequence (trac-10098); must appease lint and evade compression + allTypes = "*/".concat( "*" ), + + // Anchor tag for parsing the document origin + originAnchor = document.createElement( "a" ); + +originAnchor.href = location.href; + +// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport +function addToPrefiltersOrTransports( structure ) { + + // dataTypeExpression is optional and defaults to "*" + return function( dataTypeExpression, func ) { + + if ( typeof dataTypeExpression !== "string" ) { + func = dataTypeExpression; + dataTypeExpression = "*"; + } + + var dataType, + i = 0, + dataTypes = dataTypeExpression.toLowerCase().match( rnothtmlwhite ) || []; + + if ( isFunction( func ) ) { + + // For each dataType in the dataTypeExpression + while ( ( dataType = dataTypes[ i++ ] ) ) { + + // Prepend if requested + if ( dataType[ 0 ] === "+" ) { + dataType = dataType.slice( 1 ) || "*"; + ( structure[ dataType ] = structure[ dataType ] || [] ).unshift( func ); + + // Otherwise append + } else { + ( structure[ dataType ] = structure[ dataType ] || [] ).push( func ); + } + } + } + }; +} + +// Base inspection function for prefilters and transports +function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) { + + var inspected = {}, + seekingTransport = ( structure === transports ); + + function inspect( dataType ) { + var selected; + inspected[ dataType ] = true; + jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) { + var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR ); + if ( typeof dataTypeOrTransport === "string" && + !seekingTransport && !inspected[ dataTypeOrTransport ] ) { + + options.dataTypes.unshift( dataTypeOrTransport ); + inspect( dataTypeOrTransport ); + return false; + } else if ( seekingTransport ) { + return !( selected = dataTypeOrTransport ); + } + } ); + return selected; + } + + return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" ); +} + +// A special extend for ajax options +// that takes "flat" options (not to be deep extended) +// Fixes trac-9887 +function ajaxExtend( target, src ) { + var key, deep, + flatOptions = jQuery.ajaxSettings.flatOptions || {}; + + for ( key in src ) { + if ( src[ key ] !== undefined ) { + ( flatOptions[ key ] ? target : ( deep || ( deep = {} ) ) )[ key ] = src[ key ]; + } + } + if ( deep ) { + jQuery.extend( true, target, deep ); + } + + return target; +} + +/* Handles responses to an ajax request: + * - finds the right dataType (mediates between content-type and expected dataType) + * - returns the corresponding response + */ +function ajaxHandleResponses( s, jqXHR, responses ) { + + var ct, type, finalDataType, firstDataType, + contents = s.contents, + dataTypes = s.dataTypes; + + // Remove auto dataType and get content-type in the process + while ( dataTypes[ 0 ] === "*" ) { + dataTypes.shift(); + if ( ct === undefined ) { + ct = s.mimeType || jqXHR.getResponseHeader( "Content-Type" ); + } + } + + // Check if we're dealing with a known content-type + if ( ct ) { + for ( type in contents ) { + if ( contents[ type ] && contents[ type ].test( ct ) ) { + dataTypes.unshift( type ); + break; + } + } + } + + // Check to see if we have a response for the expected dataType + if ( dataTypes[ 0 ] in responses ) { + finalDataType = dataTypes[ 0 ]; + } else { + + // Try convertible dataTypes + for ( type in responses ) { + if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[ 0 ] ] ) { + finalDataType = type; + break; + } + if ( !firstDataType ) { + firstDataType = type; + } + } + + // Or just use first one + finalDataType = finalDataType || firstDataType; + } + + // If we found a dataType + // We add the dataType to the list if needed + // and return the corresponding response + if ( finalDataType ) { + if ( finalDataType !== dataTypes[ 0 ] ) { + dataTypes.unshift( finalDataType ); + } + return responses[ finalDataType ]; + } +} + +/* Chain conversions given the request and the original response + * Also sets the responseXXX fields on the jqXHR instance + */ +function ajaxConvert( s, response, jqXHR, isSuccess ) { + var conv2, current, conv, tmp, prev, + converters = {}, + + // Work with a copy of dataTypes in case we need to modify it for conversion + dataTypes = s.dataTypes.slice(); + + // Create converters map with lowercased keys + if ( dataTypes[ 1 ] ) { + for ( conv in s.converters ) { + converters[ conv.toLowerCase() ] = s.converters[ conv ]; + } + } + + current = dataTypes.shift(); + + // Convert to each sequential dataType + while ( current ) { + + if ( s.responseFields[ current ] ) { + jqXHR[ s.responseFields[ current ] ] = response; + } + + // Apply the dataFilter if provided + if ( !prev && isSuccess && s.dataFilter ) { + response = s.dataFilter( response, s.dataType ); + } + + prev = current; + current = dataTypes.shift(); + + if ( current ) { + + // There's only work to do if current dataType is non-auto + if ( current === "*" ) { + + current = prev; + + // Convert response if prev dataType is non-auto and differs from current + } else if ( prev !== "*" && prev !== current ) { + + // Seek a direct converter + conv = converters[ prev + " " + current ] || converters[ "* " + current ]; + + // If none found, seek a pair + if ( !conv ) { + for ( conv2 in converters ) { + + // If conv2 outputs current + tmp = conv2.split( " " ); + if ( tmp[ 1 ] === current ) { + + // If prev can be converted to accepted input + conv = converters[ prev + " " + tmp[ 0 ] ] || + converters[ "* " + tmp[ 0 ] ]; + if ( conv ) { + + // Condense equivalence converters + if ( conv === true ) { + conv = converters[ conv2 ]; + + // Otherwise, insert the intermediate dataType + } else if ( converters[ conv2 ] !== true ) { + current = tmp[ 0 ]; + dataTypes.unshift( tmp[ 1 ] ); + } + break; + } + } + } + } + + // Apply converter (if not an equivalence) + if ( conv !== true ) { + + // Unless errors are allowed to bubble, catch and return them + if ( conv && s.throws ) { + response = conv( response ); + } else { + try { + response = conv( response ); + } catch ( e ) { + return { + state: "parsererror", + error: conv ? e : "No conversion from " + prev + " to " + current + }; + } + } + } + } + } + } + + return { state: "success", data: response }; +} + +jQuery.extend( { + + // Counter for holding the number of active queries + active: 0, + + // Last-Modified header cache for next request + lastModified: {}, + etag: {}, + + ajaxSettings: { + url: location.href, + type: "GET", + isLocal: rlocalProtocol.test( location.protocol ), + global: true, + processData: true, + async: true, + contentType: "application/x-www-form-urlencoded; charset=UTF-8", + + /* + timeout: 0, + data: null, + dataType: null, + username: null, + password: null, + cache: null, + throws: false, + traditional: false, + headers: {}, + */ + + accepts: { + "*": allTypes, + text: "text/plain", + html: "text/html", + xml: "application/xml, text/xml", + json: "application/json, text/javascript" + }, + + contents: { + xml: /\bxml\b/, + html: /\bhtml/, + json: /\bjson\b/ + }, + + responseFields: { + xml: "responseXML", + text: "responseText", + json: "responseJSON" + }, + + // Data converters + // Keys separate source (or catchall "*") and destination types with a single space + converters: { + + // Convert anything to text + "* text": String, + + // Text to html (true = no transformation) + "text html": true, + + // Evaluate text as a json expression + "text json": JSON.parse, + + // Parse text as xml + "text xml": jQuery.parseXML + }, + + // For options that shouldn't be deep extended: + // you can add your own custom options here if + // and when you create one that shouldn't be + // deep extended (see ajaxExtend) + flatOptions: { + url: true, + context: true + } + }, + + // Creates a full fledged settings object into target + // with both ajaxSettings and settings fields. + // If target is omitted, writes into ajaxSettings. + ajaxSetup: function( target, settings ) { + return settings ? + + // Building a settings object + ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) : + + // Extending ajaxSettings + ajaxExtend( jQuery.ajaxSettings, target ); + }, + + ajaxPrefilter: addToPrefiltersOrTransports( prefilters ), + ajaxTransport: addToPrefiltersOrTransports( transports ), + + // Main method + ajax: function( url, options ) { + + // If url is an object, simulate pre-1.5 signature + if ( typeof url === "object" ) { + options = url; + url = undefined; + } + + // Force options to be an object + options = options || {}; + + var transport, + + // URL without anti-cache param + cacheURL, + + // Response headers + responseHeadersString, + responseHeaders, + + // timeout handle + timeoutTimer, + + // Url cleanup var + urlAnchor, + + // Request state (becomes false upon send and true upon completion) + completed, + + // To know if global events are to be dispatched + fireGlobals, + + // Loop variable + i, + + // uncached part of the url + uncached, + + // Create the final options object + s = jQuery.ajaxSetup( {}, options ), + + // Callbacks context + callbackContext = s.context || s, + + // Context for global events is callbackContext if it is a DOM node or jQuery collection + globalEventContext = s.context && + ( callbackContext.nodeType || callbackContext.jquery ) ? + jQuery( callbackContext ) : + jQuery.event, + + // Deferreds + deferred = jQuery.Deferred(), + completeDeferred = jQuery.Callbacks( "once memory" ), + + // Status-dependent callbacks + statusCode = s.statusCode || {}, + + // Headers (they are sent all at once) + requestHeaders = {}, + requestHeadersNames = {}, + + // Default abort message + strAbort = "canceled", + + // Fake xhr + jqXHR = { + readyState: 0, + + // Builds headers hashtable if needed + getResponseHeader: function( key ) { + var match; + if ( completed ) { + if ( !responseHeaders ) { + responseHeaders = {}; + while ( ( match = rheaders.exec( responseHeadersString ) ) ) { + responseHeaders[ match[ 1 ].toLowerCase() + " " ] = + ( responseHeaders[ match[ 1 ].toLowerCase() + " " ] || [] ) + .concat( match[ 2 ] ); + } + } + match = responseHeaders[ key.toLowerCase() + " " ]; + } + return match == null ? null : match.join( ", " ); + }, + + // Raw string + getAllResponseHeaders: function() { + return completed ? responseHeadersString : null; + }, + + // Caches the header + setRequestHeader: function( name, value ) { + if ( completed == null ) { + name = requestHeadersNames[ name.toLowerCase() ] = + requestHeadersNames[ name.toLowerCase() ] || name; + requestHeaders[ name ] = value; + } + return this; + }, + + // Overrides response content-type header + overrideMimeType: function( type ) { + if ( completed == null ) { + s.mimeType = type; + } + return this; + }, + + // Status-dependent callbacks + statusCode: function( map ) { + var code; + if ( map ) { + if ( completed ) { + + // Execute the appropriate callbacks + jqXHR.always( map[ jqXHR.status ] ); + } else { + + // Lazy-add the new callbacks in a way that preserves old ones + for ( code in map ) { + statusCode[ code ] = [ statusCode[ code ], map[ code ] ]; + } + } + } + return this; + }, + + // Cancel the request + abort: function( statusText ) { + var finalText = statusText || strAbort; + if ( transport ) { + transport.abort( finalText ); + } + done( 0, finalText ); + return this; + } + }; + + // Attach deferreds + deferred.promise( jqXHR ); + + // Add protocol if not provided (prefilters might expect it) + // Handle falsy url in the settings object (trac-10093: consistency with old signature) + // We also use the url parameter if available + s.url = ( ( url || s.url || location.href ) + "" ) + .replace( rprotocol, location.protocol + "//" ); + + // Alias method option to type as per ticket trac-12004 + s.type = options.method || options.type || s.method || s.type; + + // Extract dataTypes list + s.dataTypes = ( s.dataType || "*" ).toLowerCase().match( rnothtmlwhite ) || [ "" ]; + + // A cross-domain request is in order when the origin doesn't match the current origin. + if ( s.crossDomain == null ) { + urlAnchor = document.createElement( "a" ); + + // Support: IE <=8 - 11, Edge 12 - 15 + // IE throws exception on accessing the href property if url is malformed, + // e.g. http://example.com:80x/ + try { + urlAnchor.href = s.url; + + // Support: IE <=8 - 11 only + // Anchor's host property isn't correctly set when s.url is relative + urlAnchor.href = urlAnchor.href; + s.crossDomain = originAnchor.protocol + "//" + originAnchor.host !== + urlAnchor.protocol + "//" + urlAnchor.host; + } catch ( e ) { + + // If there is an error parsing the URL, assume it is crossDomain, + // it can be rejected by the transport if it is invalid + s.crossDomain = true; + } + } + + // Convert data if not already a string + if ( s.data && s.processData && typeof s.data !== "string" ) { + s.data = jQuery.param( s.data, s.traditional ); + } + + // Apply prefilters + inspectPrefiltersOrTransports( prefilters, s, options, jqXHR ); + + // If request was aborted inside a prefilter, stop there + if ( completed ) { + return jqXHR; + } + + // We can fire global events as of now if asked to + // Don't fire events if jQuery.event is undefined in an AMD-usage scenario (trac-15118) + fireGlobals = jQuery.event && s.global; + + // Watch for a new set of requests + if ( fireGlobals && jQuery.active++ === 0 ) { + jQuery.event.trigger( "ajaxStart" ); + } + + // Uppercase the type + s.type = s.type.toUpperCase(); + + // Determine if request has content + s.hasContent = !rnoContent.test( s.type ); + + // Save the URL in case we're toying with the If-Modified-Since + // and/or If-None-Match header later on + // Remove hash to simplify url manipulation + cacheURL = s.url.replace( rhash, "" ); + + // More options handling for requests with no content + if ( !s.hasContent ) { + + // Remember the hash so we can put it back + uncached = s.url.slice( cacheURL.length ); + + // If data is available and should be processed, append data to url + if ( s.data && ( s.processData || typeof s.data === "string" ) ) { + cacheURL += ( rquery.test( cacheURL ) ? "&" : "?" ) + s.data; + + // trac-9682: remove data so that it's not used in an eventual retry + delete s.data; + } + + // Add or update anti-cache param if needed + if ( s.cache === false ) { + cacheURL = cacheURL.replace( rantiCache, "$1" ); + uncached = ( rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + ( nonce.guid++ ) + + uncached; + } + + // Put hash and anti-cache on the URL that will be requested (gh-1732) + s.url = cacheURL + uncached; + + // Change '%20' to '+' if this is encoded form body content (gh-2658) + } else if ( s.data && s.processData && + ( s.contentType || "" ).indexOf( "application/x-www-form-urlencoded" ) === 0 ) { + s.data = s.data.replace( r20, "+" ); + } + + // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. + if ( s.ifModified ) { + if ( jQuery.lastModified[ cacheURL ] ) { + jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] ); + } + if ( jQuery.etag[ cacheURL ] ) { + jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] ); + } + } + + // Set the correct header, if data is being sent + if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) { + jqXHR.setRequestHeader( "Content-Type", s.contentType ); + } + + // Set the Accepts header for the server, depending on the dataType + jqXHR.setRequestHeader( + "Accept", + s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[ 0 ] ] ? + s.accepts[ s.dataTypes[ 0 ] ] + + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) : + s.accepts[ "*" ] + ); + + // Check for headers option + for ( i in s.headers ) { + jqXHR.setRequestHeader( i, s.headers[ i ] ); + } + + // Allow custom headers/mimetypes and early abort + if ( s.beforeSend && + ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || completed ) ) { + + // Abort if not done already and return + return jqXHR.abort(); + } + + // Aborting is no longer a cancellation + strAbort = "abort"; + + // Install callbacks on deferreds + completeDeferred.add( s.complete ); + jqXHR.done( s.success ); + jqXHR.fail( s.error ); + + // Get transport + transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR ); + + // If no transport, we auto-abort + if ( !transport ) { + done( -1, "No Transport" ); + } else { + jqXHR.readyState = 1; + + // Send global event + if ( fireGlobals ) { + globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] ); + } + + // If request was aborted inside ajaxSend, stop there + if ( completed ) { + return jqXHR; + } + + // Timeout + if ( s.async && s.timeout > 0 ) { + timeoutTimer = window.setTimeout( function() { + jqXHR.abort( "timeout" ); + }, s.timeout ); + } + + try { + completed = false; + transport.send( requestHeaders, done ); + } catch ( e ) { + + // Rethrow post-completion exceptions + if ( completed ) { + throw e; + } + + // Propagate others as results + done( -1, e ); + } + } + + // Callback for when everything is done + function done( status, nativeStatusText, responses, headers ) { + var isSuccess, success, error, response, modified, + statusText = nativeStatusText; + + // Ignore repeat invocations + if ( completed ) { + return; + } + + completed = true; + + // Clear timeout if it exists + if ( timeoutTimer ) { + window.clearTimeout( timeoutTimer ); + } + + // Dereference transport for early garbage collection + // (no matter how long the jqXHR object will be used) + transport = undefined; + + // Cache response headers + responseHeadersString = headers || ""; + + // Set readyState + jqXHR.readyState = status > 0 ? 4 : 0; + + // Determine if successful + isSuccess = status >= 200 && status < 300 || status === 304; + + // Get response data + if ( responses ) { + response = ajaxHandleResponses( s, jqXHR, responses ); + } + + // Use a noop converter for missing script but not if jsonp + if ( !isSuccess && + jQuery.inArray( "script", s.dataTypes ) > -1 && + jQuery.inArray( "json", s.dataTypes ) < 0 ) { + s.converters[ "text script" ] = function() {}; + } + + // Convert no matter what (that way responseXXX fields are always set) + response = ajaxConvert( s, response, jqXHR, isSuccess ); + + // If successful, handle type chaining + if ( isSuccess ) { + + // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. + if ( s.ifModified ) { + modified = jqXHR.getResponseHeader( "Last-Modified" ); + if ( modified ) { + jQuery.lastModified[ cacheURL ] = modified; + } + modified = jqXHR.getResponseHeader( "etag" ); + if ( modified ) { + jQuery.etag[ cacheURL ] = modified; + } + } + + // if no content + if ( status === 204 || s.type === "HEAD" ) { + statusText = "nocontent"; + + // if not modified + } else if ( status === 304 ) { + statusText = "notmodified"; + + // If we have data, let's convert it + } else { + statusText = response.state; + success = response.data; + error = response.error; + isSuccess = !error; + } + } else { + + // Extract error from statusText and normalize for non-aborts + error = statusText; + if ( status || !statusText ) { + statusText = "error"; + if ( status < 0 ) { + status = 0; + } + } + } + + // Set data for the fake xhr object + jqXHR.status = status; + jqXHR.statusText = ( nativeStatusText || statusText ) + ""; + + // Success/Error + if ( isSuccess ) { + deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] ); + } else { + deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] ); + } + + // Status-dependent callbacks + jqXHR.statusCode( statusCode ); + statusCode = undefined; + + if ( fireGlobals ) { + globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError", + [ jqXHR, s, isSuccess ? success : error ] ); + } + + // Complete + completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] ); + + if ( fireGlobals ) { + globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] ); + + // Handle the global AJAX counter + if ( !( --jQuery.active ) ) { + jQuery.event.trigger( "ajaxStop" ); + } + } + } + + return jqXHR; + }, + + getJSON: function( url, data, callback ) { + return jQuery.get( url, data, callback, "json" ); + }, + + getScript: function( url, callback ) { + return jQuery.get( url, undefined, callback, "script" ); + } +} ); + +jQuery.each( [ "get", "post" ], function( _i, method ) { + jQuery[ method ] = function( url, data, callback, type ) { + + // Shift arguments if data argument was omitted + if ( isFunction( data ) ) { + type = type || callback; + callback = data; + data = undefined; + } + + // The url can be an options object (which then must have .url) + return jQuery.ajax( jQuery.extend( { + url: url, + type: method, + dataType: type, + data: data, + success: callback + }, jQuery.isPlainObject( url ) && url ) ); + }; +} ); + +jQuery.ajaxPrefilter( function( s ) { + var i; + for ( i in s.headers ) { + if ( i.toLowerCase() === "content-type" ) { + s.contentType = s.headers[ i ] || ""; + } + } +} ); + + +jQuery._evalUrl = function( url, options, doc ) { + return jQuery.ajax( { + url: url, + + // Make this explicit, since user can override this through ajaxSetup (trac-11264) + type: "GET", + dataType: "script", + cache: true, + async: false, + global: false, + + // Only evaluate the response if it is successful (gh-4126) + // dataFilter is not invoked for failure responses, so using it instead + // of the default converter is kludgy but it works. + converters: { + "text script": function() {} + }, + dataFilter: function( response ) { + jQuery.globalEval( response, options, doc ); + } + } ); +}; + + +jQuery.fn.extend( { + wrapAll: function( html ) { + var wrap; + + if ( this[ 0 ] ) { + if ( isFunction( html ) ) { + html = html.call( this[ 0 ] ); + } + + // The elements to wrap the target around + wrap = jQuery( html, this[ 0 ].ownerDocument ).eq( 0 ).clone( true ); + + if ( this[ 0 ].parentNode ) { + wrap.insertBefore( this[ 0 ] ); + } + + wrap.map( function() { + var elem = this; + + while ( elem.firstElementChild ) { + elem = elem.firstElementChild; + } + + return elem; + } ).append( this ); + } + + return this; + }, + + wrapInner: function( html ) { + if ( isFunction( html ) ) { + return this.each( function( i ) { + jQuery( this ).wrapInner( html.call( this, i ) ); + } ); + } + + return this.each( function() { + var self = jQuery( this ), + contents = self.contents(); + + if ( contents.length ) { + contents.wrapAll( html ); + + } else { + self.append( html ); + } + } ); + }, + + wrap: function( html ) { + var htmlIsFunction = isFunction( html ); + + return this.each( function( i ) { + jQuery( this ).wrapAll( htmlIsFunction ? html.call( this, i ) : html ); + } ); + }, + + unwrap: function( selector ) { + this.parent( selector ).not( "body" ).each( function() { + jQuery( this ).replaceWith( this.childNodes ); + } ); + return this; + } +} ); + + +jQuery.expr.pseudos.hidden = function( elem ) { + return !jQuery.expr.pseudos.visible( elem ); +}; +jQuery.expr.pseudos.visible = function( elem ) { + return !!( elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length ); +}; + + + + +jQuery.ajaxSettings.xhr = function() { + try { + return new window.XMLHttpRequest(); + } catch ( e ) {} +}; + +var xhrSuccessStatus = { + + // File protocol always yields status code 0, assume 200 + 0: 200, + + // Support: IE <=9 only + // trac-1450: sometimes IE returns 1223 when it should be 204 + 1223: 204 + }, + xhrSupported = jQuery.ajaxSettings.xhr(); + +support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported ); +support.ajax = xhrSupported = !!xhrSupported; + +jQuery.ajaxTransport( function( options ) { + var callback, errorCallback; + + // Cross domain only allowed if supported through XMLHttpRequest + if ( support.cors || xhrSupported && !options.crossDomain ) { + return { + send: function( headers, complete ) { + var i, + xhr = options.xhr(); + + xhr.open( + options.type, + options.url, + options.async, + options.username, + options.password + ); + + // Apply custom fields if provided + if ( options.xhrFields ) { + for ( i in options.xhrFields ) { + xhr[ i ] = options.xhrFields[ i ]; + } + } + + // Override mime type if needed + if ( options.mimeType && xhr.overrideMimeType ) { + xhr.overrideMimeType( options.mimeType ); + } + + // X-Requested-With header + // For cross-domain requests, seeing as conditions for a preflight are + // akin to a jigsaw puzzle, we simply never set it to be sure. + // (it can always be set on a per-request basis or even using ajaxSetup) + // For same-domain requests, won't change header if already provided. + if ( !options.crossDomain && !headers[ "X-Requested-With" ] ) { + headers[ "X-Requested-With" ] = "XMLHttpRequest"; + } + + // Set headers + for ( i in headers ) { + xhr.setRequestHeader( i, headers[ i ] ); + } + + // Callback + callback = function( type ) { + return function() { + if ( callback ) { + callback = errorCallback = xhr.onload = + xhr.onerror = xhr.onabort = xhr.ontimeout = + xhr.onreadystatechange = null; + + if ( type === "abort" ) { + xhr.abort(); + } else if ( type === "error" ) { + + // Support: IE <=9 only + // On a manual native abort, IE9 throws + // errors on any property access that is not readyState + if ( typeof xhr.status !== "number" ) { + complete( 0, "error" ); + } else { + complete( + + // File: protocol always yields status 0; see trac-8605, trac-14207 + xhr.status, + xhr.statusText + ); + } + } else { + complete( + xhrSuccessStatus[ xhr.status ] || xhr.status, + xhr.statusText, + + // Support: IE <=9 only + // IE9 has no XHR2 but throws on binary (trac-11426) + // For XHR2 non-text, let the caller handle it (gh-2498) + ( xhr.responseType || "text" ) !== "text" || + typeof xhr.responseText !== "string" ? + { binary: xhr.response } : + { text: xhr.responseText }, + xhr.getAllResponseHeaders() + ); + } + } + }; + }; + + // Listen to events + xhr.onload = callback(); + errorCallback = xhr.onerror = xhr.ontimeout = callback( "error" ); + + // Support: IE 9 only + // Use onreadystatechange to replace onabort + // to handle uncaught aborts + if ( xhr.onabort !== undefined ) { + xhr.onabort = errorCallback; + } else { + xhr.onreadystatechange = function() { + + // Check readyState before timeout as it changes + if ( xhr.readyState === 4 ) { + + // Allow onerror to be called first, + // but that will not handle a native abort + // Also, save errorCallback to a variable + // as xhr.onerror cannot be accessed + window.setTimeout( function() { + if ( callback ) { + errorCallback(); + } + } ); + } + }; + } + + // Create the abort callback + callback = callback( "abort" ); + + try { + + // Do send the request (this may raise an exception) + xhr.send( options.hasContent && options.data || null ); + } catch ( e ) { + + // trac-14683: Only rethrow if this hasn't been notified as an error yet + if ( callback ) { + throw e; + } + } + }, + + abort: function() { + if ( callback ) { + callback(); + } + } + }; + } +} ); + + + + +// Prevent auto-execution of scripts when no explicit dataType was provided (See gh-2432) +jQuery.ajaxPrefilter( function( s ) { + if ( s.crossDomain ) { + s.contents.script = false; + } +} ); + +// Install script dataType +jQuery.ajaxSetup( { + accepts: { + script: "text/javascript, application/javascript, " + + "application/ecmascript, application/x-ecmascript" + }, + contents: { + script: /\b(?:java|ecma)script\b/ + }, + converters: { + "text script": function( text ) { + jQuery.globalEval( text ); + return text; + } + } +} ); + +// Handle cache's special case and crossDomain +jQuery.ajaxPrefilter( "script", function( s ) { + if ( s.cache === undefined ) { + s.cache = false; + } + if ( s.crossDomain ) { + s.type = "GET"; + } +} ); + +// Bind script tag hack transport +jQuery.ajaxTransport( "script", function( s ) { + + // This transport only deals with cross domain or forced-by-attrs requests + if ( s.crossDomain || s.scriptAttrs ) { + var script, callback; + return { + send: function( _, complete ) { + script = jQuery( " + + + + + + + + + + {% block extra_scripts %} {% endblock %} + + diff --git a/fweb/templates/core/converter.html b/fweb/templates/core/converter.html new file mode 100644 index 0000000..4e3c810 --- /dev/null +++ b/fweb/templates/core/converter.html @@ -0,0 +1,107 @@ +{% extends 'core/base.html' %} +{% load static %} {% block title %}{{ category|title +}} Tools - Filemac{% endblock %} {% block content %} +
    + +
    +

    + {{ category|title }} Tools +

    +

    Select a tool to get started

    +
    + + +
    + +
    + +
    +

    + Available Tools +

    +
    + {% for tool in tools %} + + {% endfor %} +
    +
    +
    + + +
    +
    +
    + + + +

    Select a Tool

    +

    + Choose a tool from the left sidebar to start processing your files +

    +
    +
    +
    +
    +
    +{% endblock %} {% block extra_scripts %} + +{% endblock %} diff --git a/fweb/templates/core/dashboard.html b/fweb/templates/core/dashboard.html new file mode 100644 index 0000000..9722d9e --- /dev/null +++ b/fweb/templates/core/dashboard.html @@ -0,0 +1,147 @@ +{% extends 'core/base.html' %} +{% load static %} + +{% block title %}Dashboard - Filemac{% endblock %} + +{% block content %} +
    + +
    +
    +

    File Management Suite

    +

    Convert, analyze, and process your files with powerful tools

    + +
    +
    + + +
    +
    +
    +
    + +
    +
    +

    Document Tools

    +

    8

    +
    +
    +
    + +
    +
    +
    + +
    +
    +

    Audio Tools

    +

    6

    +
    +
    +
    + +
    +
    +
    + +
    +
    +

    Video Tools

    +

    4

    +
    +
    +
    + +
    +
    +
    + +
    +
    +

    Image Tools

    +

    10

    +
    +
    +
    +
    + + + + +
    +

    + Recent Activity +

    +
    +
    +
    + + + +

    No recent activity

    +
    +
    +
    +{% endblock %} diff --git a/fweb/templates/core/results.html b/fweb/templates/core/results.html new file mode 100644 index 0000000..4bb3421 --- /dev/null +++ b/fweb/templates/core/results.html @@ -0,0 +1,120 @@ +{% extends 'base.html' %} +{% load static %} + +{% block title %}Processing Results - Filemac{% endblock %} + +{% block content %} +
    + +
    +
    +
    +
    + +
    +
    +

    Processing Complete!

    +

    {{ results|length }} files processed successfully

    +
    +
    +
    + + + New Conversion + +
    +
    +
    + + +
    + {% for result in results %} +
    +
    +
    + + {{ result.status|title }} + + {{ result.size }} +
    +
    + + {{ result.original_name }} +
    +
    + +
    +
    + Original + + Converted +
    +
    + {{ result.original_format }} + {{ result.target_format }} +
    +
    + +
    +
    + + Download + + +
    +
    +
    + {% endfor %} +
    + + +
    +

    Processing Summary

    +
    +
    +

    {{ total_files }}

    +

    Total Files

    +
    +
    +

    {{ success_files }}

    +

    Successful

    +
    +
    +

    {{ failed_files }}

    +

    Failed

    +
    +
    +

    {{ total_size }}

    +

    Total Size

    +
    +
    +
    +
    + + + +{% endblock %} + +{% block extra_scripts %} + +{% endblock %} diff --git a/fweb/templates/core/tools/audio_tools.html b/fweb/templates/core/tools/audio_tools.html new file mode 100644 index 0000000..e8cc8ab --- /dev/null +++ b/fweb/templates/core/tools/audio_tools.html @@ -0,0 +1,191 @@ + + + + + + + + + diff --git a/fweb/templates/core/tools/base_tools.html b/fweb/templates/core/tools/base_tools.html new file mode 100644 index 0000000..b40cd2a --- /dev/null +++ b/fweb/templates/core/tools/base_tools.html @@ -0,0 +1,139 @@ +{% extends 'core/base.html' %} {% load static %} {% block title %}{{ +category|title }} Tools - Filemac{% endblock %} {% block content %} +
    + +
    +
    +
    +

    + + {{ category|title }} Tools +

    +

    + {{ category_description }} +

    +
    +
    +
    + + +
    +
    +
    +
    + +
    + +
    +
    +

    + Available Tools +

    +
    + {% for tool in tools %} + + {% endfor %} +
    +
    +
    + + +
    +
    + +
    + + + +

    + Select a Tool +

    +

    + Choose a tool from the sidebar to start processing your files +

    +
    + + + {% include 'core/tools/document_tools.html' %} + {% include 'core/tools/audio_tools.html' %} + {% include 'core/tools/video_tools.html' %} + {% include 'core/tools/image_tools.html' %} + {% include 'core/tools/ocr_tools.html' %} + {% include 'core/tools/batch_tools.html' %} +
    +
    +
    +
    + + + +{% endblock %} {% block extra_scripts %} +{% endblock %} diff --git a/fweb/templates/core/tools/batch_tools.html b/fweb/templates/core/tools/batch_tools.html new file mode 100644 index 0000000..aa26c25 --- /dev/null +++ b/fweb/templates/core/tools/batch_tools.html @@ -0,0 +1,651 @@ + + + + + + + + diff --git a/fweb/templates/core/tools/document_tools.html b/fweb/templates/core/tools/document_tools.html new file mode 100644 index 0000000..13fa93d --- /dev/null +++ b/fweb/templates/core/tools/document_tools.html @@ -0,0 +1,645 @@ + + + + + + + + + + + + + + + + + + + diff --git a/fweb/templates/core/tools/image_tools.html b/fweb/templates/core/tools/image_tools.html new file mode 100644 index 0000000..4038029 --- /dev/null +++ b/fweb/templates/core/tools/image_tools.html @@ -0,0 +1,213 @@ + + + + + + + + + + + diff --git a/fweb/templates/core/tools/ocr_tools.html b/fweb/templates/core/tools/ocr_tools.html new file mode 100644 index 0000000..12c1eba --- /dev/null +++ b/fweb/templates/core/tools/ocr_tools.html @@ -0,0 +1,554 @@ + + + + + diff --git a/fweb/templates/core/tools/video_tools.html b/fweb/templates/core/tools/video_tools.html new file mode 100644 index 0000000..f66bb88 --- /dev/null +++ b/fweb/templates/core/tools/video_tools.html @@ -0,0 +1,627 @@ + + + + + + + + diff --git a/setup.py b/setup.py index 2d6a010..91987a1 100644 --- a/setup.py +++ b/setup.py @@ -1,86 +1,118 @@ -'''Build package.''' +"""Build package.""" + import os import subprocess + from setuptools import find_namespace_packages, setup def sri(): - if os.name == 'posix': + if os.name == "posix": result = subprocess.run( - ['dpkg', '-l', 'poppler-utils'], stdout=subprocess.PIPE, text=True) + ["dpkg", "-l", "poppler-utils"], stdout=subprocess.PIPE, text=True + ) if result.returncode != 0: print("Requirement poppler-utils installing") - subprocess.run(['sudo', 'apt', 'install', 'poppler-utils']) + subprocess.run(["sudo", "apt", "install", "poppler-utils"]) - result = subprocess.run( - ['dpkg', '-l', 'speedtest-cli'], stdout=subprocess.PIPE, text=True) - if result.returncode != 0: - print("Requirement speedtest-cli -> installing") - subprocess.run(['sudo', 'apt', 'install', 'speedtest-cli']) +def dos_req(): + if os.name == "posix": + subprocess.run( + ["pip", "install", "pdf2docx"], stdout=subprocess.PIPE, text=True + ) -DESCRIPTION = 'Open source Python CLI toolkit for conversion, manipulation, Analysis' -EXCLUDE_FROM_PACKAGES = ["build", "dist", "test"] + +DESCRIPTION = "Open source Python CLI toolkit for conversion, manipulation, Analysis of files (All major file operations)" +EXCLUDE_FROM_PACKAGES = ["build", "dist", "test", "src", "*~", "fweb"] sri() +dos_req() setup( name="filemac", - author='wambua', - author_email='wambuamwiky2001@gmail.com', - version=open("version.txt").read(), + author="wambua", + author_email="swskye17@gmail.com", + version=open(os.path.abspath("version.txt")).read(), packages=find_namespace_packages(exclude=EXCLUDE_FROM_PACKAGES), description=DESCRIPTION, - long_description=open('README.md').read(), - long_description_content_type='text/markdown', - + long_description=open("README.md").read(), + long_description_content_type="text/markdown", + url="https://pypi.org/project/filemac/", entry_points={ "console_scripts": [ - "filemac=filemac:main" - ]}, - - - python_requires=">=3.6", - install_requires=[ - 'argparse', - 'pdfminer.six', - 'python-docx', - 'python-pptx', - 'gTTS', - 'pypandoc', - 'pydub', - 'requests', - 'Pillow', - 'pandas', - 'opencv-python', - 'pytesseract', - 'PyPDF2', - 'pdf2docx', - 'requests', - 'moviepy', - 'reportlab', - 'numpy', - 'pdf2image' + "filemac=filemac:argsdev", + "Filemac=filemac:argsdev", + "FILEMAC=filemac:argsdev", + "audiobot=filemac:audiobot", ], - + }, + python_requires=">=3.8", + install_requires=[ + "argparse", + "pdfminer.six", + "python-docx", + "python-pptx", + "gTTS", + "pypandoc", + "fitz", + "pydub", + "Pillow", + "pandas", + "opencv-python", + "pytesseract", + "PyPDF2", + "pdf2docx", + "requests", + "moviepy", + "reportlab", + "numpy", + "pdf2image", + "openpyxl", + "rich", + "tqdm", + "ffmpeg-python", + "librosa", + "python-magic", + "matplotlib", + "numpy", + "soundfile", + "SpeechRecognition", + "colorama", + "scipy", + "PyMuPDF", + "pyautogui", + "imageio", + "pynput", + "pyaudio", + "cairosvg", + "frontend", + ], include_package_data=True, zip_safe=False, - license="GPL v3", - keywords=["file-conversion", "file-analysis", "file-manipulation", "ocr", "image-conversion"], - + license="GNU v3", + keywords=[ + "file-conversion", + "document-conversion", + "file-analysis", + "image-conversion", + "file-manipulation", + "audio-conversion", + "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", - "Programming Language :: Python :: 3.7", - "Programming Language :: Python :: 3.8", - "Programming Language :: Python :: 3.9", - "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", ], - - ) diff --git a/test_enhanced_cli.py b/test_enhanced_cli.py new file mode 100644 index 0000000..5420f36 --- /dev/null +++ b/test_enhanced_cli.py @@ -0,0 +1,53 @@ +#!/usr/bin/env python3 +""" +Test script for the enhanced FileMAC CLI +""" + +from filemac.cli.app import enhanced_argsdev, RichConsoleUtils, EnhancedHelpSystem, ClipboardManager +import sys +import os + +# Add the project root to Python path +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + + +def test_basic_functionality(): + """Test basic functionality of the enhanced CLI""" + print("Testing Enhanced FileMAC CLI...") + + # Test Rich console utilities + print("\n1. Testing Rich Console Utilities:") + RichConsoleUtils.print_info("This is an info message") + RichConsoleUtils.print_success("This is a success message") + RichConsoleUtils.print_warning("This is a warning message") + RichConsoleUtils.print_error("This is an error message") + RichConsoleUtils.print_header("Test Header", "Subtitle") + + # Test clipboard manager + print("\n2. Testing Clipboard Manager:") + print(f"Clipboard available: {ClipboardManager.is_available()}") + + if ClipboardManager.is_available(): + # Test copy to clipboard + test_text = "FileMAC Enhanced CLI Test" + if ClipboardManager.copy_to_clipboard(test_text): + # Test paste from clipboard + pasted = ClipboardManager.paste_from_clipboard() + if pasted == test_text: + RichConsoleUtils.print_success("Clipboard test passed!") + else: + RichConsoleUtils.print_warning("Clipboard paste test failed") + + # Test help system + print("\n3. Testing Help System:") + print("Showing quick start guide...") + EnhancedHelpSystem.show_quick_start() + + print("\n4. Testing Enhanced CLI Entry Point:") + print("This would normally call enhanced_argsdev(), but we'll skip it for testing") + + RichConsoleUtils.print_success("All basic tests completed!") + + +if __name__ == "__main__": + test_basic_functionality() diff --git a/version.txt b/version.txt index 6d7de6e..38f77a6 100644 --- a/version.txt +++ b/version.txt @@ -1 +1 @@ -1.0.2 +2.0.1 diff --git a/voice/__init__.py b/voice/__init__.py new file mode 100644 index 0000000..249bd6d --- /dev/null +++ b/voice/__init__.py @@ -0,0 +1,5 @@ +from .voice_typing import VoiceTypeEngine + +__all__ = [ + "VoiceTypeEngine" +] diff --git a/voice/voice_typing.py b/voice/voice_typing.py new file mode 100644 index 0000000..b3617ea --- /dev/null +++ b/voice/voice_typing.py @@ -0,0 +1,153 @@ +#!/usr/bin/env python +import sys +import logging +import threading +import speech_recognition as sr +import pyautogui +import subprocess # For Linux typing fallback +from queue import Queue +from threading import Event, Lock +from pynput import keyboard # Replaces `keyboard` for hotkeys + +# Configuration +CONFIG = { + "hotkey_listen": "++v", + "hotkey_exit": "", + "energy_threshold": 300, + "pause_threshold": 0.8, + "timeout_listen": 5, + "lang": "en-US", + "fallback_clipboard": True, + "log_file": "voicetype.log", +} + + +class VoiceTypeEngine: + def __init__(self): + self.r = sr.Recognizer() + self.audio_queue = Queue() + self.is_listening = Event() + self.lock = Lock() + self.setup_logging() + self.configure_recognizer() + self.auto_select_microphone() # Auto-detect microphone + + def setup_logging(self): + logging.basicConfig( + filename=CONFIG["log_file"], + level=logging.INFO, + format="%(asctime)s - %(levelname)s - %(message)s", + ) + + def configure_recognizer(self): + self.r.energy_threshold = CONFIG["energy_threshold"] + self.r.dynamic_energy_threshold = False + self.r.pause_threshold = CONFIG["pause_threshold"] + + def safe_type_text(self, text): + """Types text using GUI automation, avoiding root requirements.""" + try: + with self.lock: + if sys.platform == "linux": + # Linux alternative + subprocess.run(["xdotool", "type", text + " "]) + else: + pyautogui.write(text + " ") + except Exception as e: + logging.error("Typing failed: %s", e) + print(f"Typing failed: {e}") + if CONFIG["fallback_clipboard"]: + self.clipboard_fallback(text) + + def clipboard_fallback(self, text): + """Fallback method using clipboard if typing fails.""" + try: + import pyperclip + + pyperclip.copy(text) + pyautogui.hotkey("ctrl", "v") + except Exception as e: + logging.error("Clipboard fallback failed: %s", e) + + def process_audio(self): + """Processes recognized speech and converts it to text.""" + while self.is_listening.is_set() or not self.audio_queue.empty(): + try: + audio_data = self.audio_queue.get(timeout=1) + text = self.r.recognize_google(audio_data, language=CONFIG["lang"]) + logging.info("Recognized: %s", text) + print(f"Recognized: \033[1m{text}\033[0m") + self.safe_type_text(text) + except sr.UnknownValueError: + logging.warning("Speech not recognized") + except sr.RequestError as e: + logging.error("API unreachable: %s", e) + except Exception as e: + logging.error("Unexpected error: %s", e) + + def listen_worker(self): + """Listens for speech input and sends it to processing queue.""" + with sr.Microphone(device_index=self.microphone_index) as source: + while self.is_listening.is_set(): + try: + audio = self.r.listen( + source, timeout=CONFIG["timeout_listen"], phrase_time_limit=10 + ) + self.audio_queue.put(audio) + except sr.WaitTimeoutError: + continue + except Exception as e: + logging.error("Recording error: %s", e) + + def auto_select_microphone(self): + """Automatically selects the default microphone.""" + try: + with sr.Microphone() as source: + print(f"Using default microphone: {source}") + self.microphone_index = None # Auto-select default mic + except Exception as e: + logging.error("Microphone access error: %s", e) + sys.exit("Error: Unable to access microphone") + + def start(self): + """Starts the VoiceType engine with hotkey support.""" + logging.info("VoiceType Pro Started") + print( + f"VoiceType Pro Active\nStart typing: {CONFIG['hotkey_listen']}\nExit: {CONFIG['hotkey_exit']}" + ) + + listener = keyboard.GlobalHotKeys( + { + CONFIG["hotkey_listen"]: self.toggle_listening, + CONFIG["hotkey_exit"]: self.shutdown, + } + ) + + listener.start() + listener.join() # Keep listening for hotkeys + + def toggle_listening(self): + """Toggles the voice listening state.""" + if not self.is_listening.is_set(): + self.is_listening.set() + threading.Thread(target=self.listen_worker, daemon=True).start() + threading.Thread(target=self.process_audio, daemon=True).start() + else: + self.is_listening.clear() + + def shutdown(self): + """Gracefully shuts down the program.""" + self.is_listening.clear() + logging.info("VoiceType Pro Shutdown") + print("\nVoiceType Pro terminated") + sys.exit(0) + + +if __name__ == "__main__": + try: + engine = VoiceTypeEngine() + engine.start() + except Exception as e: + logging.critical("Critical failure: %s", e) + print(f"Critical error: {str(e)}") + sys.exit(1)