[
  {
    "path": ".gitattributes",
    "content": "*.py text=auto eol=lf\n"
  },
  {
    "path": ".github/workflows/main.yml",
    "content": "name: PyInstaller\n\non:\n  push:\n    branches:\n      - master\n  pull_request:\n    branches:\n      - master\n\njobs:\n  build:\n    runs-on: ${{ matrix.os }}\n\n    strategy:\n      matrix:\n        os: [windows-latest, macos-latest, ubuntu-latest]\n\n    steps:\n      - uses: actions/checkout@v2\n\n      - name: Install UPX\n        uses: crazy-max/ghaction-upx@v2\n        if: matrix.os == 'windows-latest' || matrix.os == 'ubuntu-latest'\n        with:\n          install-only: true\n\n      - name: UPX version\n        if: matrix.os == 'windows-latest' || matrix.os == 'ubuntu-latest'\n        run: upx --version\n\n      - name: Setup Python 3.10\n        uses: actions/setup-python@v2\n        with:\n          python-version: '3.10'\n\n      - name: Install dependencies\n        run: |\n          python -m pip install --upgrade pip\n          pip install -r requirements.txt\n          pip install face_recognition --no-deps\n          pip install pyinstaller\n\n      - name: Test number_perser.get_number\n        run: |\n          python number_parser.py -v\n\n      - name: Build with PyInstaller for macos/ubuntu\n        if: matrix.os == 'macos-latest' || matrix.os == 'ubuntu-latest'\n        run: |\n          pyinstaller \\\n            --onefile Movie_Data_Capture.py \\\n            --python-option u \\\n            --hidden-import \"ImageProcessing.cnn\" \\\n            --add-data \"$(python -c 'import cloudscraper as _; print(_.__path__[0])' | tail -n 1):cloudscraper\" \\\n            --add-data \"$(python -c 'import opencc as _; print(_.__path__[0])' | tail -n 1):opencc\" \\\n            --add-data \"$(python -c 'import face_recognition_models as _; print(_.__path__[0])' | tail -n 1):face_recognition_models\" \\\n            --add-data \"Img:Img\" \\\n            --add-data \"scrapinglib:scrapinglib\" \\\n            --add-data \"config.ini:.\" \\\n\n      - name: Build with PyInstaller for windows\n        if: matrix.os == 'windows-latest'\n        run: |\n          pyinstaller `\n            --onefile Movie_Data_Capture.py `\n            --python-option u `\n            --hidden-import \"ImageProcessing.cnn\" `\n            --add-data \"$(python -c 'import cloudscraper as _; print(_.__path__[0])' | tail -n 1);cloudscraper\" `\n            --add-data \"$(python -c 'import opencc as _; print(_.__path__[0])' | tail -n 1);opencc\" `\n            --add-data \"$(python -c 'import face_recognition_models as _; print(_.__path__[0])' | tail -n 1);face_recognition_models\" `\n            --add-data \"Img;Img\" `\n            --add-data \"scrapinglib;scrapinglib\" `\n            --add-data \"config.ini;.\" `\n\n      - name: Copy config.ini\n        run: |\n          cp config.ini dist/\n\n      - name: Set VERSION variable for macos/ubuntu\n        if: matrix.os == 'macos-latest' || matrix.os == 'ubuntu-latest'\n        run: |\n          echo \"VERSION=$(python Movie_Data_Capture.py --version)\" >> $GITHUB_ENV\n\n      - name: Set VERSION variable for windows\n        if: matrix.os == 'windows-latest'\n        run: |\n          echo \"VERSION=$(python Movie_Data_Capture.py --version)\" | Out-File -FilePath $env:GITHUB_ENV -Encoding utf8 -Append\n\n      - name: Upload build artifact\n        uses: actions/upload-artifact@v1\n        with:\n          name: MDC-${{ env.VERSION }}-${{ runner.os }}-amd64\n          path: dist\n\n      - name: Run test (Ubuntu & MacOS)\n        if: matrix.os == 'ubuntu-latest' || matrix.os == 'macos-latest'\n        run: |\n          cd dist\n          ./Movie_Data_Capture\n"
  },
  {
    "path": ".gitignore",
    "content": "# Byte-compiled / optimized / DLL files\n__pycache__/\n*.py[cod]\n*$py.class\n\n# C extensions\n*.so\n\n# Distribution / packaging\n.Python\nbuild/\ndevelop-eggs/\ndist/\ndownloads/\neggs/\n.eggs/\nlib/\nlib64/\nparts/\nsdist/\nvar/\nwheels/\n*.egg-info/\n.installed.cfg\n*.egg\nMANIFEST\n\n# PyInstaller\n#  Usually these files are written by a python script from a template\n#  before PyInstaller builds the exe, so as to inject date/other infos into it.\n*.manifest\n*.spec\n\n# Installer logs\npip-log.txt\npip-delete-this-directory.txt\n\n# Unit test / coverage reports\nhtmlcov/\n.tox/\n.coverage\n.coverage.*\n.cache\nnosetests.xml\ncoverage.xml\n*.cover\n.hypothesis/\n.pytest_cache/\n\n# Translations\n*.mo\n*.pot\n\n# Django stuff:\n*.log\nlocal_settings.py\ndb.sqlite3\n\n# Flask stuff:\ninstance/\n.webassets-cache\n\n# Scrapy stuff:\n.scrapy\n\n# Sphinx documentation\ndocs/_build/\n\n# PyBuilder\ntarget/\n\n# Jupyter Notebook\n.ipynb_checkpoints\n\n# pyenv\n.python-version\n\n# celery beat schedule file\ncelerybeat-schedule\n\n# SageMath parsed files\n*.sage.py\n\n# Environments\n.env\n.venv\nenv/\nvenv/\nENV/\nenv.bak/\nvenv.bak/\n\n# Spyder project settings\n.spyderproject\n.spyproject\n\n# Rope project settings\n.ropeproject\n\n# mkdocs documentation\n/site\n\n# mypy\n.mypy_cache/\n\n# movie files\n*.mp4\n\n# success/failed folder\nJAV_output/**/*\nfailed/*\n.vscode/launch.json\n\n.idea"
  },
  {
    "path": "ADC_function.py",
    "content": "# build-in lib\nimport os.path\nimport os\nimport re\nimport uuid\nimport json\nimport time\nimport typing\nfrom unicodedata import category\nfrom concurrent.futures import ThreadPoolExecutor\n\n# third party lib\nimport requests\nfrom requests.adapters import HTTPAdapter\nimport mechanicalsoup\nfrom pathlib import Path\nfrom urllib3.util.retry import Retry\nfrom lxml import etree\nfrom cloudscraper import create_scraper\n\n# project wide\nimport config\n\n\ndef get_xpath_single(html_code: str, xpath):\n    html = etree.fromstring(html_code, etree.HTMLParser())\n    result1 = str(html.xpath(xpath)).strip(\" ['']\")\n    return result1\n\n\nG_USER_AGENT = r'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.133 Safari/537.36'\n\n\ndef get_html(url, cookies: dict = None, ua: str = None, return_type: str = None, encoding: str = None, json_headers=None):\n    \"\"\"\n    网页请求核心函数\n    \"\"\"\n    verify = config.getInstance().cacert_file()\n    config_proxy = config.getInstance().proxy()\n    errors = \"\"\n\n    headers = {\"User-Agent\": ua or G_USER_AGENT}  # noqa\n    if json_headers is not None:\n        headers.update(json_headers)\n\n    for i in range(config_proxy.retry):\n        try:\n            if config_proxy.enable:\n                proxies = config_proxy.proxies()\n                result = requests.get(str(url), headers=headers, timeout=config_proxy.timeout, proxies=proxies,\n                                      verify=verify,\n                                      cookies=cookies)\n            else:\n                result = requests.get(str(url), headers=headers, timeout=config_proxy.timeout, cookies=cookies)\n\n            if return_type == \"object\":\n                return result\n            elif return_type == \"content\":\n                return result.content\n            else:\n                result.encoding = encoding or result.apparent_encoding\n                return result.text\n        except Exception as e:\n            print(\"[-]Connect retry {}/{}\".format(i + 1, config_proxy.retry))\n            errors = str(e)\n    if \"getaddrinfo failed\" in errors:\n        print(\"[-]Connect Failed! Please Check your proxy config\")\n        debug = config.getInstance().debug()\n        if debug:\n            print(\"[-]\" + errors)\n    else:\n        print(\"[-]\" + errors)\n        print('[-]Connect Failed! Please check your Proxy or Network!')\n    raise Exception('Connect Failed')\n\n\ndef post_html(url: str, query: dict, headers: dict = None) -> requests.Response:\n    config_proxy = config.getInstance().proxy()\n    errors = \"\"\n    headers_ua = {\"User-Agent\": G_USER_AGENT}\n    if headers is None:\n        headers = headers_ua\n    else:\n        headers.update(headers_ua)\n\n    for i in range(config_proxy.retry):\n        try:\n            if config_proxy.enable:\n                proxies = config_proxy.proxies()\n                result = requests.post(url, data=query, proxies=proxies, headers=headers, timeout=config_proxy.timeout)\n            else:\n                result = requests.post(url, data=query, headers=headers, timeout=config_proxy.timeout)\n            return result\n        except Exception as e:\n            print(\"[-]Connect retry {}/{}\".format(i + 1, config_proxy.retry))\n            errors = str(e)\n    print(\"[-]Connect Failed! Please check your Proxy or Network!\")\n    print(\"[-]\" + errors)\n\n\nG_DEFAULT_TIMEOUT = 10  # seconds\n\n\nclass TimeoutHTTPAdapter(HTTPAdapter):\n    def __init__(self, *args, **kwargs):\n        self.timeout = G_DEFAULT_TIMEOUT\n        if \"timeout\" in kwargs:\n            self.timeout = kwargs[\"timeout\"]\n            del kwargs[\"timeout\"]\n        super().__init__(*args, **kwargs)\n\n    def send(self, request, **kwargs):\n        timeout = kwargs.get(\"timeout\")\n        if timeout is None:\n            kwargs[\"timeout\"] = self.timeout\n        return super().send(request, **kwargs)\n\n\n#  with keep-alive feature\ndef get_html_session(url: str = None, cookies: dict = None, ua: str = None, return_type: str = None,\n                     encoding: str = None):\n    config_proxy = config.getInstance().proxy()\n    session = requests.Session()\n    if isinstance(cookies, dict) and len(cookies):\n        requests.utils.add_dict_to_cookiejar(session.cookies, cookies)\n    retries = Retry(total=config_proxy.retry, connect=config_proxy.retry, backoff_factor=1,\n                    status_forcelist=[429, 500, 502, 503, 504])\n    session.mount(\"https://\", TimeoutHTTPAdapter(max_retries=retries, timeout=config_proxy.timeout))\n    session.mount(\"http://\", TimeoutHTTPAdapter(max_retries=retries, timeout=config_proxy.timeout))\n    if config_proxy.enable:\n        session.verify = config.getInstance().cacert_file()\n        session.proxies = config_proxy.proxies()\n    headers = {\"User-Agent\": ua or G_USER_AGENT}\n    session.headers = headers\n    try:\n        if isinstance(url, str) and len(url):\n            result = session.get(str(url))\n        else:  # 空url参数直接返回可重用session对象，无需设置return_type\n            return session\n        if not result.ok:\n            return None\n        if return_type == \"object\":\n            return result\n        elif return_type == \"content\":\n            return result.content\n        elif return_type == \"session\":\n            return result, session\n        else:\n            result.encoding = encoding or \"utf-8\"\n            return result.text\n    except requests.exceptions.ProxyError:\n        print(\"[-]get_html_session() Proxy error! Please check your Proxy\")\n    except requests.exceptions.RequestException:\n        pass\n    except Exception as e:\n        print(f\"[-]get_html_session() failed. {e}\")\n    return None\n\n\ndef get_html_by_browser(url: str = None, cookies: dict = None, ua: str = None, return_type: str = None,\n                        encoding: str = None, use_scraper: bool = False):\n    config_proxy = config.getInstance().proxy()\n    s = create_scraper(browser={'custom': ua or G_USER_AGENT, }) if use_scraper else requests.Session()\n    if isinstance(cookies, dict) and len(cookies):\n        requests.utils.add_dict_to_cookiejar(s.cookies, cookies)\n    retries = Retry(total=config_proxy.retry, connect=config_proxy.retry, backoff_factor=1,\n                    status_forcelist=[429, 500, 502, 503, 504])\n    s.mount(\"https://\", TimeoutHTTPAdapter(max_retries=retries, timeout=config_proxy.timeout))\n    s.mount(\"http://\", TimeoutHTTPAdapter(max_retries=retries, timeout=config_proxy.timeout))\n    if config_proxy.enable:\n        s.verify = config.getInstance().cacert_file()\n        s.proxies = config_proxy.proxies()\n    try:\n        browser = mechanicalsoup.StatefulBrowser(user_agent=ua or G_USER_AGENT, session=s)\n        if isinstance(url, str) and len(url):\n            result = browser.open(url)\n        else:\n            return browser\n        if not result.ok:\n            return None\n\n        if return_type == \"object\":\n            return result\n        elif return_type == \"content\":\n            return result.content\n        elif return_type == \"browser\":\n            return result, browser\n        else:\n            result.encoding = encoding or \"utf-8\"\n            return result.text\n    except requests.exceptions.ProxyError:\n        print(\"[-]get_html_by_browser() Proxy error! Please check your Proxy\")\n    except Exception as e:\n        print(f'[-]get_html_by_browser() Failed! {e}')\n    return None\n\n\ndef get_html_by_form(url, form_select: str = None, fields: dict = None, cookies: dict = None, ua: str = None,\n                     return_type: str = None, encoding: str = None):\n    config_proxy = config.getInstance().proxy()\n    s = requests.Session()\n    if isinstance(cookies, dict) and len(cookies):\n        requests.utils.add_dict_to_cookiejar(s.cookies, cookies)\n    retries = Retry(total=config_proxy.retry, connect=config_proxy.retry, backoff_factor=1,\n                    status_forcelist=[429, 500, 502, 503, 504])\n    s.mount(\"https://\", TimeoutHTTPAdapter(max_retries=retries, timeout=config_proxy.timeout))\n    s.mount(\"http://\", TimeoutHTTPAdapter(max_retries=retries, timeout=config_proxy.timeout))\n    if config_proxy.enable:\n        s.verify = config.getInstance().cacert_file()\n        s.proxies = config_proxy.proxies()\n    try:\n        browser = mechanicalsoup.StatefulBrowser(user_agent=ua or G_USER_AGENT, session=s)\n        result = browser.open(url)\n        if not result.ok:\n            return None\n        form = browser.select_form() if form_select is None else browser.select_form(form_select)\n        if isinstance(fields, dict):\n            for k, v in fields.items():\n                browser[k] = v\n        response = browser.submit_selected()\n\n        if return_type == \"object\":\n            return response\n        elif return_type == \"content\":\n            return response.content\n        elif return_type == \"browser\":\n            return response, browser\n        else:\n            result.encoding = encoding or \"utf-8\"\n            return response.text\n    except requests.exceptions.ProxyError:\n        print(\"[-]get_html_by_form() Proxy error! Please check your Proxy\")\n    except Exception as e:\n        print(f'[-]get_html_by_form() Failed! {e}')\n    return None\n\n\ndef get_html_by_scraper(url: str = None, cookies: dict = None, ua: str = None, return_type: str = None,\n                        encoding: str = None):\n    config_proxy = config.getInstance().proxy()\n    session = create_scraper(browser={'custom': ua or G_USER_AGENT, })\n    if isinstance(cookies, dict) and len(cookies):\n        requests.utils.add_dict_to_cookiejar(session.cookies, cookies)\n    retries = Retry(total=config_proxy.retry, connect=config_proxy.retry, backoff_factor=1,\n                    status_forcelist=[429, 500, 502, 503, 504])\n    session.mount(\"https://\", TimeoutHTTPAdapter(max_retries=retries, timeout=config_proxy.timeout))\n    session.mount(\"http://\", TimeoutHTTPAdapter(max_retries=retries, timeout=config_proxy.timeout))\n    if config_proxy.enable:\n        session.verify = config.getInstance().cacert_file()\n        session.proxies = config_proxy.proxies()\n    try:\n        if isinstance(url, str) and len(url):\n            result = session.get(str(url))\n        else:  # 空url参数直接返回可重用scraper对象，无需设置return_type\n            return session\n        if not result.ok:\n            return None\n        if return_type == \"object\":\n            return result\n        elif return_type == \"content\":\n            return result.content\n        elif return_type == \"scraper\":\n            return result, session\n        else:\n            result.encoding = encoding or \"utf-8\"\n            return result.text\n    except requests.exceptions.ProxyError:\n        print(\"[-]get_html_by_scraper() Proxy error! Please check your Proxy\")\n    except Exception as e:\n        print(f\"[-]get_html_by_scraper() failed. {e}\")\n    return None\n\n\n# def get_javlib_cookie() -> [dict, str]:\n#     import cloudscraper\n#     switch, proxy, timeout, retry_count, proxytype = config.getInstance().proxy()\n#     proxies = get_proxy(proxy, proxytype)\n#\n#     raw_cookie = {}\n#     user_agent = \"\"\n#\n#     # Get __cfduid/cf_clearance and user-agent\n#     for i in range(retry_count):\n#         try:\n#             if switch == 1 or switch == '1':\n#                 raw_cookie, user_agent = cloudscraper.get_cookie_string(\n#                     \"http://www.javlibrary.com/\",\n#                     proxies=proxies\n#                 )\n#             else:\n#                 raw_cookie, user_agent = cloudscraper.get_cookie_string(\n#                     \"http://www.javlibrary.com/\"\n#                 )\n#         except requests.exceptions.ProxyError:\n#             print(\"[-] ProxyError, retry {}/{}\".format(i + 1, retry_count))\n#         except cloudscraper.exceptions.CloudflareIUAMError:\n#             print(\"[-] IUAMError, retry {}/{}\".format(i + 1, retry_count))\n#\n#     return raw_cookie, user_agent\n\n\ndef translate(\n        src: str,\n        target_language: str = config.getInstance().get_target_language(),\n        engine: str = config.getInstance().get_translate_engine(),\n        app_id: str = \"\",\n        key: str = \"\",\n        delay: int = 0,\n) -> str:\n    \"\"\"\n    translate japanese kana to simplified chinese\n    翻译日语假名到简体中文\n    :raises ValueError: Non-existent translation engine\n    \"\"\"\n    trans_result = \"\"\n    # 中文句子如果包含&等符号会被谷歌翻译截断损失内容，而且中文翻译到中文也没有意义，故而忽略，只翻译带有日语假名的\n    if (is_japanese(src) == False) and (\"zh_\" in target_language):\n        return src\n    if engine == \"google-free\":\n        gsite = config.getInstance().get_translate_service_site()\n        if not re.match('^translate\\.google\\.(com|com\\.\\w{2}|\\w{2})$', gsite):\n            gsite = 'translate.google.cn'\n        url = (\n            f\"https://{gsite}/translate_a/single?client=gtx&dt=t&dj=1&ie=UTF-8&sl=auto&tl={target_language}&q={src}\"\n        )\n        result = get_html(url=url, return_type=\"object\")\n        if not result.ok:\n            print('[-]Google-free translate web API calling failed.')\n            return ''\n\n        translate_list = [i[\"trans\"] for i in result.json()[\"sentences\"]]\n        trans_result = trans_result.join(translate_list)\n    elif engine == \"azure\":\n        url = \"https://api.cognitive.microsofttranslator.com/translate?api-version=3.0&to=\" + target_language\n        headers = {\n            'Ocp-Apim-Subscription-Key': key,\n            'Ocp-Apim-Subscription-Region': \"global\",\n            'Content-type': 'application/json',\n            'X-ClientTraceId': str(uuid.uuid4())\n        }\n        body = json.dumps([{'text': src}])\n        result = post_html(url=url, query=body, headers=headers)\n        translate_list = [i[\"text\"] for i in result.json()[0][\"translations\"]]\n        trans_result = trans_result.join(translate_list)\n    elif engine == \"deeplx\":\n        url = config.getInstance().get_translate_service_site()\n        res = requests.post(f\"{url}/translate\", json={\n            'text': src,\n            'source_lang': 'auto',\n            'target_lang': target_language,\n        })\n        if res.text.strip():\n            trans_result = res.json().get('data')\n    else:\n        raise ValueError(\"Non-existent translation engine\")\n\n    time.sleep(delay)\n    return trans_result\n\n\ndef load_cookies(cookie_json_filename: str) -> typing.Tuple[typing.Optional[dict], typing.Optional[str]]:\n    \"\"\"\n    加载cookie,用于以会员方式访问非游客内容\n\n    :filename: cookie文件名。获取cookie方式：从网站登录后，通过浏览器插件(CookieBro或EdittThisCookie)或者直接在地址栏网站链接信息处都可以复制或者导出cookie内容，以JSON方式保存\n\n    # 示例: FC2-755670 url https://javdb9.com/v/vO8Mn\n    # json 文件格式\n    # 文件名: 站点名.json，示例 javdb9.json\n    # 内容(文件编码:UTF-8)：\n    {\n        \"over18\":\"1\",\n        \"redirect_to\":\"%2Fv%2FvO8Mn\",\n        \"remember_me_token\":\"***********\",\n        \"_jdb_session\":\"************\",\n        \"locale\":\"zh\",\n        \"__cfduid\":\"*********\",\n        \"theme\":\"auto\"\n    }\n    \"\"\"\n    filename = os.path.basename(cookie_json_filename)\n    if not len(filename):\n        return None, None\n    path_search_order = (\n        Path.cwd() / filename,\n        Path.home() / filename,\n        Path.home() / f\".mdc/{filename}\",\n        Path.home() / f\".local/share/mdc/{filename}\"\n    )\n    cookies_filename = None\n    try:\n        for p in path_search_order:\n            if p.is_file():\n                cookies_filename = str(p.resolve())\n                break\n        if not cookies_filename:\n            return None, None\n        return json.loads(Path(cookies_filename).read_text(encoding='utf-8')), cookies_filename\n    except:\n        return None, None\n\n\ndef file_modification_days(filename: str) -> int:\n    \"\"\"\n    文件修改时间距此时的天数\n    \"\"\"\n    mfile = Path(filename)\n    if not mfile.is_file():\n        return 9999\n    mtime = int(mfile.stat().st_mtime)\n    now = int(time.time())\n    days = int((now - mtime) / (24 * 60 * 60))\n    if days < 0:\n        return 9999\n    return days\n\n\ndef file_not_exist_or_empty(filepath) -> bool:\n    return not os.path.isfile(filepath) or os.path.getsize(filepath) == 0\n\n\ndef is_japanese(raw: str) -> bool:\n    \"\"\"\n    日语简单检测\n    \"\"\"\n    return bool(re.search(r'[\\u3040-\\u309F\\u30A0-\\u30FF\\uFF66-\\uFF9F]', raw, re.UNICODE))\n\n\ndef download_file_with_filename(url: str, filename: str, path: str) -> None:\n    \"\"\"\n    download file save to give path with given name from given url\n    \"\"\"\n    conf = config.getInstance()\n    config_proxy = conf.proxy()\n\n    for i in range(config_proxy.retry):\n        try:\n            if config_proxy.enable:\n                if not os.path.exists(path):\n                    try:\n                        os.makedirs(path)\n                    except:\n                        print(f\"[-]Fatal error! Can not make folder '{path}'\")\n                        os._exit(0)\n                r = get_html(url=url, return_type='content')\n                if r == '':\n                    print('[-]Movie Download Data not found!')\n                    return\n                with open(os.path.join(path, filename), \"wb\") as code:\n                    code.write(r)\n                return\n            else:\n                if not os.path.exists(path):\n                    try:\n                        os.makedirs(path)\n                    except:\n                        print(f\"[-]Fatal error! Can not make folder '{path}'\")\n                        os._exit(0)\n                r = get_html(url=url, return_type='content')\n                if r == '':\n                    print('[-]Movie Download Data not found!')\n                    return\n                with open(os.path.join(path, filename), \"wb\") as code:\n                    code.write(r)\n                return\n        except requests.exceptions.ProxyError:\n            i += 1\n            print('[-]Download :  Connect retry ' + str(i) + '/' + str(config_proxy.retry))\n        except requests.exceptions.ConnectTimeout:\n            i += 1\n            print('[-]Download :  Connect retry ' + str(i) + '/' + str(config_proxy.retry))\n        except requests.exceptions.ConnectionError:\n            i += 1\n            print('[-]Download :  Connect retry ' + str(i) + '/' + str(config_proxy.retry))\n        except requests.exceptions.RequestException:\n            i += 1\n            print('[-]Download :  Connect retry ' + str(i) + '/' + str(config_proxy.retry))\n        except IOError:\n            raise ValueError(f\"[-]Create Directory '{path}' failed!\")\n            return\n    print('[-]Connect Failed! Please check your Proxy or Network!')\n    raise ValueError('[-]Connect Failed! Please check your Proxy or Network!')\n    return\n\n\ndef download_one_file(args) -> str:\n    \"\"\"\n    download file save to given path from given url\n    wrapped for map function\n    \"\"\"\n\n    (url, save_path, json_headers) = args\n    if json_headers is not None:\n        filebytes = get_html(url, return_type='content', json_headers=json_headers['headers'])\n    else:\n        filebytes = get_html(url, return_type='content')\n    if isinstance(filebytes, bytes) and len(filebytes):\n        with save_path.open('wb') as fpbyte:\n            if len(filebytes) == fpbyte.write(filebytes):\n                return str(save_path)\n\n\ndef parallel_download_files(dn_list: typing.Iterable[typing.Sequence], parallel: int = 0, json_headers=None):\n    \"\"\"\n    download files in parallel 多线程下载文件\n\n    用法示例: 2线程同时下载两个不同文件，并保存到不同路径，路径目录可未创建，但需要具备对目标目录和文件的写权限\n    parallel_download_files([\n    ('https://site1/img/p1.jpg', 'C:/temp/img/p1.jpg'),\n    ('https://site2/cover/n1.xml', 'C:/tmp/cover/n1.xml')\n    ])\n\n    :dn_list: 可以是 tuple或者list: ((url1, save_fullpath1),(url2, save_fullpath2),) fullpath可以是str或Path\n    :parallel: 并行下载的线程池线程数，为0则由函数自己决定\n    \"\"\"\n    mp_args = []\n    for url, fullpath in dn_list:\n        if url and isinstance(url, str) and url.startswith('http') \\\n                and fullpath and isinstance(fullpath, (str, Path)) and len(str(fullpath)):\n            fullpath = Path(fullpath)\n            fullpath.parent.mkdir(parents=True, exist_ok=True)\n            mp_args.append((url, fullpath, json_headers))\n    if not len(mp_args):\n        return []\n    if not isinstance(parallel, int) or parallel not in range(1, 200):\n        parallel = min(5, len(mp_args))\n    with ThreadPoolExecutor(parallel) as pool:\n        results = list(pool.map(download_one_file, mp_args))\n    return results\n\n\ndef delete_all_elements_in_list(string: str, lists: typing.Iterable[str]):\n    \"\"\"\n    delete same string in given list\n    \"\"\"\n    new_lists = []\n    for i in lists:\n        if i != string:\n            new_lists.append(i)\n    return new_lists\n\n\ndef delete_all_elements_in_str(string_delete: str, string: str):\n    \"\"\"\n    delete same string in given list\n    \"\"\"\n    for i in string:\n        if i == string_delete:\n            string = string.replace(i, \"\")\n    return string\n\n\n# print format空格填充对齐内容包含中文时的空格计算\ndef cn_space(v: str, n: int) -> int:\n    return n - [category(c) for c in v].count('Lo')\n\n\n\"\"\"\nUsage: python ./ADC_function.py https://cn.bing.com/\nPurpose: benchmark get_html_session\n         benchmark get_html_by_scraper\n         benchmark get_html_by_browser\n         benchmark get_html\nTODO: may be this should move to unittest directory\n\"\"\"\nif __name__ == \"__main__\":\n    import sys, timeit\n    from http.client import HTTPConnection\n\n\n    def benchmark(times: int, url):\n        print(f\"HTTP GET Benchmark times:{times} url:{url}\")\n        tm = timeit.timeit(f\"_ = session1.get('{url}')\",\n                           \"from __main__ import get_html_session;session1=get_html_session()\",\n                           number=times)\n        print(f' *{tm:>10.5f}s get_html_session() Keep-Alive enable')\n        tm = timeit.timeit(f\"_ = scraper1.get('{url}')\",\n                           \"from __main__ import get_html_by_scraper;scraper1=get_html_by_scraper()\",\n                           number=times)\n        print(f' *{tm:>10.5f}s get_html_by_scraper() Keep-Alive enable')\n        tm = timeit.timeit(f\"_ = browser1.open('{url}')\",\n                           \"from __main__ import get_html_by_browser;browser1=get_html_by_browser()\",\n                           number=times)\n        print(f' *{tm:>10.5f}s get_html_by_browser() Keep-Alive enable')\n        tm = timeit.timeit(f\"_ = get_html('{url}')\",\n                           \"from __main__ import get_html\",\n                           number=times)\n        print(f' *{tm:>10.5f}s get_html()')\n\n\n    # target_url = \"https://www.189.cn/\"\n    target_url = \"http://www.chinaunicom.com\"\n    HTTPConnection.debuglevel = 1\n    html_session = get_html_session()\n    _ = html_session.get(target_url)\n    HTTPConnection.debuglevel = 0\n\n    # times\n    t = 100\n    if len(sys.argv) > 1:\n        target_url = sys.argv[1]\n    benchmark(t, target_url)\n"
  },
  {
    "path": "ImageProcessing/__init__.py",
    "content": "import sys\nsys.path.append('../')\n\nimport logging\nimport os\nimport config\nimport importlib\nfrom pathlib import Path\nfrom PIL import Image\nimport shutil\nfrom ADC_function import file_not_exist_or_empty\n\n\ndef face_crop_width(filename, width, height):\n    aspect_ratio = config.getInstance().face_aspect_ratio()\n    # 新宽度是高度的2/3\n    cropWidthHalf = int(height/3)\n    try:\n        locations_model = config.getInstance().face_locations_model().lower().split(',')\n        locations_model = filter(lambda x: x, locations_model)\n        for model in locations_model:\n            center, top = face_center(filename, model)\n            # 如果找到就跳出循环\n            if center:\n                cropLeft = center-cropWidthHalf\n                cropRight = center+cropWidthHalf\n                # 越界处理\n                if cropLeft < 0:\n                    cropLeft = 0\n                    cropRight = cropWidthHalf * aspect_ratio\n                elif cropRight > width:\n                    cropLeft = width - cropWidthHalf * aspect_ratio\n                    cropRight = width\n                return (cropLeft, 0, cropRight, height)\n    except:\n        print('[-]Not found face!   ' + filename)\n    # 默认靠右切\n    return (width-cropWidthHalf * aspect_ratio, 0, width, height)\n\n\ndef face_crop_height(filename, width, height):\n    cropHeight = int(width*3/2)\n    try:\n        locations_model = config.getInstance().face_locations_model().lower().split(',')\n        locations_model = filter(lambda x: x, locations_model)\n        for model in locations_model:\n            center, top = face_center(filename, model)\n            # 如果找到就跳出循环\n            if top:\n                # 头部靠上\n                cropTop = top\n                cropBottom = cropHeight + top\n                if cropBottom > height:\n                    cropTop = 0\n                    cropBottom = cropHeight\n                return (0, cropTop, width, cropBottom)\n    except:\n        print('[-]Not found face!   ' + filename)\n    # 默认从顶部向下切割\n    return (0, 0, width, cropHeight)\n\n\ndef cutImage(imagecut, path, thumb_path, poster_path, skip_facerec=False):\n    conf = config.getInstance()\n    fullpath_fanart = os.path.join(path, thumb_path)\n    fullpath_poster = os.path.join(path, poster_path)\n    aspect_ratio = conf.face_aspect_ratio()\n    if conf.face_aways_imagecut():\n        imagecut = 1\n    elif conf.download_only_missing_images() and not file_not_exist_or_empty(fullpath_poster):\n        return\n    # imagecut为4时同时也是有码影片 也用人脸识别裁剪封面\n    if imagecut == 1 or imagecut == 4:  # 剪裁大封面\n        try:\n            img = Image.open(fullpath_fanart)\n            width, height = img.size\n            if width/height > 2/3:  # 如果宽度大于2\n                if imagecut == 4:\n                    # 以人像为中心切取\n                    img2 = img.crop(face_crop_width(fullpath_fanart, width, height))\n                elif skip_facerec:\n                    # 有码封面默认靠右切\n                    img2 = img.crop((width - int(height / 3) * aspect_ratio, 0, width, height))\n                else:\n                    # 以人像为中心切取\n                    img2 = img.crop(face_crop_width(fullpath_fanart, width, height))\n            elif width/height < 2/3:  # 如果高度大于3\n                # 从底部向上切割\n                img2 = img.crop(face_crop_height(fullpath_fanart, width, height))\n            else:  # 如果等于2/3\n                img2 = img\n            img2.save(fullpath_poster)\n            print(f\"[+]Image Cutted!     {Path(fullpath_poster).name}\")\n        except Exception as e:\n            print(e)\n            print('[-]Cover cut failed!')\n    elif imagecut == 0:  # 复制封面\n        shutil.copyfile(fullpath_fanart, fullpath_poster)\n        print(f\"[+]Image Copyed!     {Path(fullpath_poster).name}\")\n\n\ndef face_center(filename, model):\n    try:\n        mod = importlib.import_module('.' + model, 'ImageProcessing')\n        return mod.face_center(filename, model)\n    except Exception as e:\n        print('[-]Model found face  ' + filename)\n        if config.getInstance().debug() == 1:\n            logging.error(e)\n        return (0, 0)\n\nif __name__ == '__main__':\n    cutImage(1,'z:/t/','p.jpg','o.jpg')\n    #cutImage(1,'H:\\\\test\\\\','12.jpg','test.jpg')\n"
  },
  {
    "path": "ImageProcessing/cnn.py",
    "content": "import sys\nsys.path.append('../')\n\nfrom ImageProcessing.hog import face_center as hog_face_center\n\n\ndef face_center(filename, model):\n    return hog_face_center(filename, model)\n"
  },
  {
    "path": "ImageProcessing/hog.py",
    "content": "import face_recognition\n\n\ndef face_center(filename, model):\n    image = face_recognition.load_image_file(filename)\n    face_locations = face_recognition.face_locations(image, 1, model)\n    print('[+]Found person      [' + str(len(face_locations)) + ']      By model hog')\n    maxRight = 0\n    maxTop = 0\n    for face_location in face_locations:\n        top, right, bottom, left = face_location\n        # 中心点\n        x = int((right+left)/2)\n        if x > maxRight:\n            maxRight = x\n            maxTop = top\n    return maxRight,maxTop\n"
  },
  {
    "path": "LICENSE",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received.  You must make sure that they, too, receive\nor can get the source code.  And you must show them these terms so they\nknow their rights.\n\n  Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n  For the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software.  For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Use with the GNU Affero General Public License.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see <https://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n    <program>  Copyright (C) <year>  <name of author>\n    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, your program's commands\nmight be different; for a GUI interface, you would use an \"about box\".\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n<https://www.gnu.org/licenses/>.\n\n  The GNU General Public License does not permit incorporating your program\ninto proprietary programs.  If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.  But first, please read\n<https://www.gnu.org/licenses/why-not-lgpl.html>.\n"
  },
  {
    "path": "Makefile",
    "content": "#.PHONY: help prepare-dev test lint run doc\n\n#VENV_NAME?=venv\n#VENV_ACTIVATE=. $(VENV_NAME)/bin/activate\n#PYTHON=${VENV_NAME}/bin/python3\nSHELL = /bin/bash\n\n.DEFAULT: make\nmake:\n\t@echo \"[+]make prepare-dev\"\n\t#sudo apt-get -y install python3 python3-pip\n\tpip3 install -r requirements.txt\n\tpip3 install pyinstaller\n\n\t#@echo \"[+]Set CLOUDSCRAPER_PATH variable\"\n\t#export cloudscraper_path=$(python3 -c 'import cloudscraper as _; print(_.__path__[0])' | tail -n 1)\n\n\t@echo \"[+]Pyinstaller make\"\n\tpyinstaller --onefile Movie_Data_Capture.py  --hidden-import ADC_function.py --hidden-import core.py \\\n\t    --hidden-import \"ImageProcessing.cnn\" \\\n\t    --python-option u \\\n\t\t--add-data \"`python3 -c 'import cloudscraper as _; print(_.__path__[0])' | tail -n 1`:cloudscraper\" \\\n\t\t--add-data \"`python3 -c 'import opencc as _; print(_.__path__[0])' | tail -n 1`:opencc\" \\\n        --add-data \"`python3 -c 'import face_recognition_models as _; print(_.__path__[0])' | tail -n 1`:face_recognition_models\" \\\n\t\t--add-data \"Img:Img\" \\\n\t\t--add-data \"config.ini:.\" \\\n\n\t@echo \"[+]Move to bin\"\n\tif [ ! -d \"./bin\" ];then  mkdir bin; fi\n\tmv dist/* bin/\n\tcp config.ini bin/\n\trm -rf dist/\n\n\t@echo \"[+]Clean cache\"\n\t@find . -name '*.pyc' -delete\n\t@find . -name '__pycache__' -type d | xargs rm -fr\n\t@find . -name '.pytest_cache' -type d | xargs rm -fr\n\trm -rf build/\n"
  },
  {
    "path": "Movie_Data_Capture.py",
    "content": "import argparse\nimport json\nimport os\nimport random\nimport re\nimport sys\nimport time\nimport shutil\nimport typing\nimport urllib3\nimport signal\nimport platform\nimport config\n\nfrom datetime import datetime, timedelta\nfrom lxml import etree\nfrom pathlib import Path\nfrom opencc import OpenCC\n\nfrom scraper import get_data_from_json\nfrom ADC_function import file_modification_days, get_html, parallel_download_files\nfrom number_parser import get_number\nfrom core import core_main, core_main_no_net_op, moveFailedFolder, debug_print\n\ndef argparse_function(ver: str) -> typing.Tuple[str, str, str, str, bool, bool, str, str]:\n    conf = config.getInstance()\n    parser = argparse.ArgumentParser(epilog=f\"Load Config file '{conf.ini_path}'.\")\n    parser.add_argument(\"file\", default='', nargs='?', help=\"Single Movie file path.\")\n    parser.add_argument(\"-p\", \"--path\", default='', nargs='?', help=\"Analysis folder path.\")\n    parser.add_argument(\"-m\", \"--main-mode\", default='', nargs='?',\n                        help=\"Main mode. 1:Scraping 2:Organizing 3:Scraping in analysis folder\")\n    parser.add_argument(\"-n\", \"--number\", default='', nargs='?', help=\"Custom file number of single movie file.\")\n    # parser.add_argument(\"-C\", \"--config\", default='config.ini', nargs='?', help=\"The config file Path.\")\n    parser.add_argument(\"-L\", \"--link-mode\", default='', nargs='?',\n                        help=\"Create movie file link. 0:moving movie file, do not create link 1:soft link 2:try hard link first\")\n    default_logdir = str(Path.home() / '.mlogs')\n    parser.add_argument(\"-o\", \"--log-dir\", dest='logdir', default=default_logdir, nargs='?',\n                        help=f\"\"\"Duplicate stdout and stderr to logfiles in logging folder, default on.\n        default folder for current user: '{default_logdir}'. Change default folder to an empty file,\n        or use --log-dir= to turn log off.\"\"\")\n    parser.add_argument(\"-q\", \"--regex-query\", dest='regexstr', default='', nargs='?',\n                        help=\"python re module regex filepath filtering.\")\n    parser.add_argument(\"-d\", \"--nfo-skip-days\", dest='days', default='', nargs='?',\n                        help=\"Override nfo_skip_days value in config.\")\n    parser.add_argument(\"-c\", \"--stop-counter\", dest='cnt', default='', nargs='?',\n                        help=\"Override stop_counter value in config.\")\n    parser.add_argument(\"-R\", \"--rerun-delay\", dest='delaytm', default='', nargs='?',\n                        help=\"Delay (eg. 1h10m30s or 60 (second)) time and rerun, until all movies proceed. Note: stop_counter value in config or -c must none zero.\")\n    parser.add_argument(\"-i\", \"--ignore-failed-list\", action=\"store_true\", help=\"Ignore failed list '{}'\".format(\n        os.path.join(os.path.abspath(conf.failed_folder()), 'failed_list.txt')))\n    parser.add_argument(\"-a\", \"--auto-exit\", action=\"store_true\",\n                        help=\"Auto exit after program complete\")\n    parser.add_argument(\"-g\", \"--debug\", action=\"store_true\",\n                        help=\"Turn on debug mode to generate diagnostic log for issue report.\")\n    parser.add_argument(\"-N\", \"--no-network-operation\", action=\"store_true\",\n                        help=\"No network query, do not get metadata, for cover cropping purposes, only takes effect when main mode is 3.\")\n    parser.add_argument(\"-w\", \"--website\", dest='site', default='', nargs='?',\n                        help=\"Override [priority]website= in config.\")\n    parser.add_argument(\"-D\", \"--download-images\", dest='dnimg', action=\"store_true\",\n                        help=\"Override [common]download_only_missing_images=0 force invoke image downloading.\")\n    parser.add_argument(\"-C\", \"--config-override\", dest='cfgcmd', action='append', nargs=1,\n                        help=\"Common use config override. Grammar: section:key=value[;[section:]key=value] eg. 'de:s=1' or 'debug_mode:switch=1' override[debug_mode]switch=1 Note:this parameters can be used multiple times\")\n    parser.add_argument(\"-z\", \"--zero-operation\", dest='zero_op', action=\"store_true\",\n                        help=\"\"\"Only show job list of files and numbers, and **NO** actual operation\nis performed. It may help you correct wrong numbers before real job.\"\"\")\n    parser.add_argument(\"-v\", \"--version\", action=\"version\", version=ver)\n    parser.add_argument(\"-s\", \"--search\", default='', nargs='?', help=\"Search number\")\n    parser.add_argument(\"-ss\", \"--specified-source\", default='', nargs='?', help=\"specified Source.\")\n    parser.add_argument(\"-su\", \"--specified-url\", default='', nargs='?', help=\"specified Url.\")\n\n    args = parser.parse_args()\n\n    def set_natural_number_or_none(sk, value):\n        if isinstance(value, str) and value.isnumeric() and int(value) >= 0:\n            conf.set_override(f'{sk}={value}')\n\n    def set_str_or_none(sk, value):\n        if isinstance(value, str) and len(value):\n            conf.set_override(f'{sk}={value}')\n\n    def set_bool_or_none(sk, value):\n        if isinstance(value, bool) and value:\n            conf.set_override(f'{sk}=1')\n\n    set_natural_number_or_none(\"common:main_mode\", args.main_mode)\n    set_natural_number_or_none(\"common:link_mode\", args.link_mode)\n    set_str_or_none(\"common:source_folder\", args.path)\n    set_bool_or_none(\"common:auto_exit\", args.auto_exit)\n    set_natural_number_or_none(\"common:nfo_skip_days\", args.days)\n    set_natural_number_or_none(\"advenced_sleep:stop_counter\", args.cnt)\n    set_bool_or_none(\"common:ignore_failed_list\", args.ignore_failed_list)\n    set_str_or_none(\"advenced_sleep:rerun_delay\", args.delaytm)\n    set_str_or_none(\"priority:website\", args.site)\n    if isinstance(args.dnimg, bool) and args.dnimg:\n        conf.set_override(\"common:download_only_missing_images=0\")\n    set_bool_or_none(\"debug_mode:switch\", args.debug)\n    if isinstance(args.cfgcmd, list):\n        for cmd in args.cfgcmd:\n            conf.set_override(cmd[0])\n\n    no_net_op = False\n    if conf.main_mode() == 3:\n        no_net_op = args.no_network_operation\n        if no_net_op:\n            conf.set_override(\"advenced_sleep:stop_counter=0;advenced_sleep:rerun_delay=0s;face:aways_imagecut=1\")\n\n    return args.file, args.number, args.logdir, args.regexstr, args.zero_op, no_net_op, args.search, args.specified_source, args.specified_url\n\n\nclass OutLogger(object):\n    def __init__(self, logfile) -> None:\n        self.term = sys.stdout\n        self.log = open(logfile, \"w\", encoding='utf-8', buffering=1)\n        self.filepath = logfile\n\n    def __del__(self):\n        self.close()\n\n    def __enter__(self):\n        pass\n\n    def __exit__(self, *args):\n        self.close()\n\n    def write(self, msg):\n        self.term.write(msg)\n        self.log.write(msg)\n\n    def flush(self):\n        if 'flush' in dir(self.term):\n            self.term.flush()\n        if 'flush' in dir(self.log):\n            self.log.flush()\n        if 'fileno' in dir(self.log):\n            os.fsync(self.log.fileno())\n\n    def close(self):\n        if self.term is not None:\n            sys.stdout = self.term\n            self.term = None\n        if self.log is not None:\n            self.log.close()\n            self.log = None\n\n\nclass ErrLogger(OutLogger):\n\n    def __init__(self, logfile) -> None:\n        self.term = sys.stderr\n        self.log = open(logfile, \"w\", encoding='utf-8', buffering=1)\n        self.filepath = logfile\n\n    def close(self):\n        if self.term is not None:\n            sys.stderr = self.term\n            self.term = None\n\n        if self.log is not None:\n            self.log.close()\n            self.log = None\n\n\ndef dupe_stdout_to_logfile(logdir: str):\n    if not isinstance(logdir, str) or len(logdir) == 0:\n        return\n    log_dir = Path(logdir)\n    if not log_dir.exists():\n        try:\n            log_dir.mkdir(parents=True, exist_ok=True)\n        except:\n            pass\n    if not log_dir.is_dir():\n        return  # Tips for disabling logs by change directory to a same name empty regular file\n    abslog_dir = log_dir.resolve()\n    log_tmstr = datetime.now().strftime(\"%Y%m%dT%H%M%S\")\n    logfile = abslog_dir / f'mdc_{log_tmstr}.txt'\n    errlog = abslog_dir / f'mdc_{log_tmstr}_err.txt'\n\n    sys.stdout = OutLogger(logfile)\n    sys.stderr = ErrLogger(errlog)\n\n\ndef close_logfile(logdir: str):\n    if not isinstance(logdir, str) or len(logdir) == 0 or not os.path.isdir(logdir):\n        return\n    # 日志关闭前保存日志路径\n    filepath = None\n    try:\n        filepath = sys.stdout.filepath\n    except:\n        pass\n    sys.stdout.close()\n    sys.stderr.close()\n    log_dir = Path(logdir).resolve()\n    if isinstance(filepath, Path):\n        print(f\"Log file '{filepath}' saved.\")\n        assert (filepath.parent.samefile(log_dir))\n    # 清理空文件\n    for f in log_dir.glob(r'*_err.txt'):\n        if f.stat().st_size == 0:\n            try:\n                f.unlink(missing_ok=True)\n            except:\n                pass\n    # 合并日志 只检测日志目录内的文本日志，忽略子目录。三天前的日志，按日合并为单个日志，三个月前的日志，\n    # 按月合并为单个月志，去年及以前的月志，今年4月以后将之按年合并为年志\n    # 测试步骤：\n    \"\"\"\n    LOGDIR=/tmp/mlog\n    mkdir -p $LOGDIR\n    for f in {2016..2020}{01..12}{01..28};do;echo $f>$LOGDIR/mdc_${f}T235959.txt;done\n    for f in {01..09}{01..28};do;echo 2021$f>$LOGDIR/mdc_2021${f}T235959.txt;done\n    for f in {00..23};do;echo 20211001T$f>$LOGDIR/mdc_20211001T${f}5959.txt;done\n    echo \"$(ls -1 $LOGDIR|wc -l) files in $LOGDIR\"\n    # 1932 files in /tmp/mlog\n    mdc -zgic1 -d0 -m3 -o $LOGDIR\n    # python3 ./Movie_Data_Capture.py -zgic1 -o $LOGDIR\n    ls $LOGDIR\n    # rm -rf $LOGDIR\n    \"\"\"\n    today = datetime.today()\n    # 第一步，合并到日。3天前的日志，文件名是同一天的合并为一份日志\n    for i in range(1):\n        txts = [f for f in log_dir.glob(r'*.txt') if re.match(r'^mdc_\\d{8}T\\d{6}$', f.stem, re.A)]\n        if not txts or not len(txts):\n            break\n        e = [f for f in txts if '_err' in f.stem]\n        txts.sort()\n        tmstr_3_days_ago = (today.replace(hour=0) - timedelta(days=3)).strftime(\"%Y%m%dT99\")\n        deadline_day = f'mdc_{tmstr_3_days_ago}'\n        day_merge = [f for f in txts if f.stem < deadline_day]\n        if not day_merge or not len(day_merge):\n            break\n        cutday = len('T235959.txt')  # cut length mdc_20201201|T235959.txt\n        for f in day_merge:\n            try:\n                day_file_name = str(f)[:-cutday] + '.txt'  # mdc_20201201.txt\n                with open(day_file_name, 'a', encoding='utf-8') as m:\n                    m.write(f.read_text(encoding='utf-8'))\n                f.unlink(missing_ok=True)\n            except:\n                pass\n    # 第二步，合并到月\n    for i in range(1):  # 利用1次循环的break跳到第二步，避免大块if缩进或者使用goto语法\n        txts = [f for f in log_dir.glob(r'*.txt') if re.match(r'^mdc_\\d{8}$', f.stem, re.A)]\n        if not txts or not len(txts):\n            break\n        txts.sort()\n        tmstr_3_month_ago = (today.replace(day=1) - timedelta(days=3 * 30)).strftime(\"%Y%m32\")\n        deadline_month = f'mdc_{tmstr_3_month_ago}'\n        month_merge = [f for f in txts if f.stem < deadline_month]\n        if not month_merge or not len(month_merge):\n            break\n        tomonth = len('01.txt')  # cut length mdc_202012|01.txt\n        for f in month_merge:\n            try:\n                month_file_name = str(f)[:-tomonth] + '.txt'  # mdc_202012.txt\n                with open(month_file_name, 'a', encoding='utf-8') as m:\n                    m.write(f.read_text(encoding='utf-8'))\n                f.unlink(missing_ok=True)\n            except:\n                pass\n    # 第三步，月合并到年\n    for i in range(1):\n        if today.month < 4:\n            break\n        mons = [f for f in log_dir.glob(r'*.txt') if re.match(r'^mdc_\\d{6}$', f.stem, re.A)]\n        if not mons or not len(mons):\n            break\n        mons.sort()\n        deadline_year = f'mdc_{today.year - 1}13'\n        year_merge = [f for f in mons if f.stem < deadline_year]\n        if not year_merge or not len(year_merge):\n            break\n        toyear = len('12.txt')  # cut length mdc_2020|12.txt\n        for f in year_merge:\n            try:\n                year_file_name = str(f)[:-toyear] + '.txt'  # mdc_2020.txt\n                with open(year_file_name, 'a', encoding='utf-8') as y:\n                    y.write(f.read_text(encoding='utf-8'))\n                f.unlink(missing_ok=True)\n            except:\n                pass\n    # 第四步，压缩年志 如果有压缩需求，请自行手工压缩，或者使用外部脚本来定时完成。推荐nongnu的lzip，对于\n    # 这种粒度的文本日志，压缩比是目前最好的。lzip -9的运行参数下，日志压缩比要高于xz -9，而且内存占用更少，\n    # 多核利用率更高(plzip多线程版本)，解压速度更快。压缩后的大小差不多是未压缩时的2.4%到3.7%左右，\n    # 100MB的日志文件能缩小到3.7MB。\n    return filepath\n\n\ndef signal_handler(*args):\n    print('[!]Ctrl+C detected, Exit.')\n    os._exit(9)\n\n\ndef sigdebug_handler(*args):\n    conf = config.getInstance()\n    conf.set_override(f\"debug_mode:switch={int(not conf.debug())}\")\n    print(f\"[!]Debug {('oFF', 'On')[int(conf.debug())]}\")\n\n\n# 新增失败文件列表跳过处理，及.nfo修改天数跳过处理，提示跳过视频总数，调试模式(-g)下详细被跳过文件，跳过小广告\ndef movie_lists(source_folder, regexstr: str) -> typing.List[str]:\n    conf = config.getInstance()\n    main_mode = conf.main_mode()\n    debug = conf.debug()\n    nfo_skip_days = conf.nfo_skip_days()\n    link_mode = conf.link_mode()\n    file_type = conf.media_type().lower().split(\",\")\n    trailerRE = re.compile(r'-trailer\\.', re.IGNORECASE)\n    cliRE = None\n    if isinstance(regexstr, str) and len(regexstr):\n        try:\n            cliRE = re.compile(regexstr, re.IGNORECASE)\n        except:\n            pass\n    failed_list_txt_path = Path(conf.failed_folder()).resolve() / 'failed_list.txt'\n    failed_set = set()\n    if (main_mode == 3 or link_mode) and not conf.ignore_failed_list():\n        try:\n            flist = failed_list_txt_path.read_text(encoding='utf-8').splitlines()\n            failed_set = set(flist)\n            if len(flist) != len(failed_set):  # 检查去重并写回，但是不改变failed_list.txt内条目的先后次序，重复的只保留最后的\n                fset = failed_set.copy()\n                for i in range(len(flist) - 1, -1, -1):\n                    fset.remove(flist[i]) if flist[i] in fset else flist.pop(i)\n                failed_list_txt_path.write_text('\\n'.join(flist) + '\\n', encoding='utf-8')\n                assert len(fset) == 0 and len(flist) == len(failed_set)\n        except:\n            pass\n    if not Path(source_folder).is_dir():\n        print('[-]Source folder not found!')\n        return []\n    total = []\n    source = Path(source_folder).resolve()\n    skip_failed_cnt, skip_nfo_days_cnt = 0, 0\n    escape_folder_set = set(re.split(\"[,，]\", conf.escape_folder()))\n    for full_name in source.glob(r'**/*'):\n        if main_mode != 3 and set(full_name.parent.parts) & escape_folder_set:\n            continue\n        if not full_name.is_file():\n            continue\n        if not full_name.suffix.lower() in file_type:\n            continue\n        absf = str(full_name)\n        if absf in failed_set:\n            skip_failed_cnt += 1\n            if debug:\n                print('[!]Skip failed movie:', absf)\n            continue\n        is_sym = full_name.is_symlink()\n        if main_mode != 3 and (is_sym or (full_name.stat().st_nlink > 1 and not conf.scan_hardlink())):  # 短路布尔 符号链接不取stat()，因为符号链接可能指向不存在目标\n            continue  # 模式不等于3下跳过软连接和未配置硬链接刮削\n        # 调试用0字节样本允许通过，去除小于120MB的广告'苍老师强力推荐.mp4'(102.2MB)'黑道总裁.mp4'(98.4MB)'有趣的妹子激情表演.MP4'(95MB)'有趣的臺灣妹妹直播.mp4'(15.1MB)\n        movie_size = 0 if is_sym else full_name.stat().st_size  # 同上 符号链接不取stat()及st_size，直接赋0跳过小视频检测\n        # if 0 < movie_size < 125829120:  # 1024*1024*120=125829120\n        #     continue\n        if cliRE and not cliRE.search(absf) or trailerRE.search(full_name.name):\n            continue\n        if main_mode == 3:\n            nfo = full_name.with_suffix('.nfo')\n            if not nfo.is_file():\n                if debug:\n                    print(f\"[!]Metadata {nfo.name} not found for '{absf}'\")\n            elif nfo_skip_days > 0 and file_modification_days(nfo) <= nfo_skip_days:\n                skip_nfo_days_cnt += 1\n                if debug:\n                    print(f\"[!]Skip movie by it's .nfo which modified within {nfo_skip_days} days: '{absf}'\")\n                continue\n        total.append(absf)\n\n    if skip_failed_cnt:\n        print(f\"[!]Skip {skip_failed_cnt} movies in failed list '{failed_list_txt_path}'.\")\n    if skip_nfo_days_cnt:\n        print(\n            f\"[!]Skip {skip_nfo_days_cnt} movies in source folder '{source}' who's .nfo modified within {nfo_skip_days} days.\")\n    if nfo_skip_days <= 0 or not link_mode or main_mode == 3:\n        return total\n    # 软连接方式，已经成功削刮的也需要从成功目录中检查.nfo更新天数，跳过N天内更新过的\n    skip_numbers = set()\n    success_folder = Path(conf.success_folder()).resolve()\n    for f in success_folder.glob(r'**/*'):\n        if not re.match(r'\\.nfo$', f.suffix, re.IGNORECASE):\n            continue\n        if file_modification_days(f) > nfo_skip_days:\n            continue\n        number = get_number(False, f.stem)\n        if not number:\n            continue\n        skip_numbers.add(number.lower())\n\n    rm_list = []\n    for f in total:\n        n_number = get_number(False, os.path.basename(f))\n        if n_number and n_number.lower() in skip_numbers:\n            rm_list.append(f)\n    for f in rm_list:\n        total.remove(f)\n        if debug:\n            print(f\"[!]Skip file successfully processed within {nfo_skip_days} days: '{f}'\")\n    if len(rm_list):\n        print(\n            f\"[!]Skip {len(rm_list)} movies in success folder '{success_folder}' who's .nfo modified within {nfo_skip_days} days.\")\n\n    return total\n\n\ndef create_failed_folder(failed_folder: str):\n    \"\"\"\n    新建failed文件夹\n    \"\"\"\n    if not os.path.exists(failed_folder):\n        try:\n            os.makedirs(failed_folder)\n        except:\n            print(f\"[-]Fatal error! Can not make folder '{failed_folder}'\")\n            os._exit(0)\n\n\ndef rm_empty_folder(path):\n    abspath = os.path.abspath(path)\n    deleted = set()\n    for current_dir, subdirs, files in os.walk(abspath, topdown=False):\n        try:\n            still_has_subdirs = any(_ for subdir in subdirs if os.path.join(current_dir, subdir) not in deleted)\n            if not any(files) and not still_has_subdirs and not os.path.samefile(path, current_dir):\n                os.rmdir(current_dir)\n                deleted.add(current_dir)\n                print('[+]Deleting empty folder', current_dir)\n        except:\n            pass\n\n\ndef create_data_and_move(movie_path: str, zero_op: bool, no_net_op: bool, oCC):\n    # Normalized number, eg: 111xxx-222.mp4 -> xxx-222.mp4\n    debug = config.getInstance().debug()\n    n_number = get_number(debug, os.path.basename(movie_path))\n    movie_path = os.path.abspath(movie_path)\n\n    if debug is True:\n        print(f\"[!] [{n_number}] As Number Processing for '{movie_path}'\")\n        if zero_op:\n            return\n        if n_number:\n            if no_net_op:\n                core_main_no_net_op(movie_path, n_number)\n            else:\n                core_main(movie_path, n_number, oCC)\n        else:\n            print(\"[-] number empty ERROR\")\n            moveFailedFolder(movie_path)\n        print(\"[*]======================================================\")\n    else:\n        try:\n            print(f\"[!] [{n_number}] As Number Processing for '{movie_path}'\")\n            if zero_op:\n                return\n            if n_number:\n                if no_net_op:\n                    core_main_no_net_op(movie_path, n_number)\n                else:\n                    core_main(movie_path, n_number, oCC)\n            else:\n                raise ValueError(\"number empty\")\n            print(\"[*]======================================================\")\n        except Exception as err:\n            print(f\"[-] [{movie_path}] ERROR:\")\n            print('[-]', err)\n\n            try:\n                moveFailedFolder(movie_path)\n            except Exception as err:\n                print('[!]', err)\n\n\ndef create_data_and_move_with_custom_number(file_path: str, custom_number, oCC, specified_source, specified_url):\n    conf = config.getInstance()\n    file_name = os.path.basename(file_path)\n    try:\n        print(\"[!] [{1}] As Number Processing for '{0}'\".format(file_path, custom_number))\n        if custom_number:\n            core_main(file_path, custom_number, oCC, specified_source, specified_url)\n        else:\n            print(\"[-] number empty ERROR\")\n        print(\"[*]======================================================\")\n    except Exception as err:\n        print(\"[-] [{}] ERROR:\".format(file_path))\n        print('[-]', err)\n\n        if conf.link_mode():\n            print(\"[-]Link {} to failed folder\".format(file_path))\n            os.symlink(file_path, os.path.join(conf.failed_folder(), file_name))\n        else:\n            try:\n                print(\"[-]Move [{}] to failed folder\".format(file_path))\n                shutil.move(file_path, os.path.join(conf.failed_folder(), file_name))\n            except Exception as err:\n                print('[!]', err)\n\n\ndef main(args: tuple) -> Path:\n    (single_file_path, custom_number, logdir, regexstr, zero_op, no_net_op, search, specified_source,\n     specified_url) = args\n    conf = config.getInstance()\n    main_mode = conf.main_mode()\n    folder_path = \"\"\n    if main_mode not in (1, 2, 3):\n        print(f\"[-]Main mode must be 1 or 2 or 3! You can run '{os.path.basename(sys.argv[0])} --help' for more help.\")\n        os._exit(4)\n\n    signal.signal(signal.SIGINT, signal_handler)\n    if sys.platform == 'win32':\n        signal.signal(signal.SIGBREAK, sigdebug_handler)\n    else:\n        signal.signal(signal.SIGWINCH, sigdebug_handler)\n    dupe_stdout_to_logfile(logdir)\n\n    platform_total = str(\n        ' - ' + platform.platform() + ' \\n[*] - ' + platform.machine() + ' - Python-' + platform.python_version())\n\n    print('[*]================= Movie Data Capture =================')\n    print('[*]' + version.center(54))\n    print('[*]======================================================')\n    print('[*]' + platform_total)\n    print('[*]======================================================')\n\n    start_time = time.time()\n    print('[+]Start at', time.strftime(\"%Y-%m-%d %H:%M:%S\"))\n\n    print(f\"[+]Load Config file '{conf.ini_path}'.\")\n    if conf.debug():\n        print('[+]Enable debug')\n    if conf.link_mode() in (1, 2):\n        print('[!]Enable {} link'.format(('soft', 'hard')[conf.link_mode() - 1]))\n    if len(sys.argv) > 1:\n        print('[!]CmdLine:', \" \".join(sys.argv[1:]))\n    print('[+]Main Working mode ## {}: {} ## {}{}{}'\n          .format(*(main_mode, ['Scraping', 'Organizing', 'Scraping in analysis folder'][main_mode - 1],\n                    \"\" if not conf.multi_threading() else \", multi_threading on\",\n                    \"\" if conf.nfo_skip_days() == 0 else f\", nfo_skip_days={conf.nfo_skip_days()}\",\n                    \"\" if conf.stop_counter() == 0 else f\", stop_counter={conf.stop_counter()}\"\n                    ) if not single_file_path else ('-', 'Single File', '', '', ''))\n          )\n\n    create_failed_folder(conf.failed_folder())\n\n    # create OpenCC converter\n    ccm = conf.cc_convert_mode()\n    try:\n        oCC = None if ccm == 0 else OpenCC('t2s.json' if ccm == 1 else 's2t.json')\n    except:\n        # some OS no OpenCC cpython, try opencc-python-reimplemented.\n        # pip uninstall opencc && pip install opencc-python-reimplemented\n        oCC = None if ccm == 0 else OpenCC('t2s' if ccm == 1 else 's2t')\n\n    if not search == '':\n        search_list = search.split(\",\")\n        for i in search_list:\n            json_data = get_data_from_json(i, oCC, None, None)\n            debug_print(json_data)\n            time.sleep(int(config.getInstance().sleep()))\n        os._exit(0)\n\n    if not single_file_path == '':  # Single File\n        print('[+]==================== Single File =====================')\n        if custom_number == '':\n            create_data_and_move_with_custom_number(single_file_path,\n                                                    get_number(conf.debug(), os.path.basename(single_file_path)), oCC,\n                                                    specified_source, specified_url)\n        else:\n            create_data_and_move_with_custom_number(single_file_path, custom_number, oCC,\n                                                    specified_source, specified_url)\n    else:\n        folder_path = conf.source_folder()\n        if not isinstance(folder_path, str) or folder_path == '':\n            folder_path = os.path.abspath(\".\")\n\n        movie_list = movie_lists(folder_path, regexstr)\n\n        count = 0\n        count_all = str(len(movie_list))\n        print('[+]Find', count_all, 'movies.')\n        print('[*]======================================================')\n        stop_count = conf.stop_counter()\n        if stop_count < 1:\n            stop_count = 999999\n        else:\n            count_all = str(min(len(movie_list), stop_count))\n\n        for movie_path in movie_list:  # 遍历电影列表 交给core处理\n            count = count + 1\n            percentage = str(count / int(count_all) * 100)[:4] + '%'\n            print('[!] {:>30}{:>21}'.format('- ' + percentage + ' [' + str(count) + '/' + count_all + '] -',\n                                            time.strftime(\"%H:%M:%S\")))\n            create_data_and_move(movie_path, zero_op, no_net_op, oCC)\n            if count >= stop_count:\n                print(\"[!]Stop counter triggered!\")\n                break\n            sleep_seconds = random.randint(conf.sleep(), conf.sleep() + 2)\n            time.sleep(sleep_seconds)\n\n    if conf.del_empty_folder() and not zero_op:\n        rm_empty_folder(conf.success_folder())\n        rm_empty_folder(conf.failed_folder())\n        if len(folder_path):\n            rm_empty_folder(folder_path)\n\n    end_time = time.time()\n    total_time = str(timedelta(seconds=end_time - start_time))\n    print(\"[+]Running time\", total_time[:len(total_time) if total_time.rfind('.') < 0 else -3],\n          \" End at\", time.strftime(\"%Y-%m-%d %H:%M:%S\"))\n\n    print(\"[+]All finished!!!\")\n\n    return close_logfile(logdir)\n\n\ndef 分析日志文件(logfile):\n    try:\n        if not (isinstance(logfile, Path) and logfile.is_file()):\n            raise FileNotFoundError('log file not found')\n        logtxt = logfile.read_text(encoding='utf-8')\n        扫描电影数 = int(re.findall(r'\\[\\+]Find (.*) movies\\.', logtxt)[0])\n        已处理 = int(re.findall(r'\\[1/(.*?)] -', logtxt)[0])\n        完成数 = logtxt.count(r'[+]Wrote!')\n        return 扫描电影数, 已处理, 完成数\n    except:\n        return None, None, None\n\n\ndef period(delta, pattern):\n    d = {'d': delta.days}\n    d['h'], rem = divmod(delta.seconds, 3600)\n    d['m'], d['s'] = divmod(rem, 60)\n    return pattern.format(**d)\n\n\nif __name__ == '__main__':\n    version = '6.6.7'\n    urllib3.disable_warnings()  # Ignore http proxy warning\n    app_start = time.time()\n\n    # Read config.ini first, in argparse_function() need conf.failed_folder()\n    conf = config.getInstance()\n\n    # Parse command line args\n    args = tuple(argparse_function(version))\n\n    再运行延迟 = conf.rerun_delay()\n    if 再运行延迟 > 0 and conf.stop_counter() > 0:\n        while True:\n            try:\n                logfile = main(args)\n                (扫描电影数, 已处理, 完成数) = 分析结果元组 = tuple(分析日志文件(logfile))\n                if all(isinstance(v, int) for v in 分析结果元组):\n                    剩余个数 = 扫描电影数 - 已处理\n                    总用时 = timedelta(seconds = time.time() - app_start)\n                    print(f'All movies:{扫描电影数}  processed:{已处理}  successes:{完成数}  remain:{剩余个数}' +\n                        '  Elapsed time {}'.format(\n                        period(总用时, \"{d} day {h}:{m:02}:{s:02}\") if 总用时.days == 1\n                            else period(总用时, \"{d} days {h}:{m:02}:{s:02}\") if 总用时.days > 1\n                            else period(总用时, \"{h}:{m:02}:{s:02}\")))\n                    if 剩余个数 == 0:\n                        break\n                    下次运行 = datetime.now() + timedelta(seconds=再运行延迟)\n                    print(f'Next run time: {下次运行.strftime(\"%H:%M:%S\")}, rerun_delay={再运行延迟}, press Ctrl+C stop run.')\n                    time.sleep(再运行延迟)\n                else:\n                    break\n            except:\n                break\n    else:\n        main(args)\n\n    if not conf.auto_exit():\n        if sys.platform == 'win32':\n            input(\"Press enter key exit, you can check the error message before you exit...\")\n"
  },
  {
    "path": "README.md",
    "content": "<h1 align=\"center\">Movie Data Capture</h1>\r\n\r\n## 网站\r\n[www.mvdc.top](https://www.mvdc.top)\r\n\r\n## 核心代码开源\r\n \r\n"
  },
  {
    "path": "README_EN.md",
    "content": "<h1 align=\"center\">Movie Data Capture</h1>\n\n# Core of the code is open source\n\n**Movie Metadata Scraper**, with local JAV management software Emby, Jellyfin, Kodi, etc. to manage local movies, \nthe project plays the role of classification and metadata (metadata) grabbing, using metadata information to classify, only for local movie classification and organization.\n\n[中文 | Chinese](https://github.com/yoshiko2/Movie_Data_Capture/blob/master/README.md)\n\n## Website\n[docs.mvdc.top](https://docs.mvdc.top)\n\n# NOTICE\nWhen you view and download the source code or binary program of this project, it means that you have accepted the following terms:\n* **You must be over 18 years old, or leave the page immediately.**\n* This project and its results are for technical, academic exchange and Python3 performance testing purposes only.\n* The contributors to this project have written this project to learn Python3 and improve programming.\n* This project does not provide any movie download trail.\n* Legal consequences and the consequences of use are borne by the user.\n* [GPL LICENSE](https://github.com/yoshiko2/Movie_Data_Capture/blob/master/LICENSE)\n* If you do not agree to any of the above terms, please do not use the project and project results.\n\n\n\n"
  },
  {
    "path": "README_ZH.md",
    "content": "<h1 align=\"center\">Movie Data Capture</h1>\n\n# 核心代码开源\n\n**本地电影元数据 抓取工具 | 刮削器**，配合本地影片管理软件 Emby, Jellyfin, Kodi 等管理本地影片，该软件起到分类与元数据（metadata）抓取作用，利用元数据信息来分类，仅供本地影片分类整理使用。\n\n## 网站\n[docs.mvdc.top](https://docs.mvdc.top)\n\n# 申明\n当你查阅、下载了本项目源代码或二进制程序，即代表你接受了以下条款\n* 本项目和项目成果仅供技术，学术交流和Python3性能测试使用\n* 本项目贡献者编写该项目旨在学习Python3 ，提高编程水平\n* 本项目不提供任何影片下载的线索\n* 用户在使用本项目和项目成果前，请用户了解并遵守当地法律法规，如果本项目及项目成果使用过程中存在违反当地法律法规的行为，请勿使用该项目及项目成果\n* 法律后果及使用后果由使用者承担\n* [GPL LICENSE](https://github.com/yoshiko2/Movie_Data_Capture/blob/master/LICENSE)\n* 若用户不同意上述条款任意一条，请勿使用本项目和项目成果\n\n\n"
  },
  {
    "path": "config.ini",
    "content": "# 详细教程请看\n# - https://github.com/yoshiko2/Movie_Data_Capture/wiki/%E9%85%8D%E7%BD%AE%E6%96%87%E4%BB%B6\n[common]\nmain_mode = 1\nsource_folder = ./\nfailed_output_folder = failed\nsuccess_output_folder = output\nlink_mode = 0\n; 0: 不刮削硬链接文件 1: 刮削硬链接文件\nscan_hardlink = 0\nfailed_move = 0\nauto_exit = 0\ntranslate_to_sc = 0\nmulti_threading = 0\n;actor_gender value: female(♀) or male(♂) or both(♀ ♂) or all(♂ ♀ ⚧)\nactor_gender = female\ndel_empty_folder = 1\n; 跳过最近(默认:30)天新修改过的.NFO，可避免整理模式(main_mode=3)和软连接(soft_link=0)时\n; 反复刮削靠前的视频文件，0为处理所有视频文件\nnfo_skip_days = 30\nignore_failed_list = 0\ndownload_only_missing_images = 1\nmapping_table_validity = 7\n; 一些jellyfin中特有的设置 (0:不开启， 1：开启) 比如\n; 在jellyfin中tags和genres重复，因此可以只需保存genres到nfo中\n; jellyfin中只需要保存thumb，不需要保存fanart\njellyfin = 0\n; 开启后tag和genere只显示演员\nactor_only_tag = 0\nsleep = 3\nanonymous_fill = 1\n\n[advenced_sleep]\n; 处理完多少个视频文件后停止，0为处理所有视频文件\nstop_counter = 0\n; 再运行延迟时间，单位：h时m分s秒 举例: 1h30m45s(1小时30分45秒)  45(45秒)\n; stop_counter不为零的条件下才有效，每处理stop_counter部影片后延迟rerun_delay秒再次运行\nrerun_delay = 0\n; 以上参数配合使用可以以多次少量的方式刮削或整理数千个文件而不触发翻译或元数据站封禁\n\n[proxy]\n;proxytype: http or socks5 or socks5h switch: 0 1\nswitch = 0\ntype = socks5h\nproxy = 127.0.0.1:1080\ntimeout = 20\nretry = 3\ncacert_file =\n\n[Name_Rule]\nlocation_rule = actor+\"/\"+title\nnaming_rule = number+\"-\"+title\nmax_title_len = 50\n; 刮削后图片是否命名为号码\nimage_naming_with_number = 0\n; 番号大写 1 | 0, 仅在写入数据时会进行大写转换, 搜索刮削流程则不影响\nnumber_uppercase = 0\n; 自定义正则表达式, 多个正则使用空格隔开, 第一个分组为提取的番号, 若自定义正则未能匹配到番号则使用默认规则\n; example: ([A-Za-z]{2,4}\\-\\d{3}) ([A-Za-z]{2,4}00\\d{3})\nnumber_regexs = \n\n[update]\nupdate_check = 1\n\n[priority]\nwebsite = tmdb,imdb\n\n[escape]\nliterals = \\()/\nfolders = failed,output\n\n[debug_mode]\nswitch = 0\n\n[translate]\nswitch = 0\n; engine: google-free,azure,deeplx\nengine = google-free\n; en_us fr_fr de_de... (only google-free now)\ntarget_language = zh_cn\n; Azure translate API key\nkey =\n; Translate delay, Bigger Better\ndelay = 3\n; title,outline,actor,tag\nvalues = title,outline\n; Google translate site, or Deeplx site\nservice_site = translate.google.com\n\n; 预告片\n[trailer]\nswitch = 0\n\n[uncensored]\nuncensored_prefix = PT-,S2M,BT,LAF,SMD,SMBD,SM3D2DBD,SKY-,SKYHD,CWP,CWDV,CWBD,CW3D2DBD,MKD,MKBD,MXBD,MK3D2DBD,MCB3DBD,MCBD,RHJ,MMDV\n\n[media]\nmedia_type = .mp4,.avi,.rmvb,.wmv,.mov,.mkv,.flv,.ts,.webm,.iso,.mpg,.m4v\nsub_type = .smi,.srt,.idx,.sub,.sup,.psb,.ssa,.ass,.usf,.xss,.ssf,.rt,.lrc,.sbv,.vtt,.ttml\n\n; 水印\n[watermark]\nswitch = 1\nwater = 2\n; 左上 0, 右上 1, 右下 2， 左下 3\n\n; 剧照\n[extrafanart]\nswitch = 1\nparallel_download = 5\nextrafanart_folder = extrafanart\n\n; 剧情简介\n[storyline]\nswitch = 1\n; website为javbus javdb avsox xcity carib时，site censored_site uncensored_site 为获取剧情简介信息的\n; 可选数据源站点列表。列表内站点同时并发查询，取值优先级由冒号前的序号决定，从小到大，数字小的站点没数据才会采用后面站点获得的。\n; 其中airavwiki airav avno1 58avgo是中文剧情简介，区别是airav只能查有码，avno1 airavwiki 有码无码都能查，\n; 58avgo只能查无码或者流出破解马赛克的影片(此功能没使用)。\n; xcity和amazon是日语的，由于amazon商城没有番号信息，选中对应DVD的准确率仅99.6%。如果三个列表全部为空则不查询，\n; 设置成不查询可大幅提高刮削速度。\n; site=\nsite =\ncensored_site =\nuncensored_site =\n; 运行模式：0:顺序执行(最慢) 1:线程池(默认值) 2:进程池(启动开销比线程池大，并发站点越多越快)\nrun_mode = 1\n; show_result剧情简介调试信息 0关闭 1简略 2详细(详细部分不记入日志)，剧情简介失效时可打开2查看原因\nshow_result = 0\n\n; 繁简转换 繁简转换模式mode=0:不转换 1:繁转简 2:简转繁\n[cc_convert]\nmode = 1\nvars = outline,series,studio,tag,title\n\n[javdb]\nsites = 521\n\n; 人脸识别 locations_model=hog:方向梯度直方图(不太准确，速度快) cnn:深度学习模型(准确，需要GPU/CUDA,速度慢)\n; uncensored_only=0:对全部封面进行人脸识别 1:只识别无码封面，有码封面直接切右半部分\n; aways_imagecut=0:按各网站默认行为 1:总是裁剪封面，开启此项将无视[common]download_only_missing_images=1总是覆盖封面\n; 封面裁剪的宽高比可配置，公式为aspect_ratio/3。默认aspect_ratio=2.12: 适配大部分有码影片封面，前一版本默认为2/3即aspect_ratio=2\n[face]\nlocations_model = hog\nuncensored_only = 1\naways_imagecut = 0\naspect_ratio = 2.12\n\n[jellyfin]\nmulti_part_fanart = 0\n\n[actor_photo]\ndownload_for_kodi = 0\n\n[direct]\nswitch = 1\n"
  },
  {
    "path": "config.py",
    "content": "import os\nimport re\nimport sys\nimport configparser\nimport time\nimport typing\nfrom pathlib import Path\n\nG_conf_override = {\n    # index 0 save Config() first instance for quick access by using getInstance()\n    0: None,\n    # register override config items\n    # no need anymore\n}\n\n\ndef getInstance():\n    if isinstance(G_conf_override[0], Config):\n        return G_conf_override[0]\n    return Config()\n\n\nclass Config:\n    def __init__(self, path: str = \"config.ini\"):\n        path_search_order = (\n            Path(path),\n            Path.cwd() / \"config.ini\",\n            Path.home() / \"mdc.ini\",\n            Path.home() / \".mdc.ini\",\n            Path.home() / \".mdc/config.ini\",\n            Path.home() / \".config/mdc/config.ini\"\n        )\n        ini_path = None\n        for p in path_search_order:\n            if p.is_file():\n                ini_path = p.resolve()\n                break\n        if ini_path:\n            self.conf = configparser.ConfigParser()\n            self.ini_path = ini_path\n            try:\n                if self.conf.read(ini_path, encoding=\"utf-8-sig\"):\n                    if G_conf_override[0] is None:\n                        G_conf_override[0] = self\n            except UnicodeDecodeError:\n                if self.conf.read(ini_path, encoding=\"utf-8\"):\n                    if G_conf_override[0] is None:\n                        G_conf_override[0] = self\n            except Exception as e:\n                print(\"ERROR: Config file can not read!\")\n                print(\"读取配置文件出错！\")\n                print('=================================')\n                print(e)\n                print(\"======= Auto exit in 60s ======== \")\n                time.sleep(60)\n                os._exit(-1)\n        else:\n            print(\"ERROR: Config file not found!\")\n            print(\"Please put config file into one of the following path:\")\n            print('\\n'.join([str(p.resolve()) for p in path_search_order[2:]]))\n            # 对于找不到配置文件的情况，还是在打包时附上对应版本的默认配置文件，有需要时为其在搜索路径中生成，\n            # 要比用户乱找一个版本不对应的配置文件会可靠些。这样一来，单个执行文件就是功能完整的了，放在任何\n            # 执行路径下都可以放心使用。\n            res_path = None\n            # pyinstaller打包的在打包中找config.ini\n            if hasattr(sys, '_MEIPASS') and (Path(getattr(sys, '_MEIPASS')) / 'config.ini').is_file():\n                res_path = Path(getattr(sys, '_MEIPASS')) / 'config.ini'\n            # 脚本运行的所在位置找\n            elif (Path(__file__).resolve().parent / 'config.ini').is_file():\n                res_path = Path(__file__).resolve().parent / 'config.ini'\n            if res_path is None:\n                os._exit(2)\n            ins = input(\"Or, Do you want me create a config file for you? (Yes/No)[Y]:\")\n            if re.search('n', ins, re.I):\n                os._exit(2)\n            # 用户目录才确定具有写权限，因此选择 ~/mdc.ini 作为配置文件生成路径，而不是有可能并没有写权限的\n            # 当前目录。目前版本也不再鼓励使用当前路径放置配置文件了，只是作为多配置文件的切换技巧保留。\n            write_path = path_search_order[2]  # Path.home() / \"mdc.ini\"\n            write_path.write_text(res_path.read_text(encoding='utf-8'), encoding='utf-8')\n            print(\"Config file '{}' created.\".format(write_path.resolve()))\n            input(\"Press Enter key exit...\")\n            os._exit(0)\n            # self.conf = self._default_config()\n            # try:\n            #     self.conf = configparser.ConfigParser()\n            #     try: # From single crawler debug use only\n            #         self.conf.read('../' + path, encoding=\"utf-8-sig\")\n            #     except:\n            #         self.conf.read('../' + path, encoding=\"utf-8\")\n            # except Exception as e:\n            #     print(\"[-]Config file not found! Use the default settings\")\n            #     print(\"[-]\",e)\n            #     os._exit(3)\n            #     #self.conf = self._default_config()\n\n    def set_override(self, option_cmd: str):\n        \"\"\"\n        通用的参数覆盖选项 -C 配置覆盖串\n        配置覆盖串语法：小节名:键名=值[;[小节名:]键名=值][;[小节名:]键名+=值]  多个键用分号分隔 名称可省略部分尾部字符\n        或 小节名:键名+=值[;[小节名:]键名=值][;[小节名:]键名+=值]  在已有值的末尾追加内容，多个键的=和+=可以交叉出现\n        例子: face:aspect_ratio=2;aways_imagecut=1;priority:website=javdb\n        小节名必须出现在开头至少一次，分号后可只出现键名=值，不再出现小节名，如果后续全部键名都属于同一个小节\n        例如配置文件存在两个小节[proxy][priority]，那么pro可指代proxy，pri可指代priority\n        [face]  ;face小节下方有4个键名locations_model= uncensored_only= aways_imagecut= aspect_ratio=\n        l,lo,loc,loca,locat,locati...直到locations_model完整名称都可以用来指代locations_model=键名\n        u,un,unc...直到uncensored_only完整名称都可以用来指代uncensored_only=键名\n        aw,awa...直到aways_imagecut完整名称都可以用来指代aways_imagecut=键名\n        as,asp...aspect_ratio完整名称都可以用来指代aspect_ratio=键名\n        a则因为二义性，不是合法的省略键名\n        \"\"\"\n        def err_exit(str):\n            print(str)\n            os._exit(2)\n\n        sections = self.conf.sections()\n        sec_name = None\n        for cmd in option_cmd.split(';'):\n            syntax_err = True\n            rex = re.findall(r'^(.*?):(.*?)(=|\\+=)(.*)$', cmd, re.U)\n            if len(rex) and len(rex[0]) == 4:\n                (sec, key, assign, val) = rex[0]\n                sec_lo = sec.lower().strip()\n                key_lo = key.lower().strip()\n                syntax_err = False\n            elif sec_name:  # 已经出现过一次小节名，属于同一个小节的后续键名可以省略小节名\n                rex = re.findall(r'^(.*?)(=|\\+=)(.*)$', cmd, re.U)\n                if len(rex) and len(rex[0]) == 3:\n                    (key, assign, val) = rex[0]\n                    sec_lo = sec_name.lower()\n                    key_lo = key.lower().strip()\n                    syntax_err = False\n            if syntax_err:\n                err_exit(f\"[-]Config override syntax incorrect. example: 'd:s=1' or 'debug_mode:switch=1'. cmd='{cmd}' all='{option_cmd}'\")\n            if not len(sec_lo):\n                err_exit(f\"[-]Config override Section name '{sec}' is empty! cmd='{cmd}'\")\n            if not len(key_lo):\n                err_exit(f\"[-]Config override Key name '{key}' is empty! cmd='{cmd}'\")\n            if not len(val.strip()):\n                print(f\"[!]Conig overide value '{val}' is empty! cmd='{cmd}'\")\n            sec_name = None\n            for s in sections:\n                if not s.lower().startswith(sec_lo):\n                    continue\n                if sec_name:\n                    err_exit(f\"[-]Conig overide Section short name '{sec_lo}' is not unique! dup1='{sec_name}' dup2='{s}' cmd='{cmd}'\")\n                sec_name = s\n            if sec_name is None:\n                err_exit(f\"[-]Conig overide Section name '{sec}' not found! cmd='{cmd}'\")\n            key_name = None\n            keys = self.conf[sec_name]\n            for k in keys:\n                if not k.lower().startswith(key_lo):\n                    continue\n                if key_name:\n                    err_exit(f\"[-]Conig overide Key short name '{key_lo}' is not unique! dup1='{key_name}' dup2='{k}' cmd='{cmd}'\")\n                key_name = k\n            if key_name is None:\n                err_exit(f\"[-]Conig overide Key name '{key}' not found! cmd='{cmd}'\")\n            if assign == \"+=\":\n                val = keys[key_name] + val\n            if self.debug():\n                print(f\"[!]Set config override [{sec_name}]{key_name}={val}  by cmd='{cmd}'\")\n            self.conf.set(sec_name, key_name, val)\n\n    def main_mode(self) -> int:\n        try:\n            return self.conf.getint(\"common\", \"main_mode\")\n        except ValueError:\n            self._exit(\"common:main_mode\")\n\n    def source_folder(self) -> str:\n        return self.conf.get(\"common\", \"source_folder\").replace(\"\\\\\\\\\", \"/\").replace(\"\\\\\", \"/\")\n\n    def failed_folder(self) -> str:\n        return self.conf.get(\"common\", \"failed_output_folder\").replace(\"\\\\\\\\\", \"/\").replace(\"\\\\\", \"/\")\n\n    def success_folder(self) -> str:\n        return self.conf.get(\"common\", \"success_output_folder\").replace(\"\\\\\\\\\", \"/\").replace(\"\\\\\", \"/\")\n\n    def actor_gender(self) -> str:\n        return self.conf.get(\"common\", \"actor_gender\")\n\n    def link_mode(self) -> int:\n        return self.conf.getint(\"common\", \"link_mode\")\n\n    def scan_hardlink(self) -> bool:\n        return self.conf.getboolean(\"common\", \"scan_hardlink\", fallback=False)#未找到配置选项,默认不刮削\n\n    def failed_move(self) -> bool:\n        return self.conf.getboolean(\"common\", \"failed_move\")\n\n    def auto_exit(self) -> bool:\n        return self.conf.getboolean(\"common\", \"auto_exit\")\n\n    def translate_to_sc(self) -> bool:\n        return self.conf.getboolean(\"common\", \"translate_to_sc\")\n\n    def multi_threading(self) -> bool:\n        return self.conf.getboolean(\"common\", \"multi_threading\")\n\n    def del_empty_folder(self) -> bool:\n        return self.conf.getboolean(\"common\", \"del_empty_folder\")\n\n    def nfo_skip_days(self) -> int:\n        return self.conf.getint(\"common\", \"nfo_skip_days\", fallback=30)\n\n    def ignore_failed_list(self) -> bool:\n        return self.conf.getboolean(\"common\", \"ignore_failed_list\")\n\n    def download_only_missing_images(self) -> bool:\n        return self.conf.getboolean(\"common\", \"download_only_missing_images\")\n\n    def mapping_table_validity(self) -> int:\n        return self.conf.getint(\"common\", \"mapping_table_validity\")\n\n    def jellyfin(self) -> int:\n        return self.conf.getint(\"common\", \"jellyfin\")\n\n    def actor_only_tag(self) -> bool:\n        return self.conf.getboolean(\"common\", \"actor_only_tag\")\n\n    def sleep(self) -> int:\n        return self.conf.getint(\"common\", \"sleep\")\n\n    def anonymous_fill(self) -> bool:\n        return self.conf.getint(\"common\", \"anonymous_fill\")\n\n    def stop_counter(self) -> int:\n        return self.conf.getint(\"advenced_sleep\", \"stop_counter\", fallback=0)\n\n    def rerun_delay(self) -> int:\n        value = self.conf.get(\"advenced_sleep\", \"rerun_delay\")\n        if not (isinstance(value, str) and re.match(r'^[\\dsmh]+$', value, re.I)):\n            return 0  # not match '1h30m45s' or '30' or '1s2m1h4s5m'\n        if value.isnumeric() and int(value) >= 0:\n            return int(value)\n        sec = 0\n        sec += sum(int(v)  for v in re.findall(r'(\\d+)s', value, re.I))\n        sec += sum(int(v)  for v in re.findall(r'(\\d+)m', value, re.I)) * 60\n        sec += sum(int(v)  for v in re.findall(r'(\\d+)h', value, re.I)) * 3600\n        return sec\n\n    def is_translate(self) -> bool:\n        return self.conf.getboolean(\"translate\", \"switch\")\n\n    def is_trailer(self) -> bool:\n        return self.conf.getboolean(\"trailer\", \"switch\")\n\n    def is_watermark(self) -> bool:\n        return self.conf.getboolean(\"watermark\", \"switch\")\n\n    def is_extrafanart(self) -> bool:\n        return self.conf.getboolean(\"extrafanart\", \"switch\")\n\n    def extrafanart_thread_pool_download(self) -> int:\n        try:\n            v = self.conf.getint(\"extrafanart\", \"parallel_download\")\n            return v if v >= 0 else 5\n        except:\n            return 5\n\n    def watermark_type(self) -> int:\n        return int(self.conf.get(\"watermark\", \"water\"))\n\n    def get_uncensored(self):\n        try:\n            sec = \"uncensored\"\n            uncensored_prefix = self.conf.get(sec, \"uncensored_prefix\")\n            # uncensored_poster = self.conf.get(sec, \"uncensored_poster\")\n            return uncensored_prefix\n\n        except ValueError:\n            self._exit(\"uncensored\")\n\n    def get_extrafanart(self):\n        try:\n            extrafanart_download = self.conf.get(\"extrafanart\", \"extrafanart_folder\")\n            return extrafanart_download\n        except ValueError:\n            self._exit(\"extrafanart_folder\")\n\n    def get_translate_engine(self) -> str:\n        return self.conf.get(\"translate\", \"engine\")\n\n    def get_target_language(self) -> str:\n        return self.conf.get(\"translate\", \"target_language\")\n\n    # def get_translate_appId(self) ->str:\n    #     return self.conf.get(\"translate\",\"appid\")\n\n    def get_translate_key(self) -> str:\n        return self.conf.get(\"translate\", \"key\")\n\n    def get_translate_delay(self) -> int:\n        return self.conf.getint(\"translate\", \"delay\")\n\n    def translate_values(self) -> str:\n        return self.conf.get(\"translate\", \"values\")\n\n    def get_translate_service_site(self) -> str:\n        return self.conf.get(\"translate\", \"service_site\")\n\n    def proxy(self):\n        try:\n            sec = \"proxy\"\n            switch = self.conf.get(sec, \"switch\")\n            proxy = self.conf.get(sec, \"proxy\")\n            timeout = self.conf.getint(sec, \"timeout\")\n            retry = self.conf.getint(sec, \"retry\")\n            proxytype = self.conf.get(sec, \"type\")\n            iniProxy = IniProxy(switch, proxy, timeout, retry, proxytype)\n            return iniProxy\n        except ValueError:\n            self._exit(\"common\")\n\n    def cacert_file(self) -> str:\n        return self.conf.get('proxy', 'cacert_file')\n\n    def media_type(self) -> str:\n        return self.conf.get('media', 'media_type')\n\n    def sub_rule(self) -> typing.Set[str]:\n        return set(self.conf.get('media', 'sub_type').lower().split(','))\n\n    def naming_rule(self) -> str:\n        return self.conf.get(\"Name_Rule\", \"naming_rule\")\n\n    def location_rule(self) -> str:\n        return self.conf.get(\"Name_Rule\", \"location_rule\")\n\n    def max_title_len(self) -> int:\n        \"\"\"\n        Maximum title length\n        \"\"\"\n        try:\n            return self.conf.getint(\"Name_Rule\", \"max_title_len\")\n        except:\n            return 50\n\n    def image_naming_with_number(self) -> bool:\n        try:\n            return self.conf.getboolean(\"Name_Rule\", \"image_naming_with_number\")\n        except:\n            return False\n\n    def number_uppercase(self) -> bool:\n        try:\n            return self.conf.getboolean(\"Name_Rule\", \"number_uppercase\")\n        except:\n            return False\n        \n    def number_regexs(self) -> str:\n        try:\n            return self.conf.get(\"Name_Rule\", \"number_regexs\")\n        except:\n            return \"\"\n\n    def update_check(self) -> bool:\n        try:\n            return self.conf.getboolean(\"update\", \"update_check\")\n        except ValueError:\n            self._exit(\"update:update_check\")\n\n    def sources(self) -> str:\n        return self.conf.get(\"priority\", \"website\")\n\n    def escape_literals(self) -> str:\n        return self.conf.get(\"escape\", \"literals\")\n\n    def escape_folder(self) -> str:\n        return self.conf.get(\"escape\", \"folders\")\n\n    def debug(self) -> bool:\n        return self.conf.getboolean(\"debug_mode\", \"switch\")\n\n    def get_direct(self) -> bool:\n        return self.conf.getboolean(\"direct\", \"switch\")\n    \n    def is_storyline(self) -> bool:\n        try:\n            return self.conf.getboolean(\"storyline\", \"switch\")\n        except:\n            return True\n\n    def storyline_site(self) -> str:\n        try:\n            return self.conf.get(\"storyline\", \"site\")\n        except:\n            return \"1:avno1,4:airavwiki\"\n\n    def storyline_censored_site(self) -> str:\n        try:\n            return self.conf.get(\"storyline\", \"censored_site\")\n        except:\n            return \"2:airav,5:xcity,6:amazon\"\n\n    def storyline_uncensored_site(self) -> str:\n        try:\n            return self.conf.get(\"storyline\", \"uncensored_site\")\n        except:\n            return \"3:58avgo\"\n\n    def storyline_show(self) -> int:\n        v = self.conf.getint(\"storyline\", \"show_result\", fallback=0)\n        return v if v in (0, 1, 2) else 2 if v > 2 else 0\n\n    def storyline_mode(self) -> int:\n        return 1 if self.conf.getint(\"storyline\", \"run_mode\", fallback=1) > 0 else 0\n\n    def cc_convert_mode(self) -> int:\n        v = self.conf.getint(\"cc_convert\", \"mode\", fallback=1)\n        return v if v in (0, 1, 2) else 2 if v > 2 else 0\n\n    def cc_convert_vars(self) -> str:\n        return self.conf.get(\"cc_convert\", \"vars\",\n            fallback=\"actor,director,label,outline,series,studio,tag,title\")\n\n    def javdb_sites(self) -> str:\n        return self.conf.get(\"javdb\", \"sites\", fallback=\"38,39\")\n\n    def face_locations_model(self) -> str:\n        return self.conf.get(\"face\", \"locations_model\", fallback=\"hog\")\n\n    def face_uncensored_only(self) -> bool:\n        return self.conf.getboolean(\"face\", \"uncensored_only\", fallback=True)\n\n    def face_aways_imagecut(self) -> bool:\n        return self.conf.getboolean(\"face\", \"aways_imagecut\", fallback=False)\n\n    def face_aspect_ratio(self) -> float:\n        return self.conf.getfloat(\"face\", \"aspect_ratio\", fallback=2.12)\n\n    def jellyfin_multi_part_fanart(self) -> bool:\n        return self.conf.getboolean(\"jellyfin\", \"multi_part_fanart\", fallback=False)\n\n    def download_actor_photo_for_kodi(self) -> bool:\n        return self.conf.getboolean(\"actor_photo\", \"download_for_kodi\", fallback=False)\n\n    @staticmethod\n    def _exit(sec: str) -> None:\n        print(\"[-] Read config error! Please check the {} section in config.ini\", sec)\n        input(\"[-] Press ENTER key to exit.\")\n        exit()\n\n    @staticmethod\n    def _default_config() -> configparser.ConfigParser:\n        conf = configparser.ConfigParser()\n\n        sec1 = \"common\"\n        conf.add_section(sec1)\n        conf.set(sec1, \"main_mode\", \"1\")\n        conf.set(sec1, \"source_folder\", \"./\")\n        conf.set(sec1, \"failed_output_folder\", \"failed\")\n        conf.set(sec1, \"success_output_folder\", \"JAV_output\")\n        conf.set(sec1, \"link_mode\", \"0\")\n        conf.set(sec1, \"scan_hardlink\", \"0\")\n        conf.set(sec1, \"failed_move\", \"1\")\n        conf.set(sec1, \"auto_exit\", \"0\")\n        conf.set(sec1, \"translate_to_sc\", \"1\")\n        # actor_gender value: female or male or both or all(含人妖)\n        conf.set(sec1, \"actor_gender\", \"female\")\n        conf.set(sec1, \"del_empty_folder\", \"1\")\n        conf.set(sec1, \"nfo_skip_days\", \"30\")\n        conf.set(sec1, \"ignore_failed_list\", \"0\")\n        conf.set(sec1, \"download_only_missing_images\", \"1\")\n        conf.set(sec1, \"mapping_table_validity\", \"7\")\n        conf.set(sec1, \"jellyfin\", \"0\")\n        conf.set(sec1, \"actor_only_tag\", \"0\")\n        conf.set(sec1, \"sleep\", \"3\")\n        conf.set(sec1, \"anonymous_fill\", \"0\")\n\n        sec2 = \"advenced_sleep\"\n        conf.add_section(sec2)\n        conf.set(sec2, \"stop_counter\", \"0\")\n        conf.set(sec2, \"rerun_delay\", \"0\")\n\n        sec3 = \"proxy\"\n        conf.add_section(sec3)\n        conf.set(sec3, \"proxy\", \"\")\n        conf.set(sec3, \"timeout\", \"5\")\n        conf.set(sec3, \"retry\", \"3\")\n        conf.set(sec3, \"type\", \"socks5\")\n        conf.set(sec3, \"cacert_file\", \"\")\n\n        sec4 = \"Name_Rule\"\n        conf.add_section(sec4)\n        conf.set(sec4, \"location_rule\", \"actor + '/' + number\")\n        conf.set(sec4, \"naming_rule\", \"number + '-' + title\")\n        conf.set(sec4, \"max_title_len\", \"50\")\n        conf.set(sec4, \"image_naming_with_number\", \"0\")\n        conf.set(sec4, \"number_uppercase\", \"0\")\n        conf.set(sec4, \"number_regexs\", \"\")\n\n        sec5 = \"update\"\n        conf.add_section(sec5)\n        conf.set(sec5, \"update_check\", \"1\")\n\n        sec6 = \"priority\"\n        conf.add_section(sec6)\n        conf.set(sec6, \"website\", \"airav,javbus,javdb,fanza,xcity,mgstage,fc2,fc2club,avsox,jav321,xcity\")\n\n        sec7 = \"escape\"\n        conf.add_section(sec7)\n        conf.set(sec7, \"literals\", \"\\()/\")  # noqa\n        conf.set(sec7, \"folders\", \"failed, JAV_output\")\n\n        sec8 = \"debug_mode\"\n        conf.add_section(sec8)\n        conf.set(sec8, \"switch\", \"0\")\n\n        sec9 = \"translate\"\n        conf.add_section(sec9)\n        conf.set(sec9, \"switch\", \"0\")\n        conf.set(sec9, \"engine\", \"google-free\")\n        conf.set(sec9, \"target_language\", \"zh_cn\")\n        # conf.set(sec8, \"appid\", \"\")\n        conf.set(sec9, \"key\", \"\")\n        conf.set(sec9, \"delay\", \"1\")\n        conf.set(sec9, \"values\", \"title,outline\")\n        conf.set(sec9, \"service_site\", \"translate.google.cn\")\n\n        sec10 = \"trailer\"\n        conf.add_section(sec10)\n        conf.set(sec10, \"switch\", \"0\")\n\n        sec11 = \"uncensored\"\n        conf.add_section(sec11)\n        conf.set(sec11, \"uncensored_prefix\", \"S2M,BT,LAF,SMD\")\n\n        sec12 = \"media\"\n        conf.add_section(sec12)\n        conf.set(sec12, \"media_type\",\n                 \".mp4,.avi,.rmvb,.wmv,.mov,.mkv,.flv,.ts,.webm,iso\")\n        conf.set(sec12, \"sub_type\",\n                 \".smi,.srt,.idx,.sub,.sup,.psb,.ssa,.ass,.usf,.xss,.ssf,.rt,.lrc,.sbv,.vtt,.ttml\")\n\n        sec13 = \"watermark\"\n        conf.add_section(sec13)\n        conf.set(sec13, \"switch\", \"1\")\n        conf.set(sec13, \"water\", \"2\")\n\n        sec14 = \"extrafanart\"\n        conf.add_section(sec14)\n        conf.set(sec14, \"switch\", \"1\")\n        conf.set(sec14, \"extrafanart_folder\", \"extrafanart\")\n        conf.set(sec14, \"parallel_download\", \"1\")\n\n        sec15 = \"storyline\"\n        conf.add_section(sec15)\n        conf.set(sec15, \"switch\", \"1\")\n        conf.set(sec15, \"site\", \"1:avno1,4:airavwiki\")\n        conf.set(sec15, \"censored_site\", \"2:airav,5:xcity,6:amazon\")\n        conf.set(sec15, \"uncensored_site\", \"3:58avgo\")\n        conf.set(sec15, \"show_result\", \"0\")\n        conf.set(sec15, \"run_mode\", \"1\")\n        conf.set(sec15, \"cc_convert\", \"1\")\n\n        sec16 = \"cc_convert\"\n        conf.add_section(sec16)\n        conf.set(sec16, \"mode\", \"1\")\n        conf.set(sec16, \"vars\", \"actor,director,label,outline,series,studio,tag,title\")\n\n        sec17 = \"javdb\"\n        conf.add_section(sec17)\n        conf.set(sec17, \"sites\", \"33,34\")\n\n        sec18 = \"face\"\n        conf.add_section(sec18)\n        conf.set(sec18, \"locations_model\", \"hog\")\n        conf.set(sec18, \"uncensored_only\", \"1\")\n        conf.set(sec18, \"aways_imagecut\", \"0\")\n        conf.set(sec18, \"aspect_ratio\", \"2.12\")\n\n        sec19 = \"jellyfin\"\n        conf.add_section(sec19)\n        conf.set(sec19, \"multi_part_fanart\", \"0\")\n\n        sec20 = \"actor_photo\"\n        conf.add_section(sec20)\n        conf.set(sec20, \"download_for_kodi\", \"0\")\n\n        return conf\n\n\nclass IniProxy():\n    \"\"\" Proxy Config from .ini\n    \"\"\"\n    SUPPORT_PROXY_TYPE = (\"http\", \"socks5\", \"socks5h\")\n\n    enable = False\n    address = \"\"\n    timeout = 5\n    retry = 3\n    proxytype = \"socks5\"\n\n    def __init__(self, switch, address, timeout, retry, proxytype) -> None:\n        \"\"\" Initial Proxy from .ini\n        \"\"\"\n        if switch == '1' or switch == 1:\n            self.enable = True\n        self.address = address\n        self.timeout = timeout\n        self.retry = retry\n        self.proxytype = proxytype\n\n    def proxies(self):\n        \"\"\"\n        获得代理参数，默认http代理\n        get proxy params, use http proxy for default\n        \"\"\"\n        if self.address:\n            if self.proxytype in self.SUPPORT_PROXY_TYPE:\n                proxies = {\"http\": self.proxytype + \"://\" + self.address,\n                           \"https\": self.proxytype + \"://\" + self.address}\n            else:\n                proxies = {\"http\": \"http://\" + self.address, \"https\": \"https://\" + self.address}\n        else:\n            proxies = {}\n\n        return proxies\n\n\nif __name__ == \"__main__\":\n    def evprint(evstr):\n        code = compile(evstr, \"<string>\", \"eval\")\n        print('{}: \"{}\"'.format(evstr, eval(code)))\n\n\n    config = Config()\n    mfilter = {'conf', 'proxy', '_exit', '_default_config', 'ini_path', 'set_override'}\n    for _m in [m for m in dir(config) if not m.startswith('__') and m not in mfilter]:\n        evprint(f'config.{_m}()')\n    pfilter = {'proxies', 'SUPPORT_PROXY_TYPE'}\n    # test getInstance()\n    assert (getInstance() == config)\n    for _p in [p for p in dir(getInstance().proxy()) if not p.startswith('__') and p not in pfilter]:\n        evprint(f'getInstance().proxy().{_p}')\n\n    # Create new instance\n    conf2 = Config()\n    assert getInstance() != conf2\n    assert getInstance() == config\n\n    conf2.set_override(\"d:s=1;face:asp=2;f:aw=0;pri:w=javdb;f:l=\")\n    assert conf2.face_aspect_ratio() == 2\n    assert conf2.face_aways_imagecut() == False\n    assert conf2.sources() == \"javdb\"\n    print(f\"Load Config file '{conf2.ini_path}'.\")\n"
  },
  {
    "path": "core.py",
    "content": "import os.path\nimport pathlib\nimport shutil\nimport sys\n\nfrom PIL import Image\nfrom io import BytesIO\nfrom datetime import datetime\n# from videoprops import get_video_properties\n\nfrom ADC_function import *\nfrom scraper import get_data_from_json\nfrom number_parser import is_uncensored\nfrom ImageProcessing import cutImage\n\n\n# from WebCrawler import get_data_from_json\n\ndef escape_path(path, escape_literals: str):  # Remove escape literals\n    backslash = '\\\\'\n    for literal in escape_literals:\n        path = path.replace(backslash + literal, '')\n    return path\n\n\ndef moveFailedFolder(filepath):\n    conf = config.getInstance()\n    failed_folder = conf.failed_folder()\n    link_mode = conf.link_mode()\n    # 模式3或软连接，改为维护一个失败列表，启动扫描时加载用于排除该路径，以免反复处理\n    # 原先的创建软连接到失败目录，并不直观，不方便找到失败文件位置，不如直接记录该文件路径\n    if conf.main_mode() == 3 or link_mode:\n        ftxt = os.path.abspath(os.path.join(failed_folder, 'failed_list.txt'))\n        print(\"[-]Add to Failed List file, see '%s'\" % ftxt)\n        with open(ftxt, 'a', encoding='utf-8') as flt:\n            flt.write(f'{filepath}\\n')\n    elif conf.failed_move() and not link_mode:\n        failed_name = os.path.join(failed_folder, os.path.basename(filepath))\n        mtxt = os.path.abspath(os.path.join(failed_folder, 'where_was_i_before_being_moved.txt'))\n        print(\"'[-]Move to Failed output folder, see '%s'\" % mtxt)\n        with open(mtxt, 'a', encoding='utf-8') as wwibbmt:\n            tmstr = datetime.now().strftime(\"%Y-%m-%d %H:%M\")\n            wwibbmt.write(f'{tmstr} FROM[{filepath}]TO[{failed_name}]\\n')\n        try:\n            if os.path.exists(failed_name):\n                print('[-]File Exists while moving to FailedFolder')\n                return\n            shutil.move(filepath, failed_name)\n        except:\n            print('[-]File Moving to FailedFolder unsuccessful!')\n\n\ndef get_info(json_data):  # 返回json里的数据\n    title = json_data.get('title')\n    studio = json_data.get('studio')\n    year = json_data.get('year')\n    outline = json_data.get('outline')\n    runtime = json_data.get('runtime')\n    director = json_data.get('director')\n    actor_photo = json_data.get('actor_photo', {})\n    release = json_data.get('release')\n    number = json_data.get('number')\n    cover = json_data.get('cover')\n    trailer = json_data.get('trailer')\n    website = json_data.get('website')\n    series = json_data.get('series')\n    label = json_data.get('label', \"\")\n    return title, studio, year, outline, runtime, director, actor_photo, release, number, cover, trailer, website, series, label\n\n\ndef small_cover_check(path, filename, cover_small, movie_path, json_headers=None):\n    full_filepath = Path(path) / filename\n    if config.getInstance().download_only_missing_images() and not file_not_exist_or_empty(str(full_filepath)):\n        return\n    if json_headers != None:\n        download_file_with_filename(cover_small, filename, path, movie_path, json_headers['headers'])\n    else:\n        download_file_with_filename(cover_small, filename, path, movie_path)\n    print('[+]Image Downloaded! ' + full_filepath.name)\n\n\ndef create_folder(json_data):  # 创建文件夹\n    title, studio, year, outline, runtime, director, actor_photo, release, number, cover, trailer, website, series, label = get_info(\n        json_data)\n    conf = config.getInstance()\n    success_folder = conf.success_folder()\n    actor = json_data.get('actor')\n    location_rule = eval(conf.location_rule(), json_data)\n    if 'actor' in conf.location_rule() and len(actor) > 100:\n        print(conf.location_rule())\n        location_rule = eval(conf.location_rule().replace(\"actor\", \"'多人作品'\"), json_data)\n    maxlen = conf.max_title_len()\n    if 'title' in conf.location_rule() and len(title) > maxlen:\n        shorttitle = title[0:maxlen]\n        location_rule = location_rule.replace(title, shorttitle)\n    # 当演员为空时，location_rule被计算为'/number'绝对路径，导致路径连接忽略第一个路径参数，因此添加./使其始终为相对路径\n    path = os.path.join(success_folder, f'./{location_rule.strip()}')\n    if not os.path.exists(path):\n        path = escape_path(path, conf.escape_literals())\n        try:\n            os.makedirs(path)\n        except:\n            path = success_folder + '/' + location_rule.replace('/[' + number + ')-' + title, \"/number\")\n            path = escape_path(path, conf.escape_literals())\n            try:\n                os.makedirs(path)\n            except:\n                print(f\"[-]Fatal error! Can not make folder '{path}'\")\n                os._exit(0)\n\n    return os.path.normpath(path)\n\n\n# =====================资源下载部分===========================\n\n# path = examle:photo , video.in the Project Folder!\ndef download_file_with_filename(url, filename, path, filepath, json_headers=None):\n    conf = config.getInstance()\n    configProxy = conf.proxy()\n\n    for i in range(configProxy.retry):\n        try:\n            if not os.path.exists(path):\n                try:\n                    os.makedirs(path)\n                except:\n                    print(f\"[-]Fatal error! Can not make folder '{path}'\")\n                    os._exit(0)\n            r = get_html(url=url, return_type='content', json_headers=json_headers)\n            if r == '':\n                print('[-]Movie Download Data not found!')\n                return\n            with open(os.path.join(path, filename), \"wb\") as code:\n                code.write(r)\n            return\n        except requests.exceptions.ProxyError:\n            i += 1\n            print('[-]Image Download : Proxy error ' + str(i) + '/' + str(configProxy.retry))\n        # except IOError:\n        #     print(f\"[-]Create Directory '{path}' failed!\")\n        #     moveFailedFolder(filepath)\n        #     return\n        except Exception as e:\n            print('[-]Image Download :Error', e)\n    print('[-]Connect Failed! Please check your Proxy or Network!')\n    moveFailedFolder(filepath)\n    return\n\n\ndef trailer_download(trailer, leak_word, c_word, hack_word, number, path, filepath):\n    if download_file_with_filename(trailer, number + leak_word + c_word + hack_word + '-trailer.mp4', path,\n                                   filepath) == 'failed':\n        return\n    configProxy = config.getInstance().proxy()\n    for i in range(configProxy.retry):\n        if file_not_exist_or_empty(path + '/' + number + leak_word + c_word + hack_word + '-trailer.mp4'):\n            print('[!]Video Download Failed! Trying again. [{}/3]', i + 1)\n            download_file_with_filename(trailer, number + leak_word + c_word + hack_word + '-trailer.mp4', path,\n                                        filepath)\n            continue\n        else:\n            break\n    if file_not_exist_or_empty(path + '/' + number + leak_word + c_word + hack_word + '-trailer.mp4'):\n        return\n    print('[+]Video Downloaded!', path + '/' + number + leak_word + c_word + hack_word + '-trailer.mp4')\n\n\ndef actor_photo_download(actors, save_dir, number):\n    if not isinstance(actors, dict) or not len(actors) or not len(save_dir):\n        return\n    save_dir = Path(save_dir)\n    if not save_dir.is_dir():\n        return\n    conf = config.getInstance()\n    actors_dir = save_dir / '.actors'\n    download_only_missing_images = conf.download_only_missing_images()\n    dn_list = []\n    for actor_name, url in actors.items():\n        res = re.match(r'^http.*(\\.\\w+)$', url, re.A)\n        if not res:\n            continue\n        ext = res.group(1)\n        pic_fullpath = actors_dir / f'{actor_name}{ext}'\n        if download_only_missing_images and not file_not_exist_or_empty(pic_fullpath):\n            continue\n        dn_list.append((url, pic_fullpath))\n    if not len(dn_list):\n        return\n    parallel = min(len(dn_list), conf.extrafanart_thread_pool_download())\n    if parallel > 100:\n        print('[!]Warrning: Parallel download thread too large may cause website ban IP!')\n    result = parallel_download_files(dn_list, parallel)\n    failed = 0\n    for i, r in enumerate(result):\n        if not r:\n            failed += 1\n            print(f\"[-]Actor photo '{dn_list[i][0]}' to '{dn_list[i][1]}' download failed!\")\n    if failed:  # 非致命错误，电影不移入失败文件夹，将来可以用模式3补齐\n        print(\n            f\"[-]Failed downloaded {failed}/{len(result)} actor photo for [{number}] to '{actors_dir}', you may retry run mode 3 later.\")\n    else:\n        print(f\"[+]Successfully downloaded {len(result)} actor photo.\")\n\n\n# 剧照下载成功，否则移动到failed\ndef extrafanart_download(data, path, number, filepath, json_data=None):\n    if config.getInstance().extrafanart_thread_pool_download():\n        return extrafanart_download_threadpool(data, path, number, json_data)\n    extrafanart_download_one_by_one(data, path, filepath, json_data)\n\n\ndef extrafanart_download_one_by_one(data, path, filepath, json_data=None):\n    tm_start = time.perf_counter()\n    j = 1\n    conf = config.getInstance()\n    path = os.path.join(path, conf.get_extrafanart())\n    configProxy = conf.proxy()\n    download_only_missing_images = conf.download_only_missing_images()\n    for url in data:\n        jpg_filename = f'extrafanart-{j}.jpg'\n        jpg_fullpath = os.path.join(path, jpg_filename)\n        if download_only_missing_images and not file_not_exist_or_empty(jpg_fullpath):\n            continue\n        if download_file_with_filename(url, jpg_filename, path, filepath, json_data) == 'failed':\n            moveFailedFolder(filepath)\n            return\n        for i in range(configProxy.retry):\n            if file_not_exist_or_empty(jpg_fullpath):\n                print('[!]Image Download Failed! Trying again. [{}/3]', i + 1)\n                download_file_with_filename(url, jpg_filename, path, filepath, json_data)\n                continue\n            else:\n                break\n        if file_not_exist_or_empty(jpg_fullpath):\n            return\n        print('[+]Image Downloaded!', Path(jpg_fullpath).name)\n        j += 1\n    if conf.debug():\n        print(f'[!]Extrafanart download one by one mode runtime {time.perf_counter() - tm_start:.3f}s')\n\n\ndef extrafanart_download_threadpool(url_list, save_dir, number, json_data=None):\n    tm_start = time.perf_counter()\n    conf = config.getInstance()\n    extrafanart_dir = Path(save_dir) / conf.get_extrafanart()\n    download_only_missing_images = conf.download_only_missing_images()\n    dn_list = []\n    for i, url in enumerate(url_list, start=1):\n        jpg_fullpath = extrafanart_dir / f'extrafanart-{i}.jpg'\n        if download_only_missing_images and not file_not_exist_or_empty(jpg_fullpath):\n            continue\n        dn_list.append((url, jpg_fullpath))\n    if not len(dn_list):\n        return\n    parallel = min(len(dn_list), conf.extrafanart_thread_pool_download())\n    if parallel > 100:\n        print('[!]Warrning: Parallel download thread too large may cause website ban IP!')\n    result = parallel_download_files(dn_list, parallel, json_data)\n    failed = 0\n    for i, r in enumerate(result, start=1):\n        if not r:\n            failed += 1\n            print(f'[-]Extrafanart {i} for [{number}] download failed!')\n    if failed:  # 非致命错误，电影不移入失败文件夹，将来可以用模式3补齐\n        print(\n            f\"[-]Failed downloaded {failed}/{len(result)} extrafanart images for [{number}] to '{extrafanart_dir}', you may retry run mode 3 later.\")\n    else:\n        print(f\"[+]Successfully downloaded {len(result)} extrafanarts.\")\n    if conf.debug():\n        print(f'[!]Extrafanart download ThreadPool mode runtime {time.perf_counter() - tm_start:.3f}s')\n\n\ndef image_ext(url):\n    try:\n        ext = os.path.splitext(url)[-1]\n        if ext in {'.jpg', '.jpge', '.bmp', '.png', '.gif'}:\n            return ext\n        return \".jpg\"\n    except:\n        return \".jpg\"\n\n\n# 封面是否下载成功，否则移动到failed\ndef image_download(cover, fanart_path, thumb_path, path, filepath, json_headers=None):\n    full_filepath = os.path.join(path, thumb_path)\n    if config.getInstance().download_only_missing_images() and not file_not_exist_or_empty(full_filepath):\n        return\n    if json_headers != None:\n        if download_file_with_filename(cover, thumb_path, path, filepath, json_headers['headers']) == 'failed':\n            moveFailedFolder(filepath)\n            return\n    else:\n        if download_file_with_filename(cover, thumb_path, path, filepath) == 'failed':\n            moveFailedFolder(filepath)\n            return\n\n    configProxy = config.getInstance().proxy()\n    for i in range(configProxy.retry):\n        if file_not_exist_or_empty(full_filepath):\n            print('[!]Image Download Failed! Trying again. [{}/3]', i + 1)\n            if json_headers != None:\n                download_file_with_filename(cover, thumb_path, path, filepath, json_headers['headers'])\n            else:\n                download_file_with_filename(cover, thumb_path, path, filepath)\n            continue\n        else:\n            break\n    if file_not_exist_or_empty(full_filepath):\n        return\n    print('[+]Image Downloaded!', Path(full_filepath).name)\n    if not config.getInstance().jellyfin():\n        shutil.copyfile(full_filepath, os.path.join(path, fanart_path))\n\n\ndef print_files(path, leak_word, c_word, naming_rule, part, cn_sub, json_data, filepath, tag, actor_list, liuchu,\n                uncensored, hack, hack_word, _4k, fanart_path, poster_path, thumb_path, iso):\n    \n    conf = config.getInstance()\n    title, studio, year, outline, runtime, director, actor_photo, release, number, cover, trailer, website, series, label = get_info(\n        json_data)\n    if config.getInstance().main_mode() == 3:  # 模式3下，由于视频文件不做任何改变，.nfo文件必须和视频文件名称除后缀外完全一致，KODI等软件方可支持\n        nfo_path = str(Path(filepath).with_suffix('.nfo'))\n    else:\n        nfo_path = os.path.join(path, f\"{number}{part}{leak_word}{c_word}{hack_word}.nfo\")\n    try:\n        if not os.path.exists(path):\n            try:\n                os.makedirs(path)\n            except:\n                print(f\"[-]Fatal error! can not make folder '{path}'\")\n                os._exit(0)\n\n        old_nfo = None\n        try:\n            if os.path.isfile(nfo_path):\n                old_nfo = etree.parse(nfo_path)\n        except:\n            pass\n        # KODI内查看影片信息时找不到number，配置naming_rule=number+'#'+title虽可解决\n        # 但使得标题太长，放入时常为空的outline内会更适合，软件给outline留出的显示版面也较大\n        if not outline:\n            pass\n        elif json_data['source'] == 'pissplay':\n            outline = f\"{outline}\"\n        else:\n            outline = f\"{number}#{outline}\"\n        with open(nfo_path, \"wt\", encoding='UTF-8') as code:\n            print('<?xml version=\"1.0\" encoding=\"UTF-8\" ?>', file=code)\n            print(\"<movie>\", file=code)\n            if not config.getInstance().jellyfin():\n                print(\"  <title><![CDATA[\" + naming_rule + \"]]></title>\", file=code)\n                print(\"  <originaltitle><![CDATA[\" + json_data['original_naming_rule'] + \"]]></originaltitle>\",\n                      file=code)\n                print(\"  <sorttitle><![CDATA[\" + naming_rule + \"]]></sorttitle>\", file=code)\n            else:\n                print(\"  <title>\" + naming_rule + \"</title>\", file=code)\n                print(\"  <originaltitle>\" + json_data['original_naming_rule'] + \"</originaltitle>\", file=code)\n                print(\"  <sorttitle>\" + naming_rule + \"</sorttitle>\", file=code)\n            print(\"  <customrating>JP-18+</customrating>\", file=code)\n            print(\"  <mpaa>JP-18+</mpaa>\", file=code)\n            try:\n                print(\"  <set>\" + series + \"</set>\", file=code)\n            except:\n                print(\"  <set></set>\", file=code)\n            print(\"  <studio>\" + studio + \"</studio>\", file=code)\n            print(\"  <year>\" + year + \"</year>\", file=code)\n            if not config.getInstance().jellyfin():\n                print(\"  <outline><![CDATA[\" + outline + \"]]></outline>\", file=code)\n                print(\"  <plot><![CDATA[\" + outline + \"]]></plot>\", file=code)\n            else:\n                print(\"  <outline>\" + outline + \"</outline>\", file=code)\n                print(\"  <plot>\" + outline + \"</plot>\", file=code)\n            print(\"  <runtime>\" + str(runtime).replace(\" \", \"\") + \"</runtime>\", file=code)\n            \n            if False != conf.get_direct(): \n                print(\"  <director>\" + director + \"</director>\", file=code)\n                \n            print(\"  <poster>\" + poster_path + \"</poster>\", file=code)\n            print(\"  <thumb>\" + thumb_path + \"</thumb>\", file=code)\n            if not config.getInstance().jellyfin():  # jellyfin 不需要保存fanart\n                print(\"  <fanart>\" + fanart_path + \"</fanart>\", file=code)\n            try:\n                for key in actor_list:\n                    print(\"  <actor>\", file=code)\n                    print(\"    <name>\" + key + \"</name>\", file=code)\n                    try:\n                        print(\"    <thumb>\" + actor_photo.get(str(key)) + \"</thumb>\", file=code)\n                    except:\n                        pass\n                    print(\"  </actor>\", file=code)\n            except:\n                pass\n            print(\"  <maker>\" + studio + \"</maker>\", file=code)\n            print(\"  <label>\" + label + \"</label>\", file=code)\n\n            jellyfin = config.getInstance().jellyfin()\n            if not jellyfin:\n                if config.getInstance().actor_only_tag():\n                    for key in actor_list:\n                        try:\n                            print(\"  <tag>\" + key + \"</tag>\", file=code)\n                        except:\n                            pass\n                else:\n                    if cn_sub:\n                        print(\"  <tag>中文字幕</tag>\", file=code)\n                    if _4k:\n                        print(\"  <tag>4k</tag>\", file=code)\n                    if iso:\n                        print(\"  <tag>原盘</tag>\", file=code)\n                    for i in tag:\n                        print(\"  <tag>\" + i + \"</tag>\", file=code)\n            if cn_sub:\n                print(\"  <genre>中文字幕</genre>\", file=code)\n            if _4k:\n                print(\"  <genre>4k</genre>\", file=code)\n            try:\n                for i in tag:\n                    print(\"  <genre>\" + i + \"</genre>\", file=code)\n            except:\n                pass\n            print(\"  <num>\" + number + \"</num>\", file=code)\n            print(\"  <premiered>\" + release + \"</premiered>\", file=code)\n            print(\"  <releasedate>\" + release + \"</releasedate>\", file=code)\n            print(\"  <release>\" + release + \"</release>\", file=code)\n            if old_nfo:\n                try:\n                    xur = old_nfo.xpath('//userrating/text()')[0]\n                    if isinstance(xur, str) and re.match('\\d+\\.\\d+|\\d+', xur.strip()):\n                        print(f\"  <userrating>{xur.strip()}</userrating>\", file=code)\n                except:\n                    pass\n            try:\n                f_rating = json_data.get('userrating')\n                uc = json_data.get('uservotes')\n                print(f\"\"\"  <rating>{round(f_rating * 2.0, 1)}</rating>\n  <criticrating>{round(f_rating * 20.0, 1)}</criticrating>\n  <ratings>\n    <rating name=\"jdb\" max=\"5\" default=\"true\">\n      <value>{f_rating}</value>\n      <votes>{uc}</votes>\n    </rating>\n  </ratings>\"\"\", file=code)\n            except:\n                if old_nfo:\n                    try:\n                        for rtag in ('rating', 'criticrating'):\n                            xur = old_nfo.xpath(f'//{rtag}/text()')[0]\n                            if isinstance(xur, str) and re.match('\\d+\\.\\d+|\\d+', xur.strip()):\n                                print(f\"  <{rtag}>{xur.strip()}</{rtag}>\", file=code)\n                        f_rating = old_nfo.xpath(f\"//ratings/rating[@name='jdb']/value/text()\")[0]\n                        uc = old_nfo.xpath(f\"//ratings/rating[@name='jdb']/votes/text()\")[0]\n                        print(f\"\"\"  <ratings>\n    <rating name=\"jdb\" max=\"5\" default=\"true\">\n      <value>{f_rating}</value>\n      <votes>{uc}</votes>\n    </rating>\n  </ratings>\"\"\", file=code)\n                    except:\n                        pass\n            if config.getInstance().is_trailer():\n                print(\"  <trailer>\" + trailer + \"</trailer>\", file=code)\n            print(\"</movie>\", file=code)\n            print(\"[+]Wrote!            \" + nfo_path)\n    except IOError as e:\n        print(\"[-]Write Failed!\")\n        print(\"[-]\", e)\n        moveFailedFolder(filepath)\n        return\n    except Exception as e1:\n        print(\"[-]Write Failed!\")\n        print(\"[-]\", e1)\n        moveFailedFolder(filepath)\n        return\n\n\ndef add_mark(poster_path, thumb_path, cn_sub, leak, uncensored, hack, _4k, iso) -> None:\n    \"\"\"\n    add watermark on poster or thumb for describe extra properties 给海报和缩略图加属性水印\n\n    :poster_path 海报位置\n    :thumb_path 缩略图位置\n    :cn_sub: 中文字幕 可选值：1,\"1\" 或其他值\n    :uncensored 无码 可选值：1,\"1\" 或其他值\n    :hack 破解 可选值：1,\"1\" 或其他值\n    :_4k Bool\n    \"\"\"\n    mark_type = ''\n    if cn_sub:\n        mark_type += ',字幕'\n    if _4k:\n        mark_type += ',4k'\n    if iso:\n        mark_type += ',iso'\n    if mark_type == '':\n        return\n    add_mark_thread(thumb_path, cn_sub, leak, uncensored, hack, _4k, iso)\n    add_mark_thread(poster_path, cn_sub, leak, uncensored, hack, _4k, iso)\n    print('[+]Add Mark:         ' + mark_type.strip(','))\n\n\ndef add_mark_thread(pic_path, cn_sub, leak, uncensored, hack, _4k, iso):\n    size = 9\n    img_pic = Image.open(pic_path)\n    # 获取自定义位置，取余配合pos达到顺时针添加的效果\n    # 左上 0, 右上 1, 右下 2， 左下 3\n    count = config.getInstance().watermark_type()\n    if cn_sub:\n        add_to_pic(pic_path, img_pic, size, count, 1)  # 添加\n        count = (count + 1) % 4\n    if leak:\n        add_to_pic(pic_path, img_pic, size, count, 2)\n        count = (count + 1) % 4\n    if uncensored:\n        add_to_pic(pic_path, img_pic, size, count, 3)\n        count = (count + 1) % 4\n    if hack:\n        add_to_pic(pic_path, img_pic, size, count, 4)\n        count = (count + 1) % 4\n    if _4k:\n        add_to_pic(pic_path, img_pic, size, count, 5)\n        count = (count + 1) % 4\n    if iso:\n        add_to_pic(pic_path, img_pic, size, count, 6)\n    img_pic.close()\n\n\ndef add_to_pic(pic_path, img_pic, size, count, mode):\n    mark_pic_path = ''\n    pngpath = ''\n    if mode == 1:\n        pngpath = \"Img/SUB.png\"\n    elif mode == 5:\n        pngpath = \"Img/4K.png\"\n    elif mode == 6:\n        pngpath = \"Img/ISO.png\"\n    else:\n        print('[-]Error: watermark image param mode invalid!')\n        return\n    # 先找pyinstaller打包的图片\n    if hasattr(sys, '_MEIPASS') and os.path.isfile(os.path.join(getattr(sys, '_MEIPASS'), pngpath)):\n        mark_pic_path = os.path.join(getattr(sys, '_MEIPASS'), pngpath)\n    # 再找py脚本所在路径的图片\n    elif os.path.isfile(os.path.join(os.path.dirname(os.path.realpath(__file__)), pngpath)):\n        mark_pic_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), pngpath)\n    # 如果没有本地图片才通过网络下载\n    else:\n        mark_pic_path = BytesIO(\n            get_html(\"https://raw.githubusercontent.com/yoshiko2/AV_Data_Capture/master/\" + pngpath,\n                     return_type=\"content\"))\n    img_subt = Image.open(mark_pic_path)\n    scroll_high = int(img_pic.height / size)\n    scroll_wide = int(scroll_high * img_subt.width / img_subt.height)\n    img_subt = img_subt.resize((scroll_wide, scroll_high), Image.LANCZOS)\n    r, g, b, a = img_subt.split()  # 获取颜色通道，保持png的透明性\n    # 封面四个角的位置\n    pos = [\n        {'x': 0, 'y': 0},\n        {'x': img_pic.width - scroll_wide, 'y': 0},\n        {'x': img_pic.width - scroll_wide, 'y': img_pic.height - scroll_high},\n        {'x': 0, 'y': img_pic.height - scroll_high},\n    ]\n    img_pic.paste(img_subt, (pos[count]['x'], pos[count]['y']), mask=a)\n    img_pic.save(pic_path, quality=95)\n\n\n# ========================结束=================================\n\n\ndef paste_file_to_folder(filepath, path, multi_part, number, part, leak_word, c_word, hack_word):  # 文件路径，番号，后缀，要移动至的位置\n    filepath_obj = pathlib.Path(filepath)\n    houzhui = filepath_obj.suffix\n    try:\n        targetpath = os.path.join(path, f\"{number}{leak_word}{c_word}{hack_word}{houzhui}\")\n        # 任何情况下都不要覆盖，以免遭遇数据源或者引擎错误导致所有文件得到同一个number，逐一\n        # 同名覆盖致使全部文件损失且不可追回的最坏情况\n        if os.path.exists(targetpath):\n            raise FileExistsError('File Exists on destination path, we will never overwriting.')\n        link_mode = config.getInstance().link_mode()\n        # 如果link_mode 1: 建立软链接 2: 硬链接优先、无法建立硬链接再尝试软链接。\n        # 移除原先soft_link=2的功能代码，因默认记录日志，已经可追溯文件来源\n        create_softlink = False\n        if link_mode not in (1, 2):\n            shutil.move(filepath, targetpath)\n        elif link_mode == 2:\n            # 跨卷或跨盘符无法建立硬链接导致异常，回落到建立软链接\n            try:\n                os.link(filepath, targetpath, follow_symlinks=False)\n            except:\n                create_softlink = True\n        if link_mode == 1 or create_softlink:\n            # 先尝试采用相对路径，以便网络访问时能正确打开视频，失败则可能是因为跨盘符等原因无法支持\n            # 相对路径径，改用绝对路径方式尝试建立软链接\n            try:\n                filerelpath = os.path.relpath(filepath, path)\n                os.symlink(filerelpath, targetpath)\n            except:\n                os.symlink(str(filepath_obj.resolve()), targetpath)\n        return\n\n    except FileExistsError as fee:\n        print(f'[-]FileExistsError: {fee}')\n        moveFailedFolder(filepath)\n        return\n    except PermissionError:\n        print('[-]Error! Please run as administrator!')\n        return\n    except OSError as oserr:\n        print(f'[-]OS Error errno {oserr.errno}')\n        return\n\n\ndef paste_file_to_folder_mode2(filepath, path, multi_part, number, part, leak_word, c_word,\n                               hack_word):  # 文件路径，番号，后缀，要移动至的位置\n    if multi_part == 1:\n        number += part  # 这时number会被附加上CD1后缀\n    filepath_obj = pathlib.Path(filepath)\n    houzhui = filepath_obj.suffix\n    targetpath = os.path.join(path, f\"{number}{part}{leak_word}{c_word}{hack_word}{houzhui}\")\n    if os.path.exists(targetpath):\n        raise FileExistsError('File Exists on destination path, we will never overwriting.')\n    try:\n        link_mode = config.getInstance().link_mode()\n        create_softlink = False\n        if link_mode not in (1, 2):\n            shutil.move(filepath, targetpath)\n            print(\"[!]Move =>          \", path)\n            return\n        elif link_mode == 2:\n            try:\n                os.link(filepath, targetpath, follow_symlinks=False)\n            except:\n                create_softlink = True\n        if link_mode == 1 or create_softlink:\n            try:\n                filerelpath = os.path.relpath(filepath, path)\n                os.symlink(filerelpath, targetpath)\n            except:\n                os.symlink(str(filepath_obj.resolve()), targetpath)\n        print(\"[!]Link =>          \", path)\n    except FileExistsError as fee:\n        print(f'[-]FileExistsError: {fee}')\n    except PermissionError:\n        print('[-]Error! Please run as administrator!')\n    except OSError as oserr:\n        print(f'[-]OS Error errno  {oserr.errno}')\n\n\ndef linkImage(path, number, part, leak_word, c_word, hack_word, ext):\n    \"\"\"\n    首先尝试为图片建立符合Jellyfin封面图文件名规则的硬连接以节省磁盘空间\n    如果目标目录无法建立硬链接则将图片复制一份成为常规文件\n    常规文件日期已经存在时，若修改日期比源文件更旧，则将被新的覆盖，否则忽略\n    \"\"\"\n    if not all(len(v) for v in (path, number, part, ext)):\n        return\n    covers = (\"-fanart\", \"-poster\", \"-thumb\")\n    normal_prefix = f\"{number}{leak_word}{c_word}{hack_word}\"\n    multi_prefix = f\"{number}{part}{leak_word}{c_word}{hack_word}\"\n    normal_pathes = (Path(path) / f\"{normal_prefix}{c}{ext}\" for c in covers)\n    multi_pathes = (Path(path) / f\"{multi_prefix}{c}{ext}\" for c in covers)\n    for normal_path, multi_path in zip(normal_pathes, multi_pathes):\n        if not normal_path.is_file():\n            continue\n        mkLink = False\n        if not multi_path.exists():\n            mkLink = True\n        elif multi_path.is_file():\n            if multi_path.stat().st_nlink > 1:\n                continue\n            elif normal_path.stat().st_mtime <= multi_path.stat().st_mtime:\n                continue\n            mkLink = True\n            multi_path.unlink(missing_ok=True)\n        if not mkLink:\n            continue\n        try:\n            os.link(str(normal_path), str(multi_path), follow_symlinks=False)\n        except:\n            shutil.copyfile(str(normal_path), str(multi_path))\n\n\ndef debug_print(data: json):\n    try:\n        print(\"[+] ------- DEBUG INFO -------\")\n        for i, v in data.items():\n            if i == 'outline':\n                print('[+]  -', \"%-19s\" % i, ':', len(v), 'characters')\n                continue\n            if i == 'actor_photo' or i == 'year':\n                continue\n            if i == 'extrafanart':\n                print('[+]  -', \"%-19s\" % i, ':', len(v), 'links')\n                continue\n            print(f'[+]  - {i:<{cn_space(i, 19)}} : {v}')\n\n        print(\"[+] ------- DEBUG INFO -------\")\n    except:\n        pass\n\n\ndef core_main_no_net_op(movie_path, number):\n    conf = config.getInstance()\n    part = ''\n    leak_word = ''\n    leak = False\n    c_word = ''\n    cn_sub = False\n    hack = False\n    hack_word = ''\n    _4k = False\n    iso = False\n    imagecut = 1\n    multi = False\n    part = ''\n    path = str(Path(movie_path).parent)\n\n    if re.search('[-_]CD\\d+', movie_path, re.IGNORECASE):\n        part = re.findall('[-_]CD\\d+', movie_path, re.IGNORECASE)[0].upper()\n        multi = True\n    if re.search(r'[-_]C(\\.\\w+$|-\\w+)|\\d+ch(\\.\\w+$|-\\w+)', movie_path,\n                 re.I) or '中文' in movie_path or '字幕' in movie_path or \".chs\" in movie_path or '.cht' in movie_path:\n        cn_sub = True\n        c_word = '-C'  # 中文字幕影片后缀\n    uncensored = True if is_uncensored(number) else 0\n\n    if '4k'.upper() in str(movie_path).upper() or '4k' in movie_path:\n        _4k = True\n\n    if '.iso'.upper() in str(movie_path).upper() or '.iso' in movie_path:\n        iso = True\n    # try:\n\n    #     props = get_video_properties(movie_path)  # 判断是否为4K视频\n    #     if props['width'] >= 4096 or props['height'] >= 2160:\n    #         _4k = True\n    # except:\n    #     pass\n    prestr = f\"{number}{leak_word}{c_word}{hack_word}\"\n\n    full_nfo = Path(path) / f\"{prestr}{part}.nfo\"\n    if full_nfo.is_file():\n        try:\n            nfo_xml = etree.parse(full_nfo)\n            nfo_fanart_path = nfo_xml.xpath('//fanart/text()')[0]\n            ext = Path(nfo_fanart_path).suffix\n        except:\n            return\n    else:\n        return\n    fanart_path = f\"fanart{ext}\"\n    poster_path = f\"poster{ext}\"\n    thumb_path = f\"thumb{ext}\"\n    if config.getInstance().image_naming_with_number():\n        fanart_path = f\"{prestr}-fanart{ext}\"\n        poster_path = f\"{prestr}-poster{ext}\"\n        thumb_path = f\"{prestr}-thumb{ext}\"\n    full_fanart_path = os.path.join(path, fanart_path)\n    full_poster_path = os.path.join(path, poster_path)\n    full_thumb_path = os.path.join(path, thumb_path)\n\n    if not all(os.path.isfile(f) for f in (full_fanart_path, full_thumb_path)):\n        return\n\n    cutImage(imagecut, path, fanart_path, poster_path, bool(conf.face_uncensored_only() and not uncensored))\n    if conf.is_watermark():\n        add_mark(full_poster_path, full_thumb_path, cn_sub, leak, uncensored, hack, _4k, iso)\n\n    if multi and conf.jellyfin_multi_part_fanart():\n        linkImage(path, number, part, leak_word, c_word, hack_word, ext)\n\n\ndef move_subtitles(filepath, path, multi_part, number, part, leak_word, c_word, hack_word) -> bool:\n    filepath_obj = pathlib.Path(filepath)\n    link_mode = config.getInstance().link_mode()\n    sub_res = config.getInstance().sub_rule()\n    result = False\n    for subfile in filepath_obj.parent.glob('**/*'):\n        if subfile.is_file() and subfile.suffix.lower() in sub_res:\n            if multi_part and part.lower() not in subfile.name.lower():\n                continue\n            if filepath_obj.stem.split('.')[0].lower() != subfile.stem.split('.')[0].lower():\n                continue\n            sub_targetpath = Path(path) / f\"{number}{leak_word}{c_word}{hack_word}{''.join(subfile.suffixes)}\"\n            if link_mode not in (1, 2):\n                shutil.move(str(subfile), str(sub_targetpath))\n                print(f\"[+]Sub Moved!        {sub_targetpath.name}\")\n                result = True\n            else:\n                shutil.copyfile(str(subfile), str(sub_targetpath))\n                print(f\"[+]Sub Copied!       {sub_targetpath.name}\")\n                result = True\n            if result:\n                break\n    return result\n\n\ndef core_main(movie_path, number_th, oCC, specified_source=None, specified_url=None):\n    conf = config.getInstance()\n    # =======================================================================初始化所需变量\n    multi_part = False\n    part = ''\n    leak_word = ''\n    c_word = ''\n    cn_sub = False\n    liuchu = False\n    hack = False\n    hack_word = ''\n    _4k = False\n    iso = False\n\n    # 下面被注释的变量不需要\n    # rootpath = os.getcwd\n    number = number_th\n    json_data = get_data_from_json(number, oCC, specified_source, specified_url)  # 定义番号\n\n    # Return if blank dict returned (data not found)\n    if not json_data:\n        moveFailedFolder(movie_path)\n        return\n\n    if json_data[\"number\"] != number:\n        # fix issue #119\n        # the root cause is we normalize the search id\n        # print_files() will use the normalized id from website,\n        # but paste_file_to_folder() still use the input raw search id\n        # so the solution is: use the normalized search id\n        number = json_data[\"number\"]\n    imagecut = json_data.get('imagecut')\n    tag = json_data.get('tag')\n    # =======================================================================判断-C,-CD后缀\n    if re.search('[-_]CD\\d+', movie_path, re.IGNORECASE):\n        multi_part = True\n        part = re.findall('[-_]CD\\d+', movie_path, re.IGNORECASE)[0].upper()\n    if re.search(r'[-_]C(\\.\\w+$|-\\w+)|\\d+ch(\\.\\w+$|-\\w+)', movie_path,\n                 re.I) or '中文' in movie_path or '字幕' in movie_path:\n        cn_sub = True\n        c_word = '-C'  # 中文字幕影片后缀\n\n    if re.search(r'[-_]UC(\\.\\w+$|-\\w+)', movie_path,\n                 re.I):\n        cn_sub = True\n        hack_word = '-UC'  #\n        hack = True\n        \n    if re.search(r'[-_]U(\\.\\w+$|-\\w+)', movie_path,\n                 re.I):#\n        hack = True\n        hack_word = '-U'\n    uncensored = int(unce) if isinstance(unce, bool) else int(is_uncensored(number))\n\n    if '4k'.upper() in str(movie_path).upper() or '4k' in movie_path:\n        _4k = True\n\n    if '.iso'.upper() in str(movie_path).upper() or '.iso' in movie_path:\n        iso = True\n\n    # 判断是否4k\n    if '4K' in tag:\n        tag.remove('4K')  # 从tag中移除'4K'\n\n\n    # try:\n    #     props = get_video_properties(movie_path)  # 判断是否为4K视频\n    #     if props['width'] >= 4096 or props['height'] >= 2160:\n    #         _4k = True\n    # except:\n    #     pass\n\n    # 调试模式检测\n    if conf.debug():\n        debug_print(json_data)\n\n    # 创建文件夹\n    # path = create_folder(rootpath + '/' + conf.success_folder(),  json_data.get('location_rule'), json_data)\n\n    cover = json_data.get('cover')\n    ext = image_ext(cover)\n\n    fanart_path = f\"fanart{ext}\"\n    poster_path = f\"poster{ext}\"\n    thumb_path = f\"thumb{ext}\"\n    if config.getInstance().image_naming_with_number():\n        fanart_path = f\"{number}{leak_word}{c_word}{hack_word}-fanart{ext}\"\n        poster_path = f\"{number}{leak_word}{c_word}{hack_word}-poster{ext}\"\n        thumb_path = f\"{number}{leak_word}{c_word}{hack_word}-thumb{ext}\"\n\n    # main_mode\n    #  1: 刮削模式 / Scraping mode\n    #  2: 整理模式 / Organizing mode\n    #  3：不改变路径刮削\n    if conf.main_mode() == 1:\n        # 创建文件夹\n        path = create_folder(json_data)\n        if multi_part == 1:\n            number += part  # 这时number会被附加上CD1后缀\n\n        # 检查小封面, 如果image cut为3，则下载小封面\n        if imagecut == 3:\n            if 'headers' in json_data:\n                small_cover_check(path, poster_path, json_data.get('cover_small'), movie_path, json_data)\n            else:\n                small_cover_check(path, poster_path, json_data.get('cover_small'), movie_path)\n\n        # creatFolder会返回番号路径\n        if 'headers' in json_data:\n            image_download(cover, fanart_path, thumb_path, path, movie_path, json_data)\n        else:\n            image_download(cover, fanart_path, thumb_path, path, movie_path)\n\n        if not multi_part or part.lower() == '-cd1':\n            try:\n                # 下载预告片\n                if conf.is_trailer() and json_data.get('trailer'):\n                    trailer_download(json_data.get('trailer'), leak_word, c_word, hack_word, number, path, movie_path)\n\n                # 下载剧照 data, path, filepath\n                if conf.is_extrafanart() and json_data.get('extrafanart'):\n                    if 'headers' in json_data:\n                        extrafanart_download(json_data.get('extrafanart'), path, number, movie_path, json_data)\n                    else:\n                        extrafanart_download(json_data.get('extrafanart'), path, number, movie_path)\n\n                # 下载演员头像 KODI .actors 目录位置\n                if conf.download_actor_photo_for_kodi():\n                    actor_photo_download(json_data.get('actor_photo'), path, number)\n            except:\n                pass\n\n        # 裁剪图\n        cutImage(imagecut, path, thumb_path, poster_path, bool(conf.face_uncensored_only() and not uncensored))\n\n        # 兼容Jellyfin封面图文件名规则\n        if multi_part and conf.jellyfin_multi_part_fanart():\n            linkImage(path, number_th, part, leak_word, c_word, hack_word, ext)\n\n        # 移动电影\n        paste_file_to_folder(movie_path, path, multi_part, number, part, leak_word, c_word, hack_word)\n\n        # Move subtitles\n        move_status = move_subtitles(movie_path, path, multi_part, number, part, leak_word, c_word, hack_word)\n        if move_status:\n            cn_sub = True\n        # 添加水印\n        if conf.is_watermark():\n            add_mark(os.path.join(path, poster_path), os.path.join(path, thumb_path), cn_sub, leak, uncensored,\n                     hack, _4k, iso)\n\n        # 最后输出.nfo元数据文件，以完成.nfo文件创建作为任务成功标志\n        print_files(path, leak_word, c_word, json_data.get('naming_rule'), part, cn_sub, json_data, movie_path, tag,\n                    json_data.get('actor_list'), liuchu, uncensored, hack, hack_word\n                    , _4k, fanart_path, poster_path, thumb_path, iso)\n\n    elif conf.main_mode() == 2:\n        # 创建文件夹\n        path = create_folder(json_data)\n        # 移动文件\n        paste_file_to_folder_mode2(movie_path, path, multi_part, number, part, leak_word, c_word, hack_word)\n\n        # Move subtitles\n        move_subtitles(movie_path, path, multi_part, number, part, leak_word, c_word, hack_word)\n\n    elif conf.main_mode() == 3:\n        path = str(Path(movie_path).parent)\n        if multi_part == 1:\n            number += part  # 这时number会被附加上CD1后缀\n\n        # 检查小封面, 如果image cut为3，则下载小封面\n        if imagecut == 3:\n            if 'headers' in json_data:\n                small_cover_check(path, poster_path, json_data.get('cover_small'), movie_path, json_data)\n            else:\n                small_cover_check(path, poster_path, json_data.get('cover_small'), movie_path)\n\n        # creatFolder会返回番号路径\n        if 'headers' in json_data:\n            image_download(cover, fanart_path, thumb_path, path, movie_path, json_data)\n        else:\n            image_download(cover, fanart_path, thumb_path, path, movie_path)\n\n        if not multi_part or part.lower() == '-cd1':\n            try:\n                # 下载预告片\n                if conf.is_trailer() and json_data.get('trailer'):\n                    trailer_download(json_data.get('trailer'), leak_word, c_word, hack_word, number, path, movie_path)\n\n                # 下载剧照 data, path, filepath\n                if conf.is_extrafanart() and json_data.get('extrafanart'):\n                    if 'headers' in json_data:\n                        extrafanart_download(json_data.get('extrafanart'), path, number, movie_path, json_data)\n                    else:\n                        extrafanart_download(json_data.get('extrafanart'), path, number, movie_path)\n\n                # 下载演员头像 KODI .actors 目录位置\n                if conf.download_actor_photo_for_kodi():\n                    actor_photo_download(json_data.get('actor_photo'), path, number)\n            except:\n                pass\n\n        # 裁剪图\n        cutImage(imagecut, path, fanart_path, poster_path, bool(conf.face_uncensored_only() and not uncensored))\n\n        # 添加水印\n        if conf.is_watermark():\n            add_mark(os.path.join(path, poster_path), os.path.join(path, fanart_path), cn_sub, leak, uncensored, hack,\n                     _4k, iso)\n\n        # 兼容Jellyfin封面图文件名规则\n        if multi_part and conf.jellyfin_multi_part_fanart():\n            linkImage(path, number_th, part, leak_word, c_word, hack_word, ext)\n\n        # 最后输出.nfo元数据文件，以完成.nfo文件创建作为任务成功标志\n        print_files(path, leak_word, c_word, json_data.get('naming_rule'), part, cn_sub, json_data, movie_path,\n                    tag, json_data.get('actor_list'), liuchu, uncensored, hack, hack_word, _4k, fanart_path,\n                    poster_path,\n                    thumb_path, iso)\n"
  },
  {
    "path": "docker/Dockerfile",
    "content": "FROM python:slim\nRUN sed -i 's/deb.debian.org/mirrors.tuna.tsinghua.edu.cn/g' /etc/apt/sources.list \\\n    && sed -i 's/security.debian.org/mirrors.tuna.tsinghua.edu.cn/g' /etc/apt/sources.list\nRUN pip install -i https://pypi.tuna.tsinghua.edu.cn/simple pip -U \\\n    && pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple\n\nRUN apt-get update \\\n    && apt-get install -y wget ca-certificates \\\n    && wget -O - 'https://github.com/yoshiko2/Movie_Data_Capture/archive/master.tar.gz' | tar xz \\\n    && mv Movie_Data_Capture-master /mdc \\\n    && cd /mdc \\\n    && ( pip install --no-cache-dir -r requirements.txt || true ) \\\n    && pip install --no-cache-dir requests lxml Beautifulsoup4 pillow \\\n    && apt-get purge -y wget\n\nWORKDIR /mdc\n"
  },
  {
    "path": "docker/config.ini",
    "content": "[common]\nmain_mode=1\nfailed_output_folder=data/failure_output\nsuccess_output_folder=data/organized\nlink_mode=0\n\n[proxy]\nproxy=\ntimeout=10\nretry=3\n\n[Name_Rule]\nlocation_rule=actor+'/'+title\nnaming_rule=number+'-'+title\n\n[update]\nupdate_check=0\n\n[escape]\nliterals=\\()/\nfolders=data/failure_output,data/organized\n\n[debug_mode]\nswitch=0\n\n[media]\nmedia_warehouse=plex\n"
  },
  {
    "path": "docker/docker-compose.yaml",
    "content": "version: \"2.2\"\nservices:\n  jav:\n    user: \"${MDCUID}:${MDCGID}\"\n    image: jav:local\n    build: .\n    volumes:\n      - ./config.ini:/mdc/config.ini\n      - ${MDC_PATH}:/mdc/data\n    command:\n      - python\n      - /mdc/Movie_Data_Capture.py\n      - -a\n"
  },
  {
    "path": "number_parser.py",
    "content": "import os\nimport re\nimport sys\nimport config\nimport typing\n\nG_spat = re.compile(\n    \"^\\w+\\.(cc|com|net|me|club|jp|tv|xyz|biz|wiki|info|tw|us|de)@|^22-sht\\.me|\"\n    \"^(fhd|hd|sd|1080p|720p|4K)(-|_)|\"\n    \"(-|_)(fhd|hd|sd|1080p|720p|4K|x264|x265|uncensored|hack|leak)\",\n    re.IGNORECASE)\n\n\ndef get_number(debug: bool, file_path: str) -> str:\n    \"\"\"\n    从文件路径中提取号码 from number_parser import get_number\n    \"\"\"\n    filepath = os.path.basename(file_path)\n    # debug True 和 False 两块代码块合并，原因是此模块及函数只涉及字符串计算，没有IO操作，debug on时输出导致异常信息即可\n    try:\n        # 先对自定义正则进行匹配\n        if config.getInstance().number_regexs().split().__len__() > 0:\n            for regex in config.getInstance().number_regexs().split():\n                try:\n                    if re.search(regex, filepath):\n                        return re.search(regex, filepath).group()\n                except Exception as e:\n                    print(f'[-]custom regex exception: {e} [{regex}]')\n\n        file_number = get_number_by_dict(filepath)\n        if file_number:\n            return file_number\n        elif '字幕组' in filepath or 'SUB' in filepath.upper() or re.match(r'[\\u30a0-\\u30ff]+', filepath):\n            filepath = G_spat.sub(\"\", filepath)\n            filepath = re.sub(\"\\[.*?\\]\",\"\",filepath)\n            filepath = filepath.replace(\".chs\", \"\").replace(\".cht\", \"\")\n            file_number = str(re.findall(r'(.+?)\\.', filepath)).strip(\" [']\")\n            return file_number\n        elif '-' in filepath or '_' in filepath:  # 普通提取番号 主要处理包含减号-和_的番号\n            filepath = G_spat.sub(\"\", filepath)\n            filename = str(re.sub(\"\\[\\d{4}-\\d{1,2}-\\d{1,2}\\] - \", \"\", filepath))  # 去除文件名中时间\n            lower_check = filename.lower()\n            if 'fc2' in lower_check:\n                filename = lower_check.replace('--', '-').replace('_', '-').upper()\n            filename = re.sub(\"[-_]cd\\d{1,2}\", \"\", filename, flags=re.IGNORECASE)\n            if not re.search(\"-|_\", filename): # 去掉-CD1之后再无-的情况，例如n1012-CD1.wmv\n                return str(re.search(r'\\w+', filename[:filename.find('.')], re.A).group())\n            file_number =  os.path.splitext(filename)\n            filename = re.search(r'[\\w\\-_]+', filename, re.A)\n            if filename:\n                file_number = str(filename.group())\n            else:\n                file_number = file_number[0]\n            \n            new_file_number = file_number\n            if re.search(\"-c\", file_number, flags=re.IGNORECASE):\n                new_file_number = re.sub(\"(-|_)c$\", \"\", file_number, flags=re.IGNORECASE)\n            elif re.search(\"-u$\", file_number, flags=re.IGNORECASE):\n                new_file_number = re.sub(\"(-|_)u$\", \"\", file_number, flags=re.IGNORECASE)\n            elif re.search(\"-uc$\", file_number, flags=re.IGNORECASE):\n                new_file_number = re.sub(\"(-|_)uc$\", \"\", file_number, flags=re.IGNORECASE)\n            elif re.search(\"\\d+ch$\", file_number, flags=re.I):\n                new_file_number = file_number[:-2]\n                \n            return new_file_number.upper()\n        else:  # 提取不含减号-的番号，FANZA CID\n            # 欧美番号匹配规则\n            oumei = re.search(r'[a-zA-Z]+\\.\\d{2}\\.\\d{2}\\.\\d{2}', filepath)\n            if oumei:\n                return oumei.group()\n            try:\n                return str(\n                    re.findall(r'(.+?)\\.',\n                               str(re.search('([^<>/\\\\\\\\|:\"\"\\\\*\\\\?]+)\\\\.\\\\w+$', filepath).group()))).strip(\n                    \"['']\").replace('_', '-')\n            except:\n                return str(re.search(r'(.+?)\\.', filepath)[0])\n    except Exception as e:\n        if debug:\n            print(f'[-]Number Parser exception: {e} [{file_path}]')\n        return None\n\nG_TAKE_NUM_RULES = {\n    'tokyo.*hot': lambda x: str(re.search(r'(cz|gedo|k|n|red-|se)\\d{2,4}', x, re.I).group()),\n    'carib': lambda x: str(re.search(r'\\d{6}(-|_)\\d{3}', x, re.I).group()).replace('_', '-'),\n    '1pon|mura|paco': lambda x: str(re.search(r'\\d{6}(-|_)\\d{3}', x, re.I).group()).replace('-', '_'),\n    '10mu': lambda x: str(re.search(r'\\d{6}(-|_)\\d{2}', x, re.I).group()).replace('-', '_'),\n    'x-art': lambda x: str(re.search(r'x-art\\.\\d{2}\\.\\d{2}\\.\\d{2}', x, re.I).group()),\n    'xxx-av': lambda x: ''.join(['xxx-av-', re.findall(r'xxx-av[^\\d]*(\\d{3,5})[^\\d]*', x, re.I)[0]]),\n    'heydouga': lambda x: 'heydouga-' + '-'.join(re.findall(r'(\\d{4})[\\-_](\\d{3,4})[^\\d]*', x, re.I)[0]),\n    'heyzo': lambda x: 'HEYZO-' + re.findall(r'heyzo[^\\d]*(\\d{4})', x, re.I)[0],\n    'mdbk': lambda x: str(re.search(r'mdbk(-|_)(\\d{4})', x, re.I).group()),\n    'mdtm': lambda x: str(re.search(r'mdtm(-|_)(\\d{4})', x, re.I).group()),\n    'caribpr': lambda x: str(re.search(r'\\d{6}(-|_)\\d{3}', x, re.I).group()).replace('_', '-'),\n}\n\n\ndef get_number_by_dict(filename: str) -> typing.Optional[str]:\n    try:\n        for k, v in G_TAKE_NUM_RULES.items():\n            if re.search(k, filename, re.I):\n                return v(filename)\n    except:\n        pass\n    return None\n\n\nclass Cache_uncensored_conf:\n    prefix = None\n\n    def is_empty(self):\n        return bool(self.prefix is None)\n\n    def set(self, v: list):\n        if not v or not len(v) or not len(v[0]):\n            raise ValueError('input prefix list empty or None')\n        s = v[0]\n        if len(v) > 1:\n            for i in v[1:]:\n                s += f\"|{i}.+\"\n        self.prefix = re.compile(s, re.I)\n\n    def check(self, number):\n        if self.prefix is None:\n            raise ValueError('No init re compile')\n        return self.prefix.match(number)\n\n\nG_cache_uncensored_conf = Cache_uncensored_conf()\n\n\n# ========================================================================是否为无码\ndef is_uncensored(number) -> bool:\n    if re.match(\n            r'[\\d-]{4,}|\\d{6}_\\d{2,3}|(cz|gedo|k|n|red-|se)\\d{2,4}|heyzo.+|xxx-av-.+|heydouga-.+|x-art\\.\\d{2}\\.\\d{2}\\.\\d{2}',\n            number,\n            re.I\n    ):\n        return True\n    if G_cache_uncensored_conf.is_empty():\n        G_cache_uncensored_conf.set(config.getInstance().get_uncensored().split(','))\n    return bool(G_cache_uncensored_conf.check(number))\n\n\nif __name__ == \"__main__\":\n    #     import doctest\n    #     doctest.testmod(raise_on_error=True)\n    test_use_cases = (\n        \"ABC-123-C.mp4\",\n    )\n\n\n    def evprint(evstr):\n        code = compile(evstr, \"<string>\", \"eval\")\n        print(\"{1:>20} # '{0}'\".format(evstr[18:-2], eval(code)))\n\n\n    for t in test_use_cases:\n        evprint(f'get_number(True, \"{t}\")')\n\n    if len(sys.argv) <= 1 or not re.search('^[A-Z]:?', sys.argv[1], re.IGNORECASE):\n        sys.exit(0)\n\n    # 使用Everything的ES命令行工具搜集全盘视频文件名作为用例测试number数据，参数为盘符 A .. Z 或带盘符路径\n    # https://www.voidtools.com/support/everything/command_line_interface/\n    # ES命令行工具需要Everything文件搜索引擎处于运行状态，es.exe单个执行文件需放入PATH路径中。\n    # Everything是免费软件\n    # 示例：\n    # python.exe .\\number_parser.py ALL                 # 从所有磁盘搜索视频\n    # python.exe .\\number_parser.py D                   # 从D盘搜索\n    # python.exe .\\number_parser.py D:                  # 同上\n    # python.exe .\\number_parser.py D:\\download\\JAVs    # 搜索D盘的\\download\\JAVs目录，路径必须带盘符\n    # ==================\n    # Linux/WSL1|2 使用mlocate(Ubuntu/Debian)或plocate(Debian sid)搜集全盘视频文件名作为测试用例number数据\n    # 需安装'sudo apt install mlocate或plocate'并首次运行sudo updatedb建立全盘索引\n    # MAC OS X 使用findutils的glocate，需安装'sudo brew install findutils'并首次运行sudo gupdatedb建立全盘索引\n    # 示例：\n    # python3 ./number_parser.py ALL\n    import subprocess\n\n    ES_search_path = \"ALL disks\"\n    if sys.argv[1] == \"ALL\":\n        if sys.platform == \"win32\":\n            # ES_prog_path = 'C:/greensoft/es/es.exe'\n            ES_prog_path = 'es.exe'  # es.exe需要放在PATH环境变量的路径之内\n            ES_cmdline = f'{ES_prog_path} -name size:gigantic ext:mp4;avi;rmvb;wmv;mov;mkv;flv;ts;webm;iso;mpg;m4v'\n            out_bytes = subprocess.check_output(ES_cmdline.split(' '))\n            out_text = out_bytes.decode('gb18030')  # 中文版windows 10 x64默认输出GB18030，此编码为UNICODE方言与UTF-8系全射关系无转码损失\n            out_list = out_text.splitlines()\n        elif sys.platform in (\"linux\", \"darwin\"):\n            ES_prog_path = 'locate' if sys.platform == 'linux' else 'glocate'\n            ES_cmdline = r\"{} -b -i --regex '\\.mp4$|\\.avi$|\\.rmvb$|\\.wmv$|\\.mov$|\\.mkv$|\\.webm$|\\.iso$|\\.mpg$|\\.m4v$'\".format(\n                ES_prog_path)\n            out_bytes = subprocess.check_output(ES_cmdline.split(' '))\n            out_text = out_bytes.decode('utf-8')\n            out_list = [os.path.basename(line) for line in out_text.splitlines()]\n        else:\n            print('[-]Unsupported platform! Please run on OS Windows/Linux/MacOSX. Exit.')\n            sys.exit(1)\n    else:  # Windows single disk\n        if sys.platform != \"win32\":\n            print('[!]Usage: python3 ./number_parser.py ALL')\n            sys.exit(0)\n        # ES_prog_path = 'C:/greensoft/es/es.exe'\n        ES_prog_path = 'es.exe'  # es.exe需要放在PATH环境变量的路径之内\n        if os.path.isdir(sys.argv[1]):\n            ES_search_path = sys.argv[1]\n        else:\n            ES_search_path = sys.argv[1][0] + ':/'\n            if not os.path.isdir(ES_search_path):\n                ES_search_path = 'C:/'\n            ES_search_path = os.path.normcase(ES_search_path)\n        ES_cmdline = f'{ES_prog_path} -path {ES_search_path} -name size:gigantic ext:mp4;avi;rmvb;wmv;mov;mkv;webm;iso;mpg;m4v'\n        out_bytes = subprocess.check_output(ES_cmdline.split(' '))\n        out_text = out_bytes.decode('gb18030')  # 中文版windows 10 x64默认输出GB18030，此编码为UNICODE方言与UTF-8系全射关系无转码损失\n        out_list = out_text.splitlines()\n    print(f'\\n[!]{ES_prog_path} is searching {ES_search_path} for movies as number parser test cases...')\n    print(f'[+]Find {len(out_list)} Movies.')\n    for filename in out_list:\n        try:\n            n = get_number(True, filename)\n            if n:\n                print('  [{0}] {2}# {1}'.format(n, filename, '#无码' if is_uncensored(n) else ''))\n            else:\n                print(f'[-]Number return None. # {filename}')\n        except Exception as e:\n            print(f'[-]Number Parser exception: {e} [{filename}]')\n\n    sys.exit(0)\n"
  },
  {
    "path": "py_to_exe.ps1",
    "content": "# If you can't run this script, please execute the following command in PowerShell.\r\n# Set-ExecutionPolicy RemoteSigned -Scope CurrentUser -Force\r\n\r\n$CLOUDSCRAPER_PATH = $( python -c 'import cloudscraper as _; print(_.__path__[0])' | select -Last 1 )\r\n$OPENCC_PATH = $( python -c 'import opencc as _; print(_.__path__[0])' | select -Last 1 )\r\n$FACE_RECOGNITION_MODELS = $( python -c 'import face_recognition_models as _; print(_.__path__[0])' | select -Last 1 )\r\n\r\nmkdir build\r\nmkdir __pycache__\r\n\r\npyinstaller --onefile Movie_Data_Capture.py `\r\n    --hidden-import \"ImageProcessing.cnn\" `\r\n    --python-option u `\r\n    --add-data \"$FACE_RECOGNITION_MODELS;face_recognition_models\" `\r\n    --add-data \"$CLOUDSCRAPER_PATH;cloudscraper\" `\r\n    --add-data \"$OPENCC_PATH;opencc\" `\r\n    --add-data \"Img;Img\" `\r\n    --add-data \"config.ini;.\" `\r\n    --add-data \"scrapinglib;scrapinglib\" `\r\n\r\nrmdir -Recurse -Force build\r\nrmdir -Recurse -Force __pycache__\r\nrmdir -Recurse -Force Movie_Data_Capture.spec\r\n\r\necho \"[Make]Finish\"\r\npause"
  },
  {
    "path": "requirements.txt",
    "content": "requests\ndlib-bin\nClick\nnumpy\nface-recognition-models\nlxml\nbeautifulsoup4\npillow==10.3.0\ncloudscraper\npysocks==1.7.1\nurllib3==1.26.19\ncertifi\nMechanicalSoup\nopencc-python-reimplemented\n"
  },
  {
    "path": "scraper.py",
    "content": "# build-in lib\nimport json\nimport secrets\nimport typing\nfrom pathlib import Path\n\n# third party lib\nimport opencc\nfrom lxml import etree\n# project wide definitions\nimport config\nfrom ADC_function import (translate,\n                          load_cookies,\n                          file_modification_days,\n                          delete_all_elements_in_str,\n                          delete_all_elements_in_list\n                          )\nfrom scrapinglib.api import search\n\n\ndef get_data_from_json(\n        file_number: str,\n        open_cc: opencc.OpenCC,\n        specified_source: str, specified_url: str) -> typing.Optional[dict]:\n    \"\"\"\n    iterate through all services and fetch the data 从网站上查询片名解析JSON返回元数据\n    :param file_number: 影片名称\n    :param open_cc: 简繁转换器\n    :param specified_source: 指定的媒体数据源\n    :param specified_url: 指定的数据查询地址, 目前未使用\n    :return 给定影片名称的具体信息\n    \"\"\"\n    try:\n        actor_mapping_data = etree.parse(str(Path.home() / '.local' / 'share' / 'mdc' / 'mapping_actor.xml'))\n        info_mapping_data = etree.parse(str(Path.home() / '.local' / 'share' / 'mdc' / 'mapping_info.xml'))\n    except:\n        actor_mapping_data = etree.fromstring(\"<html></html>\", etree.HTMLParser())\n        info_mapping_data = etree.fromstring(\"<html></html>\", etree.HTMLParser())\n\n    conf = config.getInstance()\n    # default fetch order list, from the beginning to the end\n    sources = conf.sources()\n\n    # TODO 准备参数\n    # - 清理 ADC_function, webcrawler\n    proxies: dict = None\n    config_proxy = conf.proxy()\n    if config_proxy.enable:\n        proxies = config_proxy.proxies()\n\n    ca_cert = None\n    if conf.cacert_file():\n        ca_cert = conf.cacert_file()\n\n    json_data = search(file_number, sources, proxies=proxies, verify=ca_cert,\n                        morestoryline=conf.is_storyline(),\n                        specifiedSource=specified_source, specifiedUrl=specified_url,\n                        debug = conf.debug())\n    # Return if data not found in all sources\n    if not json_data:\n        print('[-]Movie Number not found!')\n        return None\n\n    # 增加number严格判断，避免提交任何number\n    if str(json_data.get('number')).upper() != file_number.upper():\n        try:\n            if json_data.get('allow_number_change'):\n                pass\n        except:\n            print('[-]Movie number has changed! [{}]->[{}]'.format(file_number, str(json_data.get('number'))))\n            return None\n\n    # ================================================网站规则添加结束================================================\n\n    if json_data.get('title') == '':\n        print('[-]Movie Number or Title not found!')\n        return None\n\n    title = json_data.get('title')\n    actor_list = str(json_data.get('actor')).strip(\"[ ]\").replace(\"'\", '').split(',')  # 字符串转列表\n    actor_list = [actor.strip() for actor in actor_list]  # 去除空白\n    director = json_data.get('director')\n    release = json_data.get('release')\n    number = json_data.get('number')\n    studio = json_data.get('studio')\n    source = json_data.get('source')\n    runtime = json_data.get('runtime')\n    outline = json_data.get('outline')\n    label = json_data.get('label')\n    series = json_data.get('series')\n    year = json_data.get('year')\n\n    if json_data.get('cover_small'):\n        cover_small = json_data.get('cover_small')\n    else:\n        cover_small = ''\n\n    if json_data.get('trailer'):\n        trailer = json_data.get('trailer')\n    else:\n        trailer = ''\n\n    if json_data.get('extrafanart'):\n        extrafanart = json_data.get('extrafanart')\n    else:\n        extrafanart = ''\n\n    imagecut = json_data.get('imagecut')\n    tag = str(json_data.get('tag')).strip(\"[ ]\").replace(\"'\", '').replace(\" \", '').split(',')  # 字符串转列表 @\n    while 'XXXX' in tag:\n        tag.remove('XXXX')\n    while 'xxx' in tag:\n        tag.remove('xxx')\n    actor = str(actor_list).strip(\"[ ]\").replace(\"'\", '').replace(\" \", '')\n\n    # if imagecut == '3':\n    #     DownloadFileWithFilename()\n\n    # ====================处理异常字符====================== #\\/:*?\"<>|\n    actor = special_characters_replacement(actor)\n    actor_list = [special_characters_replacement(a) for a in actor_list]\n    title = special_characters_replacement(title)\n    label = special_characters_replacement(label)\n    outline = special_characters_replacement(outline)\n    series = special_characters_replacement(series)\n    studio = special_characters_replacement(studio)\n    director = special_characters_replacement(director)\n    tag = [special_characters_replacement(t) for t in tag]\n    release = release.replace('/', '-')\n    tmpArr = cover_small.split(',')\n    if len(tmpArr) > 0:\n        cover_small = tmpArr[0].strip('\\\"').strip('\\'')\n    # ====================处理异常字符 END================== #\\/:*?\"<>|\n\n    # 处理大写\n    if conf.number_uppercase():\n        json_data['number'] = number.upper()\n\n    # 返回处理后的json_data\n    json_data['title'] = title\n    json_data['original_title'] = title\n    json_data['actor'] = actor\n    json_data['release'] = release\n    json_data['cover_small'] = cover_small\n    json_data['tag'] = tag\n    json_data['year'] = year\n    json_data['actor_list'] = actor_list\n    json_data['trailer'] = trailer\n    json_data['extrafanart'] = extrafanart\n    json_data['label'] = label\n    json_data['outline'] = outline\n    json_data['series'] = series\n    json_data['studio'] = studio\n    json_data['director'] = director\n\n    if conf.is_translate():\n        translate_values = conf.translate_values().split(\",\")\n        for translate_value in translate_values:\n            if json_data[translate_value] == \"\":\n                continue\n            if conf.get_translate_engine() == \"azure\":\n                t = translate(\n                    json_data[translate_value],\n                    target_language=\"zh-Hans\",\n                    engine=conf.get_translate_engine(),\n                    key=conf.get_translate_key(),\n                )\n            else:\n                if len(json_data[translate_value]):\n                    if type(json_data[translate_value]) == str:\n                        json_data[translate_value] = special_characters_replacement(json_data[translate_value])\n                        json_data[translate_value] = translate(json_data[translate_value])\n                    else:\n                        for i in range(len(json_data[translate_value])):\n                            json_data[translate_value][i] = special_characters_replacement(\n                                json_data[translate_value][i])\n                        list_in_str = \",\".join(json_data[translate_value])\n                        json_data[translate_value] = translate(list_in_str).split(',')\n\n    if open_cc:\n        cc_vars = conf.cc_convert_vars().split(\",\")\n        ccm = conf.cc_convert_mode()\n\n        def convert_list(mapping_data, language, vars):\n            total = []\n            for i in vars:\n                if len(mapping_data.xpath('a[contains(@keyword, $name)]/@' + language, name=f\",{i},\")) != 0:\n                    i = mapping_data.xpath('a[contains(@keyword, $name)]/@' + language, name=f\",{i},\")[0]\n                total.append(i)\n            return total\n\n        def convert(mapping_data, language, vars):\n            if len(mapping_data.xpath('a[contains(@keyword, $name)]/@' + language, name=vars)) != 0:\n                return mapping_data.xpath('a[contains(@keyword, $name)]/@' + language, name=vars)[0]\n            else:\n                raise IndexError('keyword not found')\n\n        for cc in cc_vars:\n            if json_data[cc] == \"\" or len(json_data[cc]) == 0:\n                continue\n            try:\n                if ccm == 1:\n                    json_data[cc] = convert(info_mapping_data, \"zh_cn\", json_data[cc])\n                    json_data[cc] = delete_all_elements_in_str(\"删除\", json_data[cc])\n                elif ccm == 2:\n                    json_data[cc] = convert(info_mapping_data, \"zh_tw\", json_data[cc])\n                    json_data[cc] = delete_all_elements_in_str(\"删除\", json_data[cc])\n                elif ccm == 3:\n                    json_data[cc] = convert(info_mapping_data, \"jp\", json_data[cc])\n                    json_data[cc] = delete_all_elements_in_str(\"删除\", json_data[cc])\n            except IndexError:\n                json_data[cc] = open_cc.convert(json_data[cc])\n            except:\n                pass\n\n    naming_rule = \"\"\n    original_naming_rule = \"\"\n    for i in conf.naming_rule().split(\"+\"):\n        if i not in json_data:\n            naming_rule += i.strip(\"'\").strip('\"')\n            original_naming_rule += i.strip(\"'\").strip('\"')\n        else:\n            item = json_data.get(i)\n            naming_rule += item if type(item) is not list else \"&\".join(item)\n            # PATCH：处理[title]存在翻译的情况，后续NFO文件的original_name只会直接沿用naming_rule,这导致original_name非原始名\n            # 理应在翻译处处理 naming_rule和original_naming_rule\n            if i == 'title':\n                item = json_data.get('original_title')\n            original_naming_rule += item if type(item) is not list else \"&\".join(item)\n\n    json_data['naming_rule'] = naming_rule\n    json_data['original_naming_rule'] = original_naming_rule\n    return json_data\n\n\ndef special_characters_replacement(text) -> str:\n    if not isinstance(text, str):\n        return text\n    return (text.replace('\\\\', '∖').  # U+2216 SET MINUS @ Basic Multilingual Plane\n            replace('/', '∕').  # U+2215 DIVISION SLASH @ Basic Multilingual Plane\n            replace(':', '꞉').  # U+A789 MODIFIER LETTER COLON @ Latin Extended-D\n            replace('*', '∗').  # U+2217 ASTERISK OPERATOR @ Basic Multilingual Plane\n            replace('?', '？').  # U+FF1F FULLWIDTH QUESTION MARK @ Basic Multilingual Plane\n            replace('\"', '＂').  # U+FF02 FULLWIDTH QUOTATION MARK @ Basic Multilingual Plane\n            replace('<', 'ᐸ').  # U+1438 CANADIAN SYLLABICS PA @ Basic Multilingual Plane\n            replace('>', 'ᐳ').  # U+1433 CANADIAN SYLLABICS PO @ Basic Multilingual Plane\n            replace('|', 'ǀ').  # U+01C0 LATIN LETTER DENTAL CLICK @ Basic Multilingual Plane\n            replace('&lsquo;', '‘').  # U+02018 LEFT SINGLE QUOTATION MARK\n            replace('&rsquo;', '’').  # U+02019 RIGHT SINGLE QUOTATION MARK\n            replace('&hellip;', '…').\n            replace('&amp;', '＆').\n            replace(\"&\", '＆')\n            )\n"
  },
  {
    "path": "scrapinglib/__init__.py",
    "content": "# -*- coding: utf-8 -*-\nfrom .api import search, getSupportedSources"
  },
  {
    "path": "scrapinglib/api.py",
    "content": "# -*- coding: utf-8 -*-\n\nimport re\nimport json\nfrom .parser import Parser\nimport config\nimport importlib\n\n\ndef search(number, sources: str = None, **kwargs):\n    \"\"\" 根据`电影`名搜索信息\n\n    :param number: number/name  depends on type\n    :param sources: sources string with `,` Eg: ``\n    :param type: `adult`, `general`\n    \"\"\"\n    sc = Scraping()\n    return sc.search(number, sources, **kwargs)\n\n\ndef getSupportedSources():\n    \"\"\"\n    :param tag: `adult`, `general`\n    \"\"\"\n    sc = Scraping()\n    return ','.join(sc.general_full_sources)\n\n\nclass Scraping:\n    \"\"\"\n    \"\"\"\n    adult_full_sources = []\n\n    general_full_sources = ['tmdb', 'imdb']\n\n    debug = False\n\n    proxies = None\n    verify = None\n    specifiedSource = None\n    specifiedUrl = None\n\n    dbcookies = None\n    dbsite = None\n    # 使用storyline方法进一步获取故事情节\n    morestoryline = False\n\n    def search(self, number, sources=None, proxies=None, verify=None, type='adult',\n               specifiedSource=None, specifiedUrl=None,\n               dbcookies=None, dbsite=None, morestoryline=False,\n               debug=False):\n        self.debug = debug\n        self.proxies = proxies\n        self.verify = verify\n        self.specifiedSource = specifiedSource\n        self.specifiedUrl = specifiedUrl\n        self.dbcookies = dbcookies\n        self.dbsite = dbsite\n        self.morestoryline = morestoryline\n        if type == 'adult':\n            return self.searchAdult(number, sources)\n        else:\n            return self.searchGeneral(number, sources)\n\n    def searchGeneral(self, name, sources):\n        \"\"\" 查询电影电视剧\n        imdb,tmdb\n        \"\"\"\n        if self.specifiedSource:\n            sources = [self.specifiedSource]\n        else:\n            sources = self.checkGeneralSources(sources, name)\n        json_data = {}\n        for source in sources:\n            try:\n                if self.debug:\n                    print('[+]select', source)\n                try:\n                    module = importlib.import_module('.' + source, 'scrapinglib')\n                    parser_type = getattr(module, source.capitalize())\n                    parser: Parser = parser_type()\n                    data = parser.scrape(name, self)\n                    if data == 404:\n                        continue\n                    json_data = json.loads(data)\n                except Exception as e:\n                    if config.getInstance().debug():\n                        print(e)\n                # if any service return a valid return, break\n                if self.get_data_state(json_data):\n                    if self.debug:\n                        print(f\"[+]Find movie [{name}] metadata on website '{source}'\")\n                    break\n            except:\n                continue\n\n        # Return if data not found in all sources\n        if not json_data or json_data['title'] == \"\":\n            return None\n\n        # If actor is anonymous, Fill in Anonymous\n        if len(json_data['actor']) == 0:\n            if config.getInstance().anonymous_fill() == True:\n                if \"zh_\" in config.getInstance().get_target_language() or \"ZH\" in config.getInstance().get_target_language():\n                    json_data['actor'] = \"佚名\"\n                else:\n                    json_data['actor'] = \"Anonymous\"\n\n        return json_data\n\n    def searchAdult(self, number, sources):\n        if self.specifiedSource:\n            sources = [self.specifiedSource]\n        elif type(sources) is list:\n            pass\n        else:\n            sources = self.checkAdultSources(sources, number)\n        json_data = {}\n        for source in sources:\n            try:\n                if self.debug:\n                    print('[+]select', source)\n                try:\n                    module = importlib.import_module('.' + source, 'scrapinglib')\n                    parser_type = getattr(module, source.capitalize())\n                    parser: Parser = parser_type()\n                    data = parser.scrape(number, self)\n                    if data == 404:\n                        continue\n                    json_data = json.loads(data)\n                except Exception as e:\n                    if config.getInstance().debug():\n                        print(e)\n                    # json_data = self.func_mapping[source](number, self)\n                # if any service return a valid return, break\n                if self.get_data_state(json_data):\n                    if self.debug:\n                        print(f\"[+]Find movie [{number}] metadata on website '{source}'\")\n                    break\n            except:\n                continue\n\n        # Return if data not found in all sources\n        if not json_data or json_data['title'] == \"\":\n            return None\n\n        # If actor is anonymous, Fill in Anonymous\n        if len(json_data['actor']) == 0:\n            if config.getInstance().anonymous_fill() == True:\n                if \"zh_\" in config.getInstance().get_target_language() or \"ZH\" in config.getInstance().get_target_language():\n                    json_data['actor'] = \"佚名\"\n                else:\n                    json_data['actor'] = \"Anonymous\"\n\n        return json_data\n\n    def checkGeneralSources(self, c_sources, name):\n        if not c_sources:\n            sources = self.general_full_sources\n        else:\n            sources = c_sources.split(',')\n\n        # check sources in func_mapping\n        todel = []\n        for s in sources:\n            if not s in self.general_full_sources:\n                print('[!] Source Not Exist : ' + s)\n                todel.append(s)\n        for d in todel:\n            print('[!] Remove Source : ' + s)\n            sources.remove(d)\n        return sources\n\n    def checkAdultSources(self, c_sources, file_number):\n        if not c_sources:\n            sources = self.adult_full_sources\n        else:\n            sources = c_sources.split(',')\n\n        def insert(sources, source):\n            if source in sources:\n                sources.insert(0, sources.pop(sources.index(source)))\n            return sources\n\n        # check sources in func_mapping\n        todel = []\n        for s in sources:\n            if not s in self.adult_full_sources and config.getInstance().debug():\n                print('[!] Source Not Exist : ' + s)\n                todel.append(s)\n        for d in todel:\n            if config.getInstance().debug():\n                print('[!] Remove Source : ' + d)\n            sources.remove(d)\n        return sources\n\n    def get_data_state(self, data: dict) -> bool:  # 元数据获取失败检测\n        if \"title\" not in data or \"number\" not in data:\n            return False\n        if data[\"title\"] is None or data[\"title\"] == \"\" or data[\"title\"] == \"null\":\n            return False\n        if data[\"number\"] is None or data[\"number\"] == \"\" or data[\"number\"] == \"null\":\n            return False\n        if (data[\"cover\"] is None or data[\"cover\"] == \"\" or data[\"cover\"] == \"null\") \\\n                and (data[\"cover_small\"] is None or data[\"cover_small\"] == \"\" or\n                     data[\"cover_small\"] == \"null\"):\n            return False\n        return True"
  },
  {
    "path": "scrapinglib/httprequest.py",
    "content": "# -*- coding: utf-8 -*-\n\nimport mechanicalsoup\nimport requests\nfrom requests.adapters import HTTPAdapter\nfrom urllib3.util.retry import Retry\nfrom cloudscraper import create_scraper\n\nimport config\n\nG_USER_AGENT = r'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.133 Safari/537.36'\nG_DEFAULT_TIMEOUT = 10\n\n\ndef get(url: str, cookies=None, ua: str = None, extra_headers=None, return_type: str = None, encoding: str = None,\n        retry: int = 3, timeout: int = G_DEFAULT_TIMEOUT, proxies=None, verify=None):\n    \"\"\"\n    网页请求核心函数\n\n    是否使用代理应由上层处理\n    \"\"\"\n    errors = \"\"\n    headers = {\"User-Agent\": ua or G_USER_AGENT}\n    if extra_headers != None:\n        headers.update(extra_headers)\n    for i in range(retry):\n        try:\n            result = requests.get(url, headers=headers, timeout=timeout, proxies=proxies,\n                                  verify=verify, cookies=cookies)\n            if return_type == \"object\":\n                return result\n            elif return_type == \"content\":\n                return result.content\n            else:\n                result.encoding = encoding or result.apparent_encoding\n                return result.text\n        except Exception as e:\n            if config.getInstance().debug():\n                print(f\"[-]Connect: {url} retry {i + 1}/{retry}\")\n            errors = str(e)\n    if config.getInstance().debug():\n        if \"getaddrinfo failed\" in errors:\n            print(\"[-]Connect Failed! Please Check your proxy config\")\n            print(\"[-]\" + errors)\n        else:\n            print(\"[-]\" + errors)\n            print('[-]Connect Failed! Please check your Proxy or Network!')\n    raise Exception('Connect Failed')\n\n\ndef post(url: str, data: dict=None, files=None, cookies=None, ua: str=None, return_type: str=None, encoding: str=None,\n         retry: int=3, timeout: int=G_DEFAULT_TIMEOUT, proxies=None, verify=None):\n    \"\"\"\n    是否使用代理应由上层处理\n    \"\"\"\n    errors = \"\"\n    headers = {\"User-Agent\": ua or G_USER_AGENT}\n\n    for i in range(retry):\n        try:\n            result = requests.post(url, data=data, files=files, headers=headers, timeout=timeout, proxies=proxies,\n                                   verify=verify, cookies=cookies)\n            if return_type == \"object\":\n                return result\n            elif return_type == \"content\":\n                return result.content\n            else:\n                result.encoding = encoding or result.apparent_encoding\n                return result\n        except Exception as e:\n            if config.getInstance().debug():\n                print(f\"[-]Connect: {url} retry {i + 1}/{retry}\")\n            errors = str(e)\n        if config.getInstance().debug():\n            if \"getaddrinfo failed\" in errors:\n                print(\"[-]Connect Failed! Please Check your proxy config\")\n                print(\"[-]\" + errors)\n            else:\n                print(\"[-]\" + errors)\n                print('[-]Connect Failed! Please check your Proxy or Network!')\n        raise Exception('Connect Failed')\n\n\nclass TimeoutHTTPAdapter(HTTPAdapter):\n    def __init__(self, *args, **kwargs):\n        self.timeout = G_DEFAULT_TIMEOUT\n        if \"timeout\" in kwargs:\n            self.timeout = kwargs[\"timeout\"]\n            del kwargs[\"timeout\"]\n        super().__init__(*args, **kwargs)\n\n    def send(self, request, **kwargs):\n        timeout = kwargs.get(\"timeout\")\n        if timeout is None:\n            kwargs[\"timeout\"] = self.timeout\n        return super().send(request, **kwargs)\n\n\ndef request_session(cookies=None, ua: str=None, retry: int=3, timeout: int=G_DEFAULT_TIMEOUT, proxies=None, verify=None):\n    \"\"\"\n    keep-alive\n    \"\"\"\n    session = requests.Session()\n    retries = Retry(total=retry, connect=retry, backoff_factor=1,\n                    status_forcelist=[429, 500, 502, 503, 504])\n    session.mount(\"https://\", TimeoutHTTPAdapter(max_retries=retries, timeout=timeout))\n    session.mount(\"http://\", TimeoutHTTPAdapter(max_retries=retries, timeout=timeout))\n    if isinstance(cookies, dict) and len(cookies):\n        requests.utils.add_dict_to_cookiejar(session.cookies, cookies)\n    if verify:\n        session.verify = verify\n    if proxies:\n        session.proxies = proxies\n    session.headers = {\"User-Agent\": ua or G_USER_AGENT}\n    return session\n\n\n# storyline xcity only\ndef get_html_by_form(url, form_select: str = None, fields: dict = None, cookies: dict = None, ua: str = None,\n                     return_type: str = None, encoding: str = None,\n                     retry: int = 3, timeout: int = G_DEFAULT_TIMEOUT, proxies=None, verify=None):\n    session = requests.Session()\n    if isinstance(cookies, dict) and len(cookies):\n        requests.utils.add_dict_to_cookiejar(session.cookies, cookies)\n    retries = Retry(total=retry, connect=retry, backoff_factor=1,\n                    status_forcelist=[429, 500, 502, 503, 504])\n    session.mount(\"https://\", TimeoutHTTPAdapter(max_retries=retries, timeout=timeout))\n    session.mount(\"http://\", TimeoutHTTPAdapter(max_retries=retries, timeout=timeout))\n    if verify:\n        session.verify = verify\n    if proxies:\n        session.proxies = proxies\n    try:\n        browser = mechanicalsoup.StatefulBrowser(user_agent=ua or G_USER_AGENT, session=session)\n        result = browser.open(url)\n        if not result.ok:\n            return None\n        form = browser.select_form() if form_select is None else browser.select_form(form_select)\n        if isinstance(fields, dict):\n            for k, v in fields.items():\n                browser[k] = v\n        response = browser.submit_selected()\n\n        if return_type == \"object\":\n            return response\n        elif return_type == \"content\":\n            return response.content\n        elif return_type == \"browser\":\n            return response, browser\n        else:\n            result.encoding = encoding or \"utf-8\"\n            return response.text\n    except requests.exceptions.ProxyError:\n        print(\"[-]get_html_by_form() Proxy error! Please check your Proxy\")\n    except Exception as e:\n        print(f'[-]get_html_by_form() Failed! {e}')\n    return None\n\n# storyline javdb only\ndef get_html_by_scraper(url: str = None, cookies: dict = None, ua: str = None, return_type: str = None,\n                        encoding: str = None, retry: int = 3, proxies=None, timeout: int = G_DEFAULT_TIMEOUT, verify=None):\n    session = create_scraper(browser={'custom': ua or G_USER_AGENT, })\n    if isinstance(cookies, dict) and len(cookies):\n        requests.utils.add_dict_to_cookiejar(session.cookies, cookies)\n    retries = Retry(total=retry, connect=retry, backoff_factor=1,\n                    status_forcelist=[429, 500, 502, 503, 504])\n    session.mount(\"https://\", TimeoutHTTPAdapter(max_retries=retries, timeout=timeout))\n    session.mount(\"http://\", TimeoutHTTPAdapter(max_retries=retries, timeout=timeout))\n    if verify:\n        session.verify = verify\n    if proxies:\n        session.proxies = proxies\n    try:\n        if isinstance(url, str) and len(url):\n            result = session.get(str(url))\n        else:  # 空url参数直接返回可重用scraper对象，无需设置return_type\n            return session\n        if not result.ok:\n            return None\n        if return_type == \"object\":\n            return result\n        elif return_type == \"content\":\n            return result.content\n        elif return_type == \"scraper\":\n            return result, session\n        else:\n            result.encoding = encoding or \"utf-8\"\n            return result.text\n    except requests.exceptions.ProxyError:\n        print(\"[-]get_html_by_scraper() Proxy error! Please check your Proxy\")\n    except Exception as e:\n        print(f\"[-]get_html_by_scraper() failed. {e}\")\n    return None\n"
  },
  {
    "path": "scrapinglib/imdb.py",
    "content": "# -*- coding: utf-8 -*-\n\n\nfrom .parser import Parser\n\n\nclass Imdb(Parser):\n    source = 'imdb'\n    imagecut = 0\n\n    expr_title = '//h1[@data-testid=\"hero-title-block__title\"]/text()'\n    expr_release = '//a[contains(text(),\"Release date\")]/following-sibling::div[1]/ul/li/a/text()'\n    expr_cover = '//head/meta[@property=\"og:image\"]/@content'\n    expr_outline = '//head/meta[@property=\"og:description\"]/@content'\n    expr_actor = '//h3[contains(text(),\"Top cast\")]/../../../following-sibling::div[1]/div[2]/div/div/a/text()'\n    expr_tags = '//div[@data-testid=\"genres\"]/div[2]/a/ul/li/text()'\n\n    def queryNumberUrl(self, number):\n        \"\"\"\n        TODO 区分 ID 与 名称\n        \"\"\"\n        id  = number\n        movieUrl = \"https://www.imdb.com/title/\" + id\n        return movieUrl\n"
  },
  {
    "path": "scrapinglib/parser.py",
    "content": "# -*- coding: utf-8 -*-\n\nimport json\nimport re\nfrom lxml import etree, html\n\nimport config\nfrom . import httprequest\nfrom .utils import getTreeElement, getTreeAll\n\nclass Parser:\n    \"\"\" 基础刮削类\n    \"\"\"\n    source = 'base'\n    # xpath expr\n    expr_number = ''\n    expr_title = ''\n    expr_studio = ''\n    expr_studio2 = ''\n    expr_runtime = ''\n    expr_runtime2 = ''\n    expr_release = ''\n    expr_outline = ''\n    expr_director = ''\n    expr_actor = ''\n    expr_tags = ''\n    expr_label = ''\n    expr_label2 = ''\n    expr_series = ''\n    expr_series2 = ''\n    expr_cover = ''\n    expr_cover2 = ''\n    expr_smallcover = ''\n    expr_extrafanart = ''\n    expr_trailer = ''\n    expr_actorphoto = ''\n    expr_uncensored = ''\n    expr_userrating = ''\n    expr_uservotes = ''\n\n    def init(self):\n        \"\"\" 初始化参数\n        \"\"\"\n        # 推荐剪切poster封面:\n        # `0` 复制cover\n        # `1` 裁剪cover \n        # `3` 下载小封面\n        self.imagecut = 1\n        self.uncensored = False\n        self.allow_number_change = False\n        # update\n        self.proxies = None\n        self.verify = None\n        self.extraheader = None\n        self.cookies = None\n        self.morestoryline = False\n        self.specifiedUrl = None\n        self.extraInit()\n\n    def extraInit(self):\n        \"\"\" 自定义初始化内容\n        \"\"\"\n        pass\n\n    def scrape(self, number, core: None):\n        \"\"\" 刮削番号\n        \"\"\"\n        # 每次调用，初始化参数\n        self.init()\n        self.updateCore(core)\n        result = self.search(number)\n        return result\n\n    def search(self, number):\n        \"\"\" 查询\n\n        查询主要流程:\n        1. 获取 url\n        2. 获取详情页面\n        3. 解析\n        4. 返回 result\n        \"\"\"\n        self.number = number\n        if self.specifiedUrl:\n            self.detailurl = self.specifiedUrl\n        else:\n            self.detailurl = self.queryNumberUrl(number)\n        if not self.detailurl:\n            return 404\n        htmltree = self.getHtmlTree(self.detailurl)\n        result = self.dictformat(htmltree)\n        return result\n\n    def updateCore(self, core):\n        \"\"\" 从`core`内更新参数\n        \n        针对需要传递的参数: cookies, proxy等\n        子类继承后修改\n        \"\"\"\n        if not core:\n            return\n        if core.proxies:\n            self.proxies = core.proxies\n        if core.verify:\n            self.verify = core.verify\n        if core.morestoryline:\n            self.morestoryline = True\n        if core.specifiedSource == self.source:\n            self.specifiedUrl = core.specifiedUrl\n\n    def queryNumberUrl(self, number):\n        \"\"\" 根据号码查询详细信息url\n        \n        需要针对不同站点修改,或者在上层直接获取\n        备份查询页面,预览图可能需要\n        \"\"\"\n        url = \"http://detailurl.ai/\" + number\n        return url\n\n    def getHtml(self, url, type = None):\n        \"\"\" 访问网页\n        \"\"\"\n        resp = httprequest.get(url, cookies=self.cookies, proxies=self.proxies, extra_headers=self.extraheader, verify=self.verify, return_type=type)\n        if '<title>404 Page Not Found' in resp \\\n            or '<title>未找到页面' in resp \\\n            or '404 Not Found' in resp \\\n            or '<title>404' in resp \\\n            or '<title>お探しの商品が見つかりません' in resp:\n            return 404\n        return resp\n\n    def getHtmlTree(self, url, type = None):\n        \"\"\" 访问网页,返回`etree`\n        \"\"\"\n        resp = self.getHtml(url, type)\n        if resp == 404:\n            return 404\n        ret = etree.fromstring(resp, etree.HTMLParser())\n        return ret\n\n    def dictformat(self, htmltree):\n        try:\n            dic = {\n                'number': self.getNum(htmltree),\n                'title': self.getTitle(htmltree),\n                'studio': self.getStudio(htmltree),\n                'release': self.getRelease(htmltree),\n                'year': self.getYear(htmltree),\n                'outline': self.getOutline(htmltree),\n                'runtime': self.getRuntime(htmltree),\n                'director': self.getDirector(htmltree),\n                'actor': self.getActors(htmltree),\n                'actor_photo': self.getActorPhoto(htmltree),\n                'cover': self.getCover(htmltree),\n                'cover_small': self.getSmallCover(htmltree),\n                'extrafanart': self.getExtrafanart(htmltree),\n                'trailer': self.getTrailer(htmltree),\n                'tag': self.getTags(htmltree),\n                'label': self.getLabel(htmltree),\n                'series': self.getSeries(htmltree),\n                'userrating': self.getUserRating(htmltree),\n                'uservotes': self.getUserVotes(htmltree),\n                'uncensored': self.getUncensored(htmltree),\n                'website': self.detailurl,\n                'source': self.source,\n                'imagecut': self.getImagecut(htmltree),\n            }\n            dic = self.extradict(dic)\n        except Exception as e:\n            if config.getInstance().debug():\n                print(e)\n            dic = {\"title\": \"\"}\n        js = json.dumps(dic, ensure_ascii=False, sort_keys=True, separators=(',', ':'))\n        return js\n\n    def extradict(self, dic:dict):\n        \"\"\" 额外修改dict\n        \"\"\"\n        return dic\n\n    def getNum(self, htmltree):\n        \"\"\" 增加 strip 过滤\n        \"\"\"\n        return self.getTreeElement(htmltree, self.expr_number)\n\n    def getTitle(self, htmltree):\n        return self.getTreeElement(htmltree, self.expr_title).strip()\n\n    def getRelease(self, htmltree):\n        return self.getTreeElement(htmltree, self.expr_release).strip().replace('/','-')\n\n    def getYear(self, htmltree):\n        \"\"\" year基本都是从release中解析的\n        \"\"\"\n        try:\n            release = self.getRelease(htmltree)\n            return str(re.findall('\\d{4}', release)).strip(\" ['']\")\n        except:\n            return release\n\n    def getRuntime(self, htmltree):\n        return self.getTreeElementbyExprs(htmltree, self.expr_runtime, self.expr_runtime2).strip().rstrip('mi')\n\n    def getOutline(self, htmltree):\n        return self.getTreeElement(htmltree, self.expr_outline).strip()\n\n    def getDirector(self, htmltree):\n        return self.getTreeElement(htmltree, self.expr_director).strip()\n\n    def getActors(self, htmltree) -> list:\n        return self.getTreeAll(htmltree, self.expr_actor)\n\n    def getTags(self, htmltree) -> list:\n        alls = self.getTreeAll(htmltree, self.expr_tags)\n        tags = []\n        for t in alls:\n            for tag in t.strip().split(','):\n                tag = tag.strip()\n                if tag:\n                    tags.append(tag)\n        return tags\n\n    def getStudio(self, htmltree):\n        return self.getTreeElementbyExprs(htmltree, self.expr_studio, self.expr_studio2)\n\n    def getLabel(self, htmltree):\n        return self.getTreeElementbyExprs(htmltree, self.expr_label, self.expr_label2)\n\n    def getSeries(self, htmltree):\n        return self.getTreeElementbyExprs(htmltree, self.expr_series, self.expr_series2)\n\n    def getCover(self, htmltree):\n        return self.getTreeElementbyExprs(htmltree, self.expr_cover, self.expr_cover2)\n\n    def getSmallCover(self, htmltree):\n        return self.getTreeElement(htmltree, self.expr_smallcover)\n\n    def getExtrafanart(self, htmltree) -> list:\n        return self.getTreeAll(htmltree, self.expr_extrafanart)\n\n    def getTrailer(self, htmltree):\n        return self.getTreeElement(htmltree, self.expr_trailer)\n\n    def getActorPhoto(self, htmltree) -> dict:\n        return {}\n\n    def getUncensored(self, htmltree) -> bool:\n        \"\"\" \n        tag:    無码 無修正 uncensored 无码\n        title:  無碼 無修正 uncensored\n        \"\"\"\n        if self.uncensored:\n            return self.uncensored\n        tags = [x.lower() for x in self.getTags(htmltree) if len(x)]\n        title = self.getTitle(htmltree)\n        if self.expr_uncensored:\n            u = self.getTreeAll(htmltree, self.expr_uncensored)\n            self.uncensored = bool(u)\n        elif '無码' in tags or '無修正' in tags or 'uncensored' in tags or '无码' in tags:\n            self.uncensored = True\n        elif '無码' in title or '無修正' in title or 'uncensored' in title.lower():\n            self.uncensored = True\n        return self.uncensored\n\n    def getImagecut(self, htmltree):\n        \"\"\" 修正 poster不裁剪cover\n        \"\"\"\n        # if self.imagecut == 1 and self.getUncensored(htmltree):\n        #     self.imagecut = 0\n        return self.imagecut\n\n    def getUserRating(self, htmltree):\n        numstrs = self.getTreeElement(htmltree, self.expr_userrating)\n        nums = re.findall('[0-9.]+', numstrs)\n        if len(nums) == 1:\n            return float(nums[0])\n        return ''\n\n    def getUserVotes(self, htmltree):\n        votestrs = self.getTreeElement(htmltree, self.expr_uservotes)\n        votes = re.findall('[0-9]+', votestrs)\n        if len(votes) == 1:\n            return int(votes[0])\n        return ''\n\n    def getTreeElement(self, tree: html.HtmlElement, expr, index=0):\n        \"\"\" 根据表达式从`xmltree`中获取匹配值,默认 index 为 0\n        \"\"\"\n        return getTreeElement(tree, expr, index)\n\n    def getTreeAll(self, tree: html.HtmlElement, expr):\n        \"\"\" 根据表达式从`xmltree`中获取全部匹配值\n        \"\"\"\n        return getTreeAll(tree, expr)\n\n    def getTreeElementbyExprs(self, tree: html.HtmlElement, expr, expr2=''):\n        \"\"\" 多个表达式获取element\n        使用内部的 getTreeElement 防止继承修改后出现问题\n        \"\"\"\n        try:\n            first = self.getTreeElement(tree, expr).strip()\n            if first:\n                return first\n            second = self.getTreeElement(tree, expr2).strip()\n            if second:\n                return second\n            return ''\n        except:\n            return ''\n\n    def getTreeAllbyExprs(self, tree: html.HtmlElement, expr, expr2=''):\n        \"\"\" 多个表达式获取所有element\n        合并并剔除重复元素\n        \"\"\"\n        try:\n            result1 = self.getTreeAll(tree, expr)\n            result2 = self.getTreeAll(tree, expr2)\n            clean = [ x.strip() for x in result1 if x.strip() and x.strip() != ',']\n            clean2 = [ x.strip() for x in result2 if x.strip() and x.strip() != ',']\n            result =  list(set(clean + clean2))\n            return result\n        except:\n            return []\n"
  },
  {
    "path": "scrapinglib/tmdb.py",
    "content": "# -*- coding: utf-8 -*-\n\n\nfrom .parser import Parser\n\n\nclass Tmdb(Parser):\n    \"\"\"\n    两种实现,带apikey与不带key\n    apikey\n    \"\"\"\n    source = 'tmdb'\n    imagecut = 0\n    apikey = None\n\n    expr_title = '//head/meta[@property=\"og:title\"]/@content'\n    expr_release = '//div/span[@class=\"release\"]/text()'\n    expr_cover = '//head/meta[@property=\"og:image\"]/@content'\n    expr_outline = '//head/meta[@property=\"og:description\"]/@content'\n\n    # def search(self, number):\n    #     self.detailurl = self.queryNumberUrl(number)\n    #     detailpage = self.getHtml(self.detailurl)\n\n    def queryNumberUrl(self, number):\n        \"\"\"\n        TODO 区分 ID 与 名称\n        \"\"\"\n        id  = number\n        movieUrl = \"https://www.themoviedb.org/movie/\" + id + \"?language=zh-CN\"\n        return movieUrl\n\n    def getCover(self, htmltree):\n        return \"https://www.themoviedb.org\" + self.getTreeElement(htmltree, self.expr_cover)\n\n"
  },
  {
    "path": "wrapper/FreeBSD.sh",
    "content": "pkg install python39 py39-requests py39-pip py39-lxml py39-pillow py39-cloudscraper py39-pysocks git zip py39-beautifulsoup448 py39-mechanicalsoup\npip install pyinstaller\npyinstaller --onefile Movie_Data_Capture.py  --hidden-import ADC_function.py --hidden-import core.py \\\n    --hidden-import \"ImageProcessing.cnn\" \\\n    --python-option u \\\n    --add-data \"$(python3.9 -c 'import cloudscraper as _; print(_.__path__[0])' | tail -n 1):cloudscraper\" \\\n    --add-data \"$(python3.9 -c 'import opencc as _; print(_.__path__[0])' | tail -n 1):opencc\" \\\n    --add-data \"$(python3.9 -c 'import face_recognition_models as _; print(_.__path__[0])' | tail -n 1):face_recognition_models\" \\\n    --add-data \"Img:Img\" \\\n    --add-data \"config.ini:.\" \\\n\ncp config.ini ./dist\n"
  },
  {
    "path": "wrapper/Linux.sh",
    "content": "#if [ '$(dpkg --print-architecture)' != 'amd64' ] || [ '$(dpkg --print-architecture)' != 'i386' ]; then\n#\tapt install python3 python3-pip git sudo libxml2-dev libxslt-dev build-essential wget nano libcmocka-dev libcmocka0 -y\n#\tapt install zlib* libjpeg-dev  -y\n\t#wget https://files.pythonhosted.org/packages/82/96/21ba3619647bac2b34b4996b2dbbea8e74a703767ce24192899d9153c058/pyinstaller-4.0.tar.gz\n\t#tar -zxvf pyinstaller-4.0.tar.gz\n\t#cd pyinstaller-4.0/bootloader\n\t#sed -i \"s/                                        '-Werror',//\" wscript\n\t#python3 ./waf distclean all\n\t#cd ../\n\t#python3 setup.py install\n\t#cd ../\n#fi\npip3 install -r requirements.txt\npip3 install cloudscraper==1.2.52\npyinstaller --onefile Movie_Data_Capture.py  --hidden-import ADC_function.py --hidden-import core.py \\\n    --hidden-import \"ImageProcessing.cnn\" \\\n    --python-option u \\\n    --add-data \"$(python3 -c 'import cloudscraper as _; print(_.__path__[0])' | tail -n 1):cloudscraper\" \\\n    --add-data \"$(python3 -c 'import opencc as _; print(_.__path__[0])' | tail -n 1):opencc\" \\\n    --add-data \"$(python3 -c 'import face_recognition_models as _; print(_.__path__[0])' | tail -n 1):face_recognition_models\" \\\n    --add-data \"Img:Img\" \\\n    --add-data \"config.ini:.\" \\\n\ncp config.ini ./dist\n"
  },
  {
    "path": "xlog.py",
    "content": "import os\nimport sys\nimport time\nfrom datetime import datetime\nimport traceback\nimport threading\nimport json\nimport shutil\n\nCRITICAL = 50\nFATAL = CRITICAL\nERROR = 40\nWARNING = 30\nWARN = WARNING\nINFO = 20\nDEBUG = 10\nNOTSET = 0\n\n\nclass Logger:\n    def __init__(self, name, buffer_size=0, file_name=None, roll_num=1):\n        self.err_color = '\\033[0m'\n        self.warn_color = '\\033[0m'\n        self.debug_color = '\\033[0m'\n        self.reset_color = '\\033[0m'\n        self.set_console_color = lambda color: sys.stderr.write(color)\n        self.name = str(name)\n        self.file_max_size = 1024 * 1024\n        self.buffer_lock = threading.Lock()\n        self.buffer = {}  # id => line\n        self.buffer_size = buffer_size\n        self.last_no = 0\n        self.min_level = NOTSET\n        self.log_fd = None\n        self.roll_num = roll_num\n        if file_name:\n            self.set_file(file_name)\n\n    def set_buffer(self, buffer_size):\n        with self.buffer_lock:\n            self.buffer_size = buffer_size\n            buffer_len = len(self.buffer)\n            if buffer_len > self.buffer_size:\n                for i in range(self.last_no - buffer_len, self.last_no - self.buffer_size):\n                    try:\n                        del self.buffer[i]\n                    except:\n                        pass\n\n    def setLevel(self, level):\n        if level == \"DEBUG\":\n            self.min_level = DEBUG\n        elif level == \"INFO\":\n            self.min_level = INFO\n        elif level == \"WARN\":\n            self.min_level = WARN\n        elif level == \"ERROR\":\n            self.min_level = ERROR\n        elif level == \"FATAL\":\n            self.min_level = FATAL\n        else:\n            print((\"log level not support:%s\", level))\n\n    def set_color(self):\n        self.err_color = None\n        self.warn_color = None\n        self.debug_color = None\n        self.reset_color = None\n        self.set_console_color = lambda x: None\n        if hasattr(sys.stderr, 'isatty') and sys.stderr.isatty():\n            if os.name == 'nt':\n                self.err_color = 0x04\n                self.warn_color = 0x06\n                self.debug_color = 0x002\n                self.reset_color = 0x07\n\n                import ctypes\n                SetConsoleTextAttribute = ctypes.windll.kernel32.SetConsoleTextAttribute\n                GetStdHandle = ctypes.windll.kernel32.GetStdHandle\n                self.set_console_color = lambda color: SetConsoleTextAttribute(GetStdHandle(-11), color)\n\n            elif os.name == 'posix':\n                self.err_color = '\\033[31m'\n                self.warn_color = '\\033[33m'\n                self.debug_color = '\\033[32m'\n                self.reset_color = '\\033[0m'\n\n                self.set_console_color = lambda color: sys.stderr.write(color)\n\n    def set_file(self, file_name):\n        self.log_filename = file_name\n        if os.path.isfile(file_name):\n            self.file_size = os.path.getsize(file_name)\n            if self.file_size > self.file_max_size:\n                self.roll_log()\n                self.file_size = 0\n        else:\n            self.file_size = 0\n\n        self.log_fd = open(file_name, \"a+\")\n\n    def roll_log(self):\n        for i in range(self.roll_num, 1, -1):\n            new_name = \"%s.%d\" % (self.log_filename, i)\n            old_name = \"%s.%d\" % (self.log_filename, i - 1)\n            if not os.path.isfile(old_name):\n                continue\n\n            # self.info(\"roll_log %s -> %s\", old_name, new_name)\n            shutil.move(old_name, new_name)\n\n        shutil.move(self.log_filename, self.log_filename + \".1\")\n\n    def log_console(self, level, console_color, fmt, *args, **kwargs):\n        try:\n            console_string = '[%s] %s\\n' % (level, fmt % args)\n            self.set_console_color(console_color)\n            sys.stderr.write(console_string)\n            self.set_console_color(self.reset_color)\n        except:\n            pass\n\n    def log_to_file(self, level, console_color, fmt, *args, **kwargs):\n        if self.log_fd:\n            if level == 'e':\n                string = '%s' % (fmt % args)\n            else:\n                time_str = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S.%f\")[:23]\n                string = '%s [%s] [%s] %s\\n' % (time_str, self.name, level, fmt % args)\n\n            self.log_fd.write(string)\n            try:\n                self.log_fd.flush()\n            except:\n                pass\n\n            self.file_size += len(string)\n            if self.file_size > self.file_max_size:\n                self.log_fd.close()\n                self.log_fd = None\n                self.roll_log()\n                self.log_fd = open(self.log_filename, \"w\")\n                self.file_size = 0\n\n    def log(self, level, console_color, html_color, fmt, *args, **kwargs):\n        self.buffer_lock.acquire()\n        try:\n            self.log_console(level, console_color, fmt, *args, **kwargs)\n\n            self.log_to_file(level, console_color, fmt, *args, **kwargs)\n\n            if self.buffer_size:\n                self.last_no += 1\n                self.buffer[self.last_no] = string\n                buffer_len = len(self.buffer)\n                if buffer_len > self.buffer_size:\n                    del self.buffer[self.last_no - self.buffer_size]\n        except Exception as e:\n            string = '%s - [%s]LOG_EXCEPT: %s, Except:%s<br> %s' % (\n            time.ctime()[4:-5], level, fmt % args, e, traceback.format_exc())\n            self.last_no += 1\n            self.buffer[self.last_no] = string\n            buffer_len = len(self.buffer)\n            if buffer_len > self.buffer_size:\n                del self.buffer[self.last_no - self.buffer_size]\n        finally:\n            self.buffer_lock.release()\n\n    def debug(self, fmt, *args, **kwargs):\n        if self.min_level > DEBUG:\n            return\n        self.log('-', self.debug_color, '21610b', fmt, *args, **kwargs)\n\n    def info(self, fmt, *args, **kwargs):\n        if self.min_level > INFO:\n            return\n        self.log('+', self.reset_color, '000000', fmt, *args)\n\n    def warning(self, fmt, *args, **kwargs):\n        if self.min_level > WARN:\n            return\n        self.log('#', self.warn_color, 'FF8000', fmt, *args, **kwargs)\n\n    def warn(self, fmt, *args, **kwargs):\n        self.warning(fmt, *args, **kwargs)\n\n    def error(self, fmt, *args, **kwargs):\n        if self.min_level > ERROR:\n            return\n        self.log('!', self.err_color, 'FE2E2E', fmt, *args, **kwargs)\n\n    def exception(self, fmt, *args, **kwargs):\n        self.error(fmt, *args, **kwargs)\n        string = '%s' % (traceback.format_exc())\n        self.log_to_file('e', self.err_color, string)\n\n    def critical(self, fmt, *args, **kwargs):\n        if self.min_level > CRITICAL:\n            return\n        self.log('!', self.err_color, 'D7DF01', fmt, *args, **kwargs)\n\n    def tofile(self, fmt, *args, **kwargs):\n        self.log_to_file('@', self.warn_color, fmt, *args, **kwargs)\n\n    # =================================================================\n    def set_buffer_size(self, set_size):\n        self.buffer_lock.acquire()\n        self.buffer_size = set_size\n        buffer_len = len(self.buffer)\n        if buffer_len > self.buffer_size:\n            for i in range(self.last_no - buffer_len, self.last_no - self.buffer_size):\n                try:\n                    del self.buffer[i]\n                except:\n                    pass\n        self.buffer_lock.release()\n\n    def get_last_lines(self, max_lines):\n        self.buffer_lock.acquire()\n        buffer_len = len(self.buffer)\n        if buffer_len > max_lines:\n            first_no = self.last_no - max_lines\n        else:\n            first_no = self.last_no - buffer_len + 1\n\n        jd = {}\n        if buffer_len > 0:\n            for i in range(first_no, self.last_no + 1):\n                jd[i] = self.unicode_line(self.buffer[i])\n        self.buffer_lock.release()\n        return json.dumps(jd)\n\n    def get_new_lines(self, from_no):\n        self.buffer_lock.acquire()\n        jd = {}\n        first_no = self.last_no - len(self.buffer) + 1\n        if from_no < first_no:\n            from_no = first_no\n\n        if self.last_no >= from_no:\n            for i in range(from_no, self.last_no + 1):\n                jd[i] = self.unicode_line(self.buffer[i])\n        self.buffer_lock.release()\n        return json.dumps(jd)\n\n    def unicode_line(self, line):\n        try:\n            if type(line) is str:\n                return line\n            else:\n                return str(line, errors='ignore')\n        except Exception as e:\n            print((\"unicode err:%r\" % e))\n            print((\"line can't decode:%s\" % line))\n            print((\"Except stack:%s\" % traceback.format_exc()))\n            return \"\"\n\n\nloggerDict = {}\n\n\ndef getLogger(name=None, buffer_size=0, file_name=None, roll_num=1):\n    global loggerDict, default_log\n    if name is None:\n        for n in loggerDict:\n            name = n\n            break\n    if name is None:\n        name = u\"default\"\n\n    if not isinstance(name, str):\n        raise TypeError('A logger name must be string or Unicode')\n    if isinstance(name, bytes):\n        name = name.encode('utf-8')\n\n    if name in loggerDict:\n        return loggerDict[name]\n    else:\n        logger_instance = Logger(name, buffer_size, file_name, roll_num)\n        loggerDict[name] = logger_instance\n        default_log = logger_instance\n        return logger_instance\n\n\ndefault_log = getLogger()\n\n\ndef debg(fmt, *args, **kwargs):\n    default_log.debug(fmt, *args, **kwargs)\n\n\ndef info(fmt, *args, **kwargs):\n    default_log.info(fmt, *args, **kwargs)\n\n\ndef warn(fmt, *args, **kwargs):\n    default_log.warning(fmt, *args, **kwargs)\n\n\ndef erro(fmt, *args, **kwargs):\n    default_log.error(fmt, *args, **kwargs)\n\n\ndef excp(fmt, *args, **kwargs):\n    default_log.exception(fmt, *args, **kwargs)\n\n\ndef crit(fmt, *args, **kwargs):\n    default_log.critical(fmt, *args, **kwargs)\n\n\ndef tofile(fmt, *args, **kwargs):\n    default_log.tofile(fmt, *args, **kwargs)\n\n\nif __name__ == '__main__':\n    log_file = os.path.join(os.path.dirname(sys.argv[0]), \"test.log\")\n    getLogger().set_file(log_file)\n    debg(\"debug\")\n    info(\"info\")\n    warn(\"warning\")\n    erro(\"error\")\n    crit(\"critical\")\n    tofile(\"write to file only\")\n\n    try:\n        1 / 0\n    except Exception as e:\n        excp(\"An error has occurred\")\n"
  }
]