id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
18,227
import datetime import sys import logging import urllib import urlparse from tornado import template import tornado.httpserver import tornado.ioloop import tornado.web import tornado.wsgi import tornado.escape import tornado.options import os The provided code snippet includes necessary dependencies for implementing the `breakapart` function. Write a Python function `def breakapart(s)` to solve the following problem: attempts to add spaces in a SQLi so it renders nicely on the webpage Here is the function: def breakapart(s): """ attempts to add spaces in a SQLi so it renders nicely on the webpage """ return s.replace(',', ', ').replace('/*',' /*')
attempts to add spaces in a SQLi so it renders nicely on the webpage
18,228
import datetime import sys import logging import urllib import urlparse from tornado import template import tornado.httpserver import tornado.ioloop import tornado.web import tornado.wsgi import tornado.escape import tornado.options def chunks(l, n): import os def breakify(s): output = "" for c in chunks(s, 20): output += c if ' ' not in c: output += ' ' return output
null
18,229
import datetime import sys import logging import urllib import urlparse try: import libinjection except: pass from tornado import template import tornado.httpserver import tornado.ioloop import tornado.web import tornado.wsgi import tornado.escape import tornado.options def print_token(tok): """ prints a token for use in unit testing """ out = '' if tok.type == 's': out += print_token_string(tok) elif tok.type == 'v': vc = tok.count; if vc == 1: out += '@' elif vc == 2: out += '@@' out += print_token_string(tok) else: out += tok.val return (tok.type, out) import os def alltokens(val, flags): if flags & libinjection.FLAG_QUOTE_SINGLE: contextstr = 'single' elif flags & libinjection.FLAG_QUOTE_DOUBLE: contextstr = 'double' else: contextstr = 'none' if flags & libinjection.FLAG_SQL_ANSI: commentstr = 'ansi' elif flags & libinjection.FLAG_SQL_MYSQL: commentstr = 'mysql' else: raise RuntimeException("bad quote context") parse = { 'comment': commentstr, 'quote': contextstr } args = [] sqlstate = libinjection.sqli_state() libinjection.sqli_init(sqlstate, val, flags) count = 0 while count < 25: count += 1 ok = libinjection.sqli_tokenize(sqlstate) if ok == 0: break args.append(print_token(sqlstate.current)) parse['tokens'] = args args = [] fingerprint = libinjection.sqli_fingerprint(sqlstate, flags) for i in range(len(sqlstate.fingerprint)): args.append(print_token(libinjection.sqli_get_token(sqlstate,i))) parse['folds'] = args parse['sqli'] = bool(libinjection.sqli_blacklist(sqlstate) and libinjection.sqli_not_whitelist(sqlstate)) parse['fingerprint'] = fingerprint # todo add stats return parse
null
18,230
import sys import re import libinjection import urllib import urlparse logre = re.compile(r' /diagnostics\?([^ ]+) HTTP') notsqli = set([ '1ov', 'UEvEv', 'v', 'Uv', 'Uv,', 'UoEvE', '1v', 'sov', '1nn', 'UonnE', 'no1', 'Evk', 'E1k', 'E11k', 'Ek', 'Uv,Ev', 'UvEvk', 'UvEv,', 'Uvon' ]) The provided code snippet includes necessary dependencies for implementing the `doline` function. Write a Python function `def doline(logline)` to solve the following problem: ...GET /diagnostics?id=%22union+select HTTP/1.1 Here is the function: def doline(logline): """ ...GET /diagnostics?id=%22union+select HTTP/1.1 """ mo = logre.search(logline) if not mo: return sqli= False fp = None for key, val in urlparse.parse_qsl(mo.group(1)): val = urllib.unquote(val) extra = {} argsqli = libinjection.detectsqli(val, extra) if argsqli: fp = extra['fingerprint'] print urllib.quote(val) sqli = sqli or argsqli if False: # and not sqli: #print "\n---" #print mo.group(1) for key, val in urlparse.parse_qsl(mo.group(1)): val = urllib.unquote(val) extra = {} argsqli = libinjection.detectsqli(val, extra) if not argsqli and extra['fingerprint'] not in notsqli: print "NO", extra['fingerprint'], mo.group(1) print " ", val
...GET /diagnostics?id=%22union+select HTTP/1.1
18,231
import sys import logging import urllib import tornado.httpserver import tornado.ioloop import tornado.web import libinjection import os def boring(arg): if arg == '': return True if arg == 'foo': return True if arg == 'NULL': return True try: float(arg) return True except ValueError: pass return False;
null
18,232
import datetime import json import sys from urlparse import * import urllib import libinjection from tornado import template from tornado.escape import * import re import calendar def chunks(l, n): """ Yield successive n-sized chunks from l. """ for i in xrange(0, len(l), n): yield l[i:i+n] def breakify(s): output = "" for c in chunks(s, 40): output += c if ' ' not in c: output += ' ' return output
null
18,233
import datetime import json import sys from urlparse import * import urllib import libinjection from tornado import template from tornado.escape import * import re import calendar def parse_apache(line): mo = apachelogre.match(line) if not mo: return None (time_iso, timestamp) = parse_date(mo.group(4)) try: (method, uri, protocol) = mo.group(5).split(' ', 2) except ValueError: (method, uri, protocol) = ('-', '-', '-') data = { 'remote_addr': mo.group(1), 'time_iso8601': time_iso, 'timestamp' : timestamp, 'request_protocol': protocol, 'request_method': method, 'request_uri': uri, 'request_length': '', 'request_time': '', 'status': mo.group(6), 'bytes_sent': '', 'body_bytes-sent': int(mo.group(7)), 'http_referrer': mo.group(8), 'http_user_agent': mo.group(9), 'ssl_cipher': '', 'ssl_protocol': '' } return data def doline(line): line = line.replace("\\x", "%").strip() try: data = json.loads(line) except ValueError, e: data = parse_apache(line) if data is None: sys.stderr.write("BAD LINE: {0}\n".format(line)) return None if not data.get('request_uri','').startswith("/diagnostics"): return None urlparts = urlparse(data['request_uri']) if len(urlparts.query) == 0: return None qsl = [ x.split('=', 1) for x in urlparts.query.split('&') ] target = None for k,v in qsl: if k == 'id': target = v break if target is None: #print "no 'id'" return None # part one, normal decode target = urllib.unquote_plus(target) # do it again, but preserve '+' target = urllib.unquote(target) sstate = libinjection.sqli_state() # BAD the string created by target.encode is stored in # sstate but not reference counted, so it can get # deleted by python # libinjection.sqli_init(sstate, target.encode('utf-8'), 0) # instead make a temporary var in python # with the same lifetime as sstate (above) try: targetutf8 = target.encode('utf-8') #targetutf8 = target except UnicodeDecodeError, e: targetutf8 = target #if type(target) == str: # sys.stderr.write("Target is a string\n") #if type(target) == unicode: # sys.stderr.write("Target is unicde\n") #sys.stderr.write("OOps: {0}\n".format(e)) #sys.stderr.write("Encode error: {0}\n".format(target)) try: libinjection.sqli_init(sstate, targetutf8, 0) except TypeError: sys.stderr.write("fail in decode: {0}".format(targetutf8)) if type(target) == str: sys.stderr.write("Target is a string\n") if type(target) == unicode: sys.stderr.write("Target is unicde\n") return None sqli = bool(libinjection.is_sqli(sstate)) return (target, sqli, sstate.fingerprint, data['remote_addr'])
null
18,234
import os import re import sys def load_files(path): file_contents = {} for root, _, files in os.walk(path): for file in files: if file.endswith(".lua"): p = os.path.join(root.replace(path, ""), file).lstrip("/") with open(os.path.join(root, file)) as f: file_contents[p] = f.readlines() return file_contents
null
18,235
import os import re import sys token = "[a-zA-Z0-9_]" def find_cdefs(files): cdefs = { "funcs": {}, "types": {}, } for path, lines in files.items(): start = False for i in range(len(lines)): line = lines[i] if "ffi.cdef" in line: start = True elif "]]" in line and start: start = False if start: if re.findall("^\s*//", line): # comment continue func = re.findall(f"{token}+[\s\*]+({token}+)\(", line) if func: cdefs["funcs"][func[0]] = f"{path}:{i}" type_ = re.findall(f"typedef.*?({token}+);", line) if type_: cdefs["types"][type_[0]] = f"{path}:{i}" type_ = re.findall(f"}}\s*({token}+);", line) if type_: cdefs["types"][type_[0]] = f"{path}:{i}" return cdefs
null
18,236
import os import re import sys token = "[a-zA-Z0-9_]" ignore_list = [ "OSSL_PARAM_(?:set|get)_", "PEM_read_bio_", "fake_openssl_", "(?:d2i|i2d)_(?:PUBKEY|PrivateKey)_bio", "_(?:gettable|settable)_params", "_(?:get|set)_params", "_do_all_(?:sorted|provided)", "_get0_name", ] def check_cdefs(files, cdef): unused = { "funcs": {}, "types": {}, } undefined = { "funcs": {}, "types": {}, } patterns = { "funcs": "C.%s[^a-zA-Z0-9_]", "types": "%s[^a-zA-Z0-9_]", } ignore_regex = "(?:%s)" % "|".join(ignore_list) for name, regex_pattern in patterns.items(): for token, path in cdef[name].items(): found = False for _, lines in files.items(): full_content = "".join(lines) if re.findall(regex_pattern % token, full_content): found = True break if not found and not re.findall(ignore_regex, token): unused[name][token] = path # TODO: find undefined return unused, undefined
null
18,237
import os import re import sys token = "[a-zA-Z0-9_]" def display(unused, undefined): for name, tokens in unused.items(): if len(tokens) == 0: continue print(f"Unused {name} ({len(tokens)}):") for token, path in tokens.items(): print(f" {token} on {path}") for name, tokens in undefined.items(): if len(tokens) == 0: continue print(f"Undefined {name} ({len(tokens)}):") for token, path in tokens.items(): print(f" {token} on {path}")
null
18,238
types = { "BASIC_CONSTRAINTS": { "ca": "ca_bool_int", "pathlen": "ASN1_INTEGER", }, } getter_conv_tmpl = { "ca_bool_int": "ctx.{k} == 0xFF", "ASN1_INTEGER": "tonumber(C.ASN1_INTEGER_get(ctx.{k}))", } c2t_assign_locals = ''' local {k} = {conv}''' c2t_return_table = ''' {k} = {k},''' c2t_return_partial = ''' elseif string.lower(name) == "{k}" then got = {k}''' c2t = ''' local ctx = ffi_cast("{type}*", got) {assign_locals} C.{type}_free(ctx) if not name or type(name) ~= "string" then got = {{ {return_table} }} {return_partial} end ''' def c_struct_to_table(name): t = types[name] return c2t.format( type=name, assign_locals="".join([ c2t_assign_locals.format( k=k, conv=getter_conv_tmpl[v].format(k=k) ) for k, v in t.items() ]), return_table="".join([ c2t_return_table.format(k=k) for k in t ]).lstrip("\n"), return_partial="".join([ c2t_return_partial.format(k=k) for k in t ]).lstrip("\n"), )
null
18,239
types = { "BASIC_CONSTRAINTS": { "ca": "ca_bool_int", "pathlen": "ASN1_INTEGER", }, } setter_conv_tmpl = { "ca_bool_int": ''' toset.{k} = cfg_lower.{k} and 0xFF or 0''', "ASN1_INTEGER": ''' local {k} = cfg_lower.{k} and tonumber(cfg_lower.{k}) if {k} then C.ASN1_INTEGER_free(toset.{k}) local asn1 = C.ASN1_STRING_type_new({k}) if asn1 == nil then return false, format_error("x509:set_{type}: ASN1_STRING_type_new") end toset.{k} = asn1 local code = C.ASN1_INTEGER_set(asn1, {k}) if code ~= 1 then return false, format_error("x509:set_{type}: ASN1_INTEGER_set", code) end end''' } t2c = ''' local cfg_lower = {{}} for k, v in pairs(toset) do cfg_lower[string.lower(k)] = v end toset = C.{type}_new() if toset == nil then return false, format_error("x509:set_{type}") end ffi_gc(toset, C.{type}_free) {set_members} ''' def table_to_c_struct(name): t = types[name] return t2c.format( type=name, set_members="".join([ setter_conv_tmpl[v].format( k=k, type=name, ) for k, v in t.items() ]), )
null
18,240
from base64 import b64encode from io import BytesIO from os.path import join from typing import List, Optional from qrcode.main import QRCode def check_settings(settings: dict, check: str) -> bool: return any(setting["context"] == check for setting in settings.values())
null
18,241
from contextlib import suppress from os import _exit, getenv, listdir, sep, urandom from os.path import basename, dirname, join from secrets import choice from string import ascii_letters, digits from sys import path as sys_path, modules as sys_modules from pathlib import Path from bs4 import BeautifulSoup from copy import deepcopy from datetime import datetime, timedelta, timezone from dateutil.parser import parse as dateutil_parse from docker import DockerClient from docker.errors import NotFound as docker_NotFound, APIError as docker_APIError, DockerException from flask import Flask, Response, flash, jsonify, redirect, render_template, request, send_file, session, url_for from flask_login import current_user, LoginManager, login_required, login_user, logout_user from flask_wtf.csrf import CSRFProtect, CSRFError, generate_csrf from glob import glob from hashlib import sha256 from importlib.machinery import SourceFileLoader from io import BytesIO from json import JSONDecodeError, dumps, loads as json_loads from jinja2 import Template from kubernetes import client as kube_client from kubernetes import config as kube_config from kubernetes.client.exceptions import ApiException as kube_ApiException from regex import compile as re_compile, match as regex_match from requests import get from shutil import move, rmtree from signal import SIGINT, signal, SIGTERM from subprocess import PIPE, Popen, call from tarfile import CompressionError, HeaderError, ReadError, TarError, open as tar_open from threading import Thread from tempfile import NamedTemporaryFile from time import sleep, time from traceback import format_exc from zipfile import BadZipFile, ZipFile from src.Instances import Instances from src.ConfigFiles import ConfigFiles from src.Config import Config from src.ReverseProxied import ReverseProxied from src.User import AnonymousUser, User from utils import check_settings, get_b64encoded_qr_image, path_to_dict from Database import Database from logging import getLogger def stop(status, _stop=True): Path(sep, "var", "run", "bunkerweb", "ui.pid").unlink(missing_ok=True) Path(sep, "var", "tmp", "bunkerweb", "ui.healthy").unlink(missing_ok=True) if _stop is True: stop_gunicorn() _exit(status) app = Flask(__name__, static_url_path="/", static_folder="static", template_folder="templates") app.config["SECRET_KEY"] = getenv("FLASK_SECRET", urandom(32)) app.wsgi_app = ReverseProxied(app.wsgi_app, x_for=PROXY_NUMBERS, x_proto=PROXY_NUMBERS, x_host=PROXY_NUMBERS, x_prefix=PROXY_NUMBERS) app.logger.handlers = gunicorn_logger.handlers app.logger.setLevel(gunicorn_logger.level) app.logger.info("Database is ready") try: app.config.update( DEBUG=True, INSTANCES=Instances(docker_client, kubernetes_client, INTEGRATION), CONFIG=Config(db), CONFIGFILES=ConfigFiles(app.logger, db), WTF_CSRF_SSL_STRICT=False, USER=USER, SEND_FILE_MAX_AGE_DEFAULT=86400, PLUGIN_ARGS={}, RELOADING=False, LAST_RELOAD=0, TO_FLASH=[], DARK_MODE=False, CURRENT_TOTP_TOKEN=None, ) except FileNotFoundError as e: app.logger.error(repr(e), e.filename) stop(1) app.jinja_env.globals.update(check_settings=check_settings) def handle_stop(signum, frame): app.logger.info("Caught stop operation") app.logger.info("Stopping web ui ...") stop(0, False)
null
18,242
from contextlib import suppress from os import _exit, getenv, listdir, sep, urandom from os.path import basename, dirname, join from secrets import choice from string import ascii_letters, digits from sys import path as sys_path, modules as sys_modules from pathlib import Path from bs4 import BeautifulSoup from copy import deepcopy from datetime import datetime, timedelta, timezone from dateutil.parser import parse as dateutil_parse from docker import DockerClient from docker.errors import NotFound as docker_NotFound, APIError as docker_APIError, DockerException from flask import Flask, Response, flash, jsonify, redirect, render_template, request, send_file, session, url_for from flask_login import current_user, LoginManager, login_required, login_user, logout_user from flask_wtf.csrf import CSRFProtect, CSRFError, generate_csrf from glob import glob from hashlib import sha256 from importlib.machinery import SourceFileLoader from io import BytesIO from json import JSONDecodeError, dumps, loads as json_loads from jinja2 import Template from kubernetes import client as kube_client from kubernetes import config as kube_config from kubernetes.client.exceptions import ApiException as kube_ApiException from regex import compile as re_compile, match as regex_match from requests import get from shutil import move, rmtree from signal import SIGINT, signal, SIGTERM from subprocess import PIPE, Popen, call from tarfile import CompressionError, HeaderError, ReadError, TarError, open as tar_open from threading import Thread from tempfile import NamedTemporaryFile from time import sleep, time from traceback import format_exc from zipfile import BadZipFile, ZipFile from src.Instances import Instances from src.ConfigFiles import ConfigFiles from src.Config import Config from src.ReverseProxied import ReverseProxied from src.User import AnonymousUser, User from utils import check_settings, get_b64encoded_qr_image, path_to_dict from Database import Database from logging import getLogger The provided code snippet includes necessary dependencies for implementing the `set_csp_header` function. Write a Python function `def set_csp_header(response)` to solve the following problem: Set the Content-Security-Policy header to prevent XSS attacks. Here is the function: def set_csp_header(response): """Set the Content-Security-Policy header to prevent XSS attacks.""" response.headers["Content-Security-Policy"] = "object-src 'none'; frame-ancestors 'self';" return response
Set the Content-Security-Policy header to prevent XSS attacks.
18,243
from contextlib import suppress from os import _exit, getenv, listdir, sep, urandom from os.path import basename, dirname, join from secrets import choice from string import ascii_letters, digits from sys import path as sys_path, modules as sys_modules from pathlib import Path from bs4 import BeautifulSoup from copy import deepcopy from datetime import datetime, timedelta, timezone from dateutil.parser import parse as dateutil_parse from docker import DockerClient from docker.errors import NotFound as docker_NotFound, APIError as docker_APIError, DockerException from flask import Flask, Response, flash, jsonify, redirect, render_template, request, send_file, session, url_for from flask_login import current_user, LoginManager, login_required, login_user, logout_user from flask_wtf.csrf import CSRFProtect, CSRFError, generate_csrf from glob import glob from hashlib import sha256 from importlib.machinery import SourceFileLoader from io import BytesIO from json import JSONDecodeError, dumps, loads as json_loads from jinja2 import Template from kubernetes import client as kube_client from kubernetes import config as kube_config from kubernetes.client.exceptions import ApiException as kube_ApiException from regex import compile as re_compile, match as regex_match from requests import get from shutil import move, rmtree from signal import SIGINT, signal, SIGTERM from subprocess import PIPE, Popen, call from tarfile import CompressionError, HeaderError, ReadError, TarError, open as tar_open from threading import Thread from tempfile import NamedTemporaryFile from time import sleep, time from traceback import format_exc from zipfile import BadZipFile, ZipFile from src.Instances import Instances from src.ConfigFiles import ConfigFiles from src.Config import Config from src.ReverseProxied import ReverseProxied from src.User import AnonymousUser, User from utils import check_settings, get_b64encoded_qr_image, path_to_dict from Database import Database from logging import getLogger app = Flask(__name__, static_url_path="/", static_folder="static", template_folder="templates") app.config["SECRET_KEY"] = getenv("FLASK_SECRET", urandom(32)) app.wsgi_app = ReverseProxied(app.wsgi_app, x_for=PROXY_NUMBERS, x_proto=PROXY_NUMBERS, x_host=PROXY_NUMBERS, x_prefix=PROXY_NUMBERS) app.logger.handlers = gunicorn_logger.handlers app.logger.setLevel(gunicorn_logger.level) db = Database(app.logger, ui=True) while not db.is_initialized(): app.logger.warning("Database is not initialized, retrying in 5s ...") sleep(5) app.logger.info("Database is ready") try: app.config.update( DEBUG=True, INSTANCES=Instances(docker_client, kubernetes_client, INTEGRATION), CONFIG=Config(db), CONFIGFILES=ConfigFiles(app.logger, db), WTF_CSRF_SSL_STRICT=False, USER=USER, SEND_FILE_MAX_AGE_DEFAULT=86400, PLUGIN_ARGS={}, RELOADING=False, LAST_RELOAD=0, TO_FLASH=[], DARK_MODE=False, CURRENT_TOTP_TOKEN=None, ) except FileNotFoundError as e: app.logger.error(repr(e), e.filename) stop(1) app.jinja_env.globals.update(check_settings=check_settings) def load_user(user_id): db_user = db.get_ui_user() if not db_user: app.logger.warning("Couldn't get the admin user from the database.") return None user = User(**db_user) return user if user_id == user.get_id() else None
null
18,244
from contextlib import suppress from os import _exit, getenv, listdir, sep, urandom from os.path import basename, dirname, join from secrets import choice from string import ascii_letters, digits from sys import path as sys_path, modules as sys_modules from pathlib import Path from bs4 import BeautifulSoup from copy import deepcopy from datetime import datetime, timedelta, timezone from dateutil.parser import parse as dateutil_parse from docker import DockerClient from docker.errors import NotFound as docker_NotFound, APIError as docker_APIError, DockerException from flask import Flask, Response, flash, jsonify, redirect, render_template, request, send_file, session, url_for from flask_login import current_user, LoginManager, login_required, login_user, logout_user from flask_wtf.csrf import CSRFProtect, CSRFError, generate_csrf from glob import glob from hashlib import sha256 from importlib.machinery import SourceFileLoader from io import BytesIO from json import JSONDecodeError, dumps, loads as json_loads from jinja2 import Template from kubernetes import client as kube_client from kubernetes import config as kube_config from kubernetes.client.exceptions import ApiException as kube_ApiException from regex import compile as re_compile, match as regex_match from requests import get from shutil import move, rmtree from signal import SIGINT, signal, SIGTERM from subprocess import PIPE, Popen, call from tarfile import CompressionError, HeaderError, ReadError, TarError, open as tar_open from threading import Thread from tempfile import NamedTemporaryFile from time import sleep, time from traceback import format_exc from zipfile import BadZipFile, ZipFile from src.Instances import Instances from src.ConfigFiles import ConfigFiles from src.Config import Config from src.ReverseProxied import ReverseProxied from src.User import AnonymousUser, User from utils import check_settings, get_b64encoded_qr_image, path_to_dict from Database import Database from logging import getLogger app = Flask(__name__, static_url_path="/", static_folder="static", template_folder="templates") app.config["SECRET_KEY"] = getenv("FLASK_SECRET", urandom(32)) app.wsgi_app = ReverseProxied(app.wsgi_app, x_for=PROXY_NUMBERS, x_proto=PROXY_NUMBERS, x_host=PROXY_NUMBERS, x_prefix=PROXY_NUMBERS) app.logger.handlers = gunicorn_logger.handlers app.logger.setLevel(gunicorn_logger.level) app.logger.info("Database is ready") try: app.config.update( DEBUG=True, INSTANCES=Instances(docker_client, kubernetes_client, INTEGRATION), CONFIG=Config(db), CONFIGFILES=ConfigFiles(app.logger, db), WTF_CSRF_SSL_STRICT=False, USER=USER, SEND_FILE_MAX_AGE_DEFAULT=86400, PLUGIN_ARGS={}, RELOADING=False, LAST_RELOAD=0, TO_FLASH=[], DARK_MODE=False, CURRENT_TOTP_TOKEN=None, ) except FileNotFoundError as e: app.logger.error(repr(e), e.filename) stop(1) app.jinja_env.globals.update(check_settings=check_settings) The provided code snippet includes necessary dependencies for implementing the `handle_csrf_error` function. Write a Python function `def handle_csrf_error(_)` to solve the following problem: It takes a CSRFError exception as an argument, and returns a Flask response :param e: The exception object :return: A template with the error message and a 401 status code. Here is the function: def handle_csrf_error(_): """ It takes a CSRFError exception as an argument, and returns a Flask response :param e: The exception object :return: A template with the error message and a 401 status code. """ session.clear() logout_user() flash("Wrong CSRF token !", "error") if not app.config["USER"]: return render_template("setup.html"), 403 return render_template("login.html", is_totp=current_user.is_two_factor_enabled), 403
It takes a CSRFError exception as an argument, and returns a Flask response :param e: The exception object :return: A template with the error message and a 401 status code.
18,245
from contextlib import suppress from os import _exit, getenv, listdir, sep, urandom from os.path import basename, dirname, join from secrets import choice from string import ascii_letters, digits from sys import path as sys_path, modules as sys_modules from pathlib import Path from bs4 import BeautifulSoup from copy import deepcopy from datetime import datetime, timedelta, timezone from dateutil.parser import parse as dateutil_parse from docker import DockerClient from docker.errors import NotFound as docker_NotFound, APIError as docker_APIError, DockerException from flask import Flask, Response, flash, jsonify, redirect, render_template, request, send_file, session, url_for from flask_login import current_user, LoginManager, login_required, login_user, logout_user from flask_wtf.csrf import CSRFProtect, CSRFError, generate_csrf from glob import glob from hashlib import sha256 from importlib.machinery import SourceFileLoader from io import BytesIO from json import JSONDecodeError, dumps, loads as json_loads from jinja2 import Template from kubernetes import client as kube_client from kubernetes import config as kube_config from kubernetes.client.exceptions import ApiException as kube_ApiException from regex import compile as re_compile, match as regex_match from requests import get from shutil import move, rmtree from signal import SIGINT, signal, SIGTERM from subprocess import PIPE, Popen, call from tarfile import CompressionError, HeaderError, ReadError, TarError, open as tar_open from threading import Thread from tempfile import NamedTemporaryFile from time import sleep, time from traceback import format_exc from zipfile import BadZipFile, ZipFile from src.Instances import Instances from src.ConfigFiles import ConfigFiles from src.Config import Config from src.ReverseProxied import ReverseProxied from src.User import AnonymousUser, User from utils import check_settings, get_b64encoded_qr_image, path_to_dict from Database import Database from logging import getLogger def before_request(): if current_user.is_authenticated: passed = True # Go back from totp to login if not session.get("totp_validated", False) and current_user.is_two_factor_enabled and "/totp" not in request.path and not request.path.startswith(("/css", "/images", "/js", "/json", "/webfonts")) and request.path.endswith("/login"): return redirect(url_for("login", next=request.path)) # Case not login page, keep on 2FA before any other access if not session.get("totp_validated", False) and current_user.is_two_factor_enabled and "/totp" not in request.path and not request.path.startswith(("/css", "/images", "/js", "/json", "/webfonts")): return redirect(url_for("totp", next=request.form.get("next"))) elif session.get("ip") != request.remote_addr: passed = False elif session.get("user_agent") != request.headers.get("User-Agent"): passed = False if not passed: logout_user() session.clear()
null
18,246
from contextlib import suppress from os import _exit, getenv, listdir, sep, urandom from os.path import basename, dirname, join from secrets import choice from string import ascii_letters, digits from sys import path as sys_path, modules as sys_modules from pathlib import Path from bs4 import BeautifulSoup from copy import deepcopy from datetime import datetime, timedelta, timezone from dateutil.parser import parse as dateutil_parse from docker import DockerClient from docker.errors import NotFound as docker_NotFound, APIError as docker_APIError, DockerException from flask import Flask, Response, flash, jsonify, redirect, render_template, request, send_file, session, url_for from flask_login import current_user, LoginManager, login_required, login_user, logout_user from flask_wtf.csrf import CSRFProtect, CSRFError, generate_csrf from glob import glob from hashlib import sha256 from importlib.machinery import SourceFileLoader from io import BytesIO from json import JSONDecodeError, dumps, loads as json_loads from jinja2 import Template from kubernetes import client as kube_client from kubernetes import config as kube_config from kubernetes.client.exceptions import ApiException as kube_ApiException from regex import compile as re_compile, match as regex_match from requests import get from shutil import move, rmtree from signal import SIGINT, signal, SIGTERM from subprocess import PIPE, Popen, call from tarfile import CompressionError, HeaderError, ReadError, TarError, open as tar_open from threading import Thread from tempfile import NamedTemporaryFile from time import sleep, time from traceback import format_exc from zipfile import BadZipFile, ZipFile from src.Instances import Instances from src.ConfigFiles import ConfigFiles from src.Config import Config from src.ReverseProxied import ReverseProxied from src.User import AnonymousUser, User from utils import check_settings, get_b64encoded_qr_image, path_to_dict from Database import Database from logging import getLogger def loading(): return render_template("loading.html", message=request.values.get("message", "Loading"), next=request.values.get("next", None) or url_for("home"))
null
18,247
from contextlib import suppress from os import _exit, getenv, listdir, sep, urandom from os.path import basename, dirname, join from secrets import choice from string import ascii_letters, digits from sys import path as sys_path, modules as sys_modules from pathlib import Path from bs4 import BeautifulSoup from copy import deepcopy from datetime import datetime, timedelta, timezone from dateutil.parser import parse as dateutil_parse from docker import DockerClient from docker.errors import NotFound as docker_NotFound, APIError as docker_APIError, DockerException from flask import Flask, Response, flash, jsonify, redirect, render_template, request, send_file, session, url_for from flask_login import current_user, LoginManager, login_required, login_user, logout_user from flask_wtf.csrf import CSRFProtect, CSRFError, generate_csrf from glob import glob from hashlib import sha256 from importlib.machinery import SourceFileLoader from io import BytesIO from json import JSONDecodeError, dumps, loads as json_loads from jinja2 import Template from kubernetes import client as kube_client from kubernetes import config as kube_config from kubernetes.client.exceptions import ApiException as kube_ApiException from regex import compile as re_compile, match as regex_match from requests import get from shutil import move, rmtree from signal import SIGINT, signal, SIGTERM from subprocess import PIPE, Popen, call from tarfile import CompressionError, HeaderError, ReadError, TarError, open as tar_open from threading import Thread from tempfile import NamedTemporaryFile from time import sleep, time from traceback import format_exc from zipfile import BadZipFile, ZipFile from src.Instances import Instances from src.ConfigFiles import ConfigFiles from src.Config import Config from src.ReverseProxied import ReverseProxied from src.User import AnonymousUser, User from utils import check_settings, get_b64encoded_qr_image, path_to_dict from Database import Database from logging import getLogger def check(): if "Origin" not in request.headers: return Response(status=403) return Response(status=200, headers={"Access-Control-Allow-Origin": "*"})
null
18,248
from contextlib import suppress from os import _exit, getenv, listdir, sep, urandom from os.path import basename, dirname, join from secrets import choice from string import ascii_letters, digits from sys import path as sys_path, modules as sys_modules from pathlib import Path from bs4 import BeautifulSoup from copy import deepcopy from datetime import datetime, timedelta, timezone from dateutil.parser import parse as dateutil_parse from docker import DockerClient from docker.errors import NotFound as docker_NotFound, APIError as docker_APIError, DockerException from flask import Flask, Response, flash, jsonify, redirect, render_template, request, send_file, session, url_for from flask_login import current_user, LoginManager, login_required, login_user, logout_user from flask_wtf.csrf import CSRFProtect, CSRFError, generate_csrf from glob import glob from hashlib import sha256 from importlib.machinery import SourceFileLoader from io import BytesIO from json import JSONDecodeError, dumps, loads as json_loads from jinja2 import Template from kubernetes import client as kube_client from kubernetes import config as kube_config from kubernetes.client.exceptions import ApiException as kube_ApiException from regex import compile as re_compile, match as regex_match from requests import get from shutil import move, rmtree from signal import SIGINT, signal, SIGTERM from subprocess import PIPE, Popen, call from tarfile import CompressionError, HeaderError, ReadError, TarError, open as tar_open from threading import Thread from tempfile import NamedTemporaryFile from time import sleep, time from traceback import format_exc from zipfile import BadZipFile, ZipFile from src.Instances import Instances from src.ConfigFiles import ConfigFiles from src.Config import Config from src.ReverseProxied import ReverseProxied from src.User import AnonymousUser, User from utils import check_settings, get_b64encoded_qr_image, path_to_dict from Database import Database from logging import getLogger app = Flask(__name__, static_url_path="/", static_folder="static", template_folder="templates") app.config["SECRET_KEY"] = getenv("FLASK_SECRET", urandom(32)) app.wsgi_app = ReverseProxied(app.wsgi_app, x_for=PROXY_NUMBERS, x_proto=PROXY_NUMBERS, x_host=PROXY_NUMBERS, x_prefix=PROXY_NUMBERS) app.logger.handlers = gunicorn_logger.handlers app.logger.setLevel(gunicorn_logger.level) if getenv("KUBERNETES_MODE", "no").lower() == "yes": INTEGRATION = "Kubernetes" elif getenv("SWARM_MODE", "no").lower() == "yes": INTEGRATION = "Swarm" elif getenv("AUTOCONF_MODE", "no").lower() == "yes": INTEGRATION = "Autoconf" elif integration_path.is_file(): INTEGRATION = integration_path.read_text(encoding="utf-8").strip() db = Database(app.logger, ui=True) while not db.is_initialized(): app.logger.warning("Database is not initialized, retrying in 5s ...") sleep(5) USER_PASSWORD_RX = re_compile(r"^(?=.*?\p{Lowercase_Letter})(?=.*?\p{Uppercase_Letter})(?=.*?\d)(?=.*?[ !\"#$%&'()*+,./:;<=>?@[\\\]^_`{|}~-]).{8,}$") app.logger.info("Database is ready") try: app.config.update( DEBUG=True, INSTANCES=Instances(docker_client, kubernetes_client, INTEGRATION), CONFIG=Config(db), CONFIGFILES=ConfigFiles(app.logger, db), WTF_CSRF_SSL_STRICT=False, USER=USER, SEND_FILE_MAX_AGE_DEFAULT=86400, PLUGIN_ARGS={}, RELOADING=False, LAST_RELOAD=0, TO_FLASH=[], DARK_MODE=False, CURRENT_TOTP_TOKEN=None, ) except FileNotFoundError as e: app.logger.error(repr(e), e.filename) stop(1) app.jinja_env.globals.update(check_settings=check_settings) REVERSE_PROXY_PATH = re_compile(r"^(?P<host>https?://.{1,255}(:((6553[0-5])|(655[0-2]\d)|(65[0-4]\d{2})|(6[0-4]\d{3})|([1-5]\d{4})|([0-5]{0,5})|(\d{1,4})))?)$") def manage_bunkerweb(method: str, *args, operation: str = "reloads"): # Do the operation error = False if method == "services": service_custom_confs = glob(join(sep, "etc", "bunkerweb", "configs", "*", args[1].split(" ")[0])) moved = False deleted = False if operation == "new": operation, error = app.config["CONFIG"].new_service(args[0]) elif operation == "edit": if args[1].split(" ")[0] != args[2].split(" ")[0] and service_custom_confs: for service_custom_conf in service_custom_confs: if listdir(service_custom_conf): move(service_custom_conf, service_custom_conf.replace(f"{sep}{args[1].split(' ')[0]}", f"{sep}{args[2].split(' ')[0]}")) moved = True operation, error = app.config["CONFIG"].edit_service(args[1], args[0], check_changes=not moved) elif operation == "delete": for service_custom_conf in glob(join(sep, "etc", "bunkerweb", "configs", "*", args[2].split(" ")[0])): if listdir(service_custom_conf): rmtree(service_custom_conf, ignore_errors=True) deleted = True operation, error = app.config["CONFIG"].delete_service(args[2], check_changes=not deleted) if error: app.config["TO_FLASH"].append({"content": operation, "type": "error"}) else: app.config["TO_FLASH"].append({"content": operation, "type": "success"}) if moved or deleted: changes = ["config", "custom_configs"] error = app.config["CONFIGFILES"].save_configs(check_changes=False) if error: app.config["TO_FLASH"].append({"content": error, "type": "error"}) changes.pop() # update changes in db ret = db.checked_changes(changes, value=True) if ret: app.logger.error(f"Couldn't set the changes to checked in the database: {ret}") app.config["TO_FLASH"].append({"content": f"An error occurred when setting the changes to checked in the database : {ret}", "type": "error"}) if method == "global_config": operation = app.config["CONFIG"].edit_global_conf(args[0]) elif method == "plugins": app.config["CONFIG"].reload_config() if operation == "reload": operation = app.config["INSTANCES"].reload_instance(args[0]) elif operation == "start": operation = app.config["INSTANCES"].start_instance(args[0]) elif operation == "stop": operation = app.config["INSTANCES"].stop_instance(args[0]) elif operation == "restart": operation = app.config["INSTANCES"].restart_instance(args[0]) elif not error: operation = "The scheduler will be in charge of reloading the instances." else: operation = "" if operation: if isinstance(operation, list): for op in operation: app.config["TO_FLASH"].append({"content": f"Reload failed for the instance {op}", "type": "error"}) elif operation.startswith("Can't"): app.config["TO_FLASH"].append({"content": operation, "type": "error"}) else: app.config["TO_FLASH"].append({"content": operation, "type": "success"}) app.config["RELOADING"] = False def setup(): if current_user.is_authenticated: # type: ignore return redirect(url_for("home")) db_config = app.config["CONFIG"].get_config(methods=False) for server_name in db_config["SERVER_NAME"].split(" "): if db_config.get(f"{server_name}_USE_UI", "no") == "yes": return redirect(url_for("login"), 301) if request.method == "POST": if not request.form: flash("Missing form data.", "error") return redirect(url_for("setup")) if not any(key in request.form for key in ("admin_username", "admin_password", "admin_password_check", "server_name", "ui_host", "ui_url")): flash("Missing either admin_username, admin_password, admin_password_check, server_name, ui_host, ui_url or auto_lets_encrypt parameter.", "error") return redirect(url_for("setup")) error = False if len(request.form["admin_username"]) > 256: flash("The admin username is too long. It must be less than 256 characters.", "error") error = True if request.form["admin_password"] != request.form["admin_password_check"]: flash("The passwords do not match.", "error") error = True if not USER_PASSWORD_RX.match(request.form["admin_password"]): flash("The admin password is not strong enough. It must contain at least 8 characters, including at least 1 uppercase letter, 1 lowercase letter, 1 number and 1 special character (#@?!$%^&*-).", "error") error = True server_names = db_config["SERVER_NAME"].split(" ") if request.form["server_name"] in server_names: flash(f"The hostname {request.form['server_name']} is already in use.", "error") error = True else: for server_name in server_names: if request.form["server_name"] in db_config.get(f"{server_name}_SERVER_NAME", "").split(" "): flash(f"The hostname {request.form['server_name']} is already in use.", "error") error = True break if not REVERSE_PROXY_PATH.match(request.form["ui_host"]): flash("The hostname is not valid.", "error") error = True if error: return redirect(url_for("setup")) app.config["USER"] = User(request.form["admin_username"], request.form["admin_password"], method="ui") ret = db.create_ui_user(request.form["admin_username"], app.config["USER"].password_hash, method="ui") if ret: app.logger.error(f"Couldn't create the admin user in the database: {ret}") flash(f"Couldn't create the admin user in the database: {ret}", "error") return redirect(url_for("setup")) flash("The admin user was created successfully", "success") app.config["RELOADING"] = True app.config["LAST_RELOAD"] = time() Thread( target=manage_bunkerweb, name="Reloading instances", args=( "services", { "SERVER_NAME": request.form["server_name"], "USE_UI": "yes", "USE_REVERSE_PROXY": "yes", "REVERSE_PROXY_HOST": request.form["ui_host"], "REVERSE_PROXY_URL": request.form["ui_url"] or "/", "AUTO_LETS_ENCRYPT": request.form.get("auto_lets_encrypt", "no"), "INTERCEPTED_ERROR_CODES": "400 404 405 413 429 500 501 502 503 504", }, request.form["server_name"], request.form["server_name"], ), kwargs={"operation": "new"}, ).start() return Response(status=200) return render_template( "setup.html", username=getenv("ADMIN_USERNAME", ""), password=getenv("ADMIN_PASSWORD", ""), ui_host=db_config.get("UI_HOST", getenv("UI_HOST", "")), random_url=f"/{''.join(choice(ascii_letters + digits) for _ in range(10))}", )
null
18,249
from contextlib import suppress from os import _exit, getenv, listdir, sep, urandom from os.path import basename, dirname, join from secrets import choice from string import ascii_letters, digits from sys import path as sys_path, modules as sys_modules from pathlib import Path from bs4 import BeautifulSoup from copy import deepcopy from datetime import datetime, timedelta, timezone from dateutil.parser import parse as dateutil_parse from docker import DockerClient from docker.errors import NotFound as docker_NotFound, APIError as docker_APIError, DockerException from flask import Flask, Response, flash, jsonify, redirect, render_template, request, send_file, session, url_for from flask_login import current_user, LoginManager, login_required, login_user, logout_user from flask_wtf.csrf import CSRFProtect, CSRFError, generate_csrf from glob import glob from hashlib import sha256 from importlib.machinery import SourceFileLoader from io import BytesIO from json import JSONDecodeError, dumps, loads as json_loads from jinja2 import Template from kubernetes import client as kube_client from kubernetes import config as kube_config from kubernetes.client.exceptions import ApiException as kube_ApiException from regex import compile as re_compile, match as regex_match from requests import get from shutil import move, rmtree from signal import SIGINT, signal, SIGTERM from subprocess import PIPE, Popen, call from tarfile import CompressionError, HeaderError, ReadError, TarError, open as tar_open from threading import Thread from tempfile import NamedTemporaryFile from time import sleep, time from traceback import format_exc from zipfile import BadZipFile, ZipFile from src.Instances import Instances from src.ConfigFiles import ConfigFiles from src.Config import Config from src.ReverseProxied import ReverseProxied from src.User import AnonymousUser, User from utils import check_settings, get_b64encoded_qr_image, path_to_dict from Database import Database from logging import getLogger app = Flask(__name__, static_url_path="/", static_folder="static", template_folder="templates") app.config["SECRET_KEY"] = getenv("FLASK_SECRET", urandom(32)) app.wsgi_app = ReverseProxied(app.wsgi_app, x_for=PROXY_NUMBERS, x_proto=PROXY_NUMBERS, x_host=PROXY_NUMBERS, x_prefix=PROXY_NUMBERS) app.logger.handlers = gunicorn_logger.handlers app.logger.setLevel(gunicorn_logger.level) app.logger.info("Database is ready") try: app.config.update( DEBUG=True, INSTANCES=Instances(docker_client, kubernetes_client, INTEGRATION), CONFIG=Config(db), CONFIGFILES=ConfigFiles(app.logger, db), WTF_CSRF_SSL_STRICT=False, USER=USER, SEND_FILE_MAX_AGE_DEFAULT=86400, PLUGIN_ARGS={}, RELOADING=False, LAST_RELOAD=0, TO_FLASH=[], DARK_MODE=False, CURRENT_TOTP_TOKEN=None, ) except FileNotFoundError as e: app.logger.error(repr(e), e.filename) stop(1) app.jinja_env.globals.update(check_settings=check_settings) def totp(): if request.method == "POST": if not request.form: flash("Missing form data.", "error") return redirect(url_for("totp")) if "totp_token" not in request.form: flash("Missing token parameter.", "error") return redirect(url_for("totp")) if not current_user.check_otp(request.form["totp_token"]): flash("The token is invalid.", "error") return redirect(url_for("totp")) session["totp_validated"] = True redirect(url_for("loading", next=request.form.get("next") or url_for("home"))) if not current_user.is_two_factor_enabled or session.get("totp_validated", False): return redirect(url_for("home")) return render_template("totp.html", dark_mode=app.config["DARK_MODE"])
null
18,250
from contextlib import suppress from os import _exit, getenv, listdir, sep, urandom from os.path import basename, dirname, join from secrets import choice from string import ascii_letters, digits from sys import path as sys_path, modules as sys_modules from pathlib import Path from bs4 import BeautifulSoup from copy import deepcopy from datetime import datetime, timedelta, timezone from dateutil.parser import parse as dateutil_parse from docker import DockerClient from docker.errors import NotFound as docker_NotFound, APIError as docker_APIError, DockerException from flask import Flask, Response, flash, jsonify, redirect, render_template, request, send_file, session, url_for from flask_login import current_user, LoginManager, login_required, login_user, logout_user from flask_wtf.csrf import CSRFProtect, CSRFError, generate_csrf from glob import glob from hashlib import sha256 from importlib.machinery import SourceFileLoader from io import BytesIO from json import JSONDecodeError, dumps, loads as json_loads from jinja2 import Template from kubernetes import client as kube_client from kubernetes import config as kube_config from kubernetes.client.exceptions import ApiException as kube_ApiException from regex import compile as re_compile, match as regex_match from requests import get from shutil import move, rmtree from signal import SIGINT, signal, SIGTERM from subprocess import PIPE, Popen, call from tarfile import CompressionError, HeaderError, ReadError, TarError, open as tar_open from threading import Thread from tempfile import NamedTemporaryFile from time import sleep, time from traceback import format_exc from zipfile import BadZipFile, ZipFile from src.Instances import Instances from src.ConfigFiles import ConfigFiles from src.Config import Config from src.ReverseProxied import ReverseProxied from src.User import AnonymousUser, User from utils import check_settings, get_b64encoded_qr_image, path_to_dict from Database import Database from logging import getLogger app = Flask(__name__, static_url_path="/", static_folder="static", template_folder="templates") app.config["SECRET_KEY"] = getenv("FLASK_SECRET", urandom(32)) app.wsgi_app = ReverseProxied(app.wsgi_app, x_for=PROXY_NUMBERS, x_proto=PROXY_NUMBERS, x_host=PROXY_NUMBERS, x_prefix=PROXY_NUMBERS) app.logger.handlers = gunicorn_logger.handlers app.logger.setLevel(gunicorn_logger.level) db = Database(app.logger, ui=True) while not db.is_initialized(): app.logger.warning("Database is not initialized, retrying in 5s ...") sleep(5) app.logger.info("Database is ready") bw_version = Path(sep, "usr", "share", "bunkerweb", "VERSION").read_text(encoding="utf-8").strip() try: app.config.update( DEBUG=True, INSTANCES=Instances(docker_client, kubernetes_client, INTEGRATION), CONFIG=Config(db), CONFIGFILES=ConfigFiles(app.logger, db), WTF_CSRF_SSL_STRICT=False, USER=USER, SEND_FILE_MAX_AGE_DEFAULT=86400, PLUGIN_ARGS={}, RELOADING=False, LAST_RELOAD=0, TO_FLASH=[], DARK_MODE=False, CURRENT_TOTP_TOKEN=None, ) except FileNotFoundError as e: app.logger.error(repr(e), e.filename) stop(1) app.jinja_env.globals.update(check_settings=check_settings) def instances(): # Manage instances if request.method == "POST": # Check operation if "operation" not in request.form or request.form["operation"] not in ( "reload", "start", "stop", "restart", ): flash("Missing operation parameter on /instances.", "error") return redirect(url_for("loading", next=url_for("instances"))) # Check that all fields are present if "INSTANCE_ID" not in request.form: flash("Missing INSTANCE_ID parameter.", "error") return redirect(url_for("loading", next=url_for("instances"))) app.config["RELOADING"] = True app.config["LAST_RELOAD"] = time() Thread( target=manage_bunkerweb, name="Reloading instances", args=("instances", request.form["INSTANCE_ID"]), kwargs={"operation": request.form["operation"]}, ).start() return redirect( url_for( "loading", next=url_for("instances"), message=(f"{request.form['operation'].title()}ing" if request.form["operation"] != "stop" else "Stopping") + " instance", ) ) # Display instances instances = app.config["INSTANCES"].get_instances() return render_template( "instances.html", title="Instances", instances=instances, username=current_user.get_id(), dark_mode=app.config["DARK_MODE"], ) def services(): if request.method == "POST": # Check operation if "operation" not in request.form or request.form["operation"] not in ( "new", "edit", "delete", ): flash("Missing operation parameter on /services.", "error") return redirect(url_for("loading", next=url_for("services"))) # Check variables variables = deepcopy(request.form.to_dict()) del variables["csrf_token"] if "OLD_SERVER_NAME" not in request.form and request.form["operation"] == "edit": flash("Missing OLD_SERVER_NAME parameter.", "error") return redirect(url_for("loading", next=url_for("services"))) if "SERVER_NAME" not in variables: variables["SERVER_NAME"] = variables["OLD_SERVER_NAME"] if request.form["operation"] in ("new", "edit"): del variables["operation"] del variables["OLD_SERVER_NAME"] # Edit check fields and remove already existing ones config = app.config["CONFIG"].get_config(methods=False) server_name = variables["SERVER_NAME"].split(" ")[0] for variable, value in deepcopy(variables).items(): if variable.endswith("SCHEMA"): del variables[variable] continue if value == "on": value = "yes" elif value == "off": value = "no" if variable in variables and variable != "SERVER_NAME" and value == config.get(f"{server_name}_{variable}" if request.form["operation"] == "edit" else variable, None): del variables[variable] if request.form["operation"] == "edit" and len(variables) == 1 and "SERVER_NAME" in variables and variables["SERVER_NAME"] == request.form.get("OLD_SERVER_NAME", ""): flash( "The service was not edited because no values were changed.", "error", ) return redirect(url_for("loading", next=url_for("services"))) elif request.form["operation"] == "new" and not variables: flash("The service was not created because all values had the default value.", "error") return redirect(url_for("loading", next=url_for("services"))) error = app.config["CONFIG"].check_variables(variables) if error: return redirect(url_for("loading", next=url_for("services"))) # Delete elif request.form["operation"] == "delete": if "SERVER_NAME" not in request.form: flash("Missing SERVER_NAME parameter.", "error") return redirect(url_for("loading", next=url_for("services"))) error = app.config["CONFIG"].check_variables({"SERVER_NAME": request.form["SERVER_NAME"]}) if error: return redirect(url_for("loading", next=url_for("services"))) error = 0 # Reload instances app.config["RELOADING"] = True app.config["LAST_RELOAD"] = time() Thread( target=manage_bunkerweb, name="Reloading instances", args=("services", variables, request.form.get("OLD_SERVER_NAME", ""), variables.get("SERVER_NAME", "")), kwargs={"operation": request.form["operation"]}, ).start() message = "" if request.form["operation"] == "new": message = f"Creating service {variables.get('SERVER_NAME', '').split(' ')[0]}" elif request.form["operation"] == "edit": message = f"Saving configuration for service {request.form.get('OLD_SERVER_NAME', '').split(' ')[0]}" elif request.form["operation"] == "delete": message = f"Deleting service {request.form.get('SERVER_NAME', '').split(' ')[0]}" return redirect(url_for("loading", next=url_for("services"), message=message)) # Display services services = app.config["CONFIG"].get_services() return render_template( "services.html", services=[ { "SERVER_NAME": { "value": service["SERVER_NAME"]["value"].split(" ")[0], "full_value": service["SERVER_NAME"]["value"], "method": service["SERVER_NAME"]["method"], }, "USE_REVERSE_PROXY": service["USE_REVERSE_PROXY"], "SERVE_FILES": service["SERVE_FILES"], "REMOTE_PHP": service["REMOTE_PHP"], "AUTO_LETS_ENCRYPT": service["AUTO_LETS_ENCRYPT"], "USE_CUSTOM_SSL": service["USE_CUSTOM_SSL"], "GENERATE_SELF_SIGNED_SSL": service["GENERATE_SELF_SIGNED_SSL"], "USE_MODSECURITY": service["USE_MODSECURITY"], "USE_BAD_BEHAVIOR": service["USE_BAD_BEHAVIOR"], "USE_LIMIT_REQ": service["USE_LIMIT_REQ"], "USE_DNSBL": service["USE_DNSBL"], "settings": dumps(service), } for service in services ], username=current_user.get_id(), dark_mode=app.config["DARK_MODE"], ) The provided code snippet includes necessary dependencies for implementing the `home` function. Write a Python function `def home()` to solve the following problem: It returns the home page :return: The home.html template is being rendered with the following variables: check_version: a boolean indicating whether the local version is the same as the remote version remote_version: the remote version version: the local version instances_number: the number of instances services_number: the number of services posts: a list of posts Here is the function: def home(): """ It returns the home page :return: The home.html template is being rendered with the following variables: check_version: a boolean indicating whether the local version is the same as the remote version remote_version: the remote version version: the local version instances_number: the number of instances services_number: the number of services posts: a list of posts """ try: r = get("https://github.com/bunkerity/bunkerweb/releases/latest", allow_redirects=True, timeout=5) r.raise_for_status() except BaseException: r = None remote_version = None if r and r.status_code == 200: remote_version = basename(r.url).strip().replace("v", "") instances = app.config["INSTANCES"].get_instances() services = app.config["CONFIG"].get_services() instance_health_count = 0 for instance in instances: if instance.health is True: instance_health_count += 1 services_scheduler_count = 0 services_ui_count = 0 services_autoconf_count = 0 for service in services: if service["SERVER_NAME"]["method"] == "scheduler": services_scheduler_count += 1 elif service["SERVER_NAME"]["method"] == "ui": services_ui_count += 1 elif service["SERVER_NAME"]["method"] == "autoconf": services_autoconf_count += 1 return render_template( "home.html", check_version=not remote_version or bw_version == remote_version, remote_version=remote_version, version=bw_version, instances_number=len(instances), services_number=len(services), plugins_errors=db.get_plugins_errors(), instance_health_count=instance_health_count, services_scheduler_count=services_scheduler_count, services_ui_count=services_ui_count, services_autoconf_count=services_autoconf_count, username=current_user.get_id(), dark_mode=app.config["DARK_MODE"], )
It returns the home page :return: The home.html template is being rendered with the following variables: check_version: a boolean indicating whether the local version is the same as the remote version remote_version: the remote version version: the local version instances_number: the number of instances services_number: the number of services posts: a list of posts
18,251
from contextlib import suppress from os import _exit, getenv, listdir, sep, urandom from os.path import basename, dirname, join from secrets import choice from string import ascii_letters, digits from sys import path as sys_path, modules as sys_modules from pathlib import Path from bs4 import BeautifulSoup from copy import deepcopy from datetime import datetime, timedelta, timezone from dateutil.parser import parse as dateutil_parse from docker import DockerClient from docker.errors import NotFound as docker_NotFound, APIError as docker_APIError, DockerException from flask import Flask, Response, flash, jsonify, redirect, render_template, request, send_file, session, url_for from flask_login import current_user, LoginManager, login_required, login_user, logout_user from flask_wtf.csrf import CSRFProtect, CSRFError, generate_csrf from glob import glob from hashlib import sha256 from importlib.machinery import SourceFileLoader from io import BytesIO from json import JSONDecodeError, dumps, loads as json_loads from jinja2 import Template from kubernetes import client as kube_client from kubernetes import config as kube_config from kubernetes.client.exceptions import ApiException as kube_ApiException from regex import compile as re_compile, match as regex_match from requests import get from shutil import move, rmtree from signal import SIGINT, signal, SIGTERM from subprocess import PIPE, Popen, call from tarfile import CompressionError, HeaderError, ReadError, TarError, open as tar_open from threading import Thread from tempfile import NamedTemporaryFile from time import sleep, time from traceback import format_exc from zipfile import BadZipFile, ZipFile from src.Instances import Instances from src.ConfigFiles import ConfigFiles from src.Config import Config from src.ReverseProxied import ReverseProxied from src.User import AnonymousUser, User from utils import check_settings, get_b64encoded_qr_image, path_to_dict from Database import Database from logging import getLogger app = Flask(__name__, static_url_path="/", static_folder="static", template_folder="templates") app.config["SECRET_KEY"] = getenv("FLASK_SECRET", urandom(32)) app.wsgi_app = ReverseProxied(app.wsgi_app, x_for=PROXY_NUMBERS, x_proto=PROXY_NUMBERS, x_host=PROXY_NUMBERS, x_prefix=PROXY_NUMBERS) app.logger.handlers = gunicorn_logger.handlers app.logger.setLevel(gunicorn_logger.level) db = Database(app.logger, ui=True) while not db.is_initialized(): app.logger.warning("Database is not initialized, retrying in 5s ...") sleep(5) USER_PASSWORD_RX = re_compile(r"^(?=.*?\p{Lowercase_Letter})(?=.*?\p{Uppercase_Letter})(?=.*?\d)(?=.*?[ !\"#$%&'()*+,./:;<=>?@[\\\]^_`{|}~-]).{8,}$") app.logger.info("Database is ready") try: app.config.update( DEBUG=True, INSTANCES=Instances(docker_client, kubernetes_client, INTEGRATION), CONFIG=Config(db), CONFIGFILES=ConfigFiles(app.logger, db), WTF_CSRF_SSL_STRICT=False, USER=USER, SEND_FILE_MAX_AGE_DEFAULT=86400, PLUGIN_ARGS={}, RELOADING=False, LAST_RELOAD=0, TO_FLASH=[], DARK_MODE=False, CURRENT_TOTP_TOKEN=None, ) except FileNotFoundError as e: app.logger.error(repr(e), e.filename) stop(1) app.jinja_env.globals.update(check_settings=check_settings) def get_b64encoded_qr_image(data: str): def account(): if request.method == "POST": # Check form data validity if not request.form: flash("Missing form data.", "error") return redirect(url_for("account")) elif "operation" not in request.form: flash("Missing operation parameter.", "error") return redirect(url_for("account")) if "curr_password" not in request.form or not current_user.check_password(request.form["curr_password"]): flash(f"The current password is incorrect. ({request.form['operation']})", "error") return redirect(url_for("account")) username = current_user.get_id() password = request.form["curr_password"] is_two_factor_enabled = current_user.is_two_factor_enabled secret_token = current_user.secret_token if request.form["operation"] == "username": if "admin_username" not in request.form: flash("Missing admin_username parameter. (username)", "error") return redirect(url_for("account")) elif len(request.form["admin_username"]) > 256: flash("The admin username is too long. It must be less than 256 characters. (username)", "error") return redirect(url_for("account")) username = request.form["admin_username"] session.clear() logout_user() elif request.form["operation"] == "password": if "admin_password" not in request.form: flash("Missing admin_password parameter. (password)", "error") return redirect(url_for("account")) elif request.form.get("admin_password"): if not request.form.get("admin_password_check"): flash("Missing admin_password_check parameter. (password)", "error") return redirect(url_for("account")) elif request.form["admin_password"] != request.form["admin_password_check"]: flash("The passwords does not match. (password)", "error") return redirect(url_for("account")) elif not USER_PASSWORD_RX.match(request.form["admin_password"]): flash("The admin password is not strong enough. It must contain at least 8 characters, including at least 1 uppercase letter, 1 lowercase letter, 1 number and 1 special character (#@?!$%^&*-). (password)", "error") return redirect(url_for("account")) elif request.form.get("admin_password_check"): flash("Missing admin_password parameter. (password)", "error") return redirect(url_for("account")) password = request.form["admin_password"] session.clear() logout_user() elif request.form["operation"] == "totp": if "totp_token" not in request.form: flash("Missing totp_token parameter. (totp)", "error") return redirect(url_for("account")) elif not current_user.check_otp(request.form["totp_token"], secret=app.config["CURRENT_TOTP_TOKEN"]): flash("The totp token is invalid. (totp)", "error") return redirect(url_for("account")) session["totp_validated"] = not current_user.is_two_factor_enabled is_two_factor_enabled = session["totp_validated"] secret_token = None if current_user.is_two_factor_enabled else app.config["CURRENT_TOTP_TOKEN"] app.config["CURRENT_TOTP_TOKEN"] = None else: flash("Invalid operation parameter.", "error") return redirect(url_for("account")) user = User(username, password, is_two_factor_enabled=is_two_factor_enabled, secret_token=secret_token, method=current_user.method) ret = db.update_ui_user(username, user.password_hash, is_two_factor_enabled, secret_token, current_user.method if request.form["operation"] == "totp" else "ui") if ret: app.logger.error(f"Couldn't update the admin user in the database: {ret}") flash(f"Couldn't update the admin user in the database: {ret}", "error") return redirect(url_for("account")) flash( f"The {request.form['operation']} has been successfully updated." if request.form["operation"] != "totp" else f"The two-factor authentication was successfully {'disabled' if current_user.is_two_factor_enabled else 'enabled'}.", ) return redirect(url_for("account" if request.form["operation"] == "totp" else "login")) secret_token = "" totp_qr_image = "" if not current_user.is_two_factor_enabled: current_user.refresh_totp() secret_token = current_user.secret_token totp_qr_image = get_b64encoded_qr_image(current_user.get_authentication_setup_uri()) app.config["CURRENT_TOTP_TOKEN"] = secret_token return render_template("account.html", username=current_user.get_id(), is_totp=current_user.is_two_factor_enabled, secret_token=secret_token, totp_qr_image=totp_qr_image, dark_mode=app.config["DARK_MODE"])
null
18,252
from contextlib import suppress from os import _exit, getenv, listdir, sep, urandom from os.path import basename, dirname, join from secrets import choice from string import ascii_letters, digits from sys import path as sys_path, modules as sys_modules from pathlib import Path from bs4 import BeautifulSoup from copy import deepcopy from datetime import datetime, timedelta, timezone from dateutil.parser import parse as dateutil_parse from docker import DockerClient from docker.errors import NotFound as docker_NotFound, APIError as docker_APIError, DockerException from flask import Flask, Response, flash, jsonify, redirect, render_template, request, send_file, session, url_for from flask_login import current_user, LoginManager, login_required, login_user, logout_user from flask_wtf.csrf import CSRFProtect, CSRFError, generate_csrf from glob import glob from hashlib import sha256 from importlib.machinery import SourceFileLoader from io import BytesIO from json import JSONDecodeError, dumps, loads as json_loads from jinja2 import Template from kubernetes import client as kube_client from kubernetes import config as kube_config from kubernetes.client.exceptions import ApiException as kube_ApiException from regex import compile as re_compile, match as regex_match from requests import get from shutil import move, rmtree from signal import SIGINT, signal, SIGTERM from subprocess import PIPE, Popen, call from tarfile import CompressionError, HeaderError, ReadError, TarError, open as tar_open from threading import Thread from tempfile import NamedTemporaryFile from time import sleep, time from traceback import format_exc from zipfile import BadZipFile, ZipFile from src.Instances import Instances from src.ConfigFiles import ConfigFiles from src.Config import Config from src.ReverseProxied import ReverseProxied from src.User import AnonymousUser, User from utils import check_settings, get_b64encoded_qr_image, path_to_dict from Database import Database from logging import getLogger app = Flask(__name__, static_url_path="/", static_folder="static", template_folder="templates") app.config["SECRET_KEY"] = getenv("FLASK_SECRET", urandom(32)) app.wsgi_app = ReverseProxied(app.wsgi_app, x_for=PROXY_NUMBERS, x_proto=PROXY_NUMBERS, x_host=PROXY_NUMBERS, x_prefix=PROXY_NUMBERS) app.logger.handlers = gunicorn_logger.handlers app.logger.setLevel(gunicorn_logger.level) app.logger.info("Database is ready") try: app.config.update( DEBUG=True, INSTANCES=Instances(docker_client, kubernetes_client, INTEGRATION), CONFIG=Config(db), CONFIGFILES=ConfigFiles(app.logger, db), WTF_CSRF_SSL_STRICT=False, USER=USER, SEND_FILE_MAX_AGE_DEFAULT=86400, PLUGIN_ARGS={}, RELOADING=False, LAST_RELOAD=0, TO_FLASH=[], DARK_MODE=False, CURRENT_TOTP_TOKEN=None, ) except FileNotFoundError as e: app.logger.error(repr(e), e.filename) stop(1) app.jinja_env.globals.update(check_settings=check_settings) def manage_bunkerweb(method: str, *args, operation: str = "reloads"): # Do the operation error = False if method == "services": service_custom_confs = glob(join(sep, "etc", "bunkerweb", "configs", "*", args[1].split(" ")[0])) moved = False deleted = False if operation == "new": operation, error = app.config["CONFIG"].new_service(args[0]) elif operation == "edit": if args[1].split(" ")[0] != args[2].split(" ")[0] and service_custom_confs: for service_custom_conf in service_custom_confs: if listdir(service_custom_conf): move(service_custom_conf, service_custom_conf.replace(f"{sep}{args[1].split(' ')[0]}", f"{sep}{args[2].split(' ')[0]}")) moved = True operation, error = app.config["CONFIG"].edit_service(args[1], args[0], check_changes=not moved) elif operation == "delete": for service_custom_conf in glob(join(sep, "etc", "bunkerweb", "configs", "*", args[2].split(" ")[0])): if listdir(service_custom_conf): rmtree(service_custom_conf, ignore_errors=True) deleted = True operation, error = app.config["CONFIG"].delete_service(args[2], check_changes=not deleted) if error: app.config["TO_FLASH"].append({"content": operation, "type": "error"}) else: app.config["TO_FLASH"].append({"content": operation, "type": "success"}) if moved or deleted: changes = ["config", "custom_configs"] error = app.config["CONFIGFILES"].save_configs(check_changes=False) if error: app.config["TO_FLASH"].append({"content": error, "type": "error"}) changes.pop() # update changes in db ret = db.checked_changes(changes, value=True) if ret: app.logger.error(f"Couldn't set the changes to checked in the database: {ret}") app.config["TO_FLASH"].append({"content": f"An error occurred when setting the changes to checked in the database : {ret}", "type": "error"}) if method == "global_config": operation = app.config["CONFIG"].edit_global_conf(args[0]) elif method == "plugins": app.config["CONFIG"].reload_config() if operation == "reload": operation = app.config["INSTANCES"].reload_instance(args[0]) elif operation == "start": operation = app.config["INSTANCES"].start_instance(args[0]) elif operation == "stop": operation = app.config["INSTANCES"].stop_instance(args[0]) elif operation == "restart": operation = app.config["INSTANCES"].restart_instance(args[0]) elif not error: operation = "The scheduler will be in charge of reloading the instances." else: operation = "" if operation: if isinstance(operation, list): for op in operation: app.config["TO_FLASH"].append({"content": f"Reload failed for the instance {op}", "type": "error"}) elif operation.startswith("Can't"): app.config["TO_FLASH"].append({"content": operation, "type": "error"}) else: app.config["TO_FLASH"].append({"content": operation, "type": "success"}) app.config["RELOADING"] = False def global_config(): if request.method == "POST": # Check variables variables = deepcopy(request.form.to_dict()) del variables["csrf_token"] # Edit check fields and remove already existing ones config = app.config["CONFIG"].get_config(methods=False) for variable, value in deepcopy(variables).items(): if value == "on": value = "yes" elif value == "off": value = "no" if value == config.get(variable, None) or not value.strip(): del variables[variable] if not variables: flash("The global configuration was not edited because no values were changed.") return redirect(url_for("loading", next=url_for("global_config"))) error = app.config["CONFIG"].check_variables(variables, True) if error: return redirect(url_for("loading", next=url_for("global_config"))) # Reload instances app.config["RELOADING"] = True app.config["LAST_RELOAD"] = time() Thread( target=manage_bunkerweb, name="Reloading instances", args=( "global_config", variables, ), ).start() return redirect( url_for( "loading", next=url_for("global_config"), message="Saving global configuration", ) ) # Display global config return render_template( "global_config.html", username=current_user.get_id(), dark_mode=app.config["DARK_MODE"], )
null
18,253
from contextlib import suppress from os import _exit, getenv, listdir, sep, urandom from os.path import basename, dirname, join from secrets import choice from string import ascii_letters, digits from sys import path as sys_path, modules as sys_modules from pathlib import Path from bs4 import BeautifulSoup from copy import deepcopy from datetime import datetime, timedelta, timezone from dateutil.parser import parse as dateutil_parse from docker import DockerClient from docker.errors import NotFound as docker_NotFound, APIError as docker_APIError, DockerException from flask import Flask, Response, flash, jsonify, redirect, render_template, request, send_file, session, url_for from flask_login import current_user, LoginManager, login_required, login_user, logout_user from flask_wtf.csrf import CSRFProtect, CSRFError, generate_csrf from glob import glob from hashlib import sha256 from importlib.machinery import SourceFileLoader from io import BytesIO from json import JSONDecodeError, dumps, loads as json_loads from jinja2 import Template from kubernetes import client as kube_client from kubernetes import config as kube_config from kubernetes.client.exceptions import ApiException as kube_ApiException from regex import compile as re_compile, match as regex_match from requests import get from shutil import move, rmtree from signal import SIGINT, signal, SIGTERM from subprocess import PIPE, Popen, call from tarfile import CompressionError, HeaderError, ReadError, TarError, open as tar_open from threading import Thread from tempfile import NamedTemporaryFile from time import sleep, time from traceback import format_exc from zipfile import BadZipFile, ZipFile from src.Instances import Instances from src.ConfigFiles import ConfigFiles from src.Config import Config from src.ReverseProxied import ReverseProxied from src.User import AnonymousUser, User from utils import check_settings, get_b64encoded_qr_image, path_to_dict from Database import Database from logging import getLogger app = Flask(__name__, static_url_path="/", static_folder="static", template_folder="templates") app.config["SECRET_KEY"] = getenv("FLASK_SECRET", urandom(32)) app.wsgi_app = ReverseProxied(app.wsgi_app, x_for=PROXY_NUMBERS, x_proto=PROXY_NUMBERS, x_host=PROXY_NUMBERS, x_prefix=PROXY_NUMBERS) app.logger.handlers = gunicorn_logger.handlers app.logger.setLevel(gunicorn_logger.level) db = Database(app.logger, ui=True) while not db.is_initialized(): app.logger.warning("Database is not initialized, retrying in 5s ...") sleep(5) app.logger.info("Database is ready") try: app.config.update( DEBUG=True, INSTANCES=Instances(docker_client, kubernetes_client, INTEGRATION), CONFIG=Config(db), CONFIGFILES=ConfigFiles(app.logger, db), WTF_CSRF_SSL_STRICT=False, USER=USER, SEND_FILE_MAX_AGE_DEFAULT=86400, PLUGIN_ARGS={}, RELOADING=False, LAST_RELOAD=0, TO_FLASH=[], DARK_MODE=False, CURRENT_TOTP_TOKEN=None, ) except FileNotFoundError as e: app.logger.error(repr(e), e.filename) stop(1) app.jinja_env.globals.update(check_settings=check_settings) def services(): if request.method == "POST": # Check operation if "operation" not in request.form or request.form["operation"] not in ( "new", "edit", "delete", ): flash("Missing operation parameter on /services.", "error") return redirect(url_for("loading", next=url_for("services"))) # Check variables variables = deepcopy(request.form.to_dict()) del variables["csrf_token"] if "OLD_SERVER_NAME" not in request.form and request.form["operation"] == "edit": flash("Missing OLD_SERVER_NAME parameter.", "error") return redirect(url_for("loading", next=url_for("services"))) if "SERVER_NAME" not in variables: variables["SERVER_NAME"] = variables["OLD_SERVER_NAME"] if request.form["operation"] in ("new", "edit"): del variables["operation"] del variables["OLD_SERVER_NAME"] # Edit check fields and remove already existing ones config = app.config["CONFIG"].get_config(methods=False) server_name = variables["SERVER_NAME"].split(" ")[0] for variable, value in deepcopy(variables).items(): if variable.endswith("SCHEMA"): del variables[variable] continue if value == "on": value = "yes" elif value == "off": value = "no" if variable in variables and variable != "SERVER_NAME" and value == config.get(f"{server_name}_{variable}" if request.form["operation"] == "edit" else variable, None): del variables[variable] if request.form["operation"] == "edit" and len(variables) == 1 and "SERVER_NAME" in variables and variables["SERVER_NAME"] == request.form.get("OLD_SERVER_NAME", ""): flash( "The service was not edited because no values were changed.", "error", ) return redirect(url_for("loading", next=url_for("services"))) elif request.form["operation"] == "new" and not variables: flash("The service was not created because all values had the default value.", "error") return redirect(url_for("loading", next=url_for("services"))) error = app.config["CONFIG"].check_variables(variables) if error: return redirect(url_for("loading", next=url_for("services"))) # Delete elif request.form["operation"] == "delete": if "SERVER_NAME" not in request.form: flash("Missing SERVER_NAME parameter.", "error") return redirect(url_for("loading", next=url_for("services"))) error = app.config["CONFIG"].check_variables({"SERVER_NAME": request.form["SERVER_NAME"]}) if error: return redirect(url_for("loading", next=url_for("services"))) error = 0 # Reload instances app.config["RELOADING"] = True app.config["LAST_RELOAD"] = time() Thread( target=manage_bunkerweb, name="Reloading instances", args=("services", variables, request.form.get("OLD_SERVER_NAME", ""), variables.get("SERVER_NAME", "")), kwargs={"operation": request.form["operation"]}, ).start() message = "" if request.form["operation"] == "new": message = f"Creating service {variables.get('SERVER_NAME', '').split(' ')[0]}" elif request.form["operation"] == "edit": message = f"Saving configuration for service {request.form.get('OLD_SERVER_NAME', '').split(' ')[0]}" elif request.form["operation"] == "delete": message = f"Deleting service {request.form.get('SERVER_NAME', '').split(' ')[0]}" return redirect(url_for("loading", next=url_for("services"), message=message)) # Display services services = app.config["CONFIG"].get_services() return render_template( "services.html", services=[ { "SERVER_NAME": { "value": service["SERVER_NAME"]["value"].split(" ")[0], "full_value": service["SERVER_NAME"]["value"], "method": service["SERVER_NAME"]["method"], }, "USE_REVERSE_PROXY": service["USE_REVERSE_PROXY"], "SERVE_FILES": service["SERVE_FILES"], "REMOTE_PHP": service["REMOTE_PHP"], "AUTO_LETS_ENCRYPT": service["AUTO_LETS_ENCRYPT"], "USE_CUSTOM_SSL": service["USE_CUSTOM_SSL"], "GENERATE_SELF_SIGNED_SSL": service["GENERATE_SELF_SIGNED_SSL"], "USE_MODSECURITY": service["USE_MODSECURITY"], "USE_BAD_BEHAVIOR": service["USE_BAD_BEHAVIOR"], "USE_LIMIT_REQ": service["USE_LIMIT_REQ"], "USE_DNSBL": service["USE_DNSBL"], "settings": dumps(service), } for service in services ], username=current_user.get_id(), dark_mode=app.config["DARK_MODE"], ) def path_to_dict( path: str, *, is_cache: bool = False, db_data: Optional[List[dict]] = None, services: Optional[List[dict]] = None, ) -> dict: db_data = db_data or [] services = services or [] if not is_cache: config_types = [ "http", "stream", "server-http", "server-stream", "default-server-http", "modsec", "modsec-crs", ] d = { "name": "configs", "type": "folder", "path": path, "can_create_files": False, "can_create_folders": False, "can_edit": False, "can_delete": False, "children": [ { "name": config, "type": "folder", "path": join(path, config), "can_create_files": True, "can_create_folders": False, "can_edit": False, "can_delete": False, "children": [ { "name": service, "type": "folder", "path": join(path, config, service), "can_create_files": True, "can_create_folders": False, "can_edit": False, "can_delete": False, "children": [], } for service in services ], } for config in config_types ], } for conf in db_data: type_lower = conf["type"].replace("_", "-") file_info = { "name": f"{conf['name']}.conf", "type": "file", "path": join( path, type_lower, conf["service_id"] or "", f"{conf['name']}.conf", ), "can_edit": conf["method"] == "ui", "can_delete": True, "can_download": True, "content": conf["data"].decode("utf-8"), } if conf["service_id"]: d["children"][config_types.index(type_lower)]["children"][[x["name"] for x in d["children"][config_types.index(type_lower)]["children"]].index(conf["service_id"])]["children"].append(file_info) else: d["children"][config_types.index(type_lower)]["children"].append(file_info) else: d = { "name": "cache", "type": "folder", "path": path, "can_create_files": False, "can_create_folders": False, "can_edit": False, "can_delete": False, "children": [ { "name": service, "type": "folder", "path": join(path, service), "can_create_files": False, "can_create_folders": False, "can_edit": False, "can_delete": False, "children": [], } for service in services ], } for conf in db_data: file_info = { "name": join(conf["job_name"], conf["file_name"]), "type": "file", "path": join( path, conf["service_id"] or "", conf["file_name"], ), "can_edit": False, "can_delete": False, "can_download": True, "content": conf["data"], } if conf["service_id"]: d["children"][[x["name"] for x in d["children"]].index(conf["service_id"])]["children"].append(file_info) else: d["children"].append(file_info) return d def configs(): if request.method == "POST": operation = "" # Check operation if "operation" not in request.form or request.form["operation"] not in ( "new", "edit", "delete", ): flash("Missing operation parameter on /configs.", "error") return redirect(url_for("loading", next=url_for("configs"))) # Check variables variables = deepcopy(request.form.to_dict()) del variables["csrf_token"] operation = app.config["CONFIGFILES"].check_path(variables["path"]) if operation: flash(operation, "error") return redirect(url_for("loading", next=url_for("configs"))) if request.form["operation"] in ("new", "edit"): if not app.config["CONFIGFILES"].check_name(variables["name"]): flash( f"Invalid {variables['type']} name. (Can only contain numbers, letters, underscores, dots and hyphens (min 4 characters and max 64))", "error", ) return redirect(url_for("loading", next=url_for("configs"))) if variables["type"] == "file": variables["name"] = f"{variables['name']}.conf" if "old_name" in variables: variables["old_name"] = f"{variables['old_name']}.conf" variables["content"] = BeautifulSoup(variables["content"], "html.parser").get_text() error = False if request.form["operation"] == "new": if variables["type"] == "folder": operation, error = app.config["CONFIGFILES"].create_folder(variables["path"], variables["name"]) elif variables["type"] == "file": operation, error = app.config["CONFIGFILES"].create_file(variables["path"], variables["name"], variables["content"]) elif request.form["operation"] == "edit": if variables["type"] == "folder": operation, error = app.config["CONFIGFILES"].edit_folder( variables["path"], variables["name"], variables.get("old_name", variables["name"]), ) elif variables["type"] == "file": operation, error = app.config["CONFIGFILES"].edit_file( variables["path"], variables["name"], variables.get("old_name", variables["name"]), variables["content"], ) if error: flash(operation, "error") return redirect(url_for("loading", next=url_for("configs"))) else: operation, error = app.config["CONFIGFILES"].delete_path(variables["path"]) if error: flash(operation, "error") return redirect(url_for("loading", next=url_for("configs"))) flash(operation) error = app.config["CONFIGFILES"].save_configs() if error: flash("Couldn't save custom configs to database", "error") return redirect(url_for("loading", next=url_for("configs"))) return render_template( "configs.html", folders=[ path_to_dict( join(sep, "etc", "bunkerweb", "configs"), db_data=db.get_custom_configs(), services=app.config["CONFIG"].get_config(methods=False).get("SERVER_NAME", "").split(" "), ) ], username=current_user.get_id(), dark_mode=app.config["DARK_MODE"], )
null
18,254
from contextlib import suppress from os import _exit, getenv, listdir, sep, urandom from os.path import basename, dirname, join from secrets import choice from string import ascii_letters, digits from sys import path as sys_path, modules as sys_modules from pathlib import Path from bs4 import BeautifulSoup from copy import deepcopy from datetime import datetime, timedelta, timezone from dateutil.parser import parse as dateutil_parse from docker import DockerClient from docker.errors import NotFound as docker_NotFound, APIError as docker_APIError, DockerException from flask import Flask, Response, flash, jsonify, redirect, render_template, request, send_file, session, url_for from flask_login import current_user, LoginManager, login_required, login_user, logout_user from flask_wtf.csrf import CSRFProtect, CSRFError, generate_csrf from glob import glob from hashlib import sha256 from importlib.machinery import SourceFileLoader from io import BytesIO from json import JSONDecodeError, dumps, loads as json_loads from jinja2 import Template from kubernetes import client as kube_client from kubernetes import config as kube_config from kubernetes.client.exceptions import ApiException as kube_ApiException from regex import compile as re_compile, match as regex_match from requests import get from shutil import move, rmtree from signal import SIGINT, signal, SIGTERM from subprocess import PIPE, Popen, call from tarfile import CompressionError, HeaderError, ReadError, TarError, open as tar_open from threading import Thread from tempfile import NamedTemporaryFile from time import sleep, time from traceback import format_exc from zipfile import BadZipFile, ZipFile from src.Instances import Instances from src.ConfigFiles import ConfigFiles from src.Config import Config from src.ReverseProxied import ReverseProxied from src.User import AnonymousUser, User from utils import check_settings, get_b64encoded_qr_image, path_to_dict from Database import Database from logging import getLogger Path(sep, "var", "tmp", "bunkerweb", "ui.healthy").write_text("ok", encoding="utf-8") def plugins(): tmp_ui_path = Path(sep, "var", "tmp", "bunkerweb", "ui") if request.method == "POST": operation = "" error = 0 if "operation" in request.form and request.form["operation"] == "delete": # Check variables variables = deepcopy(request.form.to_dict()) del variables["csrf_token"] if variables["external"] != "True": flash(f"Can't delete internal plugin {variables['name']}", "error") return redirect(url_for("loading", next=url_for("plugins"))) plugins = app.config["CONFIG"].get_plugins() for plugin in deepcopy(plugins): if plugin["external"] is False or plugin["id"] == variables["name"]: del plugins[plugins.index(plugin)] err = db.update_external_plugins(plugins) if err: flash( f"Couldn't update external plugins to database: {err}", "error", ) flash(f"Deleted plugin {variables['name']} successfully") else: if not tmp_ui_path.exists() or not listdir(str(tmp_ui_path)): flash("Please upload new plugins to reload plugins", "error") return redirect(url_for("loading", next=url_for("plugins"))) errors = 0 files_count = 0 new_plugins = [] new_plugins_ids = [] for file in listdir(str(tmp_ui_path)): if not tmp_ui_path.joinpath(file).is_file(): continue files_count += 1 folder_name = "" temp_folder_name = file.split(".")[0] temp_folder_path = tmp_ui_path.joinpath(temp_folder_name) is_dir = False try: if file.endswith(".zip"): try: with ZipFile(str(tmp_ui_path.joinpath(file))) as zip_file: try: zip_file.getinfo("plugin.json") except KeyError: is_dir = True zip_file.extractall(str(temp_folder_path)) except BadZipFile: errors += 1 error = 1 flash( f"{file} is not a valid zip file. ({folder_name or temp_folder_name})", "error", ) else: try: with tar_open(str(tmp_ui_path.joinpath(file)), errorlevel=2) as tar_file: try: tar_file.getmember("plugin.json") except KeyError: is_dir = True tar_file.extractall(str(temp_folder_path)) except ReadError: errors += 1 error = 1 flash( f"Couldn't read file {file} ({folder_name or temp_folder_name})", "error", ) except CompressionError: errors += 1 error = 1 flash( f"{file} is not a valid tar file ({folder_name or temp_folder_name})", "error", ) except HeaderError: errors += 1 error = 1 flash( f"The file plugin.json in {file} is not valid ({folder_name or temp_folder_name})", "error", ) if is_dir: dirs = [d for d in listdir(str(temp_folder_path)) if temp_folder_path.joinpath(d).is_dir()] if not dirs or len(dirs) > 1 or not temp_folder_path.joinpath(dirs[0], "plugin.json").is_file(): raise KeyError for file_name in listdir(str(temp_folder_path.joinpath(dirs[0]))): move( str(temp_folder_path.joinpath(dirs[0], file_name)), str(temp_folder_path.joinpath(file_name)), ) rmtree( str(temp_folder_path.joinpath(dirs[0])), ignore_errors=True, ) plugin_file = json_loads(temp_folder_path.joinpath("plugin.json").read_text(encoding="utf-8")) if not all(key in plugin_file.keys() for key in PLUGIN_KEYS): raise ValueError folder_name = plugin_file["id"] if not app.config["CONFIGFILES"].check_name(folder_name): errors += 1 error = 1 flash( f"Invalid plugin name for {temp_folder_name}. (Can only contain numbers, letters, underscores and hyphens (min 4 characters and max 64))", "error", ) raise Exception plugin_content = BytesIO() with tar_open( fileobj=plugin_content, mode="w:gz", compresslevel=9, ) as tar: tar.add( str(temp_folder_path), arcname=temp_folder_name, recursive=True, ) plugin_content.seek(0) value = plugin_content.getvalue() new_plugins.append( plugin_file | { "external": True, "page": "ui" in listdir(str(temp_folder_path)), "method": "ui", "data": value, "checksum": sha256(value).hexdigest(), } ) new_plugins_ids.append(folder_name) except KeyError: errors += 1 error = 1 flash( f"{file} is not a valid plugin (plugin.json file is missing) ({folder_name or temp_folder_name})", "error", ) except JSONDecodeError as e: errors += 1 error = 1 flash( f"The file plugin.json in {file} is not valid ({e.msg}: line {e.lineno} column {e.colno} (char {e.pos})) ({folder_name or temp_folder_name})", "error", ) except ValueError: errors += 1 error = 1 flash( f"The file plugin.json is missing one or more of the following keys: <i>{', '.join(PLUGIN_KEYS)}</i> ({folder_name or temp_folder_name})", "error", ) except FileExistsError: errors += 1 error = 1 flash( f"A plugin named {folder_name} already exists", "error", ) except (TarError, OSError) as e: errors += 1 error = 1 flash(str(e), "error") except Exception as e: errors += 1 error = 1 flash(str(e), "error") finally: if error != 1: flash(f"Successfully created plugin: <b><i>{folder_name}</i></b>") error = 0 if errors >= files_count: return redirect(url_for("loading", next=url_for("plugins"))) plugins = app.config["CONFIG"].get_plugins(external=True, with_data=True) for plugin in deepcopy(plugins): if plugin["id"] in new_plugins_ids: flash(f"Plugin {plugin['id']} already exists", "error") del new_plugins[new_plugins_ids.index(plugin["id"])] err = db.update_external_plugins(new_plugins, delete_missing=False) if err: flash( f"Couldn't update external plugins to database: {err}", "error", ) if operation: flash(operation) # Reload instances app.config["RELOADING"] = True app.config["LAST_RELOAD"] = time() Thread( target=manage_bunkerweb, name="Reloading instances", args=("plugins",), ).start() # Remove tmp folder if tmp_ui_path.exists(): rmtree(str(tmp_ui_path), ignore_errors=True) return redirect(url_for("loading", next=url_for("plugins"), message="Reloading plugins")) plugin_args = app.config["PLUGIN_ARGS"] app.config["PLUGIN_ARGS"] = {} if request.args.get("plugin_id", False): plugin_id = request.args.get("plugin_id") template = None page = db.get_plugin_template(plugin_id) if page is not None: template = Template(page.decode("utf-8")) if template is not None: return template.render( csrf_token=generate_csrf, url_for=url_for, username=current_user.get_id(), dark_mode=app.config["DARK_MODE"], **(plugin_args["args"] if plugin_args.get("plugin", None) == plugin_id else {}), ) plugins = app.config["CONFIG"].get_plugins() plugins_internal = 0 plugins_external = 0 for plugin in plugins: if plugin["external"] is True: plugins_external += 1 else: plugins_internal += 1 return render_template( "plugins.html", plugins=plugins, plugins_internal=plugins_internal, plugins_external=plugins_external, plugins_errors=db.get_plugins_errors(), username=current_user.get_id(), dark_mode=app.config["DARK_MODE"], ) def upload_plugin(): if not request.files: return {"status": "ko"}, 400 tmp_ui_path = Path(sep, "var", "tmp", "bunkerweb", "ui") tmp_ui_path.mkdir(parents=True, exist_ok=True) for uploaded_file in request.files.values(): if not uploaded_file.filename.endswith((".zip", ".tar.gz", ".tar.xz")): return {"status": "ko"}, 422 with BytesIO(uploaded_file.read()) as io: io.seek(0, 0) plugins = [] if uploaded_file.filename.endswith(".zip"): with ZipFile(io) as zip_file: for file in zip_file.namelist(): if file.endswith("plugin.json"): plugins.append(basename(dirname(file))) if len(plugins) > 1: zip_file.extractall(str(tmp_ui_path) + "/") folder_name = uploaded_file.filename.replace(".zip", "") else: with tar_open(fileobj=io) as tar_file: for file in tar_file.getnames(): if file.endswith("plugin.json"): plugins.append(basename(dirname(file))) if len(plugins) > 1: tar_file.extractall(str(tmp_ui_path) + "/") folder_name = uploaded_file.filename.replace(".tar.gz", "").replace(".tar.xz", "") if len(plugins) <= 1: io.seek(0, 0) tmp_ui_path.joinpath(uploaded_file.filename).write_bytes(io.read()) return {"status": "ok"}, 201 for plugin in plugins: with BytesIO() as tgz: with tar_open(mode="w:gz", fileobj=tgz, dereference=True, compresslevel=3) as tf: tf.add(str(tmp_ui_path.joinpath(folder_name, plugin)), arcname=plugin) tgz.seek(0, 0) tmp_ui_path.joinpath(f"{plugin}.tar.gz").write_bytes(tgz.read()) rmtree(str(tmp_ui_path.joinpath(folder_name)), ignore_errors=True) return {"status": "ok"}, 201
null
18,255
from contextlib import suppress from os import _exit, getenv, listdir, sep, urandom from os.path import basename, dirname, join from secrets import choice from string import ascii_letters, digits from sys import path as sys_path, modules as sys_modules from pathlib import Path from bs4 import BeautifulSoup from copy import deepcopy from datetime import datetime, timedelta, timezone from dateutil.parser import parse as dateutil_parse from docker import DockerClient from docker.errors import NotFound as docker_NotFound, APIError as docker_APIError, DockerException from flask import Flask, Response, flash, jsonify, redirect, render_template, request, send_file, session, url_for from flask_login import current_user, LoginManager, login_required, login_user, logout_user from flask_wtf.csrf import CSRFProtect, CSRFError, generate_csrf from glob import glob from hashlib import sha256 from importlib.machinery import SourceFileLoader from io import BytesIO from json import JSONDecodeError, dumps, loads as json_loads from jinja2 import Template from kubernetes import client as kube_client from kubernetes import config as kube_config from kubernetes.client.exceptions import ApiException as kube_ApiException from regex import compile as re_compile, match as regex_match from requests import get from shutil import move, rmtree from signal import SIGINT, signal, SIGTERM from subprocess import PIPE, Popen, call from tarfile import CompressionError, HeaderError, ReadError, TarError, open as tar_open from threading import Thread from tempfile import NamedTemporaryFile from time import sleep, time from traceback import format_exc from zipfile import BadZipFile, ZipFile from src.Instances import Instances from src.ConfigFiles import ConfigFiles from src.Config import Config from src.ReverseProxied import ReverseProxied from src.User import AnonymousUser, User from utils import check_settings, get_b64encoded_qr_image, path_to_dict from Database import Database from logging import getLogger sbin_nginx_path = Path(sep, "usr", "sbin", "nginx") app = Flask(__name__, static_url_path="/", static_folder="static", template_folder="templates") app.config["SECRET_KEY"] = getenv("FLASK_SECRET", urandom(32)) app.wsgi_app = ReverseProxied(app.wsgi_app, x_for=PROXY_NUMBERS, x_proto=PROXY_NUMBERS, x_host=PROXY_NUMBERS, x_prefix=PROXY_NUMBERS) app.logger.handlers = gunicorn_logger.handlers app.logger.setLevel(gunicorn_logger.level) db = Database(app.logger, ui=True) while not db.is_initialized(): app.logger.warning("Database is not initialized, retrying in 5s ...") sleep(5) app.logger.info("Database is ready") try: app.config.update( DEBUG=True, INSTANCES=Instances(docker_client, kubernetes_client, INTEGRATION), CONFIG=Config(db), CONFIGFILES=ConfigFiles(app.logger, db), WTF_CSRF_SSL_STRICT=False, USER=USER, SEND_FILE_MAX_AGE_DEFAULT=86400, PLUGIN_ARGS={}, RELOADING=False, LAST_RELOAD=0, TO_FLASH=[], DARK_MODE=False, CURRENT_TOTP_TOKEN=None, ) except FileNotFoundError as e: app.logger.error(repr(e), e.filename) stop(1) plugin_id_rx = re_compile(r"^[\w_-]{1,64}$") app.jinja_env.globals.update(check_settings=check_settings) def custom_plugin(plugin): if not plugin_id_rx.match(plugin): flash( f"Invalid plugin id, <b>{plugin}</b> (must be between 1 and 64 characters, only letters, numbers, underscores and hyphens)", "error", ) return redirect(url_for("loading", next=url_for("plugins", plugin_id=plugin))) module = db.get_plugin_actions(plugin) if module is None: flash( f"The <i>actions.py</i> file for the plugin <b>{plugin}</b> does not exist", "error", ) return redirect(url_for("loading", next=url_for("plugins", plugin_id=plugin))) try: # Try to import the custom plugin with NamedTemporaryFile(mode="wb", suffix=".py", delete=True) as temp: temp.write(module) temp.flush() temp.seek(0) loader = SourceFileLoader("actions", temp.name) actions = loader.load_module() except: flash( f"An error occurred while importing the plugin <b>{plugin}</b>:<br/>{format_exc()}", "error", ) return redirect(url_for("loading", next=url_for("plugins", plugin_id=plugin))) error = False res = None try: # Try to get the custom plugin custom function and call it method = getattr(actions, plugin) res = method() except AttributeError: flash( f"The plugin <b>{plugin}</b> does not have a <i>{plugin}</i> method", "error", ) error = True return redirect(url_for("loading", next=url_for("plugins", plugin_id=plugin))) except: flash( f"An error occurred while executing the plugin <b>{plugin}</b>:<br/>{format_exc()}", "error", ) error = True finally: if sbin_nginx_path.is_file(): # Remove the custom plugin from the shared library sys_path.pop() sys_modules.pop("actions") del actions if request.method != "POST" or error is True or res is None or isinstance(res, dict) is False: return redirect(url_for("loading", next=url_for("plugins", plugin_id=plugin))) app.config["PLUGIN_ARGS"] = {"plugin": plugin, "args": res} flash(f"Your action <b>{plugin}</b> has been executed") return redirect(url_for("loading", next=url_for("plugins", plugin_id=plugin)))
null
18,256
from contextlib import suppress from os import _exit, getenv, listdir, sep, urandom from os.path import basename, dirname, join from secrets import choice from string import ascii_letters, digits from sys import path as sys_path, modules as sys_modules from pathlib import Path from bs4 import BeautifulSoup from copy import deepcopy from datetime import datetime, timedelta, timezone from dateutil.parser import parse as dateutil_parse from docker import DockerClient from docker.errors import NotFound as docker_NotFound, APIError as docker_APIError, DockerException from flask import Flask, Response, flash, jsonify, redirect, render_template, request, send_file, session, url_for from flask_login import current_user, LoginManager, login_required, login_user, logout_user from flask_wtf.csrf import CSRFProtect, CSRFError, generate_csrf from glob import glob from hashlib import sha256 from importlib.machinery import SourceFileLoader from io import BytesIO from json import JSONDecodeError, dumps, loads as json_loads from jinja2 import Template from kubernetes import client as kube_client from kubernetes import config as kube_config from kubernetes.client.exceptions import ApiException as kube_ApiException from regex import compile as re_compile, match as regex_match from requests import get from shutil import move, rmtree from signal import SIGINT, signal, SIGTERM from subprocess import PIPE, Popen, call from tarfile import CompressionError, HeaderError, ReadError, TarError, open as tar_open from threading import Thread from tempfile import NamedTemporaryFile from time import sleep, time from traceback import format_exc from zipfile import BadZipFile, ZipFile from src.Instances import Instances from src.ConfigFiles import ConfigFiles from src.Config import Config from src.ReverseProxied import ReverseProxied from src.User import AnonymousUser, User from utils import check_settings, get_b64encoded_qr_image, path_to_dict from Database import Database from logging import getLogger app = Flask(__name__, static_url_path="/", static_folder="static", template_folder="templates") app.config["SECRET_KEY"] = getenv("FLASK_SECRET", urandom(32)) app.wsgi_app = ReverseProxied(app.wsgi_app, x_for=PROXY_NUMBERS, x_proto=PROXY_NUMBERS, x_host=PROXY_NUMBERS, x_prefix=PROXY_NUMBERS) app.logger.handlers = gunicorn_logger.handlers app.logger.setLevel(gunicorn_logger.level) db = Database(app.logger, ui=True) while not db.is_initialized(): app.logger.warning("Database is not initialized, retrying in 5s ...") sleep(5) app.logger.info("Database is ready") try: app.config.update( DEBUG=True, INSTANCES=Instances(docker_client, kubernetes_client, INTEGRATION), CONFIG=Config(db), CONFIGFILES=ConfigFiles(app.logger, db), WTF_CSRF_SSL_STRICT=False, USER=USER, SEND_FILE_MAX_AGE_DEFAULT=86400, PLUGIN_ARGS={}, RELOADING=False, LAST_RELOAD=0, TO_FLASH=[], DARK_MODE=False, CURRENT_TOTP_TOKEN=None, ) except FileNotFoundError as e: app.logger.error(repr(e), e.filename) stop(1) app.jinja_env.globals.update(check_settings=check_settings) def services(): def path_to_dict( path: str, *, is_cache: bool = False, db_data: Optional[List[dict]] = None, services: Optional[List[dict]] = None, ) -> dict: def cache(): return render_template( "cache.html", folders=[ path_to_dict( join(sep, "var", "cache", "bunkerweb"), is_cache=True, db_data=db.get_jobs_cache_files(), services=app.config["CONFIG"].get_config(methods=False).get("SERVER_NAME", "").split(" "), ) ], username=current_user.get_id(), dark_mode=app.config["DARK_MODE"], )
null
18,257
from contextlib import suppress from os import _exit, getenv, listdir, sep, urandom from os.path import basename, dirname, join from secrets import choice from string import ascii_letters, digits from sys import path as sys_path, modules as sys_modules from pathlib import Path from bs4 import BeautifulSoup from copy import deepcopy from datetime import datetime, timedelta, timezone from dateutil.parser import parse as dateutil_parse from docker import DockerClient from docker.errors import NotFound as docker_NotFound, APIError as docker_APIError, DockerException from flask import Flask, Response, flash, jsonify, redirect, render_template, request, send_file, session, url_for from flask_login import current_user, LoginManager, login_required, login_user, logout_user from flask_wtf.csrf import CSRFProtect, CSRFError, generate_csrf from glob import glob from hashlib import sha256 from importlib.machinery import SourceFileLoader from io import BytesIO from json import JSONDecodeError, dumps, loads as json_loads from jinja2 import Template from kubernetes import client as kube_client from kubernetes import config as kube_config from kubernetes.client.exceptions import ApiException as kube_ApiException from regex import compile as re_compile, match as regex_match from requests import get from shutil import move, rmtree from signal import SIGINT, signal, SIGTERM from subprocess import PIPE, Popen, call from tarfile import CompressionError, HeaderError, ReadError, TarError, open as tar_open from threading import Thread from tempfile import NamedTemporaryFile from time import sleep, time from traceback import format_exc from zipfile import BadZipFile, ZipFile from src.Instances import Instances from src.ConfigFiles import ConfigFiles from src.Config import Config from src.ReverseProxied import ReverseProxied from src.User import AnonymousUser, User from utils import check_settings, get_b64encoded_qr_image, path_to_dict from Database import Database from logging import getLogger sbin_nginx_path = Path(sep, "usr", "sbin", "nginx") Path(sep, "var", "tmp", "bunkerweb", "ui.healthy").write_text("ok", encoding="utf-8") LOG_RX = re_compile(r"^(?P<date>\d+/\d+/\d+\s\d+:\d+:\d+)\s\[(?P<level>[a-z]+)\]\s\d+#\d+:\s(?P<message>[^\n]+)$") def logs(): def logs_linux(): if not sbin_nginx_path.is_file(): return ( jsonify( { "status": "ko", "message": "There are no linux instances running", } ), 404, ) last_update = request.args.get("last_update", "0.0") from_date = request.args.get("from_date", None) to_date = request.args.get("to_date", None) logs_error = [] temp_multiple_lines = [] NGINX_LOG_LEVELS = [ "debug", "notice", "info", "warn", "error", "crit", "alert", "emerg", ] nginx_error_file = Path(sep, "var", "log", "bunkerweb", "error.log") if nginx_error_file.is_file(): with open(nginx_error_file, encoding="utf-8") as f: for line in f.readlines()[int(last_update.split(".")[0]) if last_update else 0 :]: # noqa: E203 match = LOG_RX.search(line) if not match: continue date = match.group("date") level = match.group("level") if not date: if logs_error: logs_error[-1] += f"\n{line}" continue logs_error.append(line) elif all(f"[{log_level}]" != level for log_level in NGINX_LOG_LEVELS) and temp_multiple_lines: temp_multiple_lines.append(line) else: logs_error.append(f"{datetime.strptime(date, '%Y/%m/%d %H:%M:%S').replace(tzinfo=timezone.utc).timestamp()} {line}") if temp_multiple_lines: logs_error.append("\n".join(temp_multiple_lines)) logs_access = [] nginx_access_file = Path(sep, "var", "log", "bunkerweb", "access.log") if nginx_access_file.is_file(): with open(nginx_access_file, encoding="utf-8") as f: for line in f.readlines()[int(last_update.split(".")[1]) if last_update else 0 :]: # noqa: E203 logs_access.append(f"{datetime.strptime(line[line.find('[') + 1: line.find(']')], '%d/%b/%Y:%H:%M:%S %z').replace(tzinfo=timezone.utc).timestamp()} {line}") raw_logs = logs_error + logs_access if from_date and from_date.isdigit(): from_date = int(from_date) // 1000 else: from_date = 0 if to_date and to_date.isdigit(): to_date = int(to_date) // 1000 else: to_date = None def date_filter(log: str): log_date = log.split(" ")[0] log_date = float(log_date) if regex_match(r"^\d+\.\d+$", log_date) else 0 if to_date is not None and log_date > int(to_date): return False return log_date > from_date logs = [] for log in filter(date_filter, raw_logs): if "[48;2" in log or not log.strip(): continue log_lower = log.lower() error_type = ( "error" if "[error]" in log_lower or "[crit]" in log_lower or "[alert]" in log_lower or "❌" in log_lower else ("warn" if "[warn]" in log_lower or "⚠️" in log_lower else ("info" if "[info]" in log_lower or "ℹ️" in log_lower else "message")) ) logs.append( { "content": " ".join(log.strip().split(" ")[1:]), "type": error_type, } ) count_error_logs = 0 for log in logs_error: if "\n" in log: for _ in log.split("\n"): count_error_logs += 1 else: count_error_logs += 1 return jsonify( { "logs": logs, "last_update": f"{count_error_logs + int(last_update.split('.')[0])}.{len(logs_access) + int(last_update.split('.')[1])}" if last_update else f"{count_error_logs}.{len(logs_access)}", } )
null
18,258
from contextlib import suppress from os import _exit, getenv, listdir, sep, urandom from os.path import basename, dirname, join from secrets import choice from string import ascii_letters, digits from sys import path as sys_path, modules as sys_modules from pathlib import Path from bs4 import BeautifulSoup from copy import deepcopy from datetime import datetime, timedelta, timezone from dateutil.parser import parse as dateutil_parse from docker import DockerClient from docker.errors import NotFound as docker_NotFound, APIError as docker_APIError, DockerException from flask import Flask, Response, flash, jsonify, redirect, render_template, request, send_file, session, url_for from flask_login import current_user, LoginManager, login_required, login_user, logout_user from flask_wtf.csrf import CSRFProtect, CSRFError, generate_csrf from glob import glob from hashlib import sha256 from importlib.machinery import SourceFileLoader from io import BytesIO from json import JSONDecodeError, dumps, loads as json_loads from jinja2 import Template from kubernetes import client as kube_client from kubernetes import config as kube_config from kubernetes.client.exceptions import ApiException as kube_ApiException from regex import compile as re_compile, match as regex_match from requests import get from shutil import move, rmtree from signal import SIGINT, signal, SIGTERM from subprocess import PIPE, Popen, call from tarfile import CompressionError, HeaderError, ReadError, TarError, open as tar_open from threading import Thread from tempfile import NamedTemporaryFile from time import sleep, time from traceback import format_exc from zipfile import BadZipFile, ZipFile from src.Instances import Instances from src.ConfigFiles import ConfigFiles from src.Config import Config from src.ReverseProxied import ReverseProxied from src.User import AnonymousUser, User from utils import check_settings, get_b64encoded_qr_image, path_to_dict from Database import Database from logging import getLogger INTEGRATION = "Linux" if getenv("KUBERNETES_MODE", "no").lower() == "yes": INTEGRATION = "Kubernetes" elif getenv("SWARM_MODE", "no").lower() == "yes": INTEGRATION = "Swarm" elif getenv("AUTOCONF_MODE", "no").lower() == "yes": INTEGRATION = "Autoconf" elif integration_path.is_file(): INTEGRATION = integration_path.read_text(encoding="utf-8").strip() docker_client = None kubernetes_client = None if INTEGRATION in ("Docker", "Swarm", "Autoconf"): try: docker_client: DockerClient = DockerClient(base_url=getenv("DOCKER_HOST", "unix:///var/run/docker.sock")) except (docker_APIError, DockerException): app.logger.warning("No docker host found") elif INTEGRATION == "Kubernetes": kube_config.load_incluster_config() kubernetes_client = kube_client.CoreV1Api() if INTEGRATION in ("Swarm", "Kubernetes", "Autoconf"): while not db.is_autoconf_loaded(): app.logger.warning("Autoconf is not loaded yet in the database, retrying in 5s ...") sleep(5) def services(): def logs(): def logs_container(container_id): last_update = request.args.get("last_update", None) from_date = request.args.get("from_date", None) to_date = request.args.get("to_date", None) if from_date is not None: last_update = from_date if any(arg and not arg.isdigit() for arg in (last_update, from_date, to_date)): return ( jsonify( { "status": "ko", "message": "arguments must all be integers (timestamps)", } ), 422, ) elif not last_update: last_update = int(datetime.now().timestamp() - timedelta(days=1).total_seconds()) # 1 day before else: last_update = int(last_update) // 1000 to_date = int(to_date) // 1000 if to_date else None logs = [] tmp_logs = [] if docker_client: try: if INTEGRATION != "Swarm": docker_logs = docker_client.containers.get(container_id).logs( stdout=True, stderr=True, since=datetime.fromtimestamp(last_update), timestamps=True, ) else: docker_logs = docker_client.services.get(container_id).logs( stdout=True, stderr=True, since=datetime.fromtimestamp(last_update), timestamps=True, ) tmp_logs = docker_logs.decode("utf-8", errors="replace").split("\n")[0:-1] except docker_NotFound: return ( jsonify( { "status": "ko", "message": f"Container with ID {container_id} not found!", } ), 404, ) elif kubernetes_client: try: kubernetes_logs = kubernetes_client.read_namespaced_pod_log( container_id, getenv("KUBERNETES_NAMESPACE", "default"), since_seconds=int(datetime.now().timestamp() - last_update), timestamps=True, ) tmp_logs = kubernetes_logs.split("\n")[0:-1] except kube_ApiException: return ( jsonify( { "status": "ko", "message": f"Pod with ID {container_id} not found!", } ), 404, ) for log in tmp_logs: split = log.split(" ") timestamp = split[0] if to_date is not None and dateutil_parse(timestamp).timestamp() > to_date: break log = " ".join(split[1:]) log_lower = log.lower() if "[48;2" in log or not log.strip(): continue logs.append( { "content": log, "type": "error" if "[error]" in log_lower or "[crit]" in log_lower or "[alert]" in log_lower or "❌" in log_lower else ("warn" if "[warn]" in log_lower or "⚠️" in log_lower else ("info" if "[info]" in log_lower or "ℹ️" in log_lower else "message")), } ) return jsonify({"logs": logs, "last_update": int(time() * 1000)})
null
18,259
from contextlib import suppress from os import _exit, getenv, listdir, sep, urandom from os.path import basename, dirname, join from secrets import choice from string import ascii_letters, digits from sys import path as sys_path, modules as sys_modules from pathlib import Path from bs4 import BeautifulSoup from copy import deepcopy from datetime import datetime, timedelta, timezone from dateutil.parser import parse as dateutil_parse from docker import DockerClient from docker.errors import NotFound as docker_NotFound, APIError as docker_APIError, DockerException from flask import Flask, Response, flash, jsonify, redirect, render_template, request, send_file, session, url_for from flask_login import current_user, LoginManager, login_required, login_user, logout_user from flask_wtf.csrf import CSRFProtect, CSRFError, generate_csrf from glob import glob from hashlib import sha256 from importlib.machinery import SourceFileLoader from io import BytesIO from json import JSONDecodeError, dumps, loads as json_loads from jinja2 import Template from kubernetes import client as kube_client from kubernetes import config as kube_config from kubernetes.client.exceptions import ApiException as kube_ApiException from regex import compile as re_compile, match as regex_match from requests import get from shutil import move, rmtree from signal import SIGINT, signal, SIGTERM from subprocess import PIPE, Popen, call from tarfile import CompressionError, HeaderError, ReadError, TarError, open as tar_open from threading import Thread from tempfile import NamedTemporaryFile from time import sleep, time from traceback import format_exc from zipfile import BadZipFile, ZipFile from src.Instances import Instances from src.ConfigFiles import ConfigFiles from src.Config import Config from src.ReverseProxied import ReverseProxied from src.User import AnonymousUser, User from utils import check_settings, get_b64encoded_qr_image, path_to_dict from Database import Database from logging import getLogger app = Flask(__name__, static_url_path="/", static_folder="static", template_folder="templates") app.config["SECRET_KEY"] = getenv("FLASK_SECRET", urandom(32)) app.wsgi_app = ReverseProxied(app.wsgi_app, x_for=PROXY_NUMBERS, x_proto=PROXY_NUMBERS, x_host=PROXY_NUMBERS, x_prefix=PROXY_NUMBERS) app.logger.handlers = gunicorn_logger.handlers app.logger.setLevel(gunicorn_logger.level) db = Database(app.logger, ui=True) while not db.is_initialized(): app.logger.warning("Database is not initialized, retrying in 5s ...") sleep(5) app.logger.info("Database is ready") try: app.config.update( DEBUG=True, INSTANCES=Instances(docker_client, kubernetes_client, INTEGRATION), CONFIG=Config(db), CONFIGFILES=ConfigFiles(app.logger, db), WTF_CSRF_SSL_STRICT=False, USER=USER, SEND_FILE_MAX_AGE_DEFAULT=86400, PLUGIN_ARGS={}, RELOADING=False, LAST_RELOAD=0, TO_FLASH=[], DARK_MODE=False, CURRENT_TOTP_TOKEN=None, ) except FileNotFoundError as e: app.logger.error(repr(e), e.filename) stop(1) app.jinja_env.globals.update(check_settings=check_settings) def jobs(): return render_template( "jobs.html", jobs=db.get_jobs(), jobs_errors=db.get_plugins_errors(), username=current_user.get_id(), dark_mode=app.config["DARK_MODE"], )
null
18,260
from contextlib import suppress from os import _exit, getenv, listdir, sep, urandom from os.path import basename, dirname, join from secrets import choice from string import ascii_letters, digits from sys import path as sys_path, modules as sys_modules from pathlib import Path from bs4 import BeautifulSoup from copy import deepcopy from datetime import datetime, timedelta, timezone from dateutil.parser import parse as dateutil_parse from docker import DockerClient from docker.errors import NotFound as docker_NotFound, APIError as docker_APIError, DockerException from flask import Flask, Response, flash, jsonify, redirect, render_template, request, send_file, session, url_for from flask_login import current_user, LoginManager, login_required, login_user, logout_user from flask_wtf.csrf import CSRFProtect, CSRFError, generate_csrf from glob import glob from hashlib import sha256 from importlib.machinery import SourceFileLoader from io import BytesIO from json import JSONDecodeError, dumps, loads as json_loads from jinja2 import Template from kubernetes import client as kube_client from kubernetes import config as kube_config from kubernetes.client.exceptions import ApiException as kube_ApiException from regex import compile as re_compile, match as regex_match from requests import get from shutil import move, rmtree from signal import SIGINT, signal, SIGTERM from subprocess import PIPE, Popen, call from tarfile import CompressionError, HeaderError, ReadError, TarError, open as tar_open from threading import Thread from tempfile import NamedTemporaryFile from time import sleep, time from traceback import format_exc from zipfile import BadZipFile, ZipFile from src.Instances import Instances from src.ConfigFiles import ConfigFiles from src.Config import Config from src.ReverseProxied import ReverseProxied from src.User import AnonymousUser, User from utils import check_settings, get_b64encoded_qr_image, path_to_dict from Database import Database from logging import getLogger db = Database(app.logger, ui=True) while not db.is_initialized(): app.logger.warning("Database is not initialized, retrying in 5s ...") sleep(5) def jobs_download(): job_name = request.args.get("job_name", None) file_name = request.args.get("file_name", None) if not job_name or not file_name: return ( jsonify( { "status": "ko", "message": "job_name and file_name are required", } ), 422, ) cache_file = db.get_job_cache_file(job_name, file_name) if not cache_file: return ( jsonify( { "status": "ko", "message": "file not found", } ), 404, ) file = BytesIO(cache_file.data) return send_file(file, as_attachment=True, download_name=file_name)
null
18,261
from contextlib import suppress from os import _exit, getenv, listdir, sep, urandom from os.path import basename, dirname, join from secrets import choice from string import ascii_letters, digits from sys import path as sys_path, modules as sys_modules from pathlib import Path from bs4 import BeautifulSoup from copy import deepcopy from datetime import datetime, timedelta, timezone from dateutil.parser import parse as dateutil_parse from docker import DockerClient from docker.errors import NotFound as docker_NotFound, APIError as docker_APIError, DockerException from flask import Flask, Response, flash, jsonify, redirect, render_template, request, send_file, session, url_for from flask_login import current_user, LoginManager, login_required, login_user, logout_user from flask_wtf.csrf import CSRFProtect, CSRFError, generate_csrf from glob import glob from hashlib import sha256 from importlib.machinery import SourceFileLoader from io import BytesIO from json import JSONDecodeError, dumps, loads as json_loads from jinja2 import Template from kubernetes import client as kube_client from kubernetes import config as kube_config from kubernetes.client.exceptions import ApiException as kube_ApiException from regex import compile as re_compile, match as regex_match from requests import get from shutil import move, rmtree from signal import SIGINT, signal, SIGTERM from subprocess import PIPE, Popen, call from tarfile import CompressionError, HeaderError, ReadError, TarError, open as tar_open from threading import Thread from tempfile import NamedTemporaryFile from time import sleep, time from traceback import format_exc from zipfile import BadZipFile, ZipFile from src.Instances import Instances from src.ConfigFiles import ConfigFiles from src.Config import Config from src.ReverseProxied import ReverseProxied from src.User import AnonymousUser, User from utils import check_settings, get_b64encoded_qr_image, path_to_dict from Database import Database from logging import getLogger def stop(status, _stop=True): Path(sep, "var", "run", "bunkerweb", "ui.pid").unlink(missing_ok=True) Path(sep, "var", "tmp", "bunkerweb", "ui.healthy").unlink(missing_ok=True) if _stop is True: stop_gunicorn() _exit(status) app = Flask(__name__, static_url_path="/", static_folder="static", template_folder="templates") app.config["SECRET_KEY"] = getenv("FLASK_SECRET", urandom(32)) app.wsgi_app = ReverseProxied(app.wsgi_app, x_for=PROXY_NUMBERS, x_proto=PROXY_NUMBERS, x_host=PROXY_NUMBERS, x_prefix=PROXY_NUMBERS) app.logger.handlers = gunicorn_logger.handlers app.logger.setLevel(gunicorn_logger.level) db = Database(app.logger, ui=True) while not db.is_initialized(): app.logger.warning("Database is not initialized, retrying in 5s ...") sleep(5) app.logger.info("Database is ready") try: app.config.update( DEBUG=True, INSTANCES=Instances(docker_client, kubernetes_client, INTEGRATION), CONFIG=Config(db), CONFIGFILES=ConfigFiles(app.logger, db), WTF_CSRF_SSL_STRICT=False, USER=USER, SEND_FILE_MAX_AGE_DEFAULT=86400, PLUGIN_ARGS={}, RELOADING=False, LAST_RELOAD=0, TO_FLASH=[], DARK_MODE=False, CURRENT_TOTP_TOKEN=None, ) except FileNotFoundError as e: app.logger.error(repr(e), e.filename) stop(1) app.jinja_env.globals.update(check_settings=check_settings) def login(): if not app.config["USER"]: return redirect(url_for("setup")) elif current_user.is_authenticated: # type: ignore return redirect(url_for("home")) fail = False if request.method == "POST" and "username" in request.form and "password" in request.form: app.logger.warning(f"Login attempt from {request.remote_addr} with username \"{request.form['username']}\"") db_user = db.get_ui_user() if not db_user: app.logger.error("Couldn't get user from database") stop(1) user = User(**db_user) if user.get_id() == request.form["username"] and user.check_password(request.form["password"]): # log the user in session["ip"] = request.remote_addr session["user_agent"] = request.headers.get("User-Agent") session["totp_validated"] = False login_user(user, duration=timedelta(hours=1)) # redirect him to the page he originally wanted or to the home page return redirect(url_for("loading", next=request.form.get("next") or url_for("home"))) else: flash("Invalid username or password", "error") fail = True kwargs = { "is_totp": current_user.is_two_factor_enabled, } | ({"error": "Invalid username or password"} if fail else {}) return render_template("login.html", **kwargs), 401 if fail else 200
null
18,262
from contextlib import suppress from os import _exit, getenv, listdir, sep, urandom from os.path import basename, dirname, join from secrets import choice from string import ascii_letters, digits from sys import path as sys_path, modules as sys_modules from pathlib import Path from bs4 import BeautifulSoup from copy import deepcopy from datetime import datetime, timedelta, timezone from dateutil.parser import parse as dateutil_parse from docker import DockerClient from docker.errors import NotFound as docker_NotFound, APIError as docker_APIError, DockerException from flask import Flask, Response, flash, jsonify, redirect, render_template, request, send_file, session, url_for from flask_login import current_user, LoginManager, login_required, login_user, logout_user from flask_wtf.csrf import CSRFProtect, CSRFError, generate_csrf from glob import glob from hashlib import sha256 from importlib.machinery import SourceFileLoader from io import BytesIO from json import JSONDecodeError, dumps, loads as json_loads from jinja2 import Template from kubernetes import client as kube_client from kubernetes import config as kube_config from kubernetes.client.exceptions import ApiException as kube_ApiException from regex import compile as re_compile, match as regex_match from requests import get from shutil import move, rmtree from signal import SIGINT, signal, SIGTERM from subprocess import PIPE, Popen, call from tarfile import CompressionError, HeaderError, ReadError, TarError, open as tar_open from threading import Thread from tempfile import NamedTemporaryFile from time import sleep, time from traceback import format_exc from zipfile import BadZipFile, ZipFile from src.Instances import Instances from src.ConfigFiles import ConfigFiles from src.Config import Config from src.ReverseProxied import ReverseProxied from src.User import AnonymousUser, User from utils import check_settings, get_b64encoded_qr_image, path_to_dict from Database import Database from logging import getLogger app = Flask(__name__, static_url_path="/", static_folder="static", template_folder="templates") app.config["SECRET_KEY"] = getenv("FLASK_SECRET", urandom(32)) app.wsgi_app = ReverseProxied(app.wsgi_app, x_for=PROXY_NUMBERS, x_proto=PROXY_NUMBERS, x_host=PROXY_NUMBERS, x_prefix=PROXY_NUMBERS) app.logger.handlers = gunicorn_logger.handlers app.logger.setLevel(gunicorn_logger.level) app.logger.info("Database is ready") try: app.config.update( DEBUG=True, INSTANCES=Instances(docker_client, kubernetes_client, INTEGRATION), CONFIG=Config(db), CONFIGFILES=ConfigFiles(app.logger, db), WTF_CSRF_SSL_STRICT=False, USER=USER, SEND_FILE_MAX_AGE_DEFAULT=86400, PLUGIN_ARGS={}, RELOADING=False, LAST_RELOAD=0, TO_FLASH=[], DARK_MODE=False, CURRENT_TOTP_TOKEN=None, ) except FileNotFoundError as e: app.logger.error(repr(e), e.filename) stop(1) app.jinja_env.globals.update(check_settings=check_settings) def darkmode(): if not request.is_json: return jsonify({"status": "ko", "message": "invalid request"}), 400 if "darkmode" in request.json: app.config["DARK_MODE"] = request.json["darkmode"] == "true" else: return jsonify({"status": "ko", "message": "darkmode is required"}), 422 return jsonify({"status": "ok"}), 200
null
18,263
from contextlib import suppress from os import _exit, getenv, listdir, sep, urandom from os.path import basename, dirname, join from secrets import choice from string import ascii_letters, digits from sys import path as sys_path, modules as sys_modules from pathlib import Path from bs4 import BeautifulSoup from copy import deepcopy from datetime import datetime, timedelta, timezone from dateutil.parser import parse as dateutil_parse from docker import DockerClient from docker.errors import NotFound as docker_NotFound, APIError as docker_APIError, DockerException from flask import Flask, Response, flash, jsonify, redirect, render_template, request, send_file, session, url_for from flask_login import current_user, LoginManager, login_required, login_user, logout_user from flask_wtf.csrf import CSRFProtect, CSRFError, generate_csrf from glob import glob from hashlib import sha256 from importlib.machinery import SourceFileLoader from io import BytesIO from json import JSONDecodeError, dumps, loads as json_loads from jinja2 import Template from kubernetes import client as kube_client from kubernetes import config as kube_config from kubernetes.client.exceptions import ApiException as kube_ApiException from regex import compile as re_compile, match as regex_match from requests import get from shutil import move, rmtree from signal import SIGINT, signal, SIGTERM from subprocess import PIPE, Popen, call from tarfile import CompressionError, HeaderError, ReadError, TarError, open as tar_open from threading import Thread from tempfile import NamedTemporaryFile from time import sleep, time from traceback import format_exc from zipfile import BadZipFile, ZipFile from src.Instances import Instances from src.ConfigFiles import ConfigFiles from src.Config import Config from src.ReverseProxied import ReverseProxied from src.User import AnonymousUser, User from utils import check_settings, get_b64encoded_qr_image, path_to_dict from Database import Database from logging import getLogger app = Flask(__name__, static_url_path="/", static_folder="static", template_folder="templates") app.config["SECRET_KEY"] = getenv("FLASK_SECRET", urandom(32)) app.wsgi_app = ReverseProxied(app.wsgi_app, x_for=PROXY_NUMBERS, x_proto=PROXY_NUMBERS, x_host=PROXY_NUMBERS, x_prefix=PROXY_NUMBERS) app.logger.handlers = gunicorn_logger.handlers app.logger.setLevel(gunicorn_logger.level) app.logger.info("Database is ready") try: app.config.update( DEBUG=True, INSTANCES=Instances(docker_client, kubernetes_client, INTEGRATION), CONFIG=Config(db), CONFIGFILES=ConfigFiles(app.logger, db), WTF_CSRF_SSL_STRICT=False, USER=USER, SEND_FILE_MAX_AGE_DEFAULT=86400, PLUGIN_ARGS={}, RELOADING=False, LAST_RELOAD=0, TO_FLASH=[], DARK_MODE=False, CURRENT_TOTP_TOKEN=None, ) except FileNotFoundError as e: app.logger.error(repr(e), e.filename) stop(1) app.jinja_env.globals.update(check_settings=check_settings) def check_reloading(): if not app.config["RELOADING"] or app.config["LAST_RELOAD"] + 60 < time(): if app.config["RELOADING"]: app.logger.warning("Reloading took too long, forcing the state to be reloaded") flash("Forced the status to be reloaded", "error") app.config["RELOADING"] = False for f in app.config["TO_FLASH"]: if f["type"] == "error": flash(f["content"], "error") else: flash(f["content"]) app.config["TO_FLASH"].clear() return jsonify({"reloading": app.config["RELOADING"]})
null
18,264
from contextlib import suppress from os import _exit, getenv, listdir, sep, urandom from os.path import basename, dirname, join from secrets import choice from string import ascii_letters, digits from sys import path as sys_path, modules as sys_modules from pathlib import Path from bs4 import BeautifulSoup from copy import deepcopy from datetime import datetime, timedelta, timezone from dateutil.parser import parse as dateutil_parse from docker import DockerClient from docker.errors import NotFound as docker_NotFound, APIError as docker_APIError, DockerException from flask import Flask, Response, flash, jsonify, redirect, render_template, request, send_file, session, url_for from flask_login import current_user, LoginManager, login_required, login_user, logout_user from flask_wtf.csrf import CSRFProtect, CSRFError, generate_csrf from glob import glob from hashlib import sha256 from importlib.machinery import SourceFileLoader from io import BytesIO from json import JSONDecodeError, dumps, loads as json_loads from jinja2 import Template from kubernetes import client as kube_client from kubernetes import config as kube_config from kubernetes.client.exceptions import ApiException as kube_ApiException from regex import compile as re_compile, match as regex_match from requests import get from shutil import move, rmtree from signal import SIGINT, signal, SIGTERM from subprocess import PIPE, Popen, call from tarfile import CompressionError, HeaderError, ReadError, TarError, open as tar_open from threading import Thread from tempfile import NamedTemporaryFile from time import sleep, time from traceback import format_exc from zipfile import BadZipFile, ZipFile from src.Instances import Instances from src.ConfigFiles import ConfigFiles from src.Config import Config from src.ReverseProxied import ReverseProxied from src.User import AnonymousUser, User from utils import check_settings, get_b64encoded_qr_image, path_to_dict from Database import Database from logging import getLogger def logout(): session.clear() logout_user() return redirect(url_for("login"))
null
18,265
from glob import glob from os import listdir, replace, sep, walk from os.path import basename, dirname, join from pathlib import Path from re import compile as re_compile from shutil import rmtree, move as shutil_move from typing import Any, Dict, List, Tuple from utils import path_to_dict def generate_custom_configs( custom_configs: List[Dict[str, Any]], *, original_path: Path = Path(sep, "etc", "bunkerweb", "configs"), ): original_path.mkdir(parents=True, exist_ok=True) for custom_config in custom_configs: tmp_path = original_path.joinpath(custom_config["type"].replace("_", "-")) if custom_config["service_id"]: tmp_path = tmp_path.joinpath(custom_config["service_id"]) tmp_path = tmp_path.joinpath(f"{custom_config['name']}.conf") tmp_path.parent.mkdir(parents=True, exist_ok=True) tmp_path.write_bytes(custom_config["data"])
null
18,266
from argparse import ArgumentParser from copy import deepcopy from glob import glob from hashlib import sha256 from io import BytesIO from json import load as json_load from os import _exit, chmod, environ, getenv, getpid, listdir, sep, walk from os.path import basename, dirname, join, normpath from pathlib import Path from shutil import copy, rmtree from signal import SIGINT, SIGTERM, signal, SIGHUP from stat import S_IEXEC from subprocess import run as subprocess_run, DEVNULL, STDOUT, PIPE from sys import path as sys_path from tarfile import open as tar_open from threading import Thread from time import sleep from traceback import format_exc from typing import Any, Dict, List, Optional, Union from dotenv import dotenv_values from logger import setup_logger from Database import Database from JobScheduler import JobScheduler SCHEDULER: Optional[JobScheduler] = None def stop(status): def handle_stop(signum, frame): if SCHEDULER is not None: SCHEDULER.clear() stop(0)
null
18,267
from argparse import ArgumentParser from copy import deepcopy from glob import glob from hashlib import sha256 from io import BytesIO from json import load as json_load from os import _exit, chmod, environ, getenv, getpid, listdir, sep, walk from os.path import basename, dirname, join, normpath from pathlib import Path from shutil import copy, rmtree from signal import SIGINT, SIGTERM, signal, SIGHUP from stat import S_IEXEC from subprocess import run as subprocess_run, DEVNULL, STDOUT, PIPE from sys import path as sys_path from tarfile import open as tar_open from threading import Thread from time import sleep from traceback import format_exc from typing import Any, Dict, List, Optional, Union from dotenv import dotenv_values from logger import setup_logger from Database import Database from JobScheduler import JobScheduler RUN = True SCHEDULER: Optional[JobScheduler] = None logger = setup_logger("Scheduler", getenv("LOG_LEVEL", "INFO")) def handle_reload(signum, frame): try: if SCHEDULER is not None and RUN: # Get the env by reading the .env file tmp_env = dotenv_values(join(sep, "etc", "bunkerweb", "variables.env")) if SCHEDULER.reload(tmp_env): logger.info("Reload successful") else: logger.error("Reload failed") else: logger.warning( "Ignored reload operation because scheduler is not running ...", ) except: logger.error( f"Exception while reloading scheduler : {format_exc()}", )
null
18,268
from argparse import ArgumentParser from copy import deepcopy from glob import glob from hashlib import sha256 from io import BytesIO from json import load as json_load from os import _exit, chmod, environ, getenv, getpid, listdir, sep, walk from os.path import basename, dirname, join, normpath from pathlib import Path from shutil import copy, rmtree from signal import SIGINT, SIGTERM, signal, SIGHUP from stat import S_IEXEC from subprocess import run as subprocess_run, DEVNULL, STDOUT, PIPE from sys import path as sys_path from tarfile import open as tar_open from threading import Thread from time import sleep from traceback import format_exc from typing import Any, Dict, List, Optional, Union from dotenv import dotenv_values from logger import setup_logger from Database import Database from JobScheduler import JobScheduler SCHEDULER: Optional[JobScheduler] = None logger = setup_logger("Scheduler", getenv("LOG_LEVEL", "INFO")) def generate_custom_configs( configs: List[Dict[str, Any]], *, original_path: Union[Path, str] = join(sep, "etc", "bunkerweb", "configs"), ): if not isinstance(original_path, Path): original_path = Path(original_path) # Remove old custom configs files logger.info("Removing old custom configs files ...") for file in glob(str(original_path.joinpath("*", "*"))): file = Path(file) if file.is_symlink() or file.is_file(): file.unlink() elif file.is_dir(): rmtree(file, ignore_errors=True) if configs: logger.info("Generating new custom configs ...") original_path.mkdir(parents=True, exist_ok=True) for custom_config in configs: tmp_path = original_path.joinpath( custom_config["type"].replace("_", "-"), custom_config["service_id"] or "", f"{custom_config['name']}.conf", ) tmp_path.parent.mkdir(parents=True, exist_ok=True) tmp_path.write_bytes(custom_config["data"]) if SCHEDULER and SCHEDULER.apis: logger.info("Sending custom configs to BunkerWeb") ret = SCHEDULER.send_files(original_path, "/custom_configs") if not ret: logger.error( "Sending custom configs failed, configuration will not work as expected...", )
null
18,269
from argparse import ArgumentParser from copy import deepcopy from glob import glob from hashlib import sha256 from io import BytesIO from json import load as json_load from os import _exit, chmod, environ, getenv, getpid, listdir, sep, walk from os.path import basename, dirname, join, normpath from pathlib import Path from shutil import copy, rmtree from signal import SIGINT, SIGTERM, signal, SIGHUP from stat import S_IEXEC from subprocess import run as subprocess_run, DEVNULL, STDOUT, PIPE from sys import path as sys_path from tarfile import open as tar_open from threading import Thread from time import sleep from traceback import format_exc from typing import Any, Dict, List, Optional, Union from dotenv import dotenv_values from logger import setup_logger from Database import Database from JobScheduler import JobScheduler SCHEDULER: Optional[JobScheduler] = None logger = setup_logger("Scheduler", getenv("LOG_LEVEL", "INFO")) def generate_external_plugins( plugins: List[Dict[str, Any]], *, original_path: Union[Path, str] = join(sep, "etc", "bunkerweb", "plugins"), ): if not isinstance(original_path, Path): original_path = Path(original_path) # Remove old external plugins files logger.info("Removing old external plugins files ...") for file in glob(str(original_path.joinpath("*"))): file = Path(file) if file.is_symlink() or file.is_file(): file.unlink() elif file.is_dir(): rmtree(file, ignore_errors=True) if plugins: logger.info("Generating new external plugins ...") original_path.mkdir(parents=True, exist_ok=True) for plugin in plugins: tmp_path = original_path.joinpath(plugin["id"], f"{plugin['name']}.tar.gz") tmp_path.parent.mkdir(parents=True, exist_ok=True) tmp_path.write_bytes(plugin["data"]) with tar_open(str(tmp_path), "r:gz") as tar: tar.extractall(original_path) tmp_path.unlink() for job_file in glob(join(str(tmp_path.parent), "jobs", "*")): st = Path(job_file).stat() chmod(job_file, st.st_mode | S_IEXEC) if SCHEDULER and SCHEDULER.apis: logger.info("Sending plugins to BunkerWeb") ret = SCHEDULER.send_files(original_path, "/plugins") if not ret: logger.error( "Sending plugins failed, configuration will not work as expected...", )
null
18,270
from argparse import ArgumentParser from copy import deepcopy from glob import glob from hashlib import sha256 from io import BytesIO from json import load as json_load from os import _exit, chmod, environ, getenv, getpid, listdir, sep, walk from os.path import basename, dirname, join, normpath from pathlib import Path from shutil import copy, rmtree from signal import SIGINT, SIGTERM, signal, SIGHUP from stat import S_IEXEC from subprocess import run as subprocess_run, DEVNULL, STDOUT, PIPE from sys import path as sys_path from tarfile import open as tar_open from threading import Thread from time import sleep from traceback import format_exc from typing import Any, Dict, List, Optional, Union from dotenv import dotenv_values from logger import setup_logger from Database import Database from JobScheduler import JobScheduler def dict_to_frozenset(d): if isinstance(d, list): return tuple(sorted(d)) elif isinstance(d, dict): return frozenset((k, dict_to_frozenset(v)) for k, v in d.items()) return d
null
18,271
from argparse import ArgumentParser from copy import deepcopy from glob import glob from hashlib import sha256 from io import BytesIO from json import load as json_load from os import _exit, chmod, environ, getenv, getpid, listdir, sep, walk from os.path import basename, dirname, join, normpath from pathlib import Path from shutil import copy, rmtree from signal import SIGINT, SIGTERM, signal, SIGHUP from stat import S_IEXEC from subprocess import run as subprocess_run, DEVNULL, STDOUT, PIPE from sys import path as sys_path from tarfile import open as tar_open from threading import Thread from time import sleep from traceback import format_exc from typing import Any, Dict, List, Optional, Union from dotenv import dotenv_values from logger import setup_logger from Database import Database from JobScheduler import JobScheduler SCHEDULER: Optional[JobScheduler] = None logger = setup_logger("Scheduler", getenv("LOG_LEVEL", "INFO")) def send_nginx_configs(): logger.info(f"Sending {join(sep, 'etc', 'nginx')} folder ...") ret = SCHEDULER.send_files(join(sep, "etc", "nginx"), "/confs") if not ret: logger.error( "Sending nginx configs failed, configuration will not work as expected...", )
null
18,272
from argparse import ArgumentParser from copy import deepcopy from glob import glob from hashlib import sha256 from io import BytesIO from json import load as json_load from os import _exit, chmod, environ, getenv, getpid, listdir, sep, walk from os.path import basename, dirname, join, normpath from pathlib import Path from shutil import copy, rmtree from signal import SIGINT, SIGTERM, signal, SIGHUP from stat import S_IEXEC from subprocess import run as subprocess_run, DEVNULL, STDOUT, PIPE from sys import path as sys_path from tarfile import open as tar_open from threading import Thread from time import sleep from traceback import format_exc from typing import Any, Dict, List, Optional, Union from dotenv import dotenv_values from logger import setup_logger from Database import Database from JobScheduler import JobScheduler SCHEDULER: Optional[JobScheduler] = None CACHE_PATH = join(sep, "var", "cache", "bunkerweb") logger = setup_logger("Scheduler", getenv("LOG_LEVEL", "INFO")) def send_nginx_cache(): logger.info(f"Sending {CACHE_PATH} folder ...") if not SCHEDULER.send_files(CACHE_PATH, "/cache"): logger.error(f"Error while sending {CACHE_PATH} folder") else: logger.info(f"Successfully sent {CACHE_PATH} folder")
null
18,273
from argparse import ArgumentParser from copy import deepcopy from glob import glob from hashlib import sha256 from io import BytesIO from json import load as json_load from os import _exit, chmod, environ, getenv, getpid, listdir, sep, walk from os.path import basename, dirname, join, normpath from pathlib import Path from shutil import copy, rmtree from signal import SIGINT, SIGTERM, signal, SIGHUP from stat import S_IEXEC from subprocess import run as subprocess_run, DEVNULL, STDOUT, PIPE from sys import path as sys_path from tarfile import open as tar_open from threading import Thread from time import sleep from traceback import format_exc from typing import Any, Dict, List, Optional, Union from dotenv import dotenv_values from logger import setup_logger from Database import Database from JobScheduler import JobScheduler SCHEDULER: Optional[JobScheduler] = None logger = setup_logger("Scheduler", getenv("LOG_LEVEL", "INFO")) def api_to_instance(api): hostname_port = api.endpoint.replace("http://", "").replace("https://", "").replace("/", "").split(":") return { "hostname": hostname_port[0], "env": {"API_HTTP_PORT": int(hostname_port[1]), "API_SERVER_NAME": api.host}, } class Database: DB_STRING_RX = re_compile(r"^(?P<database>(mariadb|mysql)(\+pymysql)?|sqlite(\+pysqlite)?|postgresql):/+(?P<path>/[^\s]+)") def __init__( self, logger: Logger, sqlalchemy_string: Optional[str] = None, *, ui: bool = False, pool: bool = True, ) -> None: """Initialize the database""" self.__logger = logger self.__session_factory = None self.__sql_engine = None if not sqlalchemy_string: sqlalchemy_string = getenv("DATABASE_URI", "sqlite:////var/lib/bunkerweb/db.sqlite3") match = self.DB_STRING_RX.search(sqlalchemy_string) if not match: self.__logger.error(f"Invalid database string provided: {sqlalchemy_string}, exiting...") _exit(1) if match.group("database").startswith("sqlite"): db_path = Path(normpath(match.group("path"))) if ui: while not db_path.is_file(): self.__logger.warning(f"Waiting for the database file to be created: {db_path}") sleep(1) else: db_path.parent.mkdir(parents=True, exist_ok=True) self.database_uri = sqlalchemy_string error = False engine_kwargs = {"future": True, "poolclass": None if pool else SingletonThreadPool, "pool_pre_ping": True, "pool_recycle": 1800} try: self.__sql_engine = create_engine(sqlalchemy_string, **engine_kwargs) except ArgumentError: self.__logger.error(f"Invalid database URI: {sqlalchemy_string}") error = True except SQLAlchemyError: self.__logger.error(f"Error when trying to create the engine: {format_exc()}") error = True finally: if error: _exit(1) try: assert self.__sql_engine is not None except AssertionError: self.__logger.error("The database engine is not initialized") _exit(1) not_connected = True retries = 15 while not_connected: try: with self.__sql_engine.connect() as conn: conn.execute(text("CREATE TABLE IF NOT EXISTS test (id INT)")) conn.execute(text("DROP TABLE test")) not_connected = False except (OperationalError, DatabaseError) as e: if retries <= 0: self.__logger.error( f"Can't connect to database : {format_exc()}", ) _exit(1) if "attempt to write a readonly database" in str(e): self.__logger.warning("The database is read-only, waiting for it to become writable. Retrying in 5 seconds ...") self.__sql_engine.dispose(close=True) self.__sql_engine = create_engine(sqlalchemy_string, **engine_kwargs) if "Unknown table" in str(e): not_connected = False continue else: self.__logger.warning( "Can't connect to database, retrying in 5 seconds ...", ) retries -= 1 sleep(5) except BaseException: self.__logger.error(f"Error when trying to connect to the database: {format_exc()}") exit(1) self.__logger.info("✅ Database connection established") self.__session_factory = sessionmaker(bind=self.__sql_engine, autoflush=True, expire_on_commit=False) self.suffix_rx = re_compile(r"_\d+$") if sqlalchemy_string.startswith("sqlite"): with self.__db_session() as session: session.execute(text("PRAGMA journal_mode=WAL")) session.commit() def __del__(self) -> None: """Close the database""" if self.__session_factory: self.__session_factory.close_all() if self.__sql_engine: self.__sql_engine.dispose() def __db_session(self): try: assert self.__session_factory is not None except AssertionError: self.__logger.error("The database session is not initialized") _exit(1) session = scoped_session(self.__session_factory) try: yield session except BaseException: session.rollback() raise finally: session.remove() def set_autoconf_load(self, value: bool = True) -> str: """Set the autoconf_loaded value""" with self.__db_session() as session: try: metadata = session.query(Metadata).get(1) if not metadata: return "The metadata are not set yet, try again" metadata.autoconf_loaded = value session.commit() except BaseException: return format_exc() return "" def is_autoconf_loaded(self) -> bool: """Check if the autoconf is loaded""" with self.__db_session() as session: try: metadata = session.query(Metadata).with_entities(Metadata.autoconf_loaded).filter_by(id=1).first() return metadata is not None and metadata.autoconf_loaded except (ProgrammingError, OperationalError): return False def set_scheduler_first_start(self, value: bool = False) -> str: """Set the scheduler_first_start value""" with self.__db_session() as session: try: metadata = session.query(Metadata).get(1) if not metadata: return "The metadata are not set yet, try again" metadata.scheduler_first_start = value session.commit() except BaseException: return format_exc() return "" def is_scheduler_first_start(self) -> bool: """Check if it's the scheduler's first start""" with self.__db_session() as session: try: metadata = session.query(Metadata).with_entities(Metadata.scheduler_first_start).filter_by(id=1).first() return metadata is not None and metadata.scheduler_first_start except (ProgrammingError, OperationalError): return True def is_first_config_saved(self) -> bool: """Check if the first configuration has been saved""" with self.__db_session() as session: try: metadata = session.query(Metadata).with_entities(Metadata.first_config_saved).filter_by(id=1).first() return metadata is not None and metadata.first_config_saved except (ProgrammingError, OperationalError): return False def is_initialized(self) -> bool: """Check if the database is initialized""" with self.__db_session() as session: try: metadata = session.query(Metadata).with_entities(Metadata.is_initialized).filter_by(id=1).first() return metadata is not None and metadata.is_initialized except (ProgrammingError, OperationalError, DatabaseError): return False def initialize_db(self, version: str, integration: str = "Unknown") -> str: """Initialize the database""" with self.__db_session() as session: try: if session.query(Metadata).get(1): session.query(Metadata).filter_by(id=1).update({Metadata.version: version, Metadata.integration: integration}) else: session.add( Metadata( is_initialized=True, first_config_saved=False, scheduler_first_start=True, version=version, integration=integration, ) ) session.commit() except BaseException: return format_exc() return "" def get_metadata(self) -> Dict[str, str]: """Get the metadata from the database""" data = {"version": "1.5.4", "integration": "unknown"} with self.__db_session() as session: with suppress(ProgrammingError, OperationalError): metadata = session.query(Metadata).with_entities(Metadata.version, Metadata.integration).filter_by(id=1).first() if metadata: data = {"version": metadata.version, "integration": metadata.integration} return data def check_changes(self) -> Union[Dict[str, bool], bool, str]: """Check if either the config, the custom configs, plugins or instances have changed inside the database""" with self.__db_session() as session: try: metadata = ( session.query(Metadata) .with_entities( Metadata.custom_configs_changed, Metadata.external_plugins_changed, Metadata.config_changed, Metadata.instances_changed, ) .filter_by(id=1) .first() ) return dict( custom_configs_changed=metadata is not None and metadata.custom_configs_changed, external_plugins_changed=metadata is not None and metadata.external_plugins_changed, config_changed=metadata is not None and metadata.config_changed, instances_changed=metadata is not None and metadata.instances_changed, ) except BaseException: return format_exc() def checked_changes(self, changes: Optional[List[str]] = None, value: Optional[bool] = False) -> str: """Set changed bit for config, custom configs, instances and plugins""" changes = changes or [ "config", "custom_configs", "external_plugins", "instances", ] with self.__db_session() as session: try: metadata = session.query(Metadata).get(1) if not metadata: return "The metadata are not set yet, try again" if "config" in changes: if not metadata.first_config_saved: metadata.first_config_saved = True metadata.config_changed = value if "custom_configs" in changes: metadata.custom_configs_changed = value if "external_plugins" in changes: metadata.external_plugins_changed = value if "instances" in changes: metadata.instances_changed = value session.commit() except BaseException: return format_exc() return "" def init_tables(self, default_plugins: List[dict], bunkerweb_version: str) -> Tuple[bool, str]: """Initialize the database tables and return the result""" inspector = inspect(self.__sql_engine) db_version = None has_all_tables = True if inspector and len(inspector.get_table_names()): db_version = self.get_metadata()["version"] if db_version != bunkerweb_version: self.__logger.warning(f"Database version ({db_version}) is different from Bunkerweb version ({bunkerweb_version}), checking if it needs to be updated") for table in Base.metadata.tables: if not inspector.has_table(table): has_all_tables = False else: missing_columns = [] db_columns = inspector.get_columns(table) for column in Base.metadata.tables[table].columns: if not any(db_column["name"] == column.name for db_column in db_columns): missing_columns.append(column) try: with self.__db_session() as session: if missing_columns: for column in missing_columns: session.execute(text(f"ALTER TABLE {table} ADD COLUMN {column.name} {column.type}")) session.commit() except BaseException: return False, format_exc() if has_all_tables and db_version and db_version == bunkerweb_version: return False, "" try: Base.metadata.create_all(self.__sql_engine, checkfirst=True) except BaseException: return False, format_exc() to_put = [] with self.__db_session() as session: for plugins in default_plugins: if not isinstance(plugins, list): plugins = [plugins] for plugin in plugins: settings = {} jobs = [] page = False if "id" not in plugin: settings = plugin plugin = { "id": "general", "name": "General", "description": "The general settings for the server", "version": "0.1", "stream": "partial", "external": False, } else: settings = plugin.pop("settings", {}) jobs = plugin.pop("jobs", []) page = plugin.pop("page", False) db_plugin = session.query(Plugins).filter_by(id=plugin["id"]).first() if db_plugin: updates = {} if plugin["name"] != db_plugin.name: updates[Plugins.name] = plugin["name"] if plugin["description"] != db_plugin.description: updates[Plugins.description] = plugin["description"] if plugin["version"] != db_plugin.version: updates[Plugins.version] = plugin["version"] if plugin["stream"] != db_plugin.stream: updates[Plugins.stream] = plugin["stream"] if plugin.get("external", False) != db_plugin.external: updates[Plugins.external] = plugin.get("external", False) if plugin.get("method", "manual") != db_plugin.method: updates[Plugins.method] = plugin.get("method", "manual") if plugin.get("data") != db_plugin.data: updates[Plugins.data] = plugin.get("data") if plugin.get("checksum") != db_plugin.checksum: updates[Plugins.checksum] = plugin.get("checksum") if updates: self.__logger.warning(f'Plugin "{plugin["id"]}" already exists, updating it with the new values') session.query(Plugins).filter(Plugins.id == plugin["id"]).update(updates) else: to_put.append( Plugins( id=plugin["id"], name=plugin["name"], description=plugin["description"], version=plugin["version"], stream=plugin["stream"], external=plugin.get("external", False), method=plugin.get("method"), data=plugin.get("data"), checksum=plugin.get("checksum"), ) ) for setting, value in settings.items(): value.update( { "plugin_id": plugin["id"], "name": value["id"], "id": setting, } ) db_setting = session.query(Settings).filter_by(id=setting).first() select_values = value.pop("select", []) if db_setting: updates = {} if value["name"] != db_setting.name: updates[Settings.name] = value["name"] if value["context"] != db_setting.context: updates[Settings.context] = value["context"] if value["default"] != db_setting.default: updates[Settings.default] = value["default"] if value["help"] != db_setting.help: updates[Settings.help] = value["help"] if value["label"] != db_setting.label: updates[Settings.label] = value["label"] if value["regex"] != db_setting.regex: updates[Settings.regex] = value["regex"] if value["type"] != db_setting.type: updates[Settings.type] = value["type"] if value.get("multiple") != db_setting.multiple: updates[Settings.multiple] = value.get("multiple") if updates: self.__logger.warning(f'Setting "{setting}" already exists, updating it with the new values') session.query(Settings).filter(Settings.id == setting).update(updates) else: if db_plugin: self.__logger.warning(f'Setting "{setting}" does not exist, creating it') to_put.append(Settings(**value)) db_selects = session.query(Selects).with_entities(Selects.value).filter_by(setting_id=value["id"]).all() db_values = [select.value for select in db_selects] missing_values = [select for select in db_values if select not in select_values] if select_values: if missing_values: # Remove selects that are no longer in the list self.__logger.warning(f'Removing {len(missing_values)} selects from setting "{setting}" as they are no longer in the list') session.query(Selects).filter(Selects.value.in_(missing_values)).delete() for select in select_values: if select not in db_values: to_put.append(Selects(setting_id=value["id"], value=select)) else: if missing_values: self.__logger.warning(f'Removing all selects from setting "{setting}" as there are no longer any in the list') session.query(Selects).filter_by(setting_id=value["id"]).delete() db_jobs = session.query(Jobs).with_entities(Jobs.name).filter_by(plugin_id=plugin["id"]).all() db_names = [job.name for job in db_jobs] job_names = [job["name"] for job in jobs] missing_names = [job for job in db_names if job not in job_names] if missing_names: # Remove jobs that are no longer in the list self.__logger.warning(f'Removing {len(missing_names)} jobs from plugin "{plugin["id"]}" as they are no longer in the list') session.query(Jobs).filter(Jobs.name.in_(missing_names)).delete() for job in jobs: db_job = session.query(Jobs).with_entities(Jobs.file_name, Jobs.every, Jobs.reload).filter_by(name=job["name"], plugin_id=plugin["id"]).first() if job["name"] not in db_names or not db_job: job["file_name"] = job.pop("file") job["reload"] = job.get("reload", False) if db_plugin: self.__logger.warning(f'Job "{job["name"]}" does not exist, creating it') to_put.append(Jobs(plugin_id=plugin["id"], **job)) else: updates = {} if job["file"] != db_job.file_name: updates[Jobs.file_name] = job["file"] if job["every"] != db_job.every: updates[Jobs.every] = job["every"] if job.get("reload", None) != db_job.reload: updates[Jobs.reload] = job.get("reload", False) if updates: self.__logger.warning(f'Job "{job["name"]}" already exists, updating it with the new values') updates[Jobs.last_run] = None session.query(Jobs_cache).filter(Jobs_cache.job_name == job["name"]).delete() session.query(Jobs).filter(Jobs.name == job["name"]).update(updates) if page: core_ui_path = Path(sep, "usr", "share", "bunkerweb", "core", plugin["id"], "ui") path_ui = core_ui_path if core_ui_path.exists() else Path(sep, "etc", "bunkerweb", "plugins", plugin["id"], "ui") if path_ui.exists(): if {"template.html", "actions.py"}.issubset(listdir(str(path_ui))): db_plugin_page = ( session.query(Plugin_pages) .with_entities( Plugin_pages.template_checksum, Plugin_pages.actions_checksum, ) .filter_by(plugin_id=plugin["id"]) .first() ) template = path_ui.joinpath("template.html").read_bytes() actions = path_ui.joinpath("actions.py").read_bytes() template_checksum = sha256(template).hexdigest() actions_checksum = sha256(actions).hexdigest() if db_plugin_page: updates = {} if template_checksum != db_plugin_page.template_checksum: updates.update( { Plugin_pages.template_file: template, Plugin_pages.template_checksum: template_checksum, } ) if actions_checksum != db_plugin_page.actions_checksum: updates.update( { Plugin_pages.actions_file: actions, Plugin_pages.actions_checksum: actions_checksum, } ) if updates: self.__logger.warning(f'Page for plugin "{plugin["id"]}" already exists, updating it with the new values') session.query(Plugin_pages).filter(Plugin_pages.plugin_id == plugin["id"]).update(updates) continue if db_plugin: self.__logger.warning(f'Page for plugin "{plugin["id"]}" does not exist, creating it') to_put.append( Plugin_pages( plugin_id=plugin["id"], template_file=template, template_checksum=template_checksum, actions_file=actions, actions_checksum=actions_checksum, ) ) try: session.add_all(to_put) session.commit() except BaseException: return False, format_exc() return True, "" def save_config(self, config: Dict[str, Any], method: str, changed: Optional[bool] = True) -> str: """Save the config in the database""" to_put = [] with self.__db_session() as session: # Delete all the old config session.query(Global_values).filter(Global_values.method == method).delete() session.query(Services_settings).filter(Services_settings.method == method).delete() if config: config.pop("DATABASE_URI", None) db_services = session.query(Services).with_entities(Services.id, Services.method).all() db_ids = [service.id for service in db_services] services = config.get("SERVER_NAME", []) if isinstance(services, str): services = services.split(" ") if db_services: missing_ids = [service.id for service in db_services if (service.method == method) and service.id not in services] if missing_ids: # Remove services that are no longer in the list session.query(Services).filter(Services.id.in_(missing_ids)).delete() if config.get("MULTISITE", "no") == "yes": global_values = [] for key, value in deepcopy(config).items(): suffix = 0 original_key = deepcopy(key) if self.suffix_rx.search(key): suffix = int(key.split("_")[-1]) key = key[: -len(str(suffix)) - 1] setting = session.query(Settings).with_entities(Settings.default).filter_by(id=key).first() if not setting and services: try: server_name = next(service for service in services if key.startswith(f"{service}_")) except StopIteration: continue if server_name not in db_ids: to_put.append(Services(id=server_name, method=method)) db_ids.append(server_name) key = key.replace(f"{server_name}_", "") setting = session.query(Settings).with_entities(Settings.default).filter_by(id=key).first() if not setting: continue service_setting = ( session.query(Services_settings) .with_entities(Services_settings.value, Services_settings.method) .filter_by( service_id=server_name, setting_id=key, suffix=suffix, ) .first() ) if not service_setting: if key != "SERVER_NAME" and ((key not in config and value == setting.default) or (key in config and value == config[key])): continue to_put.append( Services_settings( service_id=server_name, setting_id=key, value=value, suffix=suffix, method=method, ) ) elif method in (service_setting.method, "autoconf") and service_setting.value != value: if key != "SERVER_NAME" and ((key not in config and value == setting.default) or (key in config and value == config[key])): session.query(Services_settings).filter( Services_settings.service_id == server_name, Services_settings.setting_id == key, Services_settings.suffix == suffix, ).delete() continue session.query(Services_settings).filter( Services_settings.service_id == server_name, Services_settings.setting_id == key, Services_settings.suffix == suffix, ).update( { Services_settings.value: value, Services_settings.method: method, } ) elif setting and original_key not in global_values: global_values.append(original_key) global_value = ( session.query(Global_values) .with_entities(Global_values.value, Global_values.method) .filter_by( setting_id=key, suffix=suffix, ) .first() ) if not global_value: if value == setting.default: continue to_put.append( Global_values( setting_id=key, value=value, suffix=suffix, method=method, ) ) elif method in (global_value.method, "autoconf") and global_value.value != value: if value == setting.default: session.query(Global_values).filter( Global_values.setting_id == key, Global_values.suffix == suffix, ).delete() continue session.query(Global_values).filter( Global_values.setting_id == key, Global_values.suffix == suffix, ).update( { Global_values.value: value, Global_values.method: method, } ) else: if config.get("SERVER_NAME", "www.example.com") and not session.query(Services).with_entities(Services.id).filter_by(id=config.get("SERVER_NAME", "www.example.com").split(" ")[0]).first(): to_put.append(Services(id=config.get("SERVER_NAME", "www.example.com").split(" ")[0], method=method)) for key, value in config.items(): suffix = 0 if self.suffix_rx.search(key): suffix = int(key.split("_")[-1]) key = key[: -len(str(suffix)) - 1] setting = session.query(Settings).with_entities(Settings.default).filter_by(id=key).first() if not setting: continue global_value = session.query(Global_values).with_entities(Global_values.value, Global_values.method).filter_by(setting_id=key, suffix=suffix).first() if not global_value: if value == setting.default: continue to_put.append( Global_values( setting_id=key, value=value, suffix=suffix, method=method, ) ) elif global_value.method == method and value != global_value.value: if value == setting.default: session.query(Global_values).filter( Global_values.setting_id == key, Global_values.suffix == suffix, ).delete() continue session.query(Global_values).filter( Global_values.setting_id == key, Global_values.suffix == suffix, ).update({Global_values.value: value}) if changed: with suppress(ProgrammingError, OperationalError): metadata = session.query(Metadata).get(1) if metadata is not None: if not metadata.first_config_saved: metadata.first_config_saved = True metadata.config_changed = True try: session.add_all(to_put) session.commit() except BaseException: return format_exc() return "" def save_custom_configs( self, custom_configs: List[Dict[str, Tuple[str, List[str]]]], method: str, changed: Optional[bool] = True, ) -> str: """Save the custom configs in the database""" message = "" with self.__db_session() as session: # Delete all the old config session.query(Custom_configs).filter(Custom_configs.method == method).delete() to_put = [] endl = "\n" for custom_config in custom_configs: config = { "data": custom_config["value"].encode("utf-8") if isinstance(custom_config["value"], str) else custom_config["value"], "method": method, } config["checksum"] = sha256(config["data"]).hexdigest() if custom_config["exploded"][0]: if not session.query(Services).with_entities(Services.id).filter_by(id=custom_config["exploded"][0]).first(): message += f"{endl if message else ''}Service {custom_config['exploded'][0]} not found, please check your config" config.update( { "service_id": custom_config["exploded"][0], "type": custom_config["exploded"][1].replace("-", "_").lower(), "name": custom_config["exploded"][2], } ) else: config.update( { "type": custom_config["exploded"][1].replace("-", "_").lower(), "name": custom_config["exploded"][2], } ) custom_conf = ( session.query(Custom_configs) .with_entities(Custom_configs.checksum, Custom_configs.method) .filter_by( service_id=config.get("service_id", None), type=config["type"], name=config["name"], ) .first() ) if not custom_conf: to_put.append(Custom_configs(**config)) elif config["checksum"] != custom_conf.checksum and method in ( custom_conf.method, "autoconf", ): session.query(Custom_configs).filter( Custom_configs.service_id == config.get("service_id", None), Custom_configs.type == config["type"], Custom_configs.name == config["name"], ).update( { Custom_configs.data: config["data"], Custom_configs.checksum: config["checksum"], } | ({Custom_configs.method: "autoconf"} if method == "autoconf" else {}) ) if changed: with suppress(ProgrammingError, OperationalError): metadata = session.query(Metadata).get(1) if metadata is not None: metadata.custom_configs_changed = True try: session.add_all(to_put) session.commit() except BaseException: return f"{f'{message}{endl}' if message else ''}{format_exc()}" return message def get_config(self, methods: bool = False) -> Dict[str, Any]: """Get the config from the database""" with self.__db_session() as session: config = {} multisite = [] for setting in ( session.query(Settings) .with_entities( Settings.id, Settings.context, Settings.default, Settings.multiple, ) .all() ): default = setting.default or "" config[setting.id] = default if not methods else {"value": default, "global": True, "method": "default"} global_values = session.query(Global_values).with_entities(Global_values.value, Global_values.suffix, Global_values.method).filter_by(setting_id=setting.id).all() for global_value in global_values: config[setting.id + (f"_{global_value.suffix}" if setting.multiple and global_value.suffix > 0 else "")] = ( global_value.value if not methods else { "value": global_value.value, "global": True, "method": global_value.method, } ) if setting.context == "multisite": multisite.append(setting.id) is_multisite = config.get("MULTISITE", {"value": "no"})["value"] == "yes" if methods else config.get("MULTISITE", "no") == "yes" if is_multisite: for service in session.query(Services).with_entities(Services.id).all(): checked_settings = [] for key, value in deepcopy(config).items(): original_key = key if self.suffix_rx.search(key): key = key[: -len(str(key.split("_")[-1])) - 1] if key not in multisite: continue elif f"{service.id}_{original_key}" not in config: config[f"{service.id}_{original_key}"] = value if original_key not in checked_settings: checked_settings.append(original_key) else: continue service_settings = ( session.query(Services_settings) .with_entities( Services_settings.value, Services_settings.suffix, Services_settings.method, ) .filter_by(service_id=service.id, setting_id=key) .all() ) for service_setting in service_settings: config[f"{service.id}_{key}" + (f"_{service_setting.suffix}" if service_setting.suffix > 0 else "")] = ( service_setting.value if not methods else { "value": service_setting.value, "global": False, "method": service_setting.method, } ) servers = " ".join(service.id for service in session.query(Services).all()) config["SERVER_NAME"] = servers if not methods else {"value": servers, "global": True, "method": "default"} return config def get_custom_configs(self) -> List[Dict[str, Any]]: """Get the custom configs from the database""" with self.__db_session() as session: return [ { "service_id": custom_config.service_id, "type": custom_config.type, "name": custom_config.name, "data": custom_config.data, "method": custom_config.method, } for custom_config in ( session.query(Custom_configs) .with_entities( Custom_configs.service_id, Custom_configs.type, Custom_configs.name, Custom_configs.data, Custom_configs.method, ) .all() ) ] def get_services_settings(self, methods: bool = False) -> List[Dict[str, Any]]: """Get the services' configs from the database""" services = [] config = self.get_config(methods=methods) with self.__db_session() as session: service_names = [service.id for service in session.query(Services).with_entities(Services.id).all()] for service in service_names: service_settings = [] tmp_config = deepcopy(config) for key, value in deepcopy(tmp_config).items(): if key.startswith(f"{service}_"): setting = key.replace(f"{service}_", "") service_settings.append(setting) tmp_config[setting] = tmp_config.pop(key) elif any(key.startswith(f"{s}_") for s in service_names): tmp_config.pop(key) elif key not in service_settings: tmp_config[key] = ( { "value": value["value"], "global": value["global"], "method": value["method"], } if methods else value ) services.append(tmp_config) return services def update_job(self, plugin_id: str, job_name: str, success: bool) -> str: """Update the job last_run in the database""" with self.__db_session() as session: job = session.query(Jobs).filter_by(plugin_id=plugin_id, name=job_name).first() if not job: return "Job not found" job.last_run = datetime.now() job.success = success try: session.commit() except BaseException: return format_exc() return "" def delete_job_cache(self, file_name: str, *, job_name: Optional[str] = None): job_name = job_name or basename(getsourcefile(_getframe(1))).replace(".py", "") with self.__db_session() as session: session.query(Jobs_cache).filter_by(job_name=job_name, file_name=file_name).delete() def update_job_cache( self, service_id: Optional[str], file_name: str, data: bytes, *, job_name: Optional[str] = None, checksum: Optional[str] = None, ) -> str: """Update the plugin cache in the database""" job_name = job_name or basename(getsourcefile(_getframe(1))).replace(".py", "") with self.__db_session() as session: cache = session.query(Jobs_cache).filter_by(job_name=job_name, service_id=service_id, file_name=file_name).first() if not cache: session.add( Jobs_cache( job_name=job_name, service_id=service_id, file_name=file_name, data=data, last_update=datetime.now(), checksum=checksum, ) ) else: cache.data = data cache.last_update = datetime.now() cache.checksum = checksum try: session.commit() except BaseException: return format_exc() return "" def update_external_plugins(self, plugins: List[Dict[str, Any]], *, delete_missing: bool = True) -> str: """Update external plugins from the database""" to_put = [] with self.__db_session() as session: db_plugins = session.query(Plugins).with_entities(Plugins.id).filter_by(external=True).all() db_ids = [] if delete_missing and db_plugins: db_ids = [plugin.id for plugin in db_plugins] ids = [plugin["id"] for plugin in plugins] missing_ids = [plugin for plugin in db_ids if plugin not in ids] if missing_ids: # Remove plugins that are no longer in the list session.query(Plugins).filter(Plugins.id.in_(missing_ids)).delete() for plugin in plugins: settings = plugin.pop("settings", {}) jobs = plugin.pop("jobs", []) page = plugin.pop("page", False) plugin["external"] = True db_plugin = ( session.query(Plugins) .with_entities( Plugins.name, Plugins.stream, Plugins.description, Plugins.version, Plugins.method, Plugins.data, Plugins.checksum, Plugins.external, ) .filter_by(id=plugin["id"]) .first() ) if db_plugin is not None: if db_plugin.external is False: self.__logger.warning( f"Plugin \"{plugin['id']}\" is not external, skipping update (updating a non-external plugin is forbidden for security reasons)", ) continue updates = {} if plugin["stream"] != db_plugin.stream: updates[Plugins.stream] = plugin["stream"] if plugin["name"] != db_plugin.name: updates[Plugins.name] = plugin["name"] if plugin["description"] != db_plugin.description: updates[Plugins.description] = plugin["description"] if plugin["version"] != db_plugin.version: updates[Plugins.version] = plugin["version"] if plugin["method"] != db_plugin.method: updates[Plugins.method] = plugin["method"] if plugin.get("data") != db_plugin.data: updates[Plugins.data] = plugin.get("data") if plugin.get("checksum") != db_plugin.checksum: updates[Plugins.checksum] = plugin.get("checksum") if updates: session.query(Plugins).filter(Plugins.id == plugin["id"]).update(updates) db_plugin_settings = session.query(Settings).with_entities(Settings.id).filter_by(plugin_id=plugin["id"]).all() db_ids = [setting.id for setting in db_plugin_settings] setting_ids = [setting for setting in settings] missing_ids = [setting for setting in db_ids if setting not in setting_ids] if missing_ids: # Remove settings that are no longer in the list session.query(Settings).filter(Settings.id.in_(missing_ids)).delete() for setting, value in settings.items(): value.update( { "plugin_id": plugin["id"], "name": value["id"], "id": setting, } ) db_setting = ( session.query(Settings) .with_entities( Settings.name, Settings.context, Settings.default, Settings.help, Settings.label, Settings.regex, Settings.type, Settings.multiple, ) .filter_by(id=setting) .first() ) if setting not in db_ids or not db_setting: for select in value.pop("select", []): to_put.append(Selects(setting_id=value["id"], value=select)) to_put.append( Settings( **value, ) ) else: updates = {} if value["name"] != db_setting.name: updates[Settings.name] = value["name"] if value["context"] != db_setting.context: updates[Settings.context] = value["context"] if value["default"] != db_setting.default: updates[Settings.default] = value["default"] if value["help"] != db_setting.help: updates[Settings.help] = value["help"] if value["label"] != db_setting.label: updates[Settings.label] = value["label"] if value["regex"] != db_setting.regex: updates[Settings.regex] = value["regex"] if value["type"] != db_setting.type: updates[Settings.type] = value["type"] if value.get("multiple") != db_setting.multiple: updates[Settings.multiple] = value.get("multiple") if updates: session.query(Settings).filter(Settings.id == setting).update(updates) db_selects = session.query(Selects).with_entities(Selects.value).filter_by(setting_id=setting).all() db_values = [select.value for select in db_selects] select_values = value.get("select", []) missing_values = [select for select in db_values if select not in select_values] if missing_values: # Remove selects that are no longer in the list session.query(Selects).filter(Selects.value.in_(missing_values)).delete() for select in value.get("select", []): if select not in db_values: to_put.append(Selects(setting_id=setting, value=select)) db_jobs = session.query(Jobs).with_entities(Jobs.name).filter_by(plugin_id=plugin["id"]).all() db_names = [job.name for job in db_jobs] job_names = [job["name"] for job in jobs] missing_names = [job for job in db_names if job not in job_names] if missing_names: # Remove jobs that are no longer in the list session.query(Jobs).filter(Jobs.name.in_(missing_names)).delete() for job in jobs: db_job = session.query(Jobs).with_entities(Jobs.file_name, Jobs.every, Jobs.reload).filter_by(name=job["name"], plugin_id=plugin["id"]).first() if job["name"] not in db_names or not db_job: job["file_name"] = job.pop("file") job["reload"] = job.get("reload", False) to_put.append( Jobs( plugin_id=plugin["id"], **job, ) ) else: updates = {} if job["file"] != db_job.file_name: updates[Jobs.file_name] = job["file"] if job["every"] != db_job.every: updates[Jobs.every] = job["every"] if job.get("reload", None) != db_job.reload: updates[Jobs.reload] = job.get("reload", False) if updates: updates[Jobs.last_run] = None session.query(Jobs_cache).filter(Jobs_cache.job_name == job["name"]).delete() session.query(Jobs).filter(Jobs.name == job["name"]).update(updates) tmp_ui_path = Path(sep, "var", "tmp", "bunkerweb", "ui", plugin["id"], "ui") path_ui = tmp_ui_path if tmp_ui_path.exists() else Path(sep, "etc", "bunkerweb", "plugins", plugin["id"], "ui") if path_ui.exists(): if {"template.html", "actions.py"}.issubset(listdir(str(path_ui))): db_plugin_page = ( session.query(Plugin_pages) .with_entities( Plugin_pages.template_checksum, Plugin_pages.actions_checksum, ) .filter_by(plugin_id=plugin["id"]) .first() ) if not db_plugin_page: template = path_ui.joinpath("template.html").read_bytes() actions = path_ui.joinpath("actions.py").read_bytes() to_put.append( Plugin_pages( plugin_id=plugin["id"], template_file=template, template_checksum=sha256(template).hexdigest(), actions_file=actions, actions_checksum=sha256(actions).hexdigest(), ) ) else: updates = {} template_path = path_ui.joinpath("template.html") actions_path = path_ui.joinpath("actions.py") template_checksum = file_hash(str(template_path)) actions_checksum = file_hash(str(actions_path)) if template_checksum != db_plugin_page.template_checksum: updates.update( { Plugin_pages.template_file: template_path.read_bytes(), Plugin_pages.template_checksum: template_checksum, } ) if actions_checksum != db_plugin_page.actions_checksum: updates.update( { Plugin_pages.actions_file: actions_path.read_bytes(), Plugin_pages.actions_checksum: actions_checksum, } ) if updates: session.query(Plugin_pages).filter(Plugin_pages.plugin_id == plugin["id"]).update(updates) continue to_put.append( Plugins( id=plugin["id"], name=plugin["name"], description=plugin["description"], version=plugin["version"], stream=plugin["stream"], external=True, method=plugin["method"], data=plugin.get("data"), checksum=plugin.get("checksum"), ) ) for setting, value in settings.items(): db_setting = session.query(Settings).filter_by(id=setting).first() if db_setting is not None: self.__logger.warning(f"A setting with id {setting} already exists, therefore it will not be added.") continue value.update( { "plugin_id": plugin["id"], "name": value["id"], "id": setting, } ) for select in value.pop("select", []): to_put.append(Selects(setting_id=value["id"], value=select)) to_put.append( Settings( **value, ) ) for job in jobs: db_job = session.query(Jobs).with_entities(Jobs.file_name, Jobs.every, Jobs.reload).filter_by(name=job["name"], plugin_id=plugin["id"]).first() if db_job is not None: self.__logger.warning(f"A job with the name {job['name']} already exists in the database, therefore it will not be added.") continue job["file_name"] = job.pop("file") job["reload"] = job.get("reload", False) to_put.append(Jobs(plugin_id=plugin["id"], **job)) if page: tmp_ui_path = Path(sep, "var", "tmp", "bunkerweb", "ui", plugin["id"], "ui") path_ui = tmp_ui_path if tmp_ui_path.exists() else Path(sep, "etc", "bunkerweb", "plugins", plugin["id"], "ui") if path_ui.exists(): if {"template.html", "actions.py"}.issubset(listdir(str(path_ui))): db_plugin_page = ( session.query(Plugin_pages) .with_entities( Plugin_pages.template_checksum, Plugin_pages.actions_checksum, ) .filter_by(plugin_id=plugin["id"]) .first() ) if not db_plugin_page: template = path_ui.joinpath("template.html").read_bytes() actions = path_ui.joinpath("actions.py").read_bytes() to_put.append( Plugin_pages( plugin_id=plugin["id"], template_file=template, template_checksum=sha256(template).hexdigest(), actions_file=actions, actions_checksum=sha256(actions).hexdigest(), ) ) else: updates = {} template_path = path_ui.joinpath("template.html") actions_path = path_ui.joinpath("actions.py") template_checksum = file_hash(str(template_path)) actions_checksum = file_hash(str(actions_path)) if template_checksum != db_plugin_page.template_checksum: updates.update( { Plugin_pages.template_file: template_path.read_bytes(), Plugin_pages.template_checksum: template_checksum, } ) if actions_checksum != db_plugin_page.actions_checksum: updates.update( { Plugin_pages.actions_file: actions_path.read_bytes(), Plugin_pages.actions_checksum: actions_checksum, } ) if updates: session.query(Plugin_pages).filter(Plugin_pages.plugin_id == plugin["id"]).update(updates) with suppress(ProgrammingError, OperationalError): metadata = session.query(Metadata).get(1) if metadata is not None: metadata.external_plugins_changed = True try: session.add_all(to_put) session.commit() except BaseException: return format_exc() return "" def get_plugins(self, *, external: bool = False, with_data: bool = False) -> List[Dict[str, Any]]: """Get all plugins from the database.""" plugins = [] with self.__db_session() as session: for plugin in ( session.query(Plugins) .with_entities( Plugins.id, Plugins.stream, Plugins.name, Plugins.description, Plugins.version, Plugins.external, Plugins.method, Plugins.data, Plugins.checksum, ) .all() if with_data else session.query(Plugins) .with_entities( Plugins.id, Plugins.stream, Plugins.name, Plugins.description, Plugins.version, Plugins.external, Plugins.method, ) .all() ): if external and not plugin.external: continue page = session.query(Plugin_pages).with_entities(Plugin_pages.id).filter_by(plugin_id=plugin.id).first() data = { "id": plugin.id, "stream": plugin.stream, "name": plugin.name, "description": plugin.description, "version": plugin.version, "external": plugin.external, "method": plugin.method, "page": page is not None, "settings": {}, } | ({"data": plugin.data, "checksum": plugin.checksum} if with_data else {}) for setting in ( session.query(Settings) .with_entities( Settings.id, Settings.context, Settings.default, Settings.help, Settings.name, Settings.label, Settings.regex, Settings.type, Settings.multiple, ) .filter_by(plugin_id=plugin.id) .all() ): data["settings"][setting.id] = { "context": setting.context, "default": setting.default, "help": setting.help, "id": setting.name, "label": setting.label, "regex": setting.regex, "type": setting.type, } | ({"multiple": setting.multiple} if setting.multiple else {}) if setting.type == "select": data["settings"][setting.id]["select"] = [select.value for select in session.query(Selects).with_entities(Selects.value).filter_by(setting_id=setting.id).all()] plugins.append(data) return plugins def get_plugins_errors(self) -> int: """Get plugins errors.""" with self.__db_session() as session: return session.query(Jobs).filter(Jobs.success == False).count() # noqa: E712 def get_jobs(self) -> Dict[str, Dict[str, Any]]: """Get jobs.""" with self.__db_session() as session: return { job.name: { "every": job.every, "reload": job.reload, "success": job.success, "last_run": job.last_run.strftime("%Y/%m/%d, %I:%M:%S %p") if job.last_run is not None else "Never", "cache": [ { "service_id": cache.service_id, "file_name": cache.file_name, "last_update": cache.last_update.strftime("%Y/%m/%d, %I:%M:%S %p") if cache.last_update is not None else "Never", } for cache in session.query(Jobs_cache) .with_entities( Jobs_cache.service_id, Jobs_cache.file_name, Jobs_cache.last_update, ) .filter_by(job_name=job.name) .all() ], } for job in ( session.query(Jobs) .with_entities( Jobs.name, Jobs.every, Jobs.reload, Jobs.success, Jobs.last_run, ) .all() ) } def get_job_cache_file( self, job_name: str, file_name: str, *, with_info: bool = False, with_data: bool = True, ) -> Optional[Any]: """Get job cache file.""" entities = [] if with_info: entities.extend([Jobs_cache.last_update, Jobs_cache.checksum]) if with_data: entities.append(Jobs_cache.data) with self.__db_session() as session: return session.query(Jobs_cache).with_entities(*entities).filter_by(job_name=job_name, file_name=file_name).first() def get_jobs_cache_files(self) -> List[Dict[str, Any]]: """Get jobs cache files.""" with self.__db_session() as session: return [ { "job_name": cache.job_name, "service_id": cache.service_id, "file_name": cache.file_name, "data": "Download file to view content", } for cache in ( session.query(Jobs_cache) .with_entities( Jobs_cache.job_name, Jobs_cache.service_id, Jobs_cache.file_name, ) .all() ) ] def add_instance(self, hostname: str, port: int, server_name: str, changed: Optional[bool] = True) -> str: """Add instance.""" with self.__db_session() as session: db_instance = session.query(Instances).with_entities(Instances.hostname).filter_by(hostname=hostname).first() if db_instance is not None: return f"Instance {hostname} already exists, will not be added." session.add(Instances(hostname=hostname, port=port, server_name=server_name)) if changed: with suppress(ProgrammingError, OperationalError): metadata = session.query(Metadata).get(1) if metadata is not None: metadata.instances_changed = True try: session.commit() except BaseException: return f"An error occurred while adding the instance {hostname} (port: {port}, server name: {server_name}).\n{format_exc()}" return "" def update_instances(self, instances: List[Dict[str, Any]], changed: Optional[bool] = True) -> str: """Update instances.""" to_put = [] with self.__db_session() as session: session.query(Instances).delete() for instance in instances: to_put.append( Instances( hostname=instance["hostname"], port=instance["env"].get("API_HTTP_PORT", 5000), server_name=instance["env"].get("API_SERVER_NAME", "bwapi"), ) ) if changed: with suppress(ProgrammingError, OperationalError): metadata = session.query(Metadata).get(1) if metadata is not None: metadata.instances_changed = True try: session.add_all(to_put) session.commit() except BaseException: return format_exc() return "" def get_instances(self) -> List[Dict[str, Any]]: """Get instances.""" with self.__db_session() as session: return [ { "hostname": instance.hostname, "port": instance.port, "server_name": instance.server_name, } for instance in (session.query(Instances).with_entities(Instances.hostname, Instances.port, Instances.server_name).all()) ] def get_plugin_actions(self, plugin: str) -> Optional[Any]: """get actions file for the plugin""" with self.__db_session() as session: page = session.query(Plugin_pages).with_entities(Plugin_pages.actions_file).filter_by(plugin_id=plugin).first() if not page: return None return page.actions_file def get_plugin_template(self, plugin: str) -> Optional[Any]: """get template file for the plugin""" with self.__db_session() as session: page = session.query(Plugin_pages).with_entities(Plugin_pages.template_file).filter_by(plugin_id=plugin).first() if not page: return None return page.template_file def get_ui_user(self) -> Optional[dict]: """Get ui user.""" with self.__db_session() as session: user = session.query(Users).with_entities(Users.username, Users.password, Users.is_two_factor_enabled, Users.secret_token, Users.method).filter_by(id=1).first() if not user: return None return { "username": user.username, "password_hash": user.password.encode("utf-8"), "is_two_factor_enabled": user.is_two_factor_enabled, "secret_token": user.secret_token, "method": user.method, } def create_ui_user(self, username: str, password: bytes, *, secret_token: Optional[str] = None, method: str = "manual") -> str: """Create ui user.""" with self.__db_session() as session: if self.get_ui_user(): return "User already exists" session.add(Users(id=1, username=username, password=password.decode("utf-8"), secret_token=secret_token, method=method)) try: session.commit() except BaseException: return format_exc() return "" def update_ui_user(self, username: str, password: bytes, is_two_factor_enabled: bool = False, secret_token: Optional[str] = None, method: str = "ui") -> str: """Update ui user.""" with self.__db_session() as session: user = session.query(Users).filter_by(id=1).first() if not user: return "User not found" user.username = username user.password = password.decode("utf-8") user.is_two_factor_enabled = is_two_factor_enabled user.secret_token = secret_token user.method = method try: session.commit() except BaseException: return format_exc() return "" def listen_for_instances_reload(db: Database): from docker import DockerClient global SCHEDULER docker_client = DockerClient(base_url=getenv("DOCKER_HOST", "unix:///var/run/docker.sock")) for event in docker_client.events(decode=True, filters={"type": "container", "label": "bunkerweb.INSTANCE"}): if event["Action"] in ("start", "die"): logger.info(f"🐋 Detected {event['Action']} event on container {event['Actor']['Attributes']['name']}") SCHEDULER.auto_setup() db.update_instances([api_to_instance(api) for api in SCHEDULER.apis], changed=event["Action"] == "die") if event["Action"] == "start": db.checked_changes(value=True)
null
18,274
from os import _exit, getenv, sep from os.path import join from signal import SIGINT, SIGTERM, signal from sys import exit as sys_exit, path as sys_path from traceback import format_exc from pathlib import Path from logger import setup_logger from SwarmController import SwarmController from IngressController import IngressController from DockerController import DockerController logger = setup_logger("Autoconf", getenv("LOG_LEVEL", "INFO")) def exit_handler(signum, frame): logger.info("Stop signal received, exiting...") _exit(0)
null
18,275
import fileinput, string, sys def regexp_char(char, evasion): def regexp_str(str, evasion): # By convention, if the line starts with ' char, copy the rest # verbatim. if str[0] == "'": return str[1:] result = '' for i, char in enumerate(str): if i > 0: result += evasion result += regexp_char(char, evasion) return result
null
18,276
import argparse args = parser.parse_args() def commonprefix(m): def flatten(dict): def set(strings, index, flags): def prepare(s, offset): def run(): strings = args.strings r = "" r += set(strings, 0, "^") c = "" d = {} # Only find common string if we have more than one if len(strings) > 1: c = commonprefix(strings) # Collect all characters after the common substring from every string for s in strings: if len(s) > len(c) and s.startswith(c): d[s[len(c)]] = '' # Add the common string to the regex to prevent accidental matching if len(c) > 0: if len(c) > 1: r += "|" + "(?:" + prepare(c, 1) + ")" r += "|" + "(?:" + c + "[^" + flatten(d) + "]" + ")" for s in strings: g = "" # When the common string is > 0, offset with len(c) + 1 because we handled this earlier if len(c) > 0: g = prepare(s, len(c) + 1) else: g = prepare(s, 1) # Add OR boolean if necessary if len(g) > 0: r += "|" r += g print(args.prefix + "(?:" + r + ")" + args.suffix)
null
18,277
from os import getenv, sep from pathlib import Path from requests import request as requests_request, ReadTimeout from typing import Literal, Optional, Tuple, Union def request(method: Union[Literal["POST"], Literal["GET"]], url: str, _id: Optional[str] = None) -> Tuple[bool, Optional[int], Union[str, dict]]: data = {"integration": get_integration(), "version": get_version()} headers = {"User-Agent": f"BunkerWeb/{get_version()}"} if _id is not None: data["id"] = _id try: resp = requests_request( method, f"{getenv('BUNKERNET_SERVER', 'https://api.bunkerweb.io')}{url}", json=data, headers=headers, timeout=5, ) status = resp.status_code if status == 429: return True, 429, "rate limited" elif status == 403: return True, 403, "forbidden" raw_data: dict = resp.json() assert "result" in raw_data assert "data" in raw_data except ReadTimeout: return False, None, "request timed out" except Exception as e: return False, None, f"request failed: {e}" return True, status, raw_data def register() -> Tuple[bool, Optional[int], Union[str, dict]]: return request("POST", "/register")
null
18,278
from os import getenv, sep from pathlib import Path from requests import request as requests_request, ReadTimeout from typing import Literal, Optional, Tuple, Union def request(method: Union[Literal["POST"], Literal["GET"]], url: str, _id: Optional[str] = None) -> Tuple[bool, Optional[int], Union[str, dict]]: data = {"integration": get_integration(), "version": get_version()} headers = {"User-Agent": f"BunkerWeb/{get_version()}"} if _id is not None: data["id"] = _id try: resp = requests_request( method, f"{getenv('BUNKERNET_SERVER', 'https://api.bunkerweb.io')}{url}", json=data, headers=headers, timeout=5, ) status = resp.status_code if status == 429: return True, 429, "rate limited" elif status == 403: return True, 403, "forbidden" raw_data: dict = resp.json() assert "result" in raw_data assert "data" in raw_data except ReadTimeout: return False, None, "request timed out" except Exception as e: return False, None, f"request failed: {e}" return True, status, raw_data def get_id() -> str: return Path(sep, "var", "cache", "bunkerweb", "bunkernet", "instance.id").read_text(encoding="utf-8").strip() def ping(_id: Optional[str] = None) -> Tuple[bool, Optional[int], Union[str, dict]]: return request("GET", "/ping", _id=_id or get_id())
null
18,279
from hashlib import sha256 from io import BytesIO from os import getenv, listdir, chmod, _exit, sep from os.path import basename, dirname, join, normpath from pathlib import Path from stat import S_IEXEC from sys import exit as sys_exit, path as sys_path from threading import Lock from uuid import uuid4 from glob import glob from json import loads from shutil import copytree, rmtree from tarfile import open as tar_open from traceback import format_exc from zipfile import ZipFile from magic import Magic from requests import get from Database import Database from logger import setup_logger logger = setup_logger("Jobs.download-plugins", getenv("LOG_LEVEL", "INFO")) def install_plugin(plugin_dir) -> bool: # Load plugin.json metadata = loads(Path(plugin_dir, "plugin.json").read_text(encoding="utf-8")) # Don't go further if plugin is already installed if Path("etc", "bunkerweb", "plugins", metadata["id"], "plugin.json").is_file(): logger.warning( f"Skipping installation of plugin {metadata['id']} (already installed)", ) return False # Copy the plugin copytree(plugin_dir, join(sep, "etc", "bunkerweb", "plugins", metadata["id"])) # Add u+x permissions to jobs files for job_file in glob(join(plugin_dir, "jobs", "*")): st = Path(job_file).stat() chmod(job_file, st.st_mode | S_IEXEC) logger.info(f"Plugin {metadata['id']} installed") return True
null
18,280
from contextlib import suppress from ipaddress import ip_address, ip_network from os import _exit, getenv, sep from os.path import join, normpath from pathlib import Path from re import IGNORECASE, compile as re_compile from sys import exit as sys_exit, path as sys_path from traceback import format_exc from typing import Tuple from requests import get from Database import Database from logger import setup_logger from jobs import cache_file, cache_hash, del_file_in_db, is_cached_file, file_hash rdns_rx = re_compile(rb"^[^ ]+$", IGNORECASE) asn_rx = re_compile(rb"^\d+$") uri_rx = re_compile(rb"^/") def check_line(kind: str, line: bytes) -> Tuple[bool, bytes]: if kind in ("IP", "IGNORE_IP"): if b"/" in line: with suppress(ValueError): ip_network(line.decode("utf-8")) return True, line else: with suppress(ValueError): ip_address(line.decode("utf-8")) return True, line elif kind in ("RDNS", "IGNORE_RDNS"): if rdns_rx.match(line): return True, line.lower() elif kind in ("ASN", "IGNORE_ASN"): real_line = line.replace(b"AS", b"").replace(b"as", b"") if asn_rx.match(real_line): return True, real_line elif kind in ("USER_AGENT", "IGNORE_USER_AGENT"): return True, b"(?:\\b)" + line + b"(?:\\b)" elif kind in ("URI", "IGNORE_URI"): if uri_rx.match(line): return True, line return False, b""
null
18,281
from os import getenv, sep from os.path import join, normpath from pathlib import Path from sys import exit as sys_exit, path as sys_path from traceback import format_exc from base64 import b64decode from jobs import cache_file, cache_hash, file_hash from Database import Database from logger import setup_logger logger = setup_logger("CUSTOM-CERT", getenv("LOG_LEVEL", "INFO")) db = None try: Path(sep, "var", "cache", "bunkerweb", "customcert").mkdir(parents=True, exist_ok=True) if getenv("MULTISITE", "no") == "no" and getenv("USE_CUSTOM_SSL", "no") == "yes" and getenv("SERVER_NAME", "") != "": db = Database(logger, sqlalchemy_string=getenv("DATABASE_URI", None), pool=False) cert_path = getenv("CUSTOM_SSL_CERT", "") key_path = getenv("CUSTOM_SSL_KEY", "") first_server = getenv("SERVER_NAME").split(" ")[0] cert_data = b64decode(getenv("CUSTOM_SSL_CERT_DATA", "")) key_data = b64decode(getenv("CUSTOM_SSL_KEY_DATA", "")) for file, data in (("cert.pem", cert_data), ("key.pem", key_data)): if data != b"": file_path = Path(sep, "var", "tmp", "bunkerweb", "customcert", f"{first_server}.{file}") file_path.parent.mkdir(parents=True, exist_ok=True) file_path.write_bytes(data) if file == "cert.pem": cert_path = str(file_path) else: key_path = str(file_path) if cert_path and key_path: logger.info(f"Checking certificate {cert_path} ...") need_reload = check_cert(cert_path, key_path, first_server) if need_reload: logger.info(f"Detected change for certificate {cert_path}") status = 1 else: logger.info(f"No change for certificate {cert_path}") elif getenv("MULTISITE", "no") == "yes": servers = getenv("SERVER_NAME") or [] if isinstance(servers, str): servers = servers.split(" ") for first_server in servers: if not first_server or (getenv(f"{first_server}_USE_CUSTOM_SSL", getenv("USE_CUSTOM_SSL", "no")) != "yes"): continue if not db: db = Database(logger, sqlalchemy_string=getenv("DATABASE_URI", None), pool=False) cert_path = getenv(f"{first_server}_CUSTOM_SSL_CERT", "") key_path = getenv(f"{first_server}_CUSTOM_SSL_KEY", "") cert_data = b64decode(getenv(f"{first_server}_CUSTOM_SSL_CERT_DATA", "")) key_data = b64decode(getenv(f"{first_server}_CUSTOM_SSL_KEY_DATA", "")) for file, data in (("cert.pem", cert_data), ("key.pem", key_data)): if data != b"": file_path = Path(sep, "var", "tmp", "bunkerweb", "customcert", f"{first_server}.{file}") file_path.parent.mkdir(parents=True, exist_ok=True) file_path.write_bytes(data) if file == "cert.pem": cert_path = str(file_path) else: key_path = str(file_path) if cert_path and key_path: logger.info( f"Checking certificate {cert_path} ...", ) need_reload = check_cert(cert_path, key_path, first_server) if need_reload: logger.info( f"Detected change for certificate {cert_path}", ) status = 1 else: logger.info( f"No change for certificate {cert_path}", ) except: status = 2 logger.error(f"Exception while running custom-cert.py :\n{format_exc()}") def file_hash(file: Union[str, Path]) -> str: _sha512 = sha512() with open(normpath(file), "rb") as f: while True: data = f.read(1024) if not data: break _sha512.update(data) return _sha512.hexdigest() def cache_hash(cache: Union[str, Path], db=None) -> Optional[str]: with suppress(BaseException): return loads(Path(normpath(f"{cache}.md")).read_text(encoding="utf-8")).get("checksum", None) if db: cached_file = db.get_job_cache_file( basename(getsourcefile(_getframe(1))).replace(".py", ""), basename(normpath(cache)), with_info=True, with_data=False, ) if cached_file: return cached_file.checksum return None def cache_file( file: Union[str, Path], cache: Union[str, Path], _hash: Optional[str], db=None, *, delete_file: bool = True, service_id: Optional[str] = None, ) -> Tuple[bool, str]: ret, err = True, "success" try: if not isinstance(file, Path): file = Path(normpath(file)) if not isinstance(cache, Path): cache = Path(normpath(cache)) content = file.read_bytes() cache.write_bytes(content) if delete_file: file.unlink() if not _hash: _hash = file_hash(str(cache)) if db: return set_file_in_db( basename(str(cache)), content, db, job_name=basename(getsourcefile(_getframe(1))).replace(".py", ""), service_id=service_id, checksum=_hash, ) else: Path(f"{cache}.md").write_text( dumps(dict(date=datetime.now().timestamp(), checksum=_hash)), encoding="utf-8", ) except: return False, f"exception :\n{format_exc()}" return ret, err def check_cert(cert_path: str, key_path: str, first_server: str) -> bool: try: ret = False if not cert_path or not key_path: logger.warning("Both variables CUSTOM_SSL_CERT and CUSTOM_SSL_KEY have to be set to use custom certificates") return False cert_path: Path = Path(normpath(cert_path)) key_path: Path = Path(normpath(key_path)) if not cert_path.is_file(): logger.warning(f"Certificate file {cert_path} is not a valid file, ignoring the custom certificate") return False elif not key_path.is_file(): logger.warning(f"Key file {key_path} is not a valid file, ignoring the custom certificate") return False cert_cache_path = Path( sep, "var", "cache", "bunkerweb", "customcert", f"{first_server}.cert.pem", ) cert_cache_path.parent.mkdir(parents=True, exist_ok=True) cert_hash = file_hash(cert_path) old_hash = cache_hash(cert_cache_path, db) if old_hash != cert_hash: ret = True cached, err = cache_file(cert_path, cert_cache_path, cert_hash, db, delete_file=False) if not cached: logger.error(f"Error while caching custom-cert cert.pem file : {err}") key_cache_path = Path( sep, "var", "cache", "bunkerweb", "customcert", f"{first_server}.key.pem", ) key_cache_path.parent.mkdir(parents=True, exist_ok=True) key_hash = file_hash(key_path) old_hash = cache_hash(key_cache_path, db) if old_hash != key_hash: ret = True cached, err = cache_file(key_path, key_cache_path, key_hash, db, delete_file=False) if not cached: logger.error(f"Error while caching custom-cert key.pem file : {err}") return ret except: logger.error( f"Exception while running custom-cert.py (check_cert) :\n{format_exc()}", ) return False
null
18,282
from contextlib import suppress from ipaddress import ip_address, ip_network from os import _exit, getenv, sep from os.path import join, normpath from pathlib import Path from re import IGNORECASE, compile as re_compile from sys import exit as sys_exit, path as sys_path from traceback import format_exc from typing import Tuple from requests import get from Database import Database from logger import setup_logger from jobs import cache_file, cache_hash, del_file_in_db, is_cached_file, file_hash rdns_rx = re_compile(rb"^[^ ]+$", IGNORECASE) asn_rx = re_compile(rb"^\d+$") uri_rx = re_compile(rb"^/") def check_line(kind: str, line: bytes) -> Tuple[bool, bytes]: if kind == "IP": if b"/" in line: with suppress(ValueError): ip_network(line.decode("utf-8")) return True, line else: with suppress(ValueError): ip_address(line.decode("utf-8")) return True, line elif kind == "RDNS": if rdns_rx.match(line): return True, line.lower() elif kind == "ASN": real_line = line.replace(b"AS", b"").replace(b"as", b"") if asn_rx.match(real_line): return True, real_line elif kind == "USER_AGENT": return True, b"(?:\\b)" + line + b"(?:\\b)" elif kind == "URI": if uri_rx.match(line): return True, line return False, b""
null
18,283
from os import _exit, environ, getenv, sep from os.path import join from pathlib import Path from subprocess import DEVNULL, STDOUT, run, PIPE from sys import exit as sys_exit, path as sys_path from traceback import format_exc from tarfile import open as tar_open from io import BytesIO from shutil import rmtree from re import findall, MULTILINE from Database import Database from logger import setup_logger from jobs import get_file_in_db, set_file_in_db def certbot_new(domains: str, email: str, letsencrypt_path: Path, letsencrypt_job_path: Path) -> int: return run( [ join(sep, "usr", "share", "bunkerweb", "deps", "python", "bin", "certbot"), "certonly", "--config-dir", str(letsencrypt_path.joinpath("etc")), "--work-dir", join(sep, "var", "lib", "bunkerweb", "letsencrypt"), "--logs-dir", join(sep, "var", "log", "bunkerweb"), "--manual", "--preferred-challenges=http", "--manual-auth-hook", str(letsencrypt_job_path.joinpath("certbot-auth.py")), "--manual-cleanup-hook", str(letsencrypt_job_path.joinpath("certbot-cleanup.py")), "-n", "-d", domains, "--email", email, "--agree-tos", "--expand", ] + (["--staging"] if getenv("USE_LETS_ENCRYPT_STAGING", "no") == "yes" else []), stdin=DEVNULL, stderr=STDOUT, env=environ.copy() | {"PYTHONPATH": join(sep, "usr", "share", "bunkerweb", "deps", "python")}, ).returncode
null
18,284
from os import _exit, environ, getenv, sep from os.path import join from pathlib import Path from subprocess import DEVNULL, STDOUT, run, PIPE from sys import exit as sys_exit, path as sys_path from traceback import format_exc from tarfile import open as tar_open from io import BytesIO from shutil import rmtree from re import findall, MULTILINE from Database import Database from logger import setup_logger from jobs import get_file_in_db, set_file_in_db logger = setup_logger("LETS-ENCRYPT.new", getenv("LOG_LEVEL", "INFO")) def certbot_check_domains(domains: list[str], letsencrypt_path: Path) -> int: proc = run( [ join(sep, "usr", "share", "bunkerweb", "deps", "python", "bin", "certbot"), "certificates", "--config-dir", str(letsencrypt_path.joinpath("etc")), "--work-dir", join(sep, "var", "lib", "bunkerweb", "letsencrypt"), "--logs-dir", join(sep, "var", "log", "bunkerweb"), ], stdin=DEVNULL, stdout=PIPE, stderr=STDOUT, text=True, env=environ.copy() | {"PYTHONPATH": join(sep, "usr", "share", "bunkerweb", "deps", "python")}, ) if proc.returncode != 0: logger.error(f"Error while checking certificates :\n{proc.stdout}") return 2 first_needed_domain = domains[0] needed_domains = set(domains) for raw_domains in findall(r"^ Domains: (.*)$", proc.stdout, MULTILINE): current_domains = raw_domains.split(" ") if current_domains[0] == first_needed_domain and set(current_domains) == needed_domains: return 1 return 0
null
18,285
from contextlib import suppress from ipaddress import ip_address, ip_network from os import _exit, getenv, sep from os.path import join, normpath from pathlib import Path from sys import exit as sys_exit, path as sys_path from traceback import format_exc from requests import get from Database import Database from logger import setup_logger from jobs import cache_file, cache_hash, del_file_in_db, file_hash, is_cached_file def check_line(line): if "/" in line: with suppress(ValueError): ip_network(line) return True, line else: with suppress(ValueError): ip_address(line) return True, line return False, b""
null
18,286
from datetime import timedelta from os import getenv, sep from os.path import join from pathlib import Path from subprocess import DEVNULL, STDOUT, run from sys import exit as sys_exit, path as sys_path from threading import Lock from traceback import format_exc from typing import Tuple from cryptography import x509 from cryptography.hazmat.backends import default_backend from Database import Database from logger import setup_logger from jobs import set_file_in_db logger = setup_logger("self-signed", getenv("LOG_LEVEL", "INFO")) db = None def set_file_in_db( name: str, content: bytes, db, *, job_name: Optional[str] = None, service_id: Optional[str] = None, checksum: Optional[str] = None, ) -> Tuple[bool, str]: def generate_cert(first_server: str, days: str, subj: str, self_signed_path: Path) -> Tuple[bool, int]: if self_signed_path.joinpath(f"{first_server}.pem").is_file(): if ( run( [ "openssl", "x509", "-checkend", "86400", "-noout", "-in", str(self_signed_path.joinpath(f"{first_server}.pem")), ], stdin=DEVNULL, stderr=STDOUT, check=False, ).returncode == 0 ): logger.info(f"Self-signed certificate already present for {first_server}") certificate = x509.load_pem_x509_certificate( self_signed_path.joinpath(f"{first_server}.pem").read_bytes(), default_backend(), ) if sorted(attribute.rfc4514_string() for attribute in certificate.subject) != sorted(v for v in subj.split("/") if v): logger.warning(f"Subject of self-signed certificate for {first_server} is different from the one in the configuration, regenerating ...") elif certificate.not_valid_after - certificate.not_valid_before != timedelta(days=int(days)): logger.warning(f"Expiration date of self-signed certificate for {first_server} is different from the one in the configuration, regenerating ...") else: return True, 0 logger.info(f"Generating self-signed certificate for {first_server}") if ( run( [ "openssl", "req", "-nodes", "-x509", "-newkey", "rsa:4096", "-keyout", str(self_signed_path.joinpath(f"{first_server}.key")), "-out", str(self_signed_path.joinpath(f"{first_server}.pem")), "-days", days, "-subj", subj, ], stdin=DEVNULL, stderr=DEVNULL, check=False, ).returncode != 0 ): logger.error(f"Self-signed certificate generation failed for {first_server}") return False, 2 # Update db cached, err = set_file_in_db( f"{first_server}.pem", self_signed_path.joinpath(f"{first_server}.pem").read_bytes(), db, service_id=first_server, ) if not cached: logger.error(f"Error while caching self-signed {first_server}.pem file : {err}") cached, err = set_file_in_db( f"{first_server}.key", self_signed_path.joinpath(f"{first_server}.key").read_bytes(), db, service_id=first_server, ) if not cached: logger.error(f"Error while caching self-signed {first_server}.key file : {err}") logger.info(f"Successfully generated self-signed certificate for {first_server}") return True, 1
null
18,288
from dotenv import dotenv_values from os import getenv, sep from os.path import join from pathlib import Path from redis import StrictRedis from sys import path as sys_path from typing import Optional, Tuple from API import API from ApiCaller import ApiCaller from logger import setup_logger def format_remaining_time(seconds): days, seconds = divmod(seconds, 86400) hours, seconds = divmod(seconds, 3600) minutes, seconds = divmod(seconds, 60) time_parts = [] if days > 0: time_parts.append(f"{int(days)} day{'' if days == 1 else 's'}") if hours > 0: time_parts.append(f"{int(hours)} hour{'' if hours == 1 else 's'}") if minutes > 0: time_parts.append(f"{int(minutes)} minute{'' if minutes == 1 else 's'}") if seconds > 0: time_parts.append(f"{seconds} second{'' if seconds == 1 else 's'}") if len(time_parts) > 1: time_parts[-1] = f"and {time_parts[-1]}" return " ".join(time_parts)
null
18,289
from os import getegid, geteuid from pathlib import Path from stat import ( S_IRGRP, S_IROTH, S_IRUSR, S_IWGRP, S_IWOTH, S_IWUSR, S_IXGRP, S_IXOTH, S_IXUSR, ) from typing import List def has_permissions(path: str, need_permissions: List[str]) -> bool: uid = geteuid() gid = getegid() statinfo = Path(path).stat() permissions = {"R": False, "W": False, "X": False} if statinfo.st_uid == uid: if statinfo.st_mode & S_IRUSR: permissions["R"] = True if statinfo.st_mode & S_IWUSR: permissions["W"] = True if statinfo.st_mode & S_IXUSR: permissions["X"] = True if statinfo.st_uid == gid: if statinfo.st_mode & S_IRGRP: permissions["R"] = True if statinfo.st_mode & S_IWGRP: permissions["W"] = True if statinfo.st_mode & S_IXGRP: permissions["X"] = True if statinfo.st_mode & S_IROTH: permissions["R"] = True if statinfo.st_mode & S_IWOTH: permissions["W"] = True if statinfo.st_mode & S_IXOTH: permissions["X"] = True for need_permission in need_permissions: if not permissions[need_permission]: return False return True
null
18,290
from argparse import ArgumentParser from os import R_OK, X_OK, access, environ, getenv, sep from os.path import join, normpath from pathlib import Path from re import compile as re_compile from sys import exit as sys_exit, path as sys_path from time import sleep from traceback import format_exc from typing import Any from docker import DockerClient from logger import setup_logger from Database import Database from Configurator import Configurator from API import API custom_confs_rx = re_compile(r"^([0-9a-z\.-]*)_?CUSTOM_CONF_(HTTP|SERVER_STREAM|STREAM|DEFAULT_SERVER_HTTP|SERVER_HTTP|MODSEC_CRS|MODSEC)_(.+)$") class Database: DB_STRING_RX = re_compile(r"^(?P<database>(mariadb|mysql)(\+pymysql)?|sqlite(\+pysqlite)?|postgresql):/+(?P<path>/[^\s]+)") def __init__( self, logger: Logger, sqlalchemy_string: Optional[str] = None, *, ui: bool = False, pool: bool = True, ) -> None: """Initialize the database""" self.__logger = logger self.__session_factory = None self.__sql_engine = None if not sqlalchemy_string: sqlalchemy_string = getenv("DATABASE_URI", "sqlite:////var/lib/bunkerweb/db.sqlite3") match = self.DB_STRING_RX.search(sqlalchemy_string) if not match: self.__logger.error(f"Invalid database string provided: {sqlalchemy_string}, exiting...") _exit(1) if match.group("database").startswith("sqlite"): db_path = Path(normpath(match.group("path"))) if ui: while not db_path.is_file(): self.__logger.warning(f"Waiting for the database file to be created: {db_path}") sleep(1) else: db_path.parent.mkdir(parents=True, exist_ok=True) self.database_uri = sqlalchemy_string error = False engine_kwargs = {"future": True, "poolclass": None if pool else SingletonThreadPool, "pool_pre_ping": True, "pool_recycle": 1800} try: self.__sql_engine = create_engine(sqlalchemy_string, **engine_kwargs) except ArgumentError: self.__logger.error(f"Invalid database URI: {sqlalchemy_string}") error = True except SQLAlchemyError: self.__logger.error(f"Error when trying to create the engine: {format_exc()}") error = True finally: if error: _exit(1) try: assert self.__sql_engine is not None except AssertionError: self.__logger.error("The database engine is not initialized") _exit(1) not_connected = True retries = 15 while not_connected: try: with self.__sql_engine.connect() as conn: conn.execute(text("CREATE TABLE IF NOT EXISTS test (id INT)")) conn.execute(text("DROP TABLE test")) not_connected = False except (OperationalError, DatabaseError) as e: if retries <= 0: self.__logger.error( f"Can't connect to database : {format_exc()}", ) _exit(1) if "attempt to write a readonly database" in str(e): self.__logger.warning("The database is read-only, waiting for it to become writable. Retrying in 5 seconds ...") self.__sql_engine.dispose(close=True) self.__sql_engine = create_engine(sqlalchemy_string, **engine_kwargs) if "Unknown table" in str(e): not_connected = False continue else: self.__logger.warning( "Can't connect to database, retrying in 5 seconds ...", ) retries -= 1 sleep(5) except BaseException: self.__logger.error(f"Error when trying to connect to the database: {format_exc()}") exit(1) self.__logger.info("✅ Database connection established") self.__session_factory = sessionmaker(bind=self.__sql_engine, autoflush=True, expire_on_commit=False) self.suffix_rx = re_compile(r"_\d+$") if sqlalchemy_string.startswith("sqlite"): with self.__db_session() as session: session.execute(text("PRAGMA journal_mode=WAL")) session.commit() def __del__(self) -> None: """Close the database""" if self.__session_factory: self.__session_factory.close_all() if self.__sql_engine: self.__sql_engine.dispose() def __db_session(self): try: assert self.__session_factory is not None except AssertionError: self.__logger.error("The database session is not initialized") _exit(1) session = scoped_session(self.__session_factory) try: yield session except BaseException: session.rollback() raise finally: session.remove() def set_autoconf_load(self, value: bool = True) -> str: """Set the autoconf_loaded value""" with self.__db_session() as session: try: metadata = session.query(Metadata).get(1) if not metadata: return "The metadata are not set yet, try again" metadata.autoconf_loaded = value session.commit() except BaseException: return format_exc() return "" def is_autoconf_loaded(self) -> bool: """Check if the autoconf is loaded""" with self.__db_session() as session: try: metadata = session.query(Metadata).with_entities(Metadata.autoconf_loaded).filter_by(id=1).first() return metadata is not None and metadata.autoconf_loaded except (ProgrammingError, OperationalError): return False def set_scheduler_first_start(self, value: bool = False) -> str: """Set the scheduler_first_start value""" with self.__db_session() as session: try: metadata = session.query(Metadata).get(1) if not metadata: return "The metadata are not set yet, try again" metadata.scheduler_first_start = value session.commit() except BaseException: return format_exc() return "" def is_scheduler_first_start(self) -> bool: """Check if it's the scheduler's first start""" with self.__db_session() as session: try: metadata = session.query(Metadata).with_entities(Metadata.scheduler_first_start).filter_by(id=1).first() return metadata is not None and metadata.scheduler_first_start except (ProgrammingError, OperationalError): return True def is_first_config_saved(self) -> bool: """Check if the first configuration has been saved""" with self.__db_session() as session: try: metadata = session.query(Metadata).with_entities(Metadata.first_config_saved).filter_by(id=1).first() return metadata is not None and metadata.first_config_saved except (ProgrammingError, OperationalError): return False def is_initialized(self) -> bool: """Check if the database is initialized""" with self.__db_session() as session: try: metadata = session.query(Metadata).with_entities(Metadata.is_initialized).filter_by(id=1).first() return metadata is not None and metadata.is_initialized except (ProgrammingError, OperationalError, DatabaseError): return False def initialize_db(self, version: str, integration: str = "Unknown") -> str: """Initialize the database""" with self.__db_session() as session: try: if session.query(Metadata).get(1): session.query(Metadata).filter_by(id=1).update({Metadata.version: version, Metadata.integration: integration}) else: session.add( Metadata( is_initialized=True, first_config_saved=False, scheduler_first_start=True, version=version, integration=integration, ) ) session.commit() except BaseException: return format_exc() return "" def get_metadata(self) -> Dict[str, str]: """Get the metadata from the database""" data = {"version": "1.5.4", "integration": "unknown"} with self.__db_session() as session: with suppress(ProgrammingError, OperationalError): metadata = session.query(Metadata).with_entities(Metadata.version, Metadata.integration).filter_by(id=1).first() if metadata: data = {"version": metadata.version, "integration": metadata.integration} return data def check_changes(self) -> Union[Dict[str, bool], bool, str]: """Check if either the config, the custom configs, plugins or instances have changed inside the database""" with self.__db_session() as session: try: metadata = ( session.query(Metadata) .with_entities( Metadata.custom_configs_changed, Metadata.external_plugins_changed, Metadata.config_changed, Metadata.instances_changed, ) .filter_by(id=1) .first() ) return dict( custom_configs_changed=metadata is not None and metadata.custom_configs_changed, external_plugins_changed=metadata is not None and metadata.external_plugins_changed, config_changed=metadata is not None and metadata.config_changed, instances_changed=metadata is not None and metadata.instances_changed, ) except BaseException: return format_exc() def checked_changes(self, changes: Optional[List[str]] = None, value: Optional[bool] = False) -> str: """Set changed bit for config, custom configs, instances and plugins""" changes = changes or [ "config", "custom_configs", "external_plugins", "instances", ] with self.__db_session() as session: try: metadata = session.query(Metadata).get(1) if not metadata: return "The metadata are not set yet, try again" if "config" in changes: if not metadata.first_config_saved: metadata.first_config_saved = True metadata.config_changed = value if "custom_configs" in changes: metadata.custom_configs_changed = value if "external_plugins" in changes: metadata.external_plugins_changed = value if "instances" in changes: metadata.instances_changed = value session.commit() except BaseException: return format_exc() return "" def init_tables(self, default_plugins: List[dict], bunkerweb_version: str) -> Tuple[bool, str]: """Initialize the database tables and return the result""" inspector = inspect(self.__sql_engine) db_version = None has_all_tables = True if inspector and len(inspector.get_table_names()): db_version = self.get_metadata()["version"] if db_version != bunkerweb_version: self.__logger.warning(f"Database version ({db_version}) is different from Bunkerweb version ({bunkerweb_version}), checking if it needs to be updated") for table in Base.metadata.tables: if not inspector.has_table(table): has_all_tables = False else: missing_columns = [] db_columns = inspector.get_columns(table) for column in Base.metadata.tables[table].columns: if not any(db_column["name"] == column.name for db_column in db_columns): missing_columns.append(column) try: with self.__db_session() as session: if missing_columns: for column in missing_columns: session.execute(text(f"ALTER TABLE {table} ADD COLUMN {column.name} {column.type}")) session.commit() except BaseException: return False, format_exc() if has_all_tables and db_version and db_version == bunkerweb_version: return False, "" try: Base.metadata.create_all(self.__sql_engine, checkfirst=True) except BaseException: return False, format_exc() to_put = [] with self.__db_session() as session: for plugins in default_plugins: if not isinstance(plugins, list): plugins = [plugins] for plugin in plugins: settings = {} jobs = [] page = False if "id" not in plugin: settings = plugin plugin = { "id": "general", "name": "General", "description": "The general settings for the server", "version": "0.1", "stream": "partial", "external": False, } else: settings = plugin.pop("settings", {}) jobs = plugin.pop("jobs", []) page = plugin.pop("page", False) db_plugin = session.query(Plugins).filter_by(id=plugin["id"]).first() if db_plugin: updates = {} if plugin["name"] != db_plugin.name: updates[Plugins.name] = plugin["name"] if plugin["description"] != db_plugin.description: updates[Plugins.description] = plugin["description"] if plugin["version"] != db_plugin.version: updates[Plugins.version] = plugin["version"] if plugin["stream"] != db_plugin.stream: updates[Plugins.stream] = plugin["stream"] if plugin.get("external", False) != db_plugin.external: updates[Plugins.external] = plugin.get("external", False) if plugin.get("method", "manual") != db_plugin.method: updates[Plugins.method] = plugin.get("method", "manual") if plugin.get("data") != db_plugin.data: updates[Plugins.data] = plugin.get("data") if plugin.get("checksum") != db_plugin.checksum: updates[Plugins.checksum] = plugin.get("checksum") if updates: self.__logger.warning(f'Plugin "{plugin["id"]}" already exists, updating it with the new values') session.query(Plugins).filter(Plugins.id == plugin["id"]).update(updates) else: to_put.append( Plugins( id=plugin["id"], name=plugin["name"], description=plugin["description"], version=plugin["version"], stream=plugin["stream"], external=plugin.get("external", False), method=plugin.get("method"), data=plugin.get("data"), checksum=plugin.get("checksum"), ) ) for setting, value in settings.items(): value.update( { "plugin_id": plugin["id"], "name": value["id"], "id": setting, } ) db_setting = session.query(Settings).filter_by(id=setting).first() select_values = value.pop("select", []) if db_setting: updates = {} if value["name"] != db_setting.name: updates[Settings.name] = value["name"] if value["context"] != db_setting.context: updates[Settings.context] = value["context"] if value["default"] != db_setting.default: updates[Settings.default] = value["default"] if value["help"] != db_setting.help: updates[Settings.help] = value["help"] if value["label"] != db_setting.label: updates[Settings.label] = value["label"] if value["regex"] != db_setting.regex: updates[Settings.regex] = value["regex"] if value["type"] != db_setting.type: updates[Settings.type] = value["type"] if value.get("multiple") != db_setting.multiple: updates[Settings.multiple] = value.get("multiple") if updates: self.__logger.warning(f'Setting "{setting}" already exists, updating it with the new values') session.query(Settings).filter(Settings.id == setting).update(updates) else: if db_plugin: self.__logger.warning(f'Setting "{setting}" does not exist, creating it') to_put.append(Settings(**value)) db_selects = session.query(Selects).with_entities(Selects.value).filter_by(setting_id=value["id"]).all() db_values = [select.value for select in db_selects] missing_values = [select for select in db_values if select not in select_values] if select_values: if missing_values: # Remove selects that are no longer in the list self.__logger.warning(f'Removing {len(missing_values)} selects from setting "{setting}" as they are no longer in the list') session.query(Selects).filter(Selects.value.in_(missing_values)).delete() for select in select_values: if select not in db_values: to_put.append(Selects(setting_id=value["id"], value=select)) else: if missing_values: self.__logger.warning(f'Removing all selects from setting "{setting}" as there are no longer any in the list') session.query(Selects).filter_by(setting_id=value["id"]).delete() db_jobs = session.query(Jobs).with_entities(Jobs.name).filter_by(plugin_id=plugin["id"]).all() db_names = [job.name for job in db_jobs] job_names = [job["name"] for job in jobs] missing_names = [job for job in db_names if job not in job_names] if missing_names: # Remove jobs that are no longer in the list self.__logger.warning(f'Removing {len(missing_names)} jobs from plugin "{plugin["id"]}" as they are no longer in the list') session.query(Jobs).filter(Jobs.name.in_(missing_names)).delete() for job in jobs: db_job = session.query(Jobs).with_entities(Jobs.file_name, Jobs.every, Jobs.reload).filter_by(name=job["name"], plugin_id=plugin["id"]).first() if job["name"] not in db_names or not db_job: job["file_name"] = job.pop("file") job["reload"] = job.get("reload", False) if db_plugin: self.__logger.warning(f'Job "{job["name"]}" does not exist, creating it') to_put.append(Jobs(plugin_id=plugin["id"], **job)) else: updates = {} if job["file"] != db_job.file_name: updates[Jobs.file_name] = job["file"] if job["every"] != db_job.every: updates[Jobs.every] = job["every"] if job.get("reload", None) != db_job.reload: updates[Jobs.reload] = job.get("reload", False) if updates: self.__logger.warning(f'Job "{job["name"]}" already exists, updating it with the new values') updates[Jobs.last_run] = None session.query(Jobs_cache).filter(Jobs_cache.job_name == job["name"]).delete() session.query(Jobs).filter(Jobs.name == job["name"]).update(updates) if page: core_ui_path = Path(sep, "usr", "share", "bunkerweb", "core", plugin["id"], "ui") path_ui = core_ui_path if core_ui_path.exists() else Path(sep, "etc", "bunkerweb", "plugins", plugin["id"], "ui") if path_ui.exists(): if {"template.html", "actions.py"}.issubset(listdir(str(path_ui))): db_plugin_page = ( session.query(Plugin_pages) .with_entities( Plugin_pages.template_checksum, Plugin_pages.actions_checksum, ) .filter_by(plugin_id=plugin["id"]) .first() ) template = path_ui.joinpath("template.html").read_bytes() actions = path_ui.joinpath("actions.py").read_bytes() template_checksum = sha256(template).hexdigest() actions_checksum = sha256(actions).hexdigest() if db_plugin_page: updates = {} if template_checksum != db_plugin_page.template_checksum: updates.update( { Plugin_pages.template_file: template, Plugin_pages.template_checksum: template_checksum, } ) if actions_checksum != db_plugin_page.actions_checksum: updates.update( { Plugin_pages.actions_file: actions, Plugin_pages.actions_checksum: actions_checksum, } ) if updates: self.__logger.warning(f'Page for plugin "{plugin["id"]}" already exists, updating it with the new values') session.query(Plugin_pages).filter(Plugin_pages.plugin_id == plugin["id"]).update(updates) continue if db_plugin: self.__logger.warning(f'Page for plugin "{plugin["id"]}" does not exist, creating it') to_put.append( Plugin_pages( plugin_id=plugin["id"], template_file=template, template_checksum=template_checksum, actions_file=actions, actions_checksum=actions_checksum, ) ) try: session.add_all(to_put) session.commit() except BaseException: return False, format_exc() return True, "" def save_config(self, config: Dict[str, Any], method: str, changed: Optional[bool] = True) -> str: """Save the config in the database""" to_put = [] with self.__db_session() as session: # Delete all the old config session.query(Global_values).filter(Global_values.method == method).delete() session.query(Services_settings).filter(Services_settings.method == method).delete() if config: config.pop("DATABASE_URI", None) db_services = session.query(Services).with_entities(Services.id, Services.method).all() db_ids = [service.id for service in db_services] services = config.get("SERVER_NAME", []) if isinstance(services, str): services = services.split(" ") if db_services: missing_ids = [service.id for service in db_services if (service.method == method) and service.id not in services] if missing_ids: # Remove services that are no longer in the list session.query(Services).filter(Services.id.in_(missing_ids)).delete() if config.get("MULTISITE", "no") == "yes": global_values = [] for key, value in deepcopy(config).items(): suffix = 0 original_key = deepcopy(key) if self.suffix_rx.search(key): suffix = int(key.split("_")[-1]) key = key[: -len(str(suffix)) - 1] setting = session.query(Settings).with_entities(Settings.default).filter_by(id=key).first() if not setting and services: try: server_name = next(service for service in services if key.startswith(f"{service}_")) except StopIteration: continue if server_name not in db_ids: to_put.append(Services(id=server_name, method=method)) db_ids.append(server_name) key = key.replace(f"{server_name}_", "") setting = session.query(Settings).with_entities(Settings.default).filter_by(id=key).first() if not setting: continue service_setting = ( session.query(Services_settings) .with_entities(Services_settings.value, Services_settings.method) .filter_by( service_id=server_name, setting_id=key, suffix=suffix, ) .first() ) if not service_setting: if key != "SERVER_NAME" and ((key not in config and value == setting.default) or (key in config and value == config[key])): continue to_put.append( Services_settings( service_id=server_name, setting_id=key, value=value, suffix=suffix, method=method, ) ) elif method in (service_setting.method, "autoconf") and service_setting.value != value: if key != "SERVER_NAME" and ((key not in config and value == setting.default) or (key in config and value == config[key])): session.query(Services_settings).filter( Services_settings.service_id == server_name, Services_settings.setting_id == key, Services_settings.suffix == suffix, ).delete() continue session.query(Services_settings).filter( Services_settings.service_id == server_name, Services_settings.setting_id == key, Services_settings.suffix == suffix, ).update( { Services_settings.value: value, Services_settings.method: method, } ) elif setting and original_key not in global_values: global_values.append(original_key) global_value = ( session.query(Global_values) .with_entities(Global_values.value, Global_values.method) .filter_by( setting_id=key, suffix=suffix, ) .first() ) if not global_value: if value == setting.default: continue to_put.append( Global_values( setting_id=key, value=value, suffix=suffix, method=method, ) ) elif method in (global_value.method, "autoconf") and global_value.value != value: if value == setting.default: session.query(Global_values).filter( Global_values.setting_id == key, Global_values.suffix == suffix, ).delete() continue session.query(Global_values).filter( Global_values.setting_id == key, Global_values.suffix == suffix, ).update( { Global_values.value: value, Global_values.method: method, } ) else: if config.get("SERVER_NAME", "www.example.com") and not session.query(Services).with_entities(Services.id).filter_by(id=config.get("SERVER_NAME", "www.example.com").split(" ")[0]).first(): to_put.append(Services(id=config.get("SERVER_NAME", "www.example.com").split(" ")[0], method=method)) for key, value in config.items(): suffix = 0 if self.suffix_rx.search(key): suffix = int(key.split("_")[-1]) key = key[: -len(str(suffix)) - 1] setting = session.query(Settings).with_entities(Settings.default).filter_by(id=key).first() if not setting: continue global_value = session.query(Global_values).with_entities(Global_values.value, Global_values.method).filter_by(setting_id=key, suffix=suffix).first() if not global_value: if value == setting.default: continue to_put.append( Global_values( setting_id=key, value=value, suffix=suffix, method=method, ) ) elif global_value.method == method and value != global_value.value: if value == setting.default: session.query(Global_values).filter( Global_values.setting_id == key, Global_values.suffix == suffix, ).delete() continue session.query(Global_values).filter( Global_values.setting_id == key, Global_values.suffix == suffix, ).update({Global_values.value: value}) if changed: with suppress(ProgrammingError, OperationalError): metadata = session.query(Metadata).get(1) if metadata is not None: if not metadata.first_config_saved: metadata.first_config_saved = True metadata.config_changed = True try: session.add_all(to_put) session.commit() except BaseException: return format_exc() return "" def save_custom_configs( self, custom_configs: List[Dict[str, Tuple[str, List[str]]]], method: str, changed: Optional[bool] = True, ) -> str: """Save the custom configs in the database""" message = "" with self.__db_session() as session: # Delete all the old config session.query(Custom_configs).filter(Custom_configs.method == method).delete() to_put = [] endl = "\n" for custom_config in custom_configs: config = { "data": custom_config["value"].encode("utf-8") if isinstance(custom_config["value"], str) else custom_config["value"], "method": method, } config["checksum"] = sha256(config["data"]).hexdigest() if custom_config["exploded"][0]: if not session.query(Services).with_entities(Services.id).filter_by(id=custom_config["exploded"][0]).first(): message += f"{endl if message else ''}Service {custom_config['exploded'][0]} not found, please check your config" config.update( { "service_id": custom_config["exploded"][0], "type": custom_config["exploded"][1].replace("-", "_").lower(), "name": custom_config["exploded"][2], } ) else: config.update( { "type": custom_config["exploded"][1].replace("-", "_").lower(), "name": custom_config["exploded"][2], } ) custom_conf = ( session.query(Custom_configs) .with_entities(Custom_configs.checksum, Custom_configs.method) .filter_by( service_id=config.get("service_id", None), type=config["type"], name=config["name"], ) .first() ) if not custom_conf: to_put.append(Custom_configs(**config)) elif config["checksum"] != custom_conf.checksum and method in ( custom_conf.method, "autoconf", ): session.query(Custom_configs).filter( Custom_configs.service_id == config.get("service_id", None), Custom_configs.type == config["type"], Custom_configs.name == config["name"], ).update( { Custom_configs.data: config["data"], Custom_configs.checksum: config["checksum"], } | ({Custom_configs.method: "autoconf"} if method == "autoconf" else {}) ) if changed: with suppress(ProgrammingError, OperationalError): metadata = session.query(Metadata).get(1) if metadata is not None: metadata.custom_configs_changed = True try: session.add_all(to_put) session.commit() except BaseException: return f"{f'{message}{endl}' if message else ''}{format_exc()}" return message def get_config(self, methods: bool = False) -> Dict[str, Any]: """Get the config from the database""" with self.__db_session() as session: config = {} multisite = [] for setting in ( session.query(Settings) .with_entities( Settings.id, Settings.context, Settings.default, Settings.multiple, ) .all() ): default = setting.default or "" config[setting.id] = default if not methods else {"value": default, "global": True, "method": "default"} global_values = session.query(Global_values).with_entities(Global_values.value, Global_values.suffix, Global_values.method).filter_by(setting_id=setting.id).all() for global_value in global_values: config[setting.id + (f"_{global_value.suffix}" if setting.multiple and global_value.suffix > 0 else "")] = ( global_value.value if not methods else { "value": global_value.value, "global": True, "method": global_value.method, } ) if setting.context == "multisite": multisite.append(setting.id) is_multisite = config.get("MULTISITE", {"value": "no"})["value"] == "yes" if methods else config.get("MULTISITE", "no") == "yes" if is_multisite: for service in session.query(Services).with_entities(Services.id).all(): checked_settings = [] for key, value in deepcopy(config).items(): original_key = key if self.suffix_rx.search(key): key = key[: -len(str(key.split("_")[-1])) - 1] if key not in multisite: continue elif f"{service.id}_{original_key}" not in config: config[f"{service.id}_{original_key}"] = value if original_key not in checked_settings: checked_settings.append(original_key) else: continue service_settings = ( session.query(Services_settings) .with_entities( Services_settings.value, Services_settings.suffix, Services_settings.method, ) .filter_by(service_id=service.id, setting_id=key) .all() ) for service_setting in service_settings: config[f"{service.id}_{key}" + (f"_{service_setting.suffix}" if service_setting.suffix > 0 else "")] = ( service_setting.value if not methods else { "value": service_setting.value, "global": False, "method": service_setting.method, } ) servers = " ".join(service.id for service in session.query(Services).all()) config["SERVER_NAME"] = servers if not methods else {"value": servers, "global": True, "method": "default"} return config def get_custom_configs(self) -> List[Dict[str, Any]]: """Get the custom configs from the database""" with self.__db_session() as session: return [ { "service_id": custom_config.service_id, "type": custom_config.type, "name": custom_config.name, "data": custom_config.data, "method": custom_config.method, } for custom_config in ( session.query(Custom_configs) .with_entities( Custom_configs.service_id, Custom_configs.type, Custom_configs.name, Custom_configs.data, Custom_configs.method, ) .all() ) ] def get_services_settings(self, methods: bool = False) -> List[Dict[str, Any]]: """Get the services' configs from the database""" services = [] config = self.get_config(methods=methods) with self.__db_session() as session: service_names = [service.id for service in session.query(Services).with_entities(Services.id).all()] for service in service_names: service_settings = [] tmp_config = deepcopy(config) for key, value in deepcopy(tmp_config).items(): if key.startswith(f"{service}_"): setting = key.replace(f"{service}_", "") service_settings.append(setting) tmp_config[setting] = tmp_config.pop(key) elif any(key.startswith(f"{s}_") for s in service_names): tmp_config.pop(key) elif key not in service_settings: tmp_config[key] = ( { "value": value["value"], "global": value["global"], "method": value["method"], } if methods else value ) services.append(tmp_config) return services def update_job(self, plugin_id: str, job_name: str, success: bool) -> str: """Update the job last_run in the database""" with self.__db_session() as session: job = session.query(Jobs).filter_by(plugin_id=plugin_id, name=job_name).first() if not job: return "Job not found" job.last_run = datetime.now() job.success = success try: session.commit() except BaseException: return format_exc() return "" def delete_job_cache(self, file_name: str, *, job_name: Optional[str] = None): job_name = job_name or basename(getsourcefile(_getframe(1))).replace(".py", "") with self.__db_session() as session: session.query(Jobs_cache).filter_by(job_name=job_name, file_name=file_name).delete() def update_job_cache( self, service_id: Optional[str], file_name: str, data: bytes, *, job_name: Optional[str] = None, checksum: Optional[str] = None, ) -> str: """Update the plugin cache in the database""" job_name = job_name or basename(getsourcefile(_getframe(1))).replace(".py", "") with self.__db_session() as session: cache = session.query(Jobs_cache).filter_by(job_name=job_name, service_id=service_id, file_name=file_name).first() if not cache: session.add( Jobs_cache( job_name=job_name, service_id=service_id, file_name=file_name, data=data, last_update=datetime.now(), checksum=checksum, ) ) else: cache.data = data cache.last_update = datetime.now() cache.checksum = checksum try: session.commit() except BaseException: return format_exc() return "" def update_external_plugins(self, plugins: List[Dict[str, Any]], *, delete_missing: bool = True) -> str: """Update external plugins from the database""" to_put = [] with self.__db_session() as session: db_plugins = session.query(Plugins).with_entities(Plugins.id).filter_by(external=True).all() db_ids = [] if delete_missing and db_plugins: db_ids = [plugin.id for plugin in db_plugins] ids = [plugin["id"] for plugin in plugins] missing_ids = [plugin for plugin in db_ids if plugin not in ids] if missing_ids: # Remove plugins that are no longer in the list session.query(Plugins).filter(Plugins.id.in_(missing_ids)).delete() for plugin in plugins: settings = plugin.pop("settings", {}) jobs = plugin.pop("jobs", []) page = plugin.pop("page", False) plugin["external"] = True db_plugin = ( session.query(Plugins) .with_entities( Plugins.name, Plugins.stream, Plugins.description, Plugins.version, Plugins.method, Plugins.data, Plugins.checksum, Plugins.external, ) .filter_by(id=plugin["id"]) .first() ) if db_plugin is not None: if db_plugin.external is False: self.__logger.warning( f"Plugin \"{plugin['id']}\" is not external, skipping update (updating a non-external plugin is forbidden for security reasons)", ) continue updates = {} if plugin["stream"] != db_plugin.stream: updates[Plugins.stream] = plugin["stream"] if plugin["name"] != db_plugin.name: updates[Plugins.name] = plugin["name"] if plugin["description"] != db_plugin.description: updates[Plugins.description] = plugin["description"] if plugin["version"] != db_plugin.version: updates[Plugins.version] = plugin["version"] if plugin["method"] != db_plugin.method: updates[Plugins.method] = plugin["method"] if plugin.get("data") != db_plugin.data: updates[Plugins.data] = plugin.get("data") if plugin.get("checksum") != db_plugin.checksum: updates[Plugins.checksum] = plugin.get("checksum") if updates: session.query(Plugins).filter(Plugins.id == plugin["id"]).update(updates) db_plugin_settings = session.query(Settings).with_entities(Settings.id).filter_by(plugin_id=plugin["id"]).all() db_ids = [setting.id for setting in db_plugin_settings] setting_ids = [setting for setting in settings] missing_ids = [setting for setting in db_ids if setting not in setting_ids] if missing_ids: # Remove settings that are no longer in the list session.query(Settings).filter(Settings.id.in_(missing_ids)).delete() for setting, value in settings.items(): value.update( { "plugin_id": plugin["id"], "name": value["id"], "id": setting, } ) db_setting = ( session.query(Settings) .with_entities( Settings.name, Settings.context, Settings.default, Settings.help, Settings.label, Settings.regex, Settings.type, Settings.multiple, ) .filter_by(id=setting) .first() ) if setting not in db_ids or not db_setting: for select in value.pop("select", []): to_put.append(Selects(setting_id=value["id"], value=select)) to_put.append( Settings( **value, ) ) else: updates = {} if value["name"] != db_setting.name: updates[Settings.name] = value["name"] if value["context"] != db_setting.context: updates[Settings.context] = value["context"] if value["default"] != db_setting.default: updates[Settings.default] = value["default"] if value["help"] != db_setting.help: updates[Settings.help] = value["help"] if value["label"] != db_setting.label: updates[Settings.label] = value["label"] if value["regex"] != db_setting.regex: updates[Settings.regex] = value["regex"] if value["type"] != db_setting.type: updates[Settings.type] = value["type"] if value.get("multiple") != db_setting.multiple: updates[Settings.multiple] = value.get("multiple") if updates: session.query(Settings).filter(Settings.id == setting).update(updates) db_selects = session.query(Selects).with_entities(Selects.value).filter_by(setting_id=setting).all() db_values = [select.value for select in db_selects] select_values = value.get("select", []) missing_values = [select for select in db_values if select not in select_values] if missing_values: # Remove selects that are no longer in the list session.query(Selects).filter(Selects.value.in_(missing_values)).delete() for select in value.get("select", []): if select not in db_values: to_put.append(Selects(setting_id=setting, value=select)) db_jobs = session.query(Jobs).with_entities(Jobs.name).filter_by(plugin_id=plugin["id"]).all() db_names = [job.name for job in db_jobs] job_names = [job["name"] for job in jobs] missing_names = [job for job in db_names if job not in job_names] if missing_names: # Remove jobs that are no longer in the list session.query(Jobs).filter(Jobs.name.in_(missing_names)).delete() for job in jobs: db_job = session.query(Jobs).with_entities(Jobs.file_name, Jobs.every, Jobs.reload).filter_by(name=job["name"], plugin_id=plugin["id"]).first() if job["name"] not in db_names or not db_job: job["file_name"] = job.pop("file") job["reload"] = job.get("reload", False) to_put.append( Jobs( plugin_id=plugin["id"], **job, ) ) else: updates = {} if job["file"] != db_job.file_name: updates[Jobs.file_name] = job["file"] if job["every"] != db_job.every: updates[Jobs.every] = job["every"] if job.get("reload", None) != db_job.reload: updates[Jobs.reload] = job.get("reload", False) if updates: updates[Jobs.last_run] = None session.query(Jobs_cache).filter(Jobs_cache.job_name == job["name"]).delete() session.query(Jobs).filter(Jobs.name == job["name"]).update(updates) tmp_ui_path = Path(sep, "var", "tmp", "bunkerweb", "ui", plugin["id"], "ui") path_ui = tmp_ui_path if tmp_ui_path.exists() else Path(sep, "etc", "bunkerweb", "plugins", plugin["id"], "ui") if path_ui.exists(): if {"template.html", "actions.py"}.issubset(listdir(str(path_ui))): db_plugin_page = ( session.query(Plugin_pages) .with_entities( Plugin_pages.template_checksum, Plugin_pages.actions_checksum, ) .filter_by(plugin_id=plugin["id"]) .first() ) if not db_plugin_page: template = path_ui.joinpath("template.html").read_bytes() actions = path_ui.joinpath("actions.py").read_bytes() to_put.append( Plugin_pages( plugin_id=plugin["id"], template_file=template, template_checksum=sha256(template).hexdigest(), actions_file=actions, actions_checksum=sha256(actions).hexdigest(), ) ) else: updates = {} template_path = path_ui.joinpath("template.html") actions_path = path_ui.joinpath("actions.py") template_checksum = file_hash(str(template_path)) actions_checksum = file_hash(str(actions_path)) if template_checksum != db_plugin_page.template_checksum: updates.update( { Plugin_pages.template_file: template_path.read_bytes(), Plugin_pages.template_checksum: template_checksum, } ) if actions_checksum != db_plugin_page.actions_checksum: updates.update( { Plugin_pages.actions_file: actions_path.read_bytes(), Plugin_pages.actions_checksum: actions_checksum, } ) if updates: session.query(Plugin_pages).filter(Plugin_pages.plugin_id == plugin["id"]).update(updates) continue to_put.append( Plugins( id=plugin["id"], name=plugin["name"], description=plugin["description"], version=plugin["version"], stream=plugin["stream"], external=True, method=plugin["method"], data=plugin.get("data"), checksum=plugin.get("checksum"), ) ) for setting, value in settings.items(): db_setting = session.query(Settings).filter_by(id=setting).first() if db_setting is not None: self.__logger.warning(f"A setting with id {setting} already exists, therefore it will not be added.") continue value.update( { "plugin_id": plugin["id"], "name": value["id"], "id": setting, } ) for select in value.pop("select", []): to_put.append(Selects(setting_id=value["id"], value=select)) to_put.append( Settings( **value, ) ) for job in jobs: db_job = session.query(Jobs).with_entities(Jobs.file_name, Jobs.every, Jobs.reload).filter_by(name=job["name"], plugin_id=plugin["id"]).first() if db_job is not None: self.__logger.warning(f"A job with the name {job['name']} already exists in the database, therefore it will not be added.") continue job["file_name"] = job.pop("file") job["reload"] = job.get("reload", False) to_put.append(Jobs(plugin_id=plugin["id"], **job)) if page: tmp_ui_path = Path(sep, "var", "tmp", "bunkerweb", "ui", plugin["id"], "ui") path_ui = tmp_ui_path if tmp_ui_path.exists() else Path(sep, "etc", "bunkerweb", "plugins", plugin["id"], "ui") if path_ui.exists(): if {"template.html", "actions.py"}.issubset(listdir(str(path_ui))): db_plugin_page = ( session.query(Plugin_pages) .with_entities( Plugin_pages.template_checksum, Plugin_pages.actions_checksum, ) .filter_by(plugin_id=plugin["id"]) .first() ) if not db_plugin_page: template = path_ui.joinpath("template.html").read_bytes() actions = path_ui.joinpath("actions.py").read_bytes() to_put.append( Plugin_pages( plugin_id=plugin["id"], template_file=template, template_checksum=sha256(template).hexdigest(), actions_file=actions, actions_checksum=sha256(actions).hexdigest(), ) ) else: updates = {} template_path = path_ui.joinpath("template.html") actions_path = path_ui.joinpath("actions.py") template_checksum = file_hash(str(template_path)) actions_checksum = file_hash(str(actions_path)) if template_checksum != db_plugin_page.template_checksum: updates.update( { Plugin_pages.template_file: template_path.read_bytes(), Plugin_pages.template_checksum: template_checksum, } ) if actions_checksum != db_plugin_page.actions_checksum: updates.update( { Plugin_pages.actions_file: actions_path.read_bytes(), Plugin_pages.actions_checksum: actions_checksum, } ) if updates: session.query(Plugin_pages).filter(Plugin_pages.plugin_id == plugin["id"]).update(updates) with suppress(ProgrammingError, OperationalError): metadata = session.query(Metadata).get(1) if metadata is not None: metadata.external_plugins_changed = True try: session.add_all(to_put) session.commit() except BaseException: return format_exc() return "" def get_plugins(self, *, external: bool = False, with_data: bool = False) -> List[Dict[str, Any]]: """Get all plugins from the database.""" plugins = [] with self.__db_session() as session: for plugin in ( session.query(Plugins) .with_entities( Plugins.id, Plugins.stream, Plugins.name, Plugins.description, Plugins.version, Plugins.external, Plugins.method, Plugins.data, Plugins.checksum, ) .all() if with_data else session.query(Plugins) .with_entities( Plugins.id, Plugins.stream, Plugins.name, Plugins.description, Plugins.version, Plugins.external, Plugins.method, ) .all() ): if external and not plugin.external: continue page = session.query(Plugin_pages).with_entities(Plugin_pages.id).filter_by(plugin_id=plugin.id).first() data = { "id": plugin.id, "stream": plugin.stream, "name": plugin.name, "description": plugin.description, "version": plugin.version, "external": plugin.external, "method": plugin.method, "page": page is not None, "settings": {}, } | ({"data": plugin.data, "checksum": plugin.checksum} if with_data else {}) for setting in ( session.query(Settings) .with_entities( Settings.id, Settings.context, Settings.default, Settings.help, Settings.name, Settings.label, Settings.regex, Settings.type, Settings.multiple, ) .filter_by(plugin_id=plugin.id) .all() ): data["settings"][setting.id] = { "context": setting.context, "default": setting.default, "help": setting.help, "id": setting.name, "label": setting.label, "regex": setting.regex, "type": setting.type, } | ({"multiple": setting.multiple} if setting.multiple else {}) if setting.type == "select": data["settings"][setting.id]["select"] = [select.value for select in session.query(Selects).with_entities(Selects.value).filter_by(setting_id=setting.id).all()] plugins.append(data) return plugins def get_plugins_errors(self) -> int: """Get plugins errors.""" with self.__db_session() as session: return session.query(Jobs).filter(Jobs.success == False).count() # noqa: E712 def get_jobs(self) -> Dict[str, Dict[str, Any]]: """Get jobs.""" with self.__db_session() as session: return { job.name: { "every": job.every, "reload": job.reload, "success": job.success, "last_run": job.last_run.strftime("%Y/%m/%d, %I:%M:%S %p") if job.last_run is not None else "Never", "cache": [ { "service_id": cache.service_id, "file_name": cache.file_name, "last_update": cache.last_update.strftime("%Y/%m/%d, %I:%M:%S %p") if cache.last_update is not None else "Never", } for cache in session.query(Jobs_cache) .with_entities( Jobs_cache.service_id, Jobs_cache.file_name, Jobs_cache.last_update, ) .filter_by(job_name=job.name) .all() ], } for job in ( session.query(Jobs) .with_entities( Jobs.name, Jobs.every, Jobs.reload, Jobs.success, Jobs.last_run, ) .all() ) } def get_job_cache_file( self, job_name: str, file_name: str, *, with_info: bool = False, with_data: bool = True, ) -> Optional[Any]: """Get job cache file.""" entities = [] if with_info: entities.extend([Jobs_cache.last_update, Jobs_cache.checksum]) if with_data: entities.append(Jobs_cache.data) with self.__db_session() as session: return session.query(Jobs_cache).with_entities(*entities).filter_by(job_name=job_name, file_name=file_name).first() def get_jobs_cache_files(self) -> List[Dict[str, Any]]: """Get jobs cache files.""" with self.__db_session() as session: return [ { "job_name": cache.job_name, "service_id": cache.service_id, "file_name": cache.file_name, "data": "Download file to view content", } for cache in ( session.query(Jobs_cache) .with_entities( Jobs_cache.job_name, Jobs_cache.service_id, Jobs_cache.file_name, ) .all() ) ] def add_instance(self, hostname: str, port: int, server_name: str, changed: Optional[bool] = True) -> str: """Add instance.""" with self.__db_session() as session: db_instance = session.query(Instances).with_entities(Instances.hostname).filter_by(hostname=hostname).first() if db_instance is not None: return f"Instance {hostname} already exists, will not be added." session.add(Instances(hostname=hostname, port=port, server_name=server_name)) if changed: with suppress(ProgrammingError, OperationalError): metadata = session.query(Metadata).get(1) if metadata is not None: metadata.instances_changed = True try: session.commit() except BaseException: return f"An error occurred while adding the instance {hostname} (port: {port}, server name: {server_name}).\n{format_exc()}" return "" def update_instances(self, instances: List[Dict[str, Any]], changed: Optional[bool] = True) -> str: """Update instances.""" to_put = [] with self.__db_session() as session: session.query(Instances).delete() for instance in instances: to_put.append( Instances( hostname=instance["hostname"], port=instance["env"].get("API_HTTP_PORT", 5000), server_name=instance["env"].get("API_SERVER_NAME", "bwapi"), ) ) if changed: with suppress(ProgrammingError, OperationalError): metadata = session.query(Metadata).get(1) if metadata is not None: metadata.instances_changed = True try: session.add_all(to_put) session.commit() except BaseException: return format_exc() return "" def get_instances(self) -> List[Dict[str, Any]]: """Get instances.""" with self.__db_session() as session: return [ { "hostname": instance.hostname, "port": instance.port, "server_name": instance.server_name, } for instance in (session.query(Instances).with_entities(Instances.hostname, Instances.port, Instances.server_name).all()) ] def get_plugin_actions(self, plugin: str) -> Optional[Any]: """get actions file for the plugin""" with self.__db_session() as session: page = session.query(Plugin_pages).with_entities(Plugin_pages.actions_file).filter_by(plugin_id=plugin).first() if not page: return None return page.actions_file def get_plugin_template(self, plugin: str) -> Optional[Any]: """get template file for the plugin""" with self.__db_session() as session: page = session.query(Plugin_pages).with_entities(Plugin_pages.template_file).filter_by(plugin_id=plugin).first() if not page: return None return page.template_file def get_ui_user(self) -> Optional[dict]: """Get ui user.""" with self.__db_session() as session: user = session.query(Users).with_entities(Users.username, Users.password, Users.is_two_factor_enabled, Users.secret_token, Users.method).filter_by(id=1).first() if not user: return None return { "username": user.username, "password_hash": user.password.encode("utf-8"), "is_two_factor_enabled": user.is_two_factor_enabled, "secret_token": user.secret_token, "method": user.method, } def create_ui_user(self, username: str, password: bytes, *, secret_token: Optional[str] = None, method: str = "manual") -> str: """Create ui user.""" with self.__db_session() as session: if self.get_ui_user(): return "User already exists" session.add(Users(id=1, username=username, password=password.decode("utf-8"), secret_token=secret_token, method=method)) try: session.commit() except BaseException: return format_exc() return "" def update_ui_user(self, username: str, password: bytes, is_two_factor_enabled: bool = False, secret_token: Optional[str] = None, method: str = "ui") -> str: """Update ui user.""" with self.__db_session() as session: user = session.query(Users).filter_by(id=1).first() if not user: return "User not found" user.username = username user.password = password.decode("utf-8") user.is_two_factor_enabled = is_two_factor_enabled user.secret_token = secret_token user.method = method try: session.commit() except BaseException: return format_exc() return "" class API: def __init__(self, endpoint: str, host: str = "bwapi"): self.__endpoint = endpoint if not self.__endpoint.endswith("/"): self.__endpoint += "/" self.__host = host def endpoint(self) -> str: return self.__endpoint def host(self) -> str: return self.__host def request( self, method: Union[Literal["POST"], Literal["GET"]], url: str, data: Optional[Union[dict, bytes]] = None, files=None, timeout=(10, 30), ) -> tuple[bool, str, Optional[int], Optional[dict]]: try: kwargs = {} if isinstance(data, dict): kwargs["json"] = data elif isinstance(data, bytes): kwargs["data"] = data elif data is not None: return False, f"Unsupported data type: {type(data)}", None, None if files: kwargs["files"] = files resp = request( method, f"{self.__endpoint}{url if not url.startswith('/') else url[1:]}", timeout=timeout, headers={"User-Agent": "bwapi", "Host": self.__host}, **kwargs, ) except Exception as e: return False, f"Request failed: {e}", None, None return True, "ok", resp.status_code, resp.json() def get_instance_configs_and_apis(instance: Any, db, _type="Docker"): api_http_port = None api_server_name = None tmp_config = {} custom_confs = [] apis = [] for var in instance.attrs["Config"]["Env"] if _type == "Docker" else instance.attrs["Spec"]["TaskTemplate"]["ContainerSpec"]["Env"]: split = var.split("=", 1) if custom_confs_rx.match(split[0]): custom_conf = custom_confs_rx.search(split[0]).groups() custom_confs.append( { "value": f"# CREATED BY ENV\n{split[1]}", "exploded": ( custom_conf[0], custom_conf[1], custom_conf[2].replace(".conf", ""), ), } ) logger.info(f"Found custom conf env var {'for service ' + custom_conf[0] if custom_conf[0] else 'without service'} with type {custom_conf[1]} and name {custom_conf[2]}") else: tmp_config[split[0]] = split[1] if not db and split[0] == "DATABASE_URI": db = Database(logger, sqlalchemy_string=split[1], pool=False) elif split[0] == "API_HTTP_PORT": api_http_port = split[1] elif split[0] == "API_SERVER_NAME": api_server_name = split[1] apis.append( API( f"http://{instance.name}:{api_http_port or getenv('API_HTTP_PORT', '5000')}", host=api_server_name or getenv("API_SERVER_NAME", "bwapi"), ) ) return tmp_config, custom_confs, apis, db
null
18,291
from contextlib import suppress from datetime import datetime from hashlib import sha512 from inspect import getsourcefile from io import BufferedReader from json import dumps, loads from os.path import basename, normpath from pathlib import Path from sys import _getframe from threading import Lock from traceback import format_exc from typing import Literal, Optional, Tuple, Union def is_cached_file( file: Union[str, Path], expire: Union[Literal["hour"], Literal["day"], Literal["week"], Literal["month"]], db=None, ) -> bool: is_cached = False cached_file = None try: file = normpath(file) file_path = Path(f"{file}.md") if not file_path.is_file(): if not db: return False cached_file = db.get_job_cache_file( basename(getsourcefile(_getframe(1))).replace(".py", ""), basename(file), with_info=True, ) if not cached_file: return False cached_time = cached_file.last_update.timestamp() else: cached_time = loads(file_path.read_text())["date"] current_time = datetime.now().timestamp() if current_time < cached_time: is_cached = False else: diff_time = current_time - cached_time if expire == "hour": is_cached = diff_time < 3600 elif expire == "day": is_cached = diff_time < 86400 elif expire == "week": is_cached = diff_time < 604800 elif expire == "month": is_cached = diff_time < 2592000 except: is_cached = False if is_cached and cached_file: Path(file).write_bytes(cached_file.data) return is_cached and cached_file
null
18,292
from contextlib import suppress from datetime import datetime from hashlib import sha512 from inspect import getsourcefile from io import BufferedReader from json import dumps, loads from os.path import basename, normpath from pathlib import Path from sys import _getframe from threading import Lock from traceback import format_exc from typing import Literal, Optional, Tuple, Union def get_file_in_db(file: Union[str, Path], db, *, job_name: Optional[str] = None) -> Optional[bytes]: cached_file = db.get_job_cache_file( job_name or basename(getsourcefile(_getframe(1))).replace(".py", ""), normpath(file), ) if not cached_file: return None return cached_file.data
null
18,293
from contextlib import suppress from datetime import datetime from hashlib import sha512 from inspect import getsourcefile from io import BufferedReader from json import dumps, loads from os.path import basename, normpath from pathlib import Path from sys import _getframe from threading import Lock from traceback import format_exc from typing import Literal, Optional, Tuple, Union def del_file_in_db(name: str, db) -> Tuple[bool, str]: ret, err = True, "success" try: db.delete_job_cache(name, job_name=basename(getsourcefile(_getframe(1))).replace(".py", "")) except: return False, f"exception :\n{format_exc()}" return ret, err
null
18,294
from contextlib import suppress from datetime import datetime from hashlib import sha512 from inspect import getsourcefile from io import BufferedReader from json import dumps, loads from os.path import basename, normpath from pathlib import Path from sys import _getframe from threading import Lock from traceback import format_exc from typing import Literal, Optional, Tuple, Union def bytes_hash(bio: BufferedReader) -> str: _sha512 = sha512() while True: data = bio.read(1024) if not data: break _sha512.update(data) bio.seek(0) return _sha512.hexdigest()
null
18,295
from logging import ( CRITICAL, DEBUG, ERROR, INFO, WARNING, Logger, _nameToLevel, addLevelName, basicConfig, getLogger, setLoggerClass, ) from os import getenv from typing import Optional, Union default_level = _nameToLevel.get(getenv("LOG_LEVEL", "INFO").upper(), INFO) getLogger("sqlalchemy.orm.mapper.Mapper").setLevel(default_level if default_level != INFO else WARNING) getLogger("sqlalchemy.orm.relationships.RelationshipProperty").setLevel(default_level if default_level != INFO else WARNING) getLogger("sqlalchemy.orm.strategies.LazyLoader").setLevel(default_level if default_level != INFO else WARNING) getLogger("sqlalchemy.pool.impl.QueuePool").setLevel(default_level if default_level != INFO else WARNING) getLogger("sqlalchemy.pool.impl.SingletonThreadPool").setLevel(default_level if default_level != INFO else WARNING) getLogger("sqlalchemy.engine.Engine").setLevel(default_level if default_level != INFO else WARNING) The provided code snippet includes necessary dependencies for implementing the `setup_logger` function. Write a Python function `def setup_logger(title: str, level: Optional[Union[str, int]] = None) -> Logger` to solve the following problem: Set up local logger Here is the function: def setup_logger(title: str, level: Optional[Union[str, int]] = None) -> Logger: """Set up local logger""" title = title.upper() logger = getLogger(title) level = level or default_level if isinstance(level, str): logger.setLevel(_nameToLevel.get(level.upper(), default_level)) else: logger.setLevel(level) return logger
Set up local logger
18,296
import logging import os import types from functools import reduce import numpy as np logger = logging.getLogger(__name__) def environ(backend): os.environ["SOFA_BACKEND"] = backend from .models import sbert, veco, SbertConfig, SbertTokenizer, SbertTokenizerFast, SbertModel, SbertForSequenceClassification from .models import SbertForTokenClassification, SbertForQuestionAnswering, SbertForMultipleChoice, SbertForPreTraining from .models import SbertForMaskedLM, SbertForNextSentencePrediction, VecoConfig, VecoTokenizer from .models import VecoTokenizerFast, VecoModel, VecoForSequenceClassification, \ VecoForMultipleChoice, VecoForTokenClassification, VecoForQuestionAnswering from .models import palm, PalmConfig, PalmTokenizer, PalmTokenizerFast, PalmModel, PalmForConditionalGeneration from .utils import inject_model_backend inject_model_backend("sbert", "structbert", SbertConfig, SbertTokenizer, SbertTokenizerFast, backbone=SbertModel, sequence_classification=SbertForSequenceClassification, token_classification=SbertForTokenClassification, question_answering=SbertForQuestionAnswering, multiple_choice=SbertForMultipleChoice, pre_train=SbertForPreTraining, mlm=SbertForMaskedLM, nsp=SbertForNextSentencePrediction, module=sbert) inject_model_backend("veco", "veco", VecoConfig, VecoTokenizer, VecoTokenizerFast, backbone=VecoModel, sequence_classification=VecoForSequenceClassification, token_classification=VecoForTokenClassification, question_answering=VecoForQuestionAnswering, multiple_choice=VecoForMultipleChoice, slow_to_fast_converter="XLMRobertaTokenizer", module=veco) inject_model_backend("palm", "palm", PalmConfig, PalmTokenizer, PalmTokenizerFast, backbone=PalmModel, s2slm=PalmForConditionalGeneration, module=palm) The provided code snippet includes necessary dependencies for implementing the `run_classification_hf` function. Write a Python function `def run_classification_hf(pretrain_model_path, output_dir, task_type, first_sequence, label, train_file_path=None, dataset_name="text", train_dataset_config=None, eval_dataset_config=None, second_sequence=None, dev_file_path=None, child_tuning_type=None, reserve_p=0.2, label_enumerate_values=None, sequence_length=128, map_function=None, filter_function=None, load_best_model_at_end=True, save_strategy="steps", save_total_limit=1, evaluation_strategy="steps", seed=42, config_args=None, **kwargs, )` to solve the following problem: Run a classsification task with transformers code. Support regression/single_label/multi_label tasks :param config_args: :param pretrain_model_path: The local dir of pretrained model :param train_file_path: The local dir or path of train files :param task_type: The task type, support: - regression: a regression task(MSE loss). - single_label_classification: one label for one or two sentenses(CELoss). - multi_label_classification: multiple labels for one or two sentenses(BCELoss). :param first_sequence: Way to get the first sentense, can be "str" or "FunctionType" - str: Will be used in datasets.map(), and used like: examples[first_sequence], this is useful in json files. - FunctionType: Will be used in datasets.map(), and used like:first_sequence(examples) Examples: ``` python >>> # way to parse the first sentense out from a tsv-like file >>> first_sequence = lambda examples: examples["text"].split("\t")[0] >>> # or >>> first_sequence = "text" ``` :param label: Way to get the label, can be "str" or "FunctionType" - str: Will be used in datasets.map(), and used like: examples[label], this is useful in json files. available in "regression" or "single_label_classification" - FunctionType: Will be used in datasets.map(), and used like:label(examples) available in "regression" or "single_label_classification" or "multi_label_classification" If is a regression task, please make sure the return label is a float or a float-like string. If is a single_label task, please make sure the return label is a string. If is a multi_label task, please make sure the return label is a string or a list. Examples ``` python >>> # Way to parse the multiple labels out from a tsv-like file(Pretend that >>> # labels in one column and seperated by a comma) >>> label = lambda examples: examples["text"].split("\t")[1].split(",") >>> # or >>> first_sequence = "text" ``` :param dataset_name: The dataset name passed into datasets.load_dataset. Default will be "text" :param second_sequence: Way to get the second sentense, can be "str" or "FunctionType", please follow the rules of "first_sequence" :param dev_file_path: The local dir of dev file, which is used in cross-validation in training. :param child_tuning_type: The child_tuning type. Can be "ChildTuning-F", "ChildTuning-D" or None :param reserve_p: the drop-out rate of child_tuning, default 0.2 :param label_enumerate_values: Pass in a list as the labels. Else the train file will be parsed to get the labels :param sequence_length: The max sequence length for padding. :param map_function: An optional map function, will be used with datasets.map() :param filter_function: An optional filter function, will be used with datasets.filter() :param load_best_model_at_end: TrainingArguments. :param save_strategy: TrainingArguments. :param save_total_limit: TrainingArguments. :param evaluation_strategy: TrainingArguments. :param seed: Random seed, default 42. :param kwargs: Other optional hyper-parameters which is used in TrainingArguments. :return: None Here is the function: def run_classification_hf(pretrain_model_path, output_dir, task_type, first_sequence, label, train_file_path=None, dataset_name="text", train_dataset_config=None, eval_dataset_config=None, second_sequence=None, dev_file_path=None, child_tuning_type=None, reserve_p=0.2, label_enumerate_values=None, sequence_length=128, map_function=None, filter_function=None, load_best_model_at_end=True, save_strategy="steps", save_total_limit=1, evaluation_strategy="steps", seed=42, config_args=None, **kwargs, ): """ Run a classsification task with transformers code. Support regression/single_label/multi_label tasks :param config_args: :param pretrain_model_path: The local dir of pretrained model :param train_file_path: The local dir or path of train files :param task_type: The task type, support: - regression: a regression task(MSE loss). - single_label_classification: one label for one or two sentenses(CELoss). - multi_label_classification: multiple labels for one or two sentenses(BCELoss). :param first_sequence: Way to get the first sentense, can be "str" or "FunctionType" - str: Will be used in datasets.map(), and used like: examples[first_sequence], this is useful in json files. - FunctionType: Will be used in datasets.map(), and used like:first_sequence(examples) Examples: ``` python >>> # way to parse the first sentense out from a tsv-like file >>> first_sequence = lambda examples: examples["text"].split("\t")[0] >>> # or >>> first_sequence = "text" ``` :param label: Way to get the label, can be "str" or "FunctionType" - str: Will be used in datasets.map(), and used like: examples[label], this is useful in json files. available in "regression" or "single_label_classification" - FunctionType: Will be used in datasets.map(), and used like:label(examples) available in "regression" or "single_label_classification" or "multi_label_classification" If is a regression task, please make sure the return label is a float or a float-like string. If is a single_label task, please make sure the return label is a string. If is a multi_label task, please make sure the return label is a string or a list. Examples ``` python >>> # Way to parse the multiple labels out from a tsv-like file(Pretend that >>> # labels in one column and seperated by a comma) >>> label = lambda examples: examples["text"].split("\t")[1].split(",") >>> # or >>> first_sequence = "text" ``` :param dataset_name: The dataset name passed into datasets.load_dataset. Default will be "text" :param second_sequence: Way to get the second sentense, can be "str" or "FunctionType", please follow the rules of "first_sequence" :param dev_file_path: The local dir of dev file, which is used in cross-validation in training. :param child_tuning_type: The child_tuning type. Can be "ChildTuning-F", "ChildTuning-D" or None :param reserve_p: the drop-out rate of child_tuning, default 0.2 :param label_enumerate_values: Pass in a list as the labels. Else the train file will be parsed to get the labels :param sequence_length: The max sequence length for padding. :param map_function: An optional map function, will be used with datasets.map() :param filter_function: An optional filter function, will be used with datasets.filter() :param load_best_model_at_end: TrainingArguments. :param save_strategy: TrainingArguments. :param save_total_limit: TrainingArguments. :param evaluation_strategy: TrainingArguments. :param seed: Random seed, default 42. :param kwargs: Other optional hyper-parameters which is used in TrainingArguments. :return: None """ # sofa custom code if config_args is None: config_args = {} from ... import environ environ("huggingface") # end from transformers import TrainingArguments from transformers import Trainer, set_seed from datasets import load_dataset, interleave_datasets from transformers import AutoTokenizer, AutoModelForSequenceClassification # sofa child_tuning from ...utils import apply_child_tuning_to_trainer import torch cache_dir = ".cache" if "cache_dir" in kwargs: cache_dir = kwargs["cache_dir"] set_seed(seed) assert type(label) in (str, types.FunctionType) logger.info(f"Cuda available:{torch.cuda.is_available()}") # prepare data train_datasets = None dev_datasets = None def get_files(files_or_path): if type(files_or_path) is str: if os.path.isfile(files_or_path): return files_or_path if os.path.isdir(files_or_path): return [os.path.join(files_or_path, f) for f in os.listdir(files_or_path)] if type(files_or_path) is list: return files_or_path if dataset_name != 'text' and train_dataset_config is not None: data_sets = [] for data_config in train_dataset_config.split(','): data_sets.append(load_dataset(dataset_name, data_config, split="train", cache_dir=cache_dir)) train_datasets = interleave_datasets(data_sets) elif train_file_path is not None: train_files = get_files(train_file_path) data_files = {"train": train_files} train_datasets = load_dataset(dataset_name, split="train", data_files=data_files) if train_datasets is None: logger.error(f"dataset_name and train_file_path cannot both be None") if dataset_name != 'text' and eval_dataset_config is not None: data_sets = [] for data_config in eval_dataset_config.split(','): split_text = "validation" if eval_dataset_config != "mnli" else "validation_matched" data_sets.append(load_dataset(dataset_name, data_config, split=split_text, cache_dir=cache_dir)) dev_datasets = interleave_datasets(data_sets) elif dev_file_path is not None: dev_files = get_files(dev_file_path) data_files = {"dev": dev_files} dev_datasets = load_dataset(dataset_name, split="dev", data_files=data_files) if filter_function is not None: train_datasets = train_datasets.filter(filter_function) if dev_datasets: dev_datasets = dev_datasets.filter(filter_function) if map_function is not None: train_datasets = train_datasets.map(map_function) if dev_datasets: dev_datasets = dev_datasets.map(map_function) if task_type == "single_label_classification": def map_labels(examples): if isinstance(label, str): examples["label_map"] = examples[label] else: examples["label_map"] = label(examples) return examples train_datasets = train_datasets.map(map_labels) if dev_datasets: dev_datasets = dev_datasets.map(map_labels) if label_enumerate_values is None: label_enumerate_values = list(set(train_datasets["label_map"])) label_enumerate_values.sort() id2label = {} label2id = {} for i in range(len(label_enumerate_values)): id2label[i] = label_enumerate_values[i] label2id[label_enumerate_values[i]] = i model_args = { "id2label": id2label, "label2id": label2id, } def map_labels(examples): examples["label"] = label2id[examples["label_map"]] return examples train_datasets = train_datasets.map(map_labels) if dev_datasets: dev_datasets = dev_datasets.map(map_labels) elif task_type == "multi_label_classification": assert isinstance(label, types.FunctionType) def map_labels(examples): examples["label_map"] = label(examples) return examples train_datasets = train_datasets.map(map_labels) if dev_datasets: dev_datasets = dev_datasets.map(map_labels) if label_enumerate_values is None: label_enumerate_values = list(set(reduce(lambda x, y: (x if isinstance(x, list) else [x]) + (y if isinstance(y, list) else [y]), train_datasets["label_map"]))) label_enumerate_values.sort() id2label = {} label2id = {} for i in range(len(label_enumerate_values)): id2label[i] = label_enumerate_values[i] label2id[label_enumerate_values[i]] = i def label_to_one_hot(examples): label_list = examples["label_map"] if not isinstance(label_list, list): label_list = [label_list] labels = [0.0] * len(label_enumerate_values) for idx in label_list: labels[label2id[idx]] = 1.0 examples["label"] = labels return examples train_datasets = train_datasets.map(label_to_one_hot) if dev_datasets: dev_datasets = dev_datasets.map(label_to_one_hot) model_args = { "id2label": id2label, "label2id": label2id, } elif task_type == "regression": def map_labels(examples): if isinstance(label, str): examples["label"] = float(examples[label]) else: examples["label"] = float(label(examples)) return examples train_datasets = train_datasets.map(map_labels) if dev_datasets: dev_datasets = dev_datasets.map(map_labels) model_args = { "num_labels": 1 } else: raise RuntimeError(f"Unsupported task type:{task_type}") # Get sbert or veco models/tokenizers tokenizer = AutoTokenizer.from_pretrained(pretrain_model_path, model_max_length=sequence_length) model = AutoModelForSequenceClassification.from_pretrained(pretrain_model_path, **model_args, **config_args) kwargs_for_training = {} for p in TrainingArguments.__dataclass_fields__.keys(): if p in kwargs: kwargs_for_training[p] = kwargs[p] training_args = TrainingArguments(output_dir=output_dir, load_best_model_at_end=load_best_model_at_end, save_strategy=save_strategy, save_total_limit=save_total_limit, evaluation_strategy=evaluation_strategy, **kwargs_for_training, ) def tokenize_function(examples): assert isinstance(first_sequence, str) or isinstance(first_sequence, types.FunctionType) text = examples[first_sequence] if isinstance(first_sequence, str) else first_sequence(examples) pair = None if second_sequence is None else examples[second_sequence] \ if isinstance(second_sequence, str) else second_sequence(examples) return tokenizer(text, pair, padding="max_length", truncation=True) full_train_dataset = train_datasets.map(tokenize_function) if dev_datasets: full_eval_dataset = dev_datasets.map(tokenize_function) else: full_eval_dataset = None def compute_metrics(p): preds = p.predictions[0] if isinstance(p.predictions, tuple) else p.predictions if task_type == "regression": preds = np.squeeze(preds) return {"mse": ((preds - p.label_ids) ** 2).mean().item()} elif task_type == "single_label_classification": preds = np.argmax(preds, axis=1) return {"accuracy": (preds == p.label_ids).astype(np.float32).mean().item()} else: from sklearn.metrics import f1_score, precision_score, recall_score def sigmoid(x): return 1 / (1 + np.exp(-x)) probs = sigmoid(preds) predictions = (probs > 0.5).astype(int) n_class = predictions.shape[1] y_trues = np.array(p.label_ids) prec_ma = np.sum(np.all(y_trues == predictions, axis=1)) / len(y_trues) return {"accuracy": prec_ma} trainer = Trainer( model=model, args=training_args, train_dataset=full_train_dataset, eval_dataset=full_eval_dataset, compute_metrics=compute_metrics ) # apply child_tuning or not. if child_tuning_type is not None: logger.info("Applying child-tuning.") apply_child_tuning_to_trainer(trainer, mode=child_tuning_type, reserve_p=reserve_p) trainer.train()
Run a classsification task with transformers code. Support regression/single_label/multi_label tasks :param config_args: :param pretrain_model_path: The local dir of pretrained model :param train_file_path: The local dir or path of train files :param task_type: The task type, support: - regression: a regression task(MSE loss). - single_label_classification: one label for one or two sentenses(CELoss). - multi_label_classification: multiple labels for one or two sentenses(BCELoss). :param first_sequence: Way to get the first sentense, can be "str" or "FunctionType" - str: Will be used in datasets.map(), and used like: examples[first_sequence], this is useful in json files. - FunctionType: Will be used in datasets.map(), and used like:first_sequence(examples) Examples: ``` python >>> # way to parse the first sentense out from a tsv-like file >>> first_sequence = lambda examples: examples["text"].split("\t")[0] >>> # or >>> first_sequence = "text" ``` :param label: Way to get the label, can be "str" or "FunctionType" - str: Will be used in datasets.map(), and used like: examples[label], this is useful in json files. available in "regression" or "single_label_classification" - FunctionType: Will be used in datasets.map(), and used like:label(examples) available in "regression" or "single_label_classification" or "multi_label_classification" If is a regression task, please make sure the return label is a float or a float-like string. If is a single_label task, please make sure the return label is a string. If is a multi_label task, please make sure the return label is a string or a list. Examples ``` python >>> # Way to parse the multiple labels out from a tsv-like file(Pretend that >>> # labels in one column and seperated by a comma) >>> label = lambda examples: examples["text"].split("\t")[1].split(",") >>> # or >>> first_sequence = "text" ``` :param dataset_name: The dataset name passed into datasets.load_dataset. Default will be "text" :param second_sequence: Way to get the second sentense, can be "str" or "FunctionType", please follow the rules of "first_sequence" :param dev_file_path: The local dir of dev file, which is used in cross-validation in training. :param child_tuning_type: The child_tuning type. Can be "ChildTuning-F", "ChildTuning-D" or None :param reserve_p: the drop-out rate of child_tuning, default 0.2 :param label_enumerate_values: Pass in a list as the labels. Else the train file will be parsed to get the labels :param sequence_length: The max sequence length for padding. :param map_function: An optional map function, will be used with datasets.map() :param filter_function: An optional filter function, will be used with datasets.filter() :param load_best_model_at_end: TrainingArguments. :param save_strategy: TrainingArguments. :param save_total_limit: TrainingArguments. :param evaluation_strategy: TrainingArguments. :param seed: Random seed, default 42. :param kwargs: Other optional hyper-parameters which is used in TrainingArguments. :return: None
18,297
import logging import os import types from functools import reduce from typing import Optional, List, Union import importlib logger = logging.getLogger(__name__) def environ(backend): os.environ["SOFA_BACKEND"] = backend from .models import sbert, veco, SbertConfig, SbertTokenizer, SbertTokenizerFast, SbertModel, SbertForSequenceClassification from .models import SbertForTokenClassification, SbertForQuestionAnswering, SbertForMultipleChoice, SbertForPreTraining from .models import SbertForMaskedLM, SbertForNextSentencePrediction, VecoConfig, VecoTokenizer from .models import VecoTokenizerFast, VecoModel, VecoForSequenceClassification, \ VecoForMultipleChoice, VecoForTokenClassification, VecoForQuestionAnswering from .models import palm, PalmConfig, PalmTokenizer, PalmTokenizerFast, PalmModel, PalmForConditionalGeneration from .utils import inject_model_backend inject_model_backend("sbert", "structbert", SbertConfig, SbertTokenizer, SbertTokenizerFast, backbone=SbertModel, sequence_classification=SbertForSequenceClassification, token_classification=SbertForTokenClassification, question_answering=SbertForQuestionAnswering, multiple_choice=SbertForMultipleChoice, pre_train=SbertForPreTraining, mlm=SbertForMaskedLM, nsp=SbertForNextSentencePrediction, module=sbert) inject_model_backend("veco", "veco", VecoConfig, VecoTokenizer, VecoTokenizerFast, backbone=VecoModel, sequence_classification=VecoForSequenceClassification, token_classification=VecoForTokenClassification, question_answering=VecoForQuestionAnswering, multiple_choice=VecoForMultipleChoice, slow_to_fast_converter="XLMRobertaTokenizer", module=veco) inject_model_backend("palm", "palm", PalmConfig, PalmTokenizer, PalmTokenizerFast, backbone=PalmModel, s2slm=PalmForConditionalGeneration, module=palm) The provided code snippet includes necessary dependencies for implementing the `run_sequence_labeling_hf` function. Write a Python function `def run_sequence_labeling_hf(pretrain_model_path, first_sequence, label, train_file_path, dev_file_path=None, child_tuning_type=None, reserve_p=0.2, label_enumerate_values=None, data_format="text", sequence_length=128, map_function=None, filter_function=None, label_all_tokens=True, load_best_model_at_end=True, save_strategy="steps", save_total_limit=1, evaluation_strategy="steps", return_entity_level_metrics=False, seed=42, config_args=None, **kwargs, )` to solve the following problem: Run a classsification task with transformers code. Support regression/single_label/multi_label tasks :param config_args: :param pretrain_model_path: The local dir of pretrained model :param train_file_path: The local dir of train file :param first_sequence: Way to get the first sentense, should be "FunctionType" Will be used in datasets.map(), and used like:first_sequence(examples) Examples: ``` python >>> # way to parse the first sentense out from a tsv-like file, every word is seperated with a backspace. >>> # row is "I have a cat\tO O O S-ANI" >>> first_sequence = lambda examples: examples["text"].split("\t")[0].split(" ") ``` :param label: Way to get the label, should be "FunctionType" Will be used in datasets.map(), and used like:label(examples) Note: Please make sure the labels match the BIO Tags. Examples ``` python >>> # way to parse the labels out from a tsv-like file >>> # row is "I have a cat\tO O O S-ANI" >>> label = lambda examples: examples["text"].split("\t")[1].split(" ") ``` :param data_format: The data format passed into datasets.load_dataset. Default will be "text" :param return_entity_level_metrics: Evaluation will return every single token's metrics :param label_all_tokens: When a word is seperated into sub-words, how token will be mapped If True, label will be the "I-" token mapped with the "B-" token If False, label will be a invalid value(-100) :param dev_file_path: The local dir of dev file, which is used in cross-validation in training. :param child_tuning_type: The child_tuning type. Can be "ChildTuning-F", "ChildTuning-D" or None :param reserve_p: the drop-out rate of child_tuning, default 0.2 :param label_enumerate_values: Pass in a list as the labels. Else the train file will be parsed to get the labels :param sequence_length: The max sequence length for padding. :param map_function: An optional map function, will be used with datasets.map() :param filter_function: An optional filter function, will be used with datasets.filter() :param load_best_model_at_end: TrainingArguments. :param save_strategy: TrainingArguments. :param save_total_limit: TrainingArguments. :param evaluation_strategy: TrainingArguments. :param seed: Random seed, default 42. :param kwargs: Other optional hyper-parameters which is used in TrainingArguments. :return: None Here is the function: def run_sequence_labeling_hf(pretrain_model_path, first_sequence, label, train_file_path, dev_file_path=None, child_tuning_type=None, reserve_p=0.2, label_enumerate_values=None, data_format="text", sequence_length=128, map_function=None, filter_function=None, label_all_tokens=True, load_best_model_at_end=True, save_strategy="steps", save_total_limit=1, evaluation_strategy="steps", return_entity_level_metrics=False, seed=42, config_args=None, **kwargs, ): """ Run a classsification task with transformers code. Support regression/single_label/multi_label tasks :param config_args: :param pretrain_model_path: The local dir of pretrained model :param train_file_path: The local dir of train file :param first_sequence: Way to get the first sentense, should be "FunctionType" Will be used in datasets.map(), and used like:first_sequence(examples) Examples: ``` python >>> # way to parse the first sentense out from a tsv-like file, every word is seperated with a backspace. >>> # row is "I have a cat\tO O O S-ANI" >>> first_sequence = lambda examples: examples["text"].split("\t")[0].split(" ") ``` :param label: Way to get the label, should be "FunctionType" Will be used in datasets.map(), and used like:label(examples) Note: Please make sure the labels match the BIO Tags. Examples ``` python >>> # way to parse the labels out from a tsv-like file >>> # row is "I have a cat\tO O O S-ANI" >>> label = lambda examples: examples["text"].split("\t")[1].split(" ") ``` :param data_format: The data format passed into datasets.load_dataset. Default will be "text" :param return_entity_level_metrics: Evaluation will return every single token's metrics :param label_all_tokens: When a word is seperated into sub-words, how token will be mapped If True, label will be the "I-" token mapped with the "B-" token If False, label will be a invalid value(-100) :param dev_file_path: The local dir of dev file, which is used in cross-validation in training. :param child_tuning_type: The child_tuning type. Can be "ChildTuning-F", "ChildTuning-D" or None :param reserve_p: the drop-out rate of child_tuning, default 0.2 :param label_enumerate_values: Pass in a list as the labels. Else the train file will be parsed to get the labels :param sequence_length: The max sequence length for padding. :param map_function: An optional map function, will be used with datasets.map() :param filter_function: An optional filter function, will be used with datasets.filter() :param load_best_model_at_end: TrainingArguments. :param save_strategy: TrainingArguments. :param save_total_limit: TrainingArguments. :param evaluation_strategy: TrainingArguments. :param seed: Random seed, default 42. :param kwargs: Other optional hyper-parameters which is used in TrainingArguments. :return: None """ # sofa custom code if config_args is None: config_args = {} from ... import environ environ("huggingface") # end import torch from transformers import TrainingArguments, set_seed from transformers import Trainer from datasets import load_dataset from transformers import AutoTokenizer, AutoModelForTokenClassification from transformers import DataCollatorForTokenClassification # child_tuning from ...utils import apply_child_tuning_to_trainer set_seed(seed) logger.info(f"Cuda available:{torch.cuda.is_available()}") data_files = {"train": train_file_path} if dev_file_path is not None: data_files["dev"] = dev_file_path raw_datasets = load_dataset(data_format, data_files=data_files) if filter_function is not None: raw_datasets = raw_datasets.filter(filter_function) if map_function is not None: raw_datasets = raw_datasets.map(map_function) tokenizer = AutoTokenizer.from_pretrained(pretrain_model_path, model_max_length=sequence_length) def sequence_mapping(examples): assert isinstance(first_sequence, types.FunctionType) assert isinstance(label, types.FunctionType) examples["tokenized_sequence"] = first_sequence(examples) examples["label_map"] = label(examples) return examples raw_datasets = raw_datasets.map(sequence_mapping) if label_enumerate_values is None: label_enumerate_values = list(set(reduce(lambda x, y: x + y, raw_datasets["train"]["label_map"]))) label_enumerate_values.sort() id2label = {} label2id = {} for i in range(len(label_enumerate_values)): id2label[i] = label_enumerate_values[i] label2id[label_enumerate_values[i]] = i # Map that sends B-Xxx label to its I-Xxx counterpart b_to_i_label = [] for idx, label in enumerate(label_enumerate_values): if label.startswith("B-") and label.replace("B-", "I-") in label_enumerate_values: b_to_i_label.append(label_enumerate_values.index(label.replace("B-", "I-"))) else: b_to_i_label.append(idx) def tokenize_function(examples): tokenized_inputs = tokenizer(examples["tokenized_sequence"], truncation=True, is_split_into_words=True) labels = [] for idx, label_row in enumerate(examples["label_map"]): label_row = [label2id[lb] for lb in label_row] word_ids = tokenized_inputs.word_ids(batch_index=idx) previous_word_idx = None label_ids = [] for word_idx in word_ids: if word_idx is None: label_ids.append(-100) elif word_idx != previous_word_idx: label_ids.append(label_row[word_idx]) else: if label_all_tokens: label_ids.append(b_to_i_label[label_row[word_idx]]) else: label_ids.append(-100) previous_word_idx = word_idx labels.append(label_ids) tokenized_inputs["labels"] = labels return tokenized_inputs tokenized_datasets = raw_datasets.map(tokenize_function, batched=True) training_args = TrainingArguments(load_best_model_at_end=load_best_model_at_end, save_strategy=save_strategy, save_total_limit=save_total_limit, evaluation_strategy=evaluation_strategy, **kwargs, ) model = AutoModelForTokenClassification.from_pretrained(pretrain_model_path, id2label=id2label, label2id=label2id, **config_args) import numpy as np # Code from huggingface datasets.seqeval, some users cannot download the file. def _compute( predictions, references, suffix: bool = False, scheme: Optional[str] = None, mode: Optional[str] = None, sample_weight: Optional[List[int]] = None, zero_division: Union[str, int] = "warn", ): from seqeval.metrics import accuracy_score, classification_report if scheme is not None: try: scheme_module = importlib.import_module("seqeval.scheme") scheme = getattr(scheme_module, scheme) except AttributeError: raise ValueError(f"Scheme should be one of [IOB1, IOB2, IOE1, IOE2, IOBES, BILOU], got {scheme}") report = classification_report( y_true=references, y_pred=predictions, suffix=suffix, output_dict=True, scheme=scheme, mode=mode, sample_weight=sample_weight, zero_division=zero_division, ) report.pop("macro avg") report.pop("weighted avg") overall_score = report.pop("micro avg") scores = { type_name: { "precision": score["precision"], "recall": score["recall"], "f1": score["f1-score"], "number": score["support"], } for type_name, score in report.items() } scores["overall_precision"] = overall_score["precision"] scores["overall_recall"] = overall_score["recall"] scores["overall_f1"] = overall_score["f1-score"] scores["overall_accuracy"] = accuracy_score(y_true=references, y_pred=predictions) return scores def compute_metrics(p): predictions, labels = p predictions = np.argmax(predictions, axis=2) true_predictions = [ [id2label[p] for (p, l) in zip(prediction, label) if l != -100] for prediction, label in zip(predictions, labels) ] true_labels = [ [id2label[l] for (p, l) in zip(prediction, label) if l != -100] for prediction, label in zip(predictions, labels) ] results = _compute(predictions=true_predictions, references=true_labels) if return_entity_level_metrics: final_results = {} for key, value in results.items(): if isinstance(value, dict): for n, v in value.items(): final_results[f"{key}_{n}"] = v else: final_results[key] = value return final_results else: return { "precision": results["overall_precision"], "recall": results["overall_recall"], "f1": results["overall_f1"], "accuracy": results["overall_accuracy"], } full_train_dataset = tokenized_datasets["train"] data_collator = DataCollatorForTokenClassification(tokenizer) if dev_file_path is not None: full_eval_dataset = tokenized_datasets["dev"] else: full_eval_dataset = None trainer = Trainer( model=model, args=training_args, train_dataset=full_train_dataset, eval_dataset=full_eval_dataset, data_collator=data_collator, tokenizer=tokenizer, compute_metrics=compute_metrics ) # apply child_tuning if child_tuning_type is not None: logger.info("Applying child-tuning.") apply_child_tuning_to_trainer(trainer, mode=child_tuning_type, reserve_p=reserve_p) trainer.train()
Run a classsification task with transformers code. Support regression/single_label/multi_label tasks :param config_args: :param pretrain_model_path: The local dir of pretrained model :param train_file_path: The local dir of train file :param first_sequence: Way to get the first sentense, should be "FunctionType" Will be used in datasets.map(), and used like:first_sequence(examples) Examples: ``` python >>> # way to parse the first sentense out from a tsv-like file, every word is seperated with a backspace. >>> # row is "I have a cat\tO O O S-ANI" >>> first_sequence = lambda examples: examples["text"].split("\t")[0].split(" ") ``` :param label: Way to get the label, should be "FunctionType" Will be used in datasets.map(), and used like:label(examples) Note: Please make sure the labels match the BIO Tags. Examples ``` python >>> # way to parse the labels out from a tsv-like file >>> # row is "I have a cat\tO O O S-ANI" >>> label = lambda examples: examples["text"].split("\t")[1].split(" ") ``` :param data_format: The data format passed into datasets.load_dataset. Default will be "text" :param return_entity_level_metrics: Evaluation will return every single token's metrics :param label_all_tokens: When a word is seperated into sub-words, how token will be mapped If True, label will be the "I-" token mapped with the "B-" token If False, label will be a invalid value(-100) :param dev_file_path: The local dir of dev file, which is used in cross-validation in training. :param child_tuning_type: The child_tuning type. Can be "ChildTuning-F", "ChildTuning-D" or None :param reserve_p: the drop-out rate of child_tuning, default 0.2 :param label_enumerate_values: Pass in a list as the labels. Else the train file will be parsed to get the labels :param sequence_length: The max sequence length for padding. :param map_function: An optional map function, will be used with datasets.map() :param filter_function: An optional filter function, will be used with datasets.filter() :param load_best_model_at_end: TrainingArguments. :param save_strategy: TrainingArguments. :param save_total_limit: TrainingArguments. :param evaluation_strategy: TrainingArguments. :param seed: Random seed, default 42. :param kwargs: Other optional hyper-parameters which is used in TrainingArguments. :return: None
18,298
import logging import os import types from functools import reduce import numpy as np import torch from torch import nn logger = logging.getLogger(__name__) class TextGenerator: """ Uses a model to translate a batch of sentences. Args: model (:obj:`onmt.modules.NMTModel`): NMT model to use for translation fields (dict of Fields): data fields beam_size (int): size of beam to use n_best (int): number of translations produced max_length (int): maximum length output to produce global_scores (:obj:`GlobalScorer`): object to rescore final translations copy_attn (bool): use copy attention during translation cuda (bool): use cuda beam_trace (bool): trace beam search for debugging logger(logging.Logger): logger. """ def __init__(self, model, vocab, symbols, beam_size=5, min_length=0, max_length=100, global_scorer=None, logger=None, dump_beam=""): self.alpha = 0.6 self.logger = logger # self.cuda = args.visible_gpus != '-1' self.cuda = (torch.cuda.device_count() > 0) self.model = model # TODO generator #self.generator = self.model.generator self.vocab = vocab self.symbols = symbols self.start_token = symbols['[CLS]'] #['[PAD]'] self.end_token = symbols['[SEP]'] #'[PAD]'] self.global_scorer = global_scorer self.beam_size = beam_size self.min_length = min_length self.max_length = max_length self.dump_beam = dump_beam # for debugging self.beam_trace = self.dump_beam != "" self.beam_accum = None if self.beam_trace: self.beam_accum = { "predicted_ids": [], "beam_parent_ids": [], "scores": [], "log_probs": []} def _build_target_tokens(self, pred): # vocab = self.fields["tgt"].vocab tokens = [] for tok in pred: tok = int(tok) tokens.append(tok) if tokens[-1] == self.end_token: tokens = tokens[:-1] break tokens = [t for t in tokens if t < len(self.vocab)] tokens = self.vocab.DecodeIds(tokens).split(' ') return tokens def tile(self, x, count, dim=0): """ Tiles x on dimension dim count times. """ perm = list(range(len(x.size()))) if dim != 0: perm[0], perm[dim] = perm[dim], perm[0] x = x.permute(perm).contiguous() out_size = list(x.size()) out_size[0] *= count batch = x.size(0) x = x.view(batch, -1) \ .transpose(0, 1) \ .repeat(count, 1) \ .transpose(0, 1) \ .contiguous() \ .view(*out_size) if dim != 0: x = x.permute(perm).contiguous() return x def translate_batch(self, encoder_inputs, fast=False): """ Translate a batch of sentences. Mostly a wrapper around :obj:`Beam`. Args: batch (:obj:`Batch`): a batch from a dataset object data (:obj:`Dataset`): the dataset object fast (bool): enables fast beam search (may not support all features) Todo: Shouldn't need the original dataset. """ with torch.no_grad(): return self._fast_translate_batch(encoder_inputs, self.max_length, min_length=self.min_length) def _fast_translate_batch(self, encoder_inputs, max_length, min_length=0): # TODO: faster code path for beam_size == 1. # TODO: support these blacklisted features. assert not self.dump_beam beam_size = self.beam_size tokens, types, padding_mask = encoder_inputs batch_size = tokens.size(0) device = tokens.device tmp_alive_seq = torch.full( [batch_size, 1], self.start_token, dtype=torch.long, device=device) prediction_scores, dec_feat_seq, sequence_output = self.model(tokens, types, padding_mask, tmp_alive_seq, None, None, checkpoint_activations=False, is_infer=True, sequence_output=None) src_features = sequence_output # Tile states and memory beam_size times. # dec_states.map_batch_fn( # lambda state, dim: tile(state, beam_size, dim=dim)) src_features = self.tile(src_features, beam_size, dim=0) attention_mask = self.tile(padding_mask, beam_size, dim=0) #TODO support p_gen ... # if self.args.p_gen: # src = tile(batch.src, beam_size, dim=0) batch_offset = torch.arange( batch_size, dtype=torch.long, device=device) beam_offset = torch.arange( 0, batch_size * beam_size, step=beam_size, dtype=torch.long, device=device) alive_seq = torch.full( [batch_size * beam_size, 1], self.start_token, dtype=torch.long, device=device) # Give full probability to the first beam on the first step. topk_log_probs = ( torch.tensor([0.0] + [float("-inf")] * (beam_size - 1), device=device).repeat(batch_size)) # Structure that holds finished hypotheses. hypotheses = [[] for _ in range(batch_size)] # noqa: F812 results = {} results["predictions"] = [[] for _ in range(batch_size)] # noqa: F812 results["scores"] = [[] for _ in range(batch_size)] # noqa: F812 results["gold_score"] = [0] * batch_size results["batch"] = [] dec_attn_mask = None dec_position_ids = None for step in range(max_length): tgt_len = alive_seq.size()[1] ## modified with tgt_len #repeat_attention_mask = attention_mask.repeat([1, 1, tgt_len, 1]) #dec_attn_mask = _make_causal_mask(alive_seq.shape, attention_mask.dtype, device=alive_seq.device) #dec_feat_seq = self.model.decode(self.model.bert.embeddings, src_features, alive_seq, # enc_attn_mask=repeat_attention_mask, dec_attn_mask=dec_attn_mask) prediction_scores, dec_feat_seq, _ = self.model(tokens, types, attention_mask, alive_seq, dec_position_ids, dec_attn_mask, checkpoint_activations=False, is_infer=True, sequence_output=src_features) dec_feat_seq = dec_feat_seq[:, -1, :] vocab_size = dec_feat_seq.size(-1) log_probs = torch.log(torch.softmax(dec_feat_seq.view(-1, vocab_size), dim=-1)) if step < min_length: log_probs[:, self.end_token] = -1e20 log_probs += topk_log_probs.view(-1).unsqueeze(1) alpha = self.alpha #global_scorer.alpha length_penalty = ((5.0 + (step + 1)) / 6.0) ** alpha curr_scores = log_probs / length_penalty curr_scores = curr_scores.reshape(-1, beam_size * vocab_size) topk_scores, topk_ids = curr_scores.topk(beam_size, dim=-1) topk_log_probs = topk_scores * length_penalty # Resolve beam origin and true word ids. topk_beam_index = topk_ids.div(vocab_size, rounding_mode="trunc") topk_ids = topk_ids.fmod(vocab_size) # Map beam_index to batch_index in the flat representation. batch_index = ( topk_beam_index + beam_offset[:topk_beam_index.size(0)].unsqueeze(1)) select_indices = batch_index.view(-1) # Append last prediction. alive_seq = torch.cat( [alive_seq.index_select(0, select_indices), topk_ids.view(-1, 1)], -1) is_finished = topk_ids.eq(self.end_token) if step + 1 == max_length: is_finished.fill_(1) #self.end_token) # End condition is top beam is finished. end_condition = is_finished[:, 0].eq(1) #self.end_token) # Save finished hypotheses. if is_finished.any(): predictions = alive_seq.view(-1, beam_size, alive_seq.size(-1)) for i in range(is_finished.size(0)): b = batch_offset[i] if end_condition[i]: is_finished[i].fill_(1) #self.end_token) finished_hyp = is_finished[i].nonzero().view(-1) # Store finished hypotheses for this batch. for j in finished_hyp: hypotheses[b].append(( topk_scores[i, j], predictions[i, j, 1:])) # If the batch reached the end, save the n_best hypotheses. if end_condition[i]: best_hyp = sorted( hypotheses[b], key=lambda x: x[0], reverse=True) # if self.args.dataset == "qg_ranking_test" or (self.args.dataset == 'paraphrase' and (not self.args.sample_topk)): # for each in best_hyp[:beam_size]: # score, pred = each # results["scores"][b].append(score) # results["predictions"][b].append(pred) # else: score, pred = best_hyp[0] results["scores"][b].append(score) results["predictions"][b].append(pred) non_finished = end_condition.eq(0).nonzero().view(-1) # If all sentences are translated, no need to go further. if len(non_finished) == 0: break # Remove finished batches for the next step. topk_log_probs = topk_log_probs.index_select(0, non_finished) batch_index = batch_index.index_select(0, non_finished) batch_offset = batch_offset.index_select(0, non_finished) alive_seq = predictions.index_select(0, non_finished) \ .view(-1, alive_seq.size(-1)) # Reorder states. select_indices = batch_index.view(-1) src_features = src_features.index_select(0, select_indices) attention_mask = attention_mask.index_select(0, select_indices) return results def environ(backend): os.environ["SOFA_BACKEND"] = backend from .models import sbert, veco, SbertConfig, SbertTokenizer, SbertTokenizerFast, SbertModel, SbertForSequenceClassification from .models import SbertForTokenClassification, SbertForQuestionAnswering, SbertForMultipleChoice, SbertForPreTraining from .models import SbertForMaskedLM, SbertForNextSentencePrediction, VecoConfig, VecoTokenizer from .models import VecoTokenizerFast, VecoModel, VecoForSequenceClassification, \ VecoForMultipleChoice, VecoForTokenClassification, VecoForQuestionAnswering from .models import palm, PalmConfig, PalmTokenizer, PalmTokenizerFast, PalmModel, PalmForConditionalGeneration from .utils import inject_model_backend inject_model_backend("sbert", "structbert", SbertConfig, SbertTokenizer, SbertTokenizerFast, backbone=SbertModel, sequence_classification=SbertForSequenceClassification, token_classification=SbertForTokenClassification, question_answering=SbertForQuestionAnswering, multiple_choice=SbertForMultipleChoice, pre_train=SbertForPreTraining, mlm=SbertForMaskedLM, nsp=SbertForNextSentencePrediction, module=sbert) inject_model_backend("veco", "veco", VecoConfig, VecoTokenizer, VecoTokenizerFast, backbone=VecoModel, sequence_classification=VecoForSequenceClassification, token_classification=VecoForTokenClassification, question_answering=VecoForQuestionAnswering, multiple_choice=VecoForMultipleChoice, slow_to_fast_converter="XLMRobertaTokenizer", module=veco) inject_model_backend("palm", "palm", PalmConfig, PalmTokenizer, PalmTokenizerFast, backbone=PalmModel, s2slm=PalmForConditionalGeneration, module=palm) class PreTrainedTokenizer(object): """ Base class for all tokenizers. Handle all the shared methods for tokenization and special tokens as well as methods dowloading/caching/loading pretrained tokenizers as well as adding tokens to the vocabulary. This class also contain the added tokens in a unified way on top of all tokenizers so we don't have to handle the specific vocabulary augmentation methods of the various underlying dictionary structures (BPE, sentencepiece...). Class attributes (overridden by derived classes): - ``vocab_files_names``: a python ``dict`` with, as keys, the ``__init__`` keyword name of each vocabulary file required by the model, and as associated values, the filename for saving the associated file (string). - ``pretrained_vocab_files_map``: a python ``dict of dict`` the high-level keys being the ``__init__`` keyword name of each vocabulary file required by the model, the low-level being the `short-cut-names` (string) of the pretrained models with, as associated values, the `url` (string) to the associated pretrained vocabulary file. - ``max_model_input_sizes``: a python ``dict`` with, as keys, the `short-cut-names` (string) of the pretrained models, and as associated values, the maximum length of the sequence inputs of this model, or None if the model has no maximum input size. - ``pretrained_init_configuration``: a python ``dict`` with, as keys, the `short-cut-names` (string) of the pretrained models, and as associated values, a dictionnary of specific arguments to pass to the ``__init__``method of the tokenizer class for this pretrained model when loading the tokenizer with the ``from_pretrained()`` method. Parameters: - ``bos_token``: (`Optional`) string: a beginning of sentence token. Will be associated to ``self.bos_token`` and ``self.bos_token_id`` - ``eos_token``: (`Optional`) string: an end of sentence token. Will be associated to ``self.eos_token`` and ``self.eos_token_id`` - ``unk_token``: (`Optional`) string: an unknown token. Will be associated to ``self.unk_token`` and ``self.unk_token_id`` - ``sep_token``: (`Optional`) string: a separation token (e.g. to separate context and query in an input sequence). Will be associated to ``self.sep_token`` and ``self.sep_token_id`` - ``pad_token``: (`Optional`) string: a padding token. Will be associated to ``self.pad_token`` and ``self.pad_token_id`` - ``cls_token``: (`Optional`) string: a classification token (e.g. to extract a summary of an input sequence leveraging self-attention along the full depth of the model). Will be associated to ``self.cls_token`` and ``self.cls_token_id`` - ``mask_token``: (`Optional`) string: a masking token (e.g. when training a model with masked-language modeling). Will be associated to ``self.mask_token`` and ``self.mask_token_id`` - ``additional_special_tokens``: (`Optional`) list: a list of additional special tokens. Adding all special tokens here ensure they won't be split by the tokenization process. Will be associated to ``self.additional_special_tokens`` and ``self.additional_special_tokens_ids`` """ vocab_files_names = {} pretrained_vocab_files_map = {} pretrained_init_configuration = {} max_model_input_sizes = {} SPECIAL_TOKENS_ATTRIBUTES = ["bos_token", "eos_token", "unk_token", "sep_token", "pad_token", "cls_token", "mask_token", "additional_special_tokens"] def bos_token(self): """ Beginning of sentence token (string). Log an error if used while not having been set. """ if self._bos_token is None: logger.error("Using bos_token, but it is not set yet.") return self._bos_token def eos_token(self): """ End of sentence token (string). Log an error if used while not having been set. """ if self._eos_token is None: logger.error("Using eos_token, but it is not set yet.") return self._eos_token def unk_token(self): """ Unknown token (string). Log an error if used while not having been set. """ if self._unk_token is None: logger.error("Using unk_token, but it is not set yet.") return self._unk_token def sep_token(self): """ Separation token (string). E.g. separate context and query in an input sequence. Log an error if used while not having been set. """ if self._sep_token is None: logger.error("Using sep_token, but it is not set yet.") return self._sep_token def pad_token(self): """ Padding token (string). Log an error if used while not having been set. """ if self._pad_token is None: logger.error("Using pad_token, but it is not set yet.") return self._pad_token def cls_token(self): """ Classification token (string). E.g. to extract a summary of an input sequence leveraging self-attention along the full depth of the model. Log an error if used while not having been set. """ if self._cls_token is None: logger.error("Using cls_token, but it is not set yet.") return self._cls_token def mask_token(self): """ Mask token (string). E.g. when training a model with masked-language modeling. Log an error if used while not having been set. """ if self._mask_token is None: logger.error("Using mask_token, but it is not set yet.") return self._mask_token def additional_special_tokens(self): """ All the additional special tokens you may want to use (list of strings). Log an error if used while not having been set. """ if self._additional_special_tokens is None: logger.error("Using additional_special_tokens, but it is not set yet.") return self._additional_special_tokens def bos_token(self, value): self._bos_token = value def eos_token(self, value): self._eos_token = value def unk_token(self, value): self._unk_token = value def sep_token(self, value): self._sep_token = value def pad_token(self, value): self._pad_token = value def cls_token(self, value): self._cls_token = value def mask_token(self, value): self._mask_token = value def additional_special_tokens(self, value): self._additional_special_tokens = value def bos_token_id(self): """ Id of the beginning of sentence token in the vocabulary. Log an error if used while not having been set. """ return self.convert_tokens_to_ids(self.bos_token) def eos_token_id(self): """ Id of the end of sentence token in the vocabulary. Log an error if used while not having been set. """ return self.convert_tokens_to_ids(self.eos_token) def unk_token_id(self): """ Id of the unknown token in the vocabulary. Log an error if used while not having been set. """ return self.convert_tokens_to_ids(self.unk_token) def sep_token_id(self): """ Id of the separation token in the vocabulary. E.g. separate context and query in an input sequence. Log an error if used while not having been set. """ return self.convert_tokens_to_ids(self.sep_token) def pad_token_id(self): """ Id of the padding token in the vocabulary. Log an error if used while not having been set. """ return self.convert_tokens_to_ids(self.pad_token) def cls_token_id(self): """ Id of the classification token in the vocabulary. E.g. to extract a summary of an input sequence leveraging self-attention along the full depth of the model. Log an error if used while not having been set. """ return self.convert_tokens_to_ids(self.cls_token) def mask_token_id(self): """ Id of the mask token in the vocabulary. E.g. when training a model with masked-language modeling. Log an error if used while not having been set. """ return self.convert_tokens_to_ids(self.mask_token) def additional_special_tokens_ids(self): """ Ids of all the additional special tokens in the vocabulary (list of integers). Log an error if used while not having been set. """ return self.convert_tokens_to_ids(self.additional_special_tokens) def __init__(self, max_len=None, **kwargs): self._bos_token = None self._eos_token = None self._unk_token = None self._sep_token = None self._pad_token = None self._cls_token = None self._mask_token = None self._additional_special_tokens = [] self.max_len = max_len if max_len is not None else int(1e12) # Added tokens self.added_tokens_encoder = {} self.added_tokens_decoder = {} # inputs and kwargs for saving and re-loading (see ``from_pretrained`` and ``save_pretrained``) self.init_inputs = () self.init_kwargs = {} for key, value in kwargs.items(): if key in self.SPECIAL_TOKENS_ATTRIBUTES: if key == 'additional_special_tokens': assert isinstance(value, (list, tuple)) and all(isinstance(t, str) or (six.PY2 and isinstance(t, unicode)) for t in value) else: assert isinstance(value, str) or (six.PY2 and isinstance(value, unicode)) setattr(self, key, value) def from_pretrained(cls, *inputs, **kwargs): r""" Instantiate a :class:`~transformers.PreTrainedTokenizer` (or a derived class) from a predefined tokenizer. Args: pretrained_model_name_or_path: either: - a string with the `shortcut name` of a predefined tokenizer to load from cache or download, e.g.: ``bert-base-uncased``. - a path to a `directory` containing vocabulary files required by the tokenizer, for instance saved using the :func:`~transformers.PreTrainedTokenizer.save_pretrained` method, e.g.: ``./my_model_directory/``. - (not applicable to all derived classes) a path or url to a single saved vocabulary file if and only if the tokenizer only requires a single vocabulary file (e.g. Bert, XLNet), e.g.: ``./my_model_directory/vocab.txt``. cache_dir: (`optional`) string: Path to a directory in which a downloaded predefined tokenizer vocabulary files should be cached if the standard cache should not be used. force_download: (`optional`) boolean, default False: Force to (re-)download the vocabulary files and override the cached versions if they exists. proxies: (`optional`) dict, default None: A dictionary of proxy servers to use by protocol or endpoint, e.g.: {'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}. The proxies are used on each request. inputs: (`optional`) positional arguments: will be passed to the Tokenizer ``__init__`` method. kwargs: (`optional`) keyword arguments: will be passed to the Tokenizer ``__init__`` method. Can be used to set special tokens like ``bos_token``, ``eos_token``, ``unk_token``, ``sep_token``, ``pad_token``, ``cls_token``, ``mask_token``, ``additional_special_tokens``. See parameters in the doc string of :class:`~transformers.PreTrainedTokenizer` for details. Examples:: # We can't instantiate directly the base class `PreTrainedTokenizer` so let's show our examples on a derived class: BertTokenizer # Download vocabulary from S3 and cache. tokenizer = BertTokenizer.from_pretrained('bert-base-uncased') # If vocabulary files are in a directory (e.g. tokenizer was saved using `save_pretrained('./test/saved_model/')`) tokenizer = BertTokenizer.from_pretrained('./test/saved_model/') # If the tokenizer uses a single vocabulary file, you can point directly to this file tokenizer = BertTokenizer.from_pretrained('./test/saved_model/my_vocab.txt') # You can link tokens to special vocabulary when instantiating tokenizer = BertTokenizer.from_pretrained('bert-base-uncased', unk_token='<unk>') # You should be sure '<unk>' is in the vocabulary when doing that. # Otherwise use tokenizer.add_special_tokens({'unk_token': '<unk>'}) instead) assert tokenizer.unk_token == '<unk>' """ return cls._from_pretrained(*inputs, **kwargs) def _from_pretrained(cls, pretrained_model_name_or_path, *init_inputs, **kwargs): cache_dir = kwargs.pop('cache_dir', None) force_download = kwargs.pop('force_download', False) proxies = kwargs.pop('proxies', None) s3_models = list(cls.max_model_input_sizes.keys()) vocab_files = {} init_configuration = {} if pretrained_model_name_or_path in s3_models: # Get the vocabulary from AWS S3 bucket for file_id, map_list in cls.pretrained_vocab_files_map.items(): vocab_files[file_id] = map_list[pretrained_model_name_or_path] if cls.pretrained_init_configuration and pretrained_model_name_or_path in cls.pretrained_init_configuration: init_configuration = cls.pretrained_init_configuration[pretrained_model_name_or_path] else: # Get the vocabulary from local files logger.info( "Model name '{}' not found in model shortcut name list ({}). " "Assuming '{}' is a path or url to a directory containing tokenizer files.".format( pretrained_model_name_or_path, ', '.join(s3_models), pretrained_model_name_or_path)) # Look for the tokenizer main vocabulary files for file_id, file_name in cls.vocab_files_names.items(): if os.path.isdir(pretrained_model_name_or_path): # If a directory is provided we look for the standard filenames full_file_name = os.path.join(pretrained_model_name_or_path, file_name) else: # If a path to a file is provided we use it (will only work for non-BPE tokenizer using a single vocabulary file) full_file_name = pretrained_model_name_or_path if not os.path.exists(full_file_name): logger.info("Didn't find file {}. We won't load it.".format(full_file_name)) full_file_name = None vocab_files[file_id] = full_file_name # Look for the additional tokens files additional_files_names = {'added_tokens_file': ADDED_TOKENS_FILE, 'special_tokens_map_file': SPECIAL_TOKENS_MAP_FILE, 'tokenizer_config_file': TOKENIZER_CONFIG_FILE, } # If a path to a file was provided, get the parent directory saved_directory = pretrained_model_name_or_path if os.path.exists(saved_directory) and not os.path.isdir(saved_directory): saved_directory = os.path.dirname(saved_directory) for file_id, file_name in additional_files_names.items(): full_file_name = os.path.join(saved_directory, file_name) if not os.path.exists(full_file_name): logger.info("Didn't find file {}. We won't load it.".format(full_file_name)) full_file_name = None vocab_files[file_id] = full_file_name if all(full_file_name is None for full_file_name in vocab_files.values()): raise EnvironmentError( "Model name '{}' was not found in tokenizers model name list ({}). " "We assumed '{}' was a path or url to a directory containing vocabulary files " "named {} but couldn't find such vocabulary files at this path or url.".format( pretrained_model_name_or_path, ', '.join(s3_models), pretrained_model_name_or_path, list(cls.vocab_files_names.values()))) # Get files from url, cache, or disk depending on the case try: resolved_vocab_files = {} for file_id, file_path in vocab_files.items(): if file_path is None: resolved_vocab_files[file_id] = None else: resolved_vocab_files[file_id] = cached_path(file_path, cache_dir=cache_dir, force_download=force_download, proxies=proxies) except EnvironmentError: if pretrained_model_name_or_path in s3_models: msg = "Couldn't reach server at '{}' to download vocabulary files." else: msg = "Model name '{}' was not found in tokenizers model name list ({}). " \ "We assumed '{}' was a path or url to a directory containing vocabulary files " \ "named {}, but couldn't find such vocabulary files at this path or url.".format( pretrained_model_name_or_path, ', '.join(s3_models), pretrained_model_name_or_path, list(cls.vocab_files_names.values())) raise EnvironmentError(msg) for file_id, file_path in vocab_files.items(): if file_path == resolved_vocab_files[file_id]: logger.info("loading file {}".format(file_path)) else: logger.info("loading file {} from cache at {}".format( file_path, resolved_vocab_files[file_id])) # Prepare tokenizer initialization kwargs # Did we saved some inputs and kwargs to reload ? tokenizer_config_file = resolved_vocab_files.pop('tokenizer_config_file', None) if tokenizer_config_file is not None: init_kwargs = json.load(open(tokenizer_config_file, encoding="utf-8")) saved_init_inputs = init_kwargs.pop('init_inputs', ()) if not init_inputs: init_inputs = saved_init_inputs else: init_kwargs = init_configuration # Update with newly provided kwargs init_kwargs.update(kwargs) # Set max length if needed if pretrained_model_name_or_path in cls.max_model_input_sizes: # if we're using a pretrained model, ensure the tokenizer # wont index sequences longer than the number of positional embeddings max_len = cls.max_model_input_sizes[pretrained_model_name_or_path] if max_len is not None and isinstance(max_len, (int, float)): init_kwargs['max_len'] = min(init_kwargs.get('max_len', int(1e12)), max_len) # Merge resolved_vocab_files arguments in init_kwargs. added_tokens_file = resolved_vocab_files.pop('added_tokens_file', None) special_tokens_map_file = resolved_vocab_files.pop('special_tokens_map_file', None) for args_name, file_path in resolved_vocab_files.items(): if args_name not in init_kwargs: init_kwargs[args_name] = file_path if special_tokens_map_file is not None: special_tokens_map = json.load(open(special_tokens_map_file, encoding="utf-8")) for key, value in special_tokens_map.items(): if key not in init_kwargs: init_kwargs[key] = value # Instantiate tokenizer. tokenizer = cls(*init_inputs, **init_kwargs) # Save inputs and kwargs for saving and re-loading with ``save_pretrained`` tokenizer.init_inputs = init_inputs tokenizer.init_kwargs = init_kwargs # Add supplementary tokens. if added_tokens_file is not None: added_tok_encoder = json.load(open(added_tokens_file, encoding="utf-8")) added_tok_decoder = {v:k for k, v in added_tok_encoder.items()} tokenizer.added_tokens_encoder.update(added_tok_encoder) tokenizer.added_tokens_decoder.update(added_tok_decoder) return tokenizer def save_pretrained(self, save_directory): """ Save the tokenizer vocabulary files together with: - added tokens, - special-tokens-to-class-attributes-mapping, - tokenizer instantiation positional and keywords inputs (e.g. do_lower_case for Bert). This won't save modifications other than (added tokens and special token mapping) you may have applied to the tokenizer after the instantiation (e.g. modifying tokenizer.do_lower_case after creation). This method make sure the full tokenizer can then be re-loaded using the :func:`~transformers.PreTrainedTokenizer.from_pretrained` class method. """ if not os.path.isdir(save_directory): logger.error("Saving directory ({}) should be a directory".format(save_directory)) return special_tokens_map_file = os.path.join(save_directory, SPECIAL_TOKENS_MAP_FILE) added_tokens_file = os.path.join(save_directory, ADDED_TOKENS_FILE) tokenizer_config_file = os.path.join(save_directory, TOKENIZER_CONFIG_FILE) tokenizer_config = copy.deepcopy(self.init_kwargs) tokenizer_config['init_inputs'] = copy.deepcopy(self.init_inputs) for file_id in self.vocab_files_names.keys(): tokenizer_config.pop(file_id, None) with open(tokenizer_config_file, 'w', encoding='utf-8') as f: f.write(json.dumps(tokenizer_config, ensure_ascii=False)) with open(special_tokens_map_file, 'w', encoding='utf-8') as f: f.write(json.dumps(self.special_tokens_map, ensure_ascii=False)) with open(added_tokens_file, 'w', encoding='utf-8') as f: if self.added_tokens_encoder: out_str = json.dumps(self.added_tokens_encoder, ensure_ascii=False) else: out_str = u"{}" f.write(out_str) vocab_files = self.save_vocabulary(save_directory) return vocab_files + (special_tokens_map_file, added_tokens_file) def save_vocabulary(self, save_directory): """ Save the tokenizer vocabulary to a directory. This method does *NOT* save added tokens and special token mappings. Please use :func:`~transformers.PreTrainedTokenizer.save_pretrained` `()` to save the full Tokenizer state if you want to reload it using the :func:`~transformers.PreTrainedTokenizer.from_pretrained` class method. """ raise NotImplementedError def vocab_size(self): """ Size of the base vocabulary (without the added tokens) """ raise NotImplementedError def __len__(self): """ Size of the full vocabulary with the added tokens """ return self.vocab_size + len(self.added_tokens_encoder) def add_tokens(self, new_tokens): """ Add a list of new tokens to the tokenizer class. If the new tokens are not in the vocabulary, they are added to it with indices starting from length of the current vocabulary. Args: new_tokens: list of string. Each string is a token to add. Tokens are only added if they are not already in the vocabulary (tested by checking if the tokenizer assign the index of the ``unk_token`` to them). Returns: Number of tokens added to the vocabulary. Examples:: # Let's see how to increase the vocabulary of Bert model and tokenizer tokenizer = BertTokenizer.from_pretrained('bert-base-uncased') model = BertModel.from_pretrained('bert-base-uncased') num_added_toks = tokenizer.add_tokens(['new_tok1', 'my_new-tok2']) print('We have added', num_added_toks, 'tokens') model.resize_token_embeddings(len(tokenizer)) # Notice: resize_token_embeddings expect to receive the full size of the new vocabulary, i.e. the length of the tokenizer. """ if not new_tokens: return 0 to_add_tokens = [] for token in new_tokens: assert isinstance(token, str) or (six.PY2 and isinstance(token, unicode)) if token != self.unk_token and \ self.convert_tokens_to_ids(token) == self.convert_tokens_to_ids(self.unk_token) and \ token not in to_add_tokens: to_add_tokens.append(token) logger.info("Adding %s to the vocabulary", token) added_tok_encoder = dict((tok, len(self) + i) for i, tok in enumerate(to_add_tokens)) added_tok_decoder = {v:k for k, v in added_tok_encoder.items()} self.added_tokens_encoder.update(added_tok_encoder) self.added_tokens_decoder.update(added_tok_decoder) return len(to_add_tokens) def num_added_tokens(self, pair=False): """ Returns the number of added tokens when encoding a sequence with special tokens. Note: This encodes inputs and checks the number of added tokens, and is therefore not efficient. Do not put this inside your training loop. Args: pair: Returns the number of added tokens in the case of a sequence pair if set to True, returns the number of added tokens in the case of a single sequence if set to False. Returns: Number of tokens added to sequences """ token_ids_0 = [] token_ids_1 = [] return len(self.build_inputs_with_special_tokens(token_ids_0, token_ids_1 if pair else None)) def add_special_tokens(self, special_tokens_dict): """ Add a dictionary of special tokens (eos, pad, cls...) to the encoder and link them to class attributes. If special tokens are NOT in the vocabulary, they are added to it (indexed starting from the last index of the current vocabulary). Using `add_special_tokens` will ensure your special tokens can be used in several ways: - special tokens are carefully handled by the tokenizer (they are never split) - you can easily refer to special tokens using tokenizer class attributes like `tokenizer.cls_token`. This makes it easy to develop model-agnostic training and fine-tuning scripts. When possible, special tokens are already registered for provided pretrained models (ex: BertTokenizer cls_token is already registered to be '[CLS]' and XLM's one is also registered to be '</s>') Args: special_tokens_dict: dict of string. Keys should be in the list of predefined special attributes: [``bos_token``, ``eos_token``, ``unk_token``, ``sep_token``, ``pad_token``, ``cls_token``, ``mask_token``, ``additional_special_tokens``]. Tokens are only added if they are not already in the vocabulary (tested by checking if the tokenizer assign the index of the ``unk_token`` to them). Returns: Number of tokens added to the vocabulary. Examples:: # Let's see how to add a new classification token to GPT-2 tokenizer = GPT2Tokenizer.from_pretrained('gpt2') model = GPT2Model.from_pretrained('gpt2') special_tokens_dict = {'cls_token': '<CLS>'} num_added_toks = tokenizer.add_special_tokens(special_tokens_dict) print('We have added', num_added_toks, 'tokens') model.resize_token_embeddings(len(tokenizer)) # Notice: resize_token_embeddings expect to receive the full size of the new vocabulary, i.e. the length of the tokenizer. assert tokenizer.cls_token == '<CLS>' """ if not special_tokens_dict: return 0 added_tokens = 0 for key, value in special_tokens_dict.items(): assert key in self.SPECIAL_TOKENS_ATTRIBUTES if key == 'additional_special_tokens': assert isinstance(value, (list, tuple)) and all(isinstance(t, str) or (six.PY2 and isinstance(t, unicode)) for t in value) added_tokens += self.add_tokens(value) else: assert isinstance(value, str) or (six.PY2 and isinstance(value, unicode)) added_tokens += self.add_tokens([value]) logger.info("Assigning %s to the %s key of the tokenizer", value, key) setattr(self, key, value) return added_tokens def tokenize(self, text, **kwargs): """ Converts a string in a sequence of tokens (string), using the tokenizer. Split in words for word-based vocabulary or sub-words for sub-word-based vocabularies (BPE/SentencePieces/WordPieces). Take care of added tokens. """ def split_on_token(tok, text): result = [] split_text = text.split(tok) for i, sub_text in enumerate(split_text): sub_text = sub_text.strip() if i == 0 and not sub_text: result += [tok] elif i == len(split_text) - 1: if sub_text: result += [sub_text] else: pass else: if sub_text: result += [sub_text] result += [tok] return result def split_on_tokens(tok_list, text): if not text: return [] if not tok_list: return self._tokenize(text, **kwargs) tokenized_text = [] text_list = [text] for tok in tok_list: tokenized_text = [] for sub_text in text_list: if sub_text not in self.added_tokens_encoder \ and sub_text not in self.all_special_tokens: tokenized_text += split_on_token(tok, sub_text) else: tokenized_text += [sub_text] text_list = tokenized_text return sum((self._tokenize(token, **kwargs) if token not \ in self.added_tokens_encoder and token not in self.all_special_tokens \ else [token] for token in tokenized_text), []) added_tokens = list(self.added_tokens_encoder.keys()) + self.all_special_tokens tokenized_text = split_on_tokens(added_tokens, text) return tokenized_text def _tokenize(self, text, **kwargs): """ Converts a string in a sequence of tokens (string), using the tokenizer. Split in words for word-based vocabulary or sub-words for sub-word-based vocabularies (BPE/SentencePieces/WordPieces). Do NOT take care of added tokens. """ raise NotImplementedError def convert_tokens_to_ids(self, tokens): """ Converts a single token, or a sequence of tokens, (str/unicode) in a single integer id (resp. a sequence of ids), using the vocabulary. """ if tokens is None: return None if isinstance(tokens, str) or (six.PY2 and isinstance(tokens, unicode)): return self._convert_token_to_id_with_added_voc(tokens) ids = [] for token in tokens: ids.append(self._convert_token_to_id_with_added_voc(token)) if len(ids) > self.max_len: logger.warning("Token indices sequence length is longer than the specified maximum sequence length " "for this model ({} > {}). Running this sequence through the model will result in " "indexing errors".format(len(ids), self.max_len)) return ids def _convert_token_to_id_with_added_voc(self, token): if token is None: return None if token in self.added_tokens_encoder: return self.added_tokens_encoder[token] return self._convert_token_to_id(token) def _convert_token_to_id(self, token): raise NotImplementedError def encode(self, text, text_pair=None, add_special_tokens=False, max_length=None, stride=0, truncation_strategy='longest_first', return_tensors=None, **kwargs): """ Converts a string in a sequence of ids (integer), using the tokenizer and vocabulary. Same as doing ``self.convert_tokens_to_ids(self.tokenize(text))``. Args: text: The first sequence to be encoded. This can be a string, a list of strings (tokenized string using the `tokenize` method) or a list of integers (tokenized string ids using the `convert_tokens_to_ids` method) text_pair: Optional second sequence to be encoded. This can be a string, a list of strings (tokenized string using the `tokenize` method) or a list of integers (tokenized string ids using the `convert_tokens_to_ids` method) add_special_tokens: if set to ``True``, the sequences will be encoded with the special tokens relative to their model. max_length: if set to a number, will limit the total sequence returned so that it has a maximum length. If there are overflowing tokens, those will be added to the returned dictionary stride: if set to a number along with max_length, the overflowing tokens returned will contain some tokens from the main sequence returned. The value of this argument defines the number of additional tokens. truncation_strategy: string selected in the following options: - 'longest_first' (default) Iteratively reduce the inputs sequence until the input is under max_length starting from the longest one at each token (when there is a pair of input sequences) - 'only_first': Only truncate the first sequence - 'only_second': Only truncate the second sequence - 'do_not_truncate': Does not truncate (raise an error if the input sequence is longer than max_length) return_tensors: (optional) can be set to 'tf' or 'pt' to return respectively TensorFlow tf.constant or PyTorch torch.Tensor instead of a list of python integers. **kwargs: passed to the `self.tokenize()` method """ encoded_inputs = self.encode_plus(text, text_pair=text_pair, max_length=max_length, add_special_tokens=add_special_tokens, stride=stride, truncation_strategy=truncation_strategy, return_tensors=return_tensors, **kwargs) return encoded_inputs["input_ids"] def encode_plus(self, text, text_pair=None, add_special_tokens=False, max_length=None, stride=0, truncation_strategy='longest_first', return_tensors=None, **kwargs): """ Returns a dictionary containing the encoded sequence or sequence pair and additional informations: the mask for sequence classification and the overflowing elements if a ``max_length`` is specified. Args: text: The first sequence to be encoded. This can be a string, a list of strings (tokenized string using the `tokenize` method) or a list of integers (tokenized string ids using the `convert_tokens_to_ids` method) text_pair: Optional second sequence to be encoded. This can be a string, a list of strings (tokenized string using the `tokenize` method) or a list of integers (tokenized string ids using the `convert_tokens_to_ids` method) add_special_tokens: if set to ``True``, the sequences will be encoded with the special tokens relative to their model. max_length: if set to a number, will limit the total sequence returned so that it has a maximum length. If there are overflowing tokens, those will be added to the returned dictionary stride: if set to a number along with max_length, the overflowing tokens returned will contain some tokens from the main sequence returned. The value of this argument defines the number of additional tokens. truncation_strategy: string selected in the following options: - 'longest_first' (default) Iteratively reduce the inputs sequence until the input is under max_length starting from the longest one at each token (when there is a pair of input sequences) - 'only_first': Only truncate the first sequence - 'only_second': Only truncate the second sequence - 'do_not_truncate': Does not truncate (raise an error if the input sequence is longer than max_length) return_tensors: (optional) can be set to 'tf' or 'pt' to return respectively TensorFlow tf.constant or PyTorch torch.Tensor instead of a list of python integers. **kwargs: passed to the `self.tokenize()` method """ def get_input_ids(text): if isinstance(text, six.string_types): return self.convert_tokens_to_ids(self.tokenize(text, **kwargs)) elif isinstance(text, (list, tuple)) and len(text) > 0 and isinstance(text[0], six.string_types): return self.convert_tokens_to_ids(text) elif isinstance(text, (list, tuple)) and len(text) > 0 and isinstance(text[0], int): return text else: raise ValueError("Input is not valid. Should be a string, a list/tuple of strings or a list/tuple of integers.") first_ids = get_input_ids(text) second_ids = get_input_ids(text_pair) if text_pair is not None else None return self.prepare_for_model(first_ids, pair_ids=second_ids, max_length=max_length, add_special_tokens=add_special_tokens, stride=stride, truncation_strategy=truncation_strategy, return_tensors=return_tensors) def prepare_for_model(self, ids, pair_ids=None, max_length=None, add_special_tokens=False, stride=0, truncation_strategy='longest_first', return_tensors=None): """ Prepares a sequence of input id, or a pair of sequences of inputs ids so that it can be used by the model. It adds special tokens, truncates sequences if overflowing while taking into account the special tokens and manages a window stride for overflowing tokens Args: ids: list of tokenized input ids. Can be obtained from a string by chaining the `tokenize` and `convert_tokens_to_ids` methods. pair_ids: Optional second list of input ids. Can be obtained from a string by chaining the `tokenize` and `convert_tokens_to_ids` methods. max_length: maximum length of the returned list. Will truncate by taking into account the special tokens. add_special_tokens: if set to ``True``, the sequences will be encoded with the special tokens relative to their model. stride: window stride for overflowing tokens. Can be useful for edge effect removal when using sequential list of inputs. truncation_strategy: string selected in the following options: - 'longest_first' (default) Iteratively reduce the inputs sequence until the input is under max_length starting from the longest one at each token (when there is a pair of input sequences) - 'only_first': Only truncate the first sequence - 'only_second': Only truncate the second sequence - 'do_not_truncate': Does not truncate (raise an error if the input sequence is longer than max_length) return_tensors: (optional) can be set to 'tf' or 'pt' to return respectively TensorFlow tf.constant or PyTorch torch.Tensor instead of a list of python integers. Return: A Dictionary of shape:: { input_ids: list[int], overflowing_tokens: list[int] if a ``max_length`` is specified, else None special_tokens_mask: list[int] if ``add_special_tokens`` if set to ``True`` } With the fields: ``input_ids``: list of tokens to be fed to a model ``overflowing_tokens``: list of overflowing tokens if a max length is specified. ``special_tokens_mask``: if adding special tokens, this is a list of [0, 1], with 0 specifying special added tokens and 1 specifying sequence tokens. """ pair = bool(pair_ids is not None) len_ids = len(ids) len_pair_ids = len(pair_ids) if pair else 0 encoded_inputs = {} total_len = len_ids + len_pair_ids + (self.num_added_tokens(pair=pair) if add_special_tokens else 0) if max_length and total_len > max_length: ids, pair_ids, overflowing_tokens = self.truncate_sequences(ids, pair_ids=pair_ids, num_tokens_to_remove=total_len-max_length, truncation_strategy=truncation_strategy, stride=stride) encoded_inputs["overflowing_tokens"] = overflowing_tokens encoded_inputs["num_truncated_tokens"] = total_len - max_length if add_special_tokens: sequence = self.build_inputs_with_special_tokens(ids, pair_ids) token_type_ids = self.create_token_type_ids_from_sequences(ids, pair_ids) encoded_inputs["special_tokens_mask"] = self.get_special_tokens_mask(ids, pair_ids) else: sequence = ids + pair_ids if pair else ids token_type_ids = [0] * len(ids) + ([1] * len(pair_ids) if pair else []) if return_tensors == 'tf' and is_tf_available(): sequence = tf.constant([sequence]) token_type_ids = tf.constant([token_type_ids]) elif return_tensors == 'pt' and is_torch_available(): sequence = torch.tensor([sequence]) token_type_ids = torch.tensor([token_type_ids]) elif return_tensors is not None: logger.warning("Unable to convert output to tensors format {}, PyTorch or TensorFlow is not available.".format(return_tensors)) encoded_inputs["input_ids"] = sequence encoded_inputs["token_type_ids"] = token_type_ids if max_length and len(encoded_inputs["input_ids"]) > max_length: encoded_inputs["input_ids"] = encoded_inputs["input_ids"][:max_length] encoded_inputs["token_type_ids"] = encoded_inputs["token_type_ids"][:max_length] encoded_inputs["special_tokens_mask"] = encoded_inputs["special_tokens_mask"][:max_length] return encoded_inputs def truncate_sequences(self, ids, pair_ids=None, num_tokens_to_remove=0, truncation_strategy='longest_first', stride=0): """Truncates a sequence pair in place to the maximum length. truncation_strategy: string selected in the following options: - 'longest_first' (default) Iteratively reduce the inputs sequence until the input is under max_length starting from the longest one at each token (when there is a pair of input sequences). Overflowing tokens only contains overflow from the first sequence. - 'only_first': Only truncate the first sequence. raise an error if the first sequence is shorter or equal to than num_tokens_to_remove. - 'only_second': Only truncate the second sequence - 'do_not_truncate': Does not truncate (raise an error if the input sequence is longer than max_length) """ if num_tokens_to_remove <= 0: return ids, pair_ids, [] if truncation_strategy == 'longest_first': overflowing_tokens = [] for _ in range(num_tokens_to_remove): if pair_ids is None or len(ids) > len(pair_ids): overflowing_tokens = [ids[-1]] + overflowing_tokens ids = ids[:-1] else: pair_ids = pair_ids[:-1] window_len = min(len(ids), stride) if window_len > 0: overflowing_tokens = ids[-window_len:] + overflowing_tokens elif truncation_strategy == 'only_first': assert len(ids) > num_tokens_to_remove window_len = min(len(ids), stride + num_tokens_to_remove) overflowing_tokens = ids[-window_len:] ids = ids[:-num_tokens_to_remove] elif truncation_strategy == 'only_second': assert pair_ids is not None and len(pair_ids) > num_tokens_to_remove window_len = min(len(pair_ids), stride + num_tokens_to_remove) overflowing_tokens = pair_ids[-window_len:] pair_ids = pair_ids[:-num_tokens_to_remove] elif truncation_strategy == 'do_not_truncate': raise ValueError("Input sequence are too long for max_length. Please select a truncation strategy.") else: raise ValueError("Truncation_strategy should be selected in ['longest_first', 'only_first', 'only_second', 'do_not_truncate']") return (ids, pair_ids, overflowing_tokens) def create_token_type_ids_from_sequences(self, token_ids_0, token_ids_1=None): logger.warning("This tokenizer does not make use of special tokens.") if token_ids_1 is None: return len(token_ids_0) * [0] return [0] * len(token_ids_0) + [1] * len(token_ids_1) def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None): """ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and adding special tokens. A RoBERTa sequence has the following format: single sequence: <s> X </s> pair of sequences: <s> A </s></s> B </s> """ logger.warning("This tokenizer does not make use of special tokens. Input is returned with no modification.") if token_ids_1 is None: return token_ids_0 return token_ids_0 + token_ids_1 def get_special_tokens_mask(self, token_ids_0, token_ids_1=None, already_has_special_tokens=False): """ Retrieves sequence ids from a token list that has no special tokens added. This method is called when adding special tokens using the tokenizer ``prepare_for_model`` or ``encode_plus`` methods. Args: token_ids_0: list of ids (must not contain special tokens) token_ids_1: Optional list of ids (must not contain special tokens), necessary when fetching sequence ids for sequence pairs already_has_special_tokens: (default False) Set to True if the token list is already formated with special tokens for the model Returns: A list of integers in the range [0, 1]: 0 for a special token, 1 for a sequence token. """ return [0] * ((len(token_ids_1) if token_ids_1 else 0) + len(token_ids_0)) def convert_ids_to_tokens(self, ids, skip_special_tokens=False): """ Converts a single index or a sequence of indices (integers) in a token " (resp.) a sequence of tokens (str/unicode), using the vocabulary and added tokens. Args: skip_special_tokens: Don't decode special tokens (self.all_special_tokens). Default: False """ if isinstance(ids, int): if ids in self.added_tokens_decoder: return self.added_tokens_decoder[ids] else: return self._convert_id_to_token(ids) tokens = [] for index in ids: if skip_special_tokens and index in self.all_special_ids: continue if index in self.added_tokens_decoder: tokens.append(self.added_tokens_decoder[index]) else: tokens.append(self._convert_id_to_token(index)) return tokens def _convert_id_to_token(self, index): raise NotImplementedError def convert_tokens_to_string(self, tokens): """ Converts a sequence of tokens (string) in a single string. The most simple way to do it is ' '.join(self.convert_ids_to_tokens(token_ids)) but we often want to remove sub-word tokenization artifacts at the same time. """ return ' '.join(self.convert_ids_to_tokens(tokens)) def decode(self, token_ids, skip_special_tokens=False, clean_up_tokenization_spaces=True): """ Converts a sequence of ids (integer) in a string, using the tokenizer and vocabulary with options to remove special tokens and clean up tokenization spaces. Similar to doing ``self.convert_tokens_to_string(self.convert_ids_to_tokens(token_ids))``. Args: token_ids: list of tokenized input ids. Can be obtained using the `encode` or `encode_plus` methods. skip_special_tokens: if set to True, will replace special tokens. clean_up_tokenization_spaces: if set to True, will clean up the tokenization spaces. """ filtered_tokens = self.convert_ids_to_tokens(token_ids, skip_special_tokens=skip_special_tokens) # To avoid mixing byte-level and unicode for byte-level BPT # we need to build string separatly for added tokens and byte-level tokens # cf. https://github.com/huggingface/transformers/issues/1133 sub_texts = [] current_sub_text = [] for token in filtered_tokens: if skip_special_tokens and token in self.all_special_ids: continue if token in self.added_tokens_encoder: if current_sub_text: sub_texts.append(self.convert_tokens_to_string(current_sub_text)) current_sub_text = [] sub_texts.append(" " + token) else: current_sub_text.append(token) if current_sub_text: sub_texts.append(self.convert_tokens_to_string(current_sub_text)) text = ''.join(sub_texts) if clean_up_tokenization_spaces: clean_text = self.clean_up_tokenization(text) return clean_text else: return text def special_tokens_map(self): """ A dictionary mapping special token class attribute (cls_token, unk_token...) to their values ('<unk>', '<cls>'...) """ set_attr = {} for attr in self.SPECIAL_TOKENS_ATTRIBUTES: attr_value = getattr(self, "_" + attr) if attr_value: set_attr[attr] = attr_value return set_attr def all_special_tokens(self): """ List all the special tokens ('<unk>', '<cls>'...) mapped to class attributes (cls_token, unk_token...). """ all_toks = [] set_attr = self.special_tokens_map for attr_value in set_attr.values(): all_toks = all_toks + (list(attr_value) if isinstance(attr_value, (list, tuple)) else [attr_value]) all_toks = list(set(all_toks)) return all_toks def all_special_ids(self): """ List the vocabulary indices of the special tokens ('<unk>', '<cls>'...) mapped to class attributes (cls_token, unk_token...). """ all_toks = self.all_special_tokens all_ids = list(self._convert_token_to_id(t) for t in all_toks) return all_ids def clean_up_tokenization(out_string): """ Clean up a list of simple English tokenization artifacts like spaces before punctuations and abreviated forms. """ out_string = out_string.replace(' .', '.').replace(' ?', '?').replace(' !', '!').replace(' ,', ',' ).replace(" ' ", "'").replace(" n't", "n't").replace(" 'm", "'m").replace(" do not", " don't" ).replace(" 's", "'s").replace(" 've", "'ve").replace(" 're", "'re") return out_string def normalize(s): """ Normalize strings to space joined chars. Args: s: a list of strings. Returns: A list of normalized strings. """ if not s: return s normalized = [] for ss in s: tokens = [c for c in list(ss) if len(c.strip()) != 0] normalized.append(' '.join(tokens)) return normalized def compute_bleu_rouge(pred_dict, ref_dict, bleu_order=4): """ Compute bleu and rouge scores. """ assert set(pred_dict.keys()) == set(ref_dict.keys()), \ "missing keys: {}".format(set(ref_dict.keys()) - set(pred_dict.keys())) scores = {} bleu_scores, _ = Bleu(bleu_order).compute_score(ref_dict, pred_dict) for i, bleu_score in enumerate(bleu_scores): scores['Bleu-%d' % (i + 1)] = bleu_score rouge_score, _ = Rouge().compute_score(ref_dict, pred_dict) scores['Rouge-L'] = rouge_score return scores The provided code snippet includes necessary dependencies for implementing the `run_generation_hf` function. Write a Python function `def run_generation_hf(pretrain_model_path, output_dir, task_type, train_file_path=None, dataset_name="text", dev_file_path=None, child_tuning_type=None, reserve_p=0.2, sequence_length=128, target_length=100, map_function=None, filter_function=None, save_strategy="steps", save_total_limit=1, seed=42, config_args=None, num_train_epochs=3, **kwargs, )` to solve the following problem: TODO Run a generation task with transformers code. :param pretrain_model_path: The local dir of pretrained model :param output_dir: The output directory where the model predictions and checkpoints will be written :param task_type: The task type, only support generation currently :param train_file_path: The local dir of train file :param dataset_name: The dataset name passed into datasets.load_dataset. Default will be "text" :param dev_file_path: The local dir of dev file, which is used in cross-validation in training. :param child_tuning_type: The child_tuning type. Can be "ChildTuning-F", "ChildTuning-D" or None :param reserve_p: the drop-out rate of child_tuning, default 0.2 :param sequence_length: The max sequence length for padding :param target_length: The max target length for padding in generative task :param map_function: An optional map function, will be used with datasets.map() :param filter_function: An optional filter function, will be used with datasets.filter() :param save_strategy: TrainingArguments. :param save_total_limit: TrainingArguments. :param seed: Random seed, default 42. :param num_train_epochs: Total number of training epochs to perform, default 3.0. :param kwargs: Other optional hyper-parameters which is used in TrainingArguments. :return: None Here is the function: def run_generation_hf(pretrain_model_path, output_dir, task_type, train_file_path=None, dataset_name="text", dev_file_path=None, child_tuning_type=None, reserve_p=0.2, sequence_length=128, target_length=100, map_function=None, filter_function=None, save_strategy="steps", save_total_limit=1, seed=42, config_args=None, num_train_epochs=3, **kwargs, ): """ TODO Run a generation task with transformers code. :param pretrain_model_path: The local dir of pretrained model :param output_dir: The output directory where the model predictions and checkpoints will be written :param task_type: The task type, only support generation currently :param train_file_path: The local dir of train file :param dataset_name: The dataset name passed into datasets.load_dataset. Default will be "text" :param dev_file_path: The local dir of dev file, which is used in cross-validation in training. :param child_tuning_type: The child_tuning type. Can be "ChildTuning-F", "ChildTuning-D" or None :param reserve_p: the drop-out rate of child_tuning, default 0.2 :param sequence_length: The max sequence length for padding :param target_length: The max target length for padding in generative task :param map_function: An optional map function, will be used with datasets.map() :param filter_function: An optional filter function, will be used with datasets.filter() :param save_strategy: TrainingArguments. :param save_total_limit: TrainingArguments. :param seed: Random seed, default 42. :param num_train_epochs: Total number of training epochs to perform, default 3.0. :param kwargs: Other optional hyper-parameters which is used in TrainingArguments. :return: None """ # sofa custom code if config_args is None: config_args = {} from ... import environ environ("huggingface") # end from transformers import TrainingArguments from transformers import Trainer, set_seed import datasets from datasets import load_dataset, interleave_datasets from transformers import AutoTokenizer, AutoModelForSeq2SeqLM from transformers import TrainerCallback, TrainerState, TrainerControl from transformers.tokenization_utils import PreTrainedTokenizer # sofa dureader_eval from ...utils.dureader_eval import normalize, compute_bleu_rouge # sofa child_tuning from ...utils import apply_child_tuning_to_trainer cache_dir = ".cache" if "cache_dir" in kwargs: cache_dir = kwargs["cache_dir"] set_seed(seed) # assert type(label) in (str, types.FunctionType) logger.info(f"Cuda available:{torch.cuda.is_available()}") # prepare data train_datasets = None dev_datasets = None def get_files(files_or_path): if type(files_or_path) is str: if os.path.isfile(files_or_path): return files_or_path if os.path.isdir(files_or_path): return [os.path.join(files_or_path, f) for f in os.listdir(files_or_path)] if type(files_or_path) is list: return files_or_path if train_file_path is not None: train_files = get_files(train_file_path) data_files = {"train": train_files} train_datasets = load_dataset(dataset_name, split="train", data_files=data_files) if train_datasets is None: logger.error(f"dataset_name and train_file_path cannot both be None") if dev_file_path is not None: dev_files = get_files(dev_file_path) data_files = {"dev": dev_files} dev_datasets = load_dataset(dataset_name, split="dev", data_files=data_files) if filter_function is not None: train_datasets = train_datasets.filter(filter_function) if dev_datasets: dev_datasets = dev_datasets.filter(filter_function) if map_function is not None: train_datasets = train_datasets.map(map_function) if dev_datasets: dev_datasets = dev_datasets.map(map_function) if task_type != "generation": raise RuntimeError(f"Unsupported task type:{task_type}") def split_text(example): text_a, text_b = example[dataset_name].split('\t') return {"text_a": text_a, "text_b": text_b} train_datasets = train_datasets.map(split_text, remove_columns=["text"]) if dev_datasets: dev_datasets = dev_datasets.map(split_text, remove_columns=["text"]) tokenizer = AutoTokenizer.from_pretrained(pretrain_model_path) model = AutoModelForSeq2SeqLM.from_pretrained(pretrain_model_path) kwargs_for_training = {} for p in TrainingArguments.__dataclass_fields__.keys(): if p in kwargs: kwargs_for_training[p] = kwargs[p] kwargs_for_training["remove_unused_columns"] = False training_args = TrainingArguments(output_dir=output_dir, save_strategy=save_strategy, save_total_limit=save_total_limit, num_train_epochs=num_train_epochs, **kwargs_for_training) def tokenize_function(example): input_tokens = ["[CLS]"] + tokenizer.tokenize(example["text_a"]) + ["[SEP]"] if len(input_tokens) > sequence_length: input_tokens = input_tokens[:sequence_length-1] + ["[SEP]"] input_ids = tokenizer.convert_tokens_to_ids(input_tokens) input_mask = [1] * len(input_ids) segment_ids = [0] * len(input_ids) while len(input_ids) < sequence_length: input_ids.append(0) input_mask.append(0) segment_ids.append(0) target_tokens = ["[CLS]"] + tokenizer.tokenize(example["text_b"]) + ["[SEP]"] if len(target_tokens) > target_length: target_tokens = target_tokens[:target_length-1] + ["[SEP]"] target_ids = tokenizer.convert_tokens_to_ids(target_tokens) while len(target_ids) < target_length: target_ids.append(0) return {"input_ids": input_ids, "input_mask": input_mask, "segment_ids": segment_ids, "target_ids": target_ids} full_train_dataset = train_datasets.map(tokenize_function, remove_columns=["text_a", "text_b"]) if dev_datasets: full_eval_dataset = dev_datasets.map(tokenize_function, remove_columns=["text_a", "text_b"]) else: full_eval_dataset = None # Currently only supports palm model, better compatibility will be provided in the future class GeneratorCallback(TrainerCallback): def __init__(self, tokenizer: PreTrainedTokenizer, model: nn.Module, dataset: "datasets.Dataset", eval_batch_size: int = 16, num_workers: int = 1): self.tokenizer = tokenizer self.model = model self.eval_iters = len(dataset) // eval_batch_size sampler = torch.utils.data.SequentialSampler(dataset) self.data_loader = torch.utils.data.DataLoader(dataset, batch_size=eval_batch_size, sampler=sampler, num_workers=num_workers, pin_memory=True, collate_fn=model.palm_batchify) def on_epoch_end(self, args: TrainingArguments, state: TrainerState, control: TrainerControl, **kwargs): """Evaluation.""" device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") tokenizer, model, eval_iters, data_iterator = self.tokenizer, self.model, self.eval_iters, iter(self.data_loader) # Turn on evaluation mode which disables dropout. model.eval() pred_dict = {} ref_dict = {} vocab_size = 21127 beam_generator = TextGenerator(model, tokenizer, tokenizer.vocab) counter_all = 0 with torch.no_grad(): iteration = 0 while iteration < eval_iters: iteration += 1 # Forward evaluation. # tokens, types, padding_mask, target_tokens, target_labels, dec_loss_mask, attention_mask, position_ids = self.get_batch(data_iterator, args, timers) data = next(data_iterator) tokens, types, padding_mask, target_labels = data["input_tokens"].to(device), data["token_type_ids"].to(device), data["attention_mask"].to(device), data["labels"] batch_size = tokens.size(0) # sequence_output = self.model.bert(input_ids, token_type_ids, attention_mask,output_all_encoded_layers=False, checkpoint_activations=args.checkpoint_activations) encoder_inputs = [tokens, types, padding_mask] result_dict = beam_generator.translate_batch(encoder_inputs) pred_list = result_dict["predictions"] target_list = target_labels.cpu().numpy().tolist() for i in range(batch_size): pred_ids = pred_list[i][0].cpu().numpy().tolist() for j in range(len(pred_ids)): if pred_ids[j] > vocab_size-1: pred_ids[j] = 100 gold = tokenizer.convert_ids_to_tokens(target_list[i]) pred = tokenizer.convert_ids_to_tokens(pred_ids) gold_string = "".join(gold).replace("##", "").split("[SEP]")[0].replace("[CLS]", "").replace("[SEP]", "").replace("[UNK]", "") pred_string = "".join(pred).replace("##", "").split("[SEP]")[0].replace("[CLS]", "").replace("[SEP]", "").replace("[UNK]", "") if len(gold_string) < 3: continue pred_dict[str(counter_all)] = normalize([pred_string]) ref_dict[str(counter_all)] = normalize([gold_string]) counter_all += 1 bleu_rouge = compute_bleu_rouge(pred_dict, ref_dict) print (ref_dict["0"]) print (pred_dict["0"]) print("test result %d: " % counter_all, bleu_rouge) trainer = Trainer(model=model, args=training_args, data_collator=model.palm_batchify, train_dataset=full_train_dataset, callbacks=[GeneratorCallback(tokenizer, model, full_eval_dataset)]) # apply child_tuning or not. if child_tuning_type is not None: logger.info("Applying child-tuning.") apply_child_tuning_to_trainer(trainer, mode=child_tuning_type, reserve_p=reserve_p) trainer.train()
TODO Run a generation task with transformers code. :param pretrain_model_path: The local dir of pretrained model :param output_dir: The output directory where the model predictions and checkpoints will be written :param task_type: The task type, only support generation currently :param train_file_path: The local dir of train file :param dataset_name: The dataset name passed into datasets.load_dataset. Default will be "text" :param dev_file_path: The local dir of dev file, which is used in cross-validation in training. :param child_tuning_type: The child_tuning type. Can be "ChildTuning-F", "ChildTuning-D" or None :param reserve_p: the drop-out rate of child_tuning, default 0.2 :param sequence_length: The max sequence length for padding :param target_length: The max target length for padding in generative task :param map_function: An optional map function, will be used with datasets.map() :param filter_function: An optional filter function, will be used with datasets.filter() :param save_strategy: TrainingArguments. :param save_total_limit: TrainingArguments. :param seed: Random seed, default 42. :param num_train_epochs: Total number of training epochs to perform, default 3.0. :param kwargs: Other optional hyper-parameters which is used in TrainingArguments. :return: None
18,299
import torch import deepspeed import random import os import numpy as np from sofa.utils import mpu The provided code snippet includes necessary dependencies for implementing the `set_random_seed` function. Write a Python function `def set_random_seed(seed)` to solve the following problem: Set random seed for reproducability. Here is the function: def set_random_seed(seed): """Set random seed for reproducability.""" if seed is not None and seed > 0: random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) mpu.model_parallel_cuda_manual_seed(seed) else: raise ValueError('Seed ({}) should be a positive integer.'.format(seed))
Set random seed for reproducability.
18,300
import torch import deepspeed import random import os import numpy as np from sofa.utils import mpu def set_deepspeed_activation_checkpointing(args): deepspeed.checkpointing.configure(mpu, deepspeed_config=args.deepspeed_config, num_checkpoints=args.num_layers) mpu.checkpoint = deepspeed.checkpointing.checkpoint mpu.get_cuda_rng_tracker = deepspeed.checkpointing.get_cuda_rng_tracker mpu.model_parallel_cuda_manual_seed = deepspeed.checkpointing.model_parallel_cuda_manual_seed The provided code snippet includes necessary dependencies for implementing the `initialize_distributed` function. Write a Python function `def initialize_distributed(args)` to solve the following problem: Initialize torch.distributed. Here is the function: def initialize_distributed(args): """Initialize torch.distributed.""" # Manually set the device ids. device = args.rank % torch.cuda.device_count() if args.local_rank is not None: device = args.local_rank torch.cuda.set_device(device) # Call the init process init_method = 'tcp://' master_ip = os.getenv('MASTER_ADDR', 'localhost') master_port = os.getenv('MASTER_PORT', '6000') init_method += master_ip + ':' + master_port torch.distributed.init_process_group( backend=args.distributed_backend, world_size=args.world_size, rank=args.rank, init_method=init_method) # Set the model-parallel / data-parallel communicators. mpu.initialize_model_parallel(args.model_parallel_size) if args.deepspeed and args.deepspeed_activation_checkpointing: set_deepspeed_activation_checkpointing(args)
Initialize torch.distributed.
18,301
import math import torch import torch.utils.checkpoint from packaging import version from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...utils.activations import ACT2FN, gelu from ...utils.file_utils import ( add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, replace_return_docstrings, ) from ...utils.modeling_outputs import ( BaseModelOutputWithPastAndCrossAttentions, BaseModelOutputWithPoolingAndCrossAttentions, CausalLMOutputWithCrossAttentions, MaskedLMOutput, MultipleChoiceModelOutput, QuestionAnsweringModelOutput, SequenceClassifierOutput, TokenClassifierOutput, ) from ...utils.modeling_utils import ( PreTrainedModel, apply_chunking_to_forward, find_pruneable_heads_and_indices, prune_linear_layer, ) from ...utils import logging from .configuration_roberta import RobertaConfig The provided code snippet includes necessary dependencies for implementing the `create_position_ids_from_input_ids` function. Write a Python function `def create_position_ids_from_input_ids(input_ids, padding_idx, past_key_values_length=0)` to solve the following problem: Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding symbols are ignored. This is modified from fairseq's `utils.make_positions`. Args: x: torch.Tensor x: Returns: torch.Tensor Here is the function: def create_position_ids_from_input_ids(input_ids, padding_idx, past_key_values_length=0): """ Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding symbols are ignored. This is modified from fairseq's `utils.make_positions`. Args: x: torch.Tensor x: Returns: torch.Tensor """ # The series of casts and type-conversions here are carefully balanced to both work with ONNX export and XLA. mask = input_ids.ne(padding_idx).int() incremental_indices = (torch.cumsum(mask, dim=1).type_as(mask) + past_key_values_length) * mask return incremental_indices.long() + padding_idx
Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding symbols are ignored. This is modified from fairseq's `utils.make_positions`. Args: x: torch.Tensor x: Returns: torch.Tensor
18,302
import json import os from functools import lru_cache from typing import TYPE_CHECKING, List, Optional, Tuple import regex as re from ...utils.tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging The provided code snippet includes necessary dependencies for implementing the `bytes_to_unicode` function. Write a Python function `def bytes_to_unicode()` to solve the following problem: Returns list of utf-8 byte and a mapping to unicode strings. We specifically avoids mapping to whitespace/control characters the bpe code barfs on. The reversible bpe codes work on unicode strings. This means you need a large # of unicode characters in your vocab if you want to avoid UNKs. When you're at something like a 10B token dataset you end up needing around 5K for decent coverage. This is a significant percentage of your normal, say, 32K bpe vocab. To avoid that, we want lookup tables between utf-8 bytes and unicode strings. Here is the function: def bytes_to_unicode(): """ Returns list of utf-8 byte and a mapping to unicode strings. We specifically avoids mapping to whitespace/control characters the bpe code barfs on. The reversible bpe codes work on unicode strings. This means you need a large # of unicode characters in your vocab if you want to avoid UNKs. When you're at something like a 10B token dataset you end up needing around 5K for decent coverage. This is a significant percentage of your normal, say, 32K bpe vocab. To avoid that, we want lookup tables between utf-8 bytes and unicode strings. """ bs = ( list(range(ord("!"), ord("~") + 1)) + list(range(ord("¡"), ord("¬") + 1)) + list(range(ord("®"), ord("ÿ") + 1)) ) cs = bs[:] n = 0 for b in range(2 ** 8): if b not in bs: bs.append(b) cs.append(2 ** 8 + n) n += 1 cs = [chr(n) for n in cs] return dict(zip(bs, cs))
Returns list of utf-8 byte and a mapping to unicode strings. We specifically avoids mapping to whitespace/control characters the bpe code barfs on. The reversible bpe codes work on unicode strings. This means you need a large # of unicode characters in your vocab if you want to avoid UNKs. When you're at something like a 10B token dataset you end up needing around 5K for decent coverage. This is a significant percentage of your normal, say, 32K bpe vocab. To avoid that, we want lookup tables between utf-8 bytes and unicode strings.
18,303
import json import os from functools import lru_cache from typing import TYPE_CHECKING, List, Optional, Tuple import regex as re from ...utils.tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging The provided code snippet includes necessary dependencies for implementing the `get_pairs` function. Write a Python function `def get_pairs(word)` to solve the following problem: Return set of symbol pairs in a word. Word is represented as tuple of symbols (symbols being variable-length strings). Here is the function: def get_pairs(word): """ Return set of symbol pairs in a word. Word is represented as tuple of symbols (symbols being variable-length strings). """ pairs = set() prev_char = word[0] for char in word[1:]: pairs.add((prev_char, char)) prev_char = char return pairs
Return set of symbol pairs in a word. Word is represented as tuple of symbols (symbols being variable-length strings).
18,304
import os import json import torch import random import logging import h5py import torch.distributed as dist from torch.utils.data import Dataset, Subset from multiprocessing import Pool from .tokenization_plug import BertTokenizer from .data_plug import get_train_val_test_data_clean from sofa.utils import mpu from .data_plug import InputExample, DataProcessor, \ create_instances_from_document, \ convert_instance_to_feature, \ make_data_loader, get_spli class PalmHDF5Dataset(Dataset): """HDF5 dataset""" def __init__(self, args, input_file, tokenizer, vocab_words, iter_per_epoch, is_training=True): self.oss_file = input_file #[dist.get_rank()] self.input_file = self.oss_file.split('/')[-1]+str(dist.get_rank()) if args.environ == 'jiuding' else self.oss_file self.input_json_file = self.input_file+'.json' if args.environ == 'jiuding' else self.oss_file.replace('token.', 'token.json') self.is_training = is_training self.args = args self.sent_to_doc = json.load(open(self.input_json_file,'r'))['dict'] self.total_len = len(self.sent_to_doc) self.vocab_words = vocab_words self.tokenizer = tokenizer self.iter_per_epoch = iter_per_epoch def __len__(self): return self.iter_per_epoch def remove_local_file(self): os.remove(self.input_file) os.remove(self.input_json_file) logger.info("Remove local token file & json file!") def __getitem__(self, index): with h5py.File(self.input_file, 'r') as all_documents: document_index = str(self.sent_to_doc[random.randint(0, self.total_len - 1)]) instance, lenth = create_instances_from_document( self.args, document_index, all_documents, self.vocab_words, random, self.tokenizer, index) feature = convert_instance_to_feature(self.args, instance, self.tokenizer, lenth) return feature class BertTokenizer(PreTrainedTokenizer): """Runs end-to-end tokenization: punctuation splitting + wordpiece""" def __init__(self, vocab_file, do_lower_case=True, max_len=None, do_basic_tokenize=True, never_split=("[UNK]", "[SEP]", "[PAD]", "[CLS]", "[MASK]")): """Constructs a BertTokenizer. Args: vocab_file: Path to a one-wordpiece-per-line vocabulary file do_lower_case: Whether to lower case the input Only has an effect when do_wordpiece_only=False do_basic_tokenize: Whether to do basic tokenization before wordpiece. max_len: An artificial maximum length to truncate tokenized sequences to; Effective maximum length is always the minimum of this value (if specified) and the underlying BERT model's sequence length. never_split: List of tokens which will never be split during tokenization. Only has an effect when do_wordpiece_only=False """ if not os.path.isfile(vocab_file): raise ValueError( "Can't find a vocabulary file at path '{}'. To load the vocabulary from a Google pretrained " "model use `tokenizer = BertTokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`".format(vocab_file)) self.vocab = load_vocab(vocab_file) self.ids_to_tokens = collections.OrderedDict( [(ids, tok) for tok, ids in self.vocab.items()]) self.do_basic_tokenize = do_basic_tokenize if do_basic_tokenize: self.basic_tokenizer = BasicTokenizer(do_lower_case=do_lower_case, never_split=never_split) self.wordpiece_tokenizer = WordpieceTokenizer(vocab=self.vocab) self.max_len = max_len if max_len is not None else int(1e12) def tokenize(self, text): if self.do_basic_tokenize: split_tokens = [] for token in self.basic_tokenizer.tokenize(text): for sub_token in self.wordpiece_tokenizer.tokenize(token): split_tokens.append(sub_token) else: split_tokens = self.wordpiece_tokenizer.tokenize(text) return split_tokens def convert_tokens_to_ids(self, tokens): """Converts a sequence of tokens into ids using the vocab.""" ids = [] for token in tokens: ids.append(self.vocab[token]) if len(ids) > self.max_len: logger.warning( "Token indices sequence length is longer than the specified maximum " " sequence length for this BERT model ({} > {}). Running this" " sequence through BERT will result in indexing errors".format(len(ids), self.max_len) ) return ids def convert_ids_to_tokens(self, ids): """Converts a sequence of ids in wordpiece tokens using the vocab.""" tokens = [] for i in ids: tokens.append(self.ids_to_tokens[i]) return tokens def from_pretrained(cls, pretrained_model_name_or_path, cache_dir=None, *inputs, **kwargs): """ Instantiate a PreTrainedBertModel from a pre-trained model file. Download and cache the pre-trained model file if needed. """ if pretrained_model_name_or_path in PRETRAINED_VOCAB_ARCHIVE_MAP: vocab_file = PRETRAINED_VOCAB_ARCHIVE_MAP[pretrained_model_name_or_path] else: vocab_file = pretrained_model_name_or_path if os.path.isdir(vocab_file): vocab_file = os.path.join(vocab_file, VOCAB_NAME) # redirect to the cache, if necessary try: resolved_vocab_file = cached_path(vocab_file, cache_dir=cache_dir) except EnvironmentError: logger.error( "Model name '{}' was not found in model name list ({}). " "We assumed '{}' was a path or url but couldn't find any file " "associated to this path or url.".format( pretrained_model_name_or_path, ', '.join(PRETRAINED_VOCAB_ARCHIVE_MAP.keys()), vocab_file)) return None if resolved_vocab_file == vocab_file: logger.info("loading vocabulary file {}".format(vocab_file)) else: logger.info("loading vocabulary file {} from cache at {}".format( vocab_file, resolved_vocab_file)) if pretrained_model_name_or_path in PRETRAINED_VOCAB_POSITIONAL_EMBEDDINGS_SIZE_MAP: # if we're using a pretrained model, ensure the tokenizer wont index sequences longer # than the number of positional embeddings max_len = PRETRAINED_VOCAB_POSITIONAL_EMBEDDINGS_SIZE_MAP[pretrained_model_name_or_path] kwargs['max_len'] = min(kwargs.get('max_len', int(1e12)), max_len) # Instantiate tokenizer. tokenizer = cls(resolved_vocab_file, *inputs, **kwargs) # apply the change from DataConfig.setup_tokenizer_for_structbert tokenizer.num_tokens = len(tokenizer.vocab) tokenizer.num_type_tokens = 3 return tokenizer def make_data_loader(dataset, batch_size, args): shuffle = args.shuffle if shuffle: #if not args.struct_bert_dataset and not args.palm_dataset: # sampler = data_utils.samplers.RandomSampler(dataset, replacement=True, num_samples=batch_size*args.train_iters) #else: if 1: sampler = data_utils.samplers.RandomSampler(dataset, replacement=False) else: sampler = torch.utils.data.SequentialSampler(dataset) world_size = torch.distributed.get_world_size( group=mpu.get_data_parallel_group()) rank = torch.distributed.get_rank(group=mpu.get_data_parallel_group()) distributed = world_size > 1 drop_last = distributed if not args.struct_bert_dataset and not args.palm_dataset and not args.image_dataset: if distributed: batch_sampler = data_utils.samplers.DistributedBatchSampler(sampler, batch_size, shuffle, #if not shuffle, than don't drop_last rank, world_size) else: batch_sampler = torch.utils.data.BatchSampler(sampler, batch_size, shuffle) #if not shuffle, than don't drop_last data_loader = torch.utils.data.DataLoader(dataset, batch_sampler=batch_sampler, num_workers=args.num_workers, pin_memory=True) else: _worker_init_fn = WorkerInitObj(args.seed + torch.distributed.get_rank()) data_loader = torch.utils.data.DataLoader(dataset, batch_size=batch_size, sampler=sampler, num_workers=args.num_workers, pin_memory=True, collate_fn=batchify if args.struct_bert_dataset else PalmBatchify, worker_init_fn=_worker_init_fn) return data_loader def get_split(args): """ Get dataset splits from comma separated string list """ splits = [] if args.split.find(',') != -1: splits = [float(s) for s in args.split.split(',')] elif args.split.find('/') != -1: splits = [float(s) for s in args.split.split('/')] else: splits = [float(args.split)] split_total = sum(splits) if split_total < 1.: splits.append(1-split_total) while len(splits) < 3: splits.append(0.) splits = splits[:3] if args.valid_data is not None: splits[1] = 0. if args.test_data is not None: splits[2] = 0. final_sum = sum(splits) return [s/final_sum for s in splits] def make_palm_loaders(args): #world_size = torch.distributed.get_world_size( # group=mpu.get_data_parallel_group()) #batch_size = args.batch_size * world_size #we don't need multiple world_size because we don't use distributed batch sampler batch_size = args.batch_size eval_batch_size = batch_size if args.eval_batch_size is not None: eval_batch_size = args.eval_batch_size #* world_size seq_length = args.seq_length if seq_length < 0: seq_length = seq_length# * world_size eval_seq_length = args.eval_seq_length if eval_seq_length is not None and eval_seq_length < 0: eval_seq_length = eval_seq_length# * world_size split = get_split(args) tokenizer = BertTokenizer.from_pretrained(args.tokenizer_model_type) tokenizer.num_tokens = len(tokenizer.vocab) tokenizer.num_type_tokens = 3 args.tokenizer = tokenizer args.cls_token, args.sep_token, args.mask_token = '[CLS]', '[SEP]', '[MASK]' args.bos_token, args.eos_token = '[CLS]', '[SEP]' args.vocab_words = list(tokenizer.vocab) #add palm args args.start_length = 30 args.tgt_length = 128 args.full_sent_prob = 0.3 #add structbert args args.environ = 'local' args.dataset_has_lang_id = False args.one_sentence = False args.short_seq_prob = 0 args.ns_type = 3 args.jieba = False args.do_whole_word_mask = False args.masked_lm_prob = 0.15 args.do_mask_rate_range = False args.all_token_mlm = False args.predict_context_prob = 0 args.continue_mask_prob = 0 args.shuffle_order_prob = 0 args.tokenizer_type = 'bert' args.do_train = True args.do_valid = True args.do_test = False data_parallel_rank = torch.distributed.get_rank(group=mpu.get_data_parallel_group()) train = PalmHDF5Dataset(args, args.sub_train_lst[data_parallel_rank], args.tokenizer, args.vocab_words, args.train_iters * args.gradient_accumulation_steps * args.batch_size // args.num_epochs, is_training=True) valid = Subset(train, list(range(args.eval_iters * eval_batch_size))) train = make_data_loader(train, batch_size, args) valid = make_data_loader(valid, eval_batch_size, args) return (train, valid, None), tokenizer
null
18,305
import os import json import torch import random import logging import h5py import torch.distributed as dist from torch.utils.data import Dataset, Subset from multiprocessing import Pool from .tokenization_plug import BertTokenizer from .data_plug import get_train_val_test_data_clean from sofa.utils import mpu from .data_plug import InputExample, DataProcessor, \ create_instances_from_document, \ convert_instance_to_feature, \ make_data_loader, get_spli def PalmBatchify(batch): input_ids, input_mask, segment_ids, target_ids, masked_lm_positions, masked_lm_ids, masked_lm_weights = \ list(), list(), list(), list(), list(), list(), list() for feature in batch: input_ids.append(torch.tensor(feature["input_ids"], dtype=torch.long)) input_mask.append(torch.tensor(feature["input_mask"], dtype=torch.long)) segment_ids.append(torch.tensor(feature["segment_ids"], dtype=torch.long)) target_ids.append(torch.tensor(feature["target_ids"], dtype=torch.long)) if "masked_lm_positions" in feature: masked_lm_positions.append(torch.tensor(feature["masked_lm_positions"], dtype=torch.long)) masked_lm_ids.append(torch.tensor(feature["masked_lm_ids"], dtype=torch.long)) masked_lm_weights.append(torch.tensor(feature["masked_lm_weights"], dtype=torch.float)) input_ids = torch.stack(input_ids, 0) input_mask = torch.stack(input_mask, 0) segment_ids = torch.stack(segment_ids, 0) target_ids = torch.stack(target_ids, 0) if "masked_lm_positions" not in batch[0]: return {'text':input_ids, 'pad_mask':input_mask, 'types':segment_ids, 'target_ids':target_ids} else: masked_lm_positions = torch.stack(masked_lm_positions, 0) masked_lm_ids = torch.stack(masked_lm_ids, 0) masked_lm_weights = torch.stack(masked_lm_weights, 0) masked_lm_ids_ = torch.zeros(input_ids.size()).long() masked_lm_ids_.scatter_(1, masked_lm_positions, masked_lm_ids) masked_lm_ids_[:,0] = 0 mask = torch.zeros(input_ids.size()).long().scatter(1, masked_lm_positions, 1) mask[:,0] = 0 return {'text':input_ids, 'pad_mask':input_mask, 'types':segment_ids, 'target_ids':target_ids, 'masked_lm_positions':masked_lm_positions, 'mask_labels':masked_lm_ids_, 'mask':mask}
null
18,306
import os import json import torch import random import logging import h5py import torch.distributed as dist from torch.utils.data import Dataset, Subset from multiprocessing import Pool from .tokenization_plug import BertTokenizer from .data_plug import get_train_val_test_data_clean from sofa.utils import mpu from .data_plug import InputExample, DataProcessor, \ create_instances_from_document, \ convert_instance_to_feature, \ make_data_loader, get_spli def get_masks_and_position_ids(data, eod_token, reset_position_ids=False, reset_attention_mask=False): # Extract batch size and sequence length. batch_size, seq_length = data.size() # Attention mask (lower triangular). if reset_attention_mask: att_mask_batch = batch_size else: att_mask_batch = 1 attention_mask = torch.tril(torch.ones( (att_mask_batch, seq_length, seq_length), device=data.device)).view( att_mask_batch, 1, seq_length, seq_length) # Loss mask. loss_mask = torch.ones(data.size(), dtype=torch.float, device=data.device) loss_mask[data == eod_token] = 0.0 # Position ids. position_ids = torch.arange(seq_length, dtype=torch.long, device=data.device) position_ids = position_ids.unsqueeze(0).expand_as(data) # We need to clone as the ids will be modifed based on batch index. if reset_position_ids: position_ids = position_ids.clone() if reset_position_ids or reset_attention_mask: # Loop through the batches: for b in range(batch_size): # Find indecies where EOD token is. eod_index = position_ids[b, data[b] == eod_token] # Detach indecies from positions if going to modify positions. if reset_position_ids: eod_index = eod_index.clone() # Loop through EOD indecies: prev_index = 0 for j in range(eod_index.size()[0]): i = eod_index[j] # Mask attention loss. if reset_attention_mask: attention_mask[b, 0, (i+1):, :(i+1)] = 0 # Reset positions. if reset_position_ids: position_ids[b, (i+1):] -= (i + 1 - prev_index) prev_index = i + 1 return attention_mask, loss_mask, position_ids
null
18,307
import os import json import torch import random import logging import h5py import torch.distributed as dist from torch.utils.data import Dataset, Subset from multiprocessing import Pool from .tokenization_plug import BertTokenizer from .data_plug import get_train_val_test_data_clean from sofa.utils import mpu from .data_plug import InputExample, DataProcessor, \ create_instances_from_document, \ convert_instance_to_feature, \ make_data_loader, get_spli class FeatureDataset(Dataset): """Squad dataset""" def __init__(self, features): self.features = features def __len__(self): return len(self.features) def __getitem__(self, index): feat = self.features[index] feat_dict = {'input_ids': feat.input_ids, 'input_mask': feat.input_mask, 'segment_ids': feat.segment_ids, 'target_ids': feat.target_ids } return feat_dict #return self.features[index] def lengths(self): return [len(feature.input_ids) for feature in self.features] def convert_examples_to_features(args, examples, max_seq_length, tokenizer, is_training=False): features = [] for example in examples: input_tokens = ["[CLS]"] + tokenizer.tokenize(example.text_a) + ["[SEP]"] if len(input_tokens) > max_seq_length: input_tokens = input_tokens[:max_seq_length-1] + ["[SEP]"] input_ids = tokenizer.convert_tokens_to_ids(input_tokens) input_mask = [1] * len(input_ids) segment_ids = [0] * len(input_ids) while len(input_ids) < max_seq_length: input_ids.append(0) input_mask.append(0) segment_ids.append(0) target_tokens = ["[CLS]"] + tokenizer.tokenize(example.text_b) + ["[SEP]"] if len(target_tokens) > args.tgt_length: target_tokens = target_tokens[:args.tgt_length-1] + ["[SEP]"] target_ids = tokenizer.convert_tokens_to_ids(target_tokens) while len(target_ids) < args.tgt_length: target_ids.append(0) features.append(InputFeatures( input_ids=input_ids, input_mask=input_mask, segment_ids=segment_ids, target_ids=target_ids)) return features def get_train_val_test_data_clean(args, tokenizer, train, dev, test): (train_data, val_data, test_data) = (None, None, None) if mpu.get_model_parallel_rank() == 0: data_config = configure_data(tokenizer) data_config.set_defaults(data_set_type='BERT', transpose=False) (train_data, val_data, test_data), _ = data_config.apply(args, train, dev, test) return train_data, val_data, test_data def data_preparation_nlg(tokenizer, processor, args): args.fast_train = False if mpu.get_model_parallel_rank() == 0: dev_examples = processor.get_dev_examples(args.dev_data) if args.dev_data else [] # should be none [] test_examples = processor.get_test_examples(args.test_data) if args.test_data else [] # suppose to be [] if len(dev_examples) == 0: train_examples, dev_examples = processor.train_dev_split(args.train_data) else: train_examples = processor.get_train_examples(args.train_data) train_features = convert_examples_to_features(args, train_examples, args.seq_length, tokenizer, True) dev_features = convert_examples_to_features(args, dev_examples, args.seq_length, tokenizer, True) test_features = convert_examples_to_features(args, test_examples, args.seq_length, tokenizer, False) train_dataset = FeatureDataset(train_features) dev_dataset = FeatureDataset(dev_features) test_dataset = FeatureDataset(test_features) data_size = torch.cuda.LongTensor([len(train_dataset), len(dev_dataset), len(test_dataset)]) else: train_dataset, dev_dataset, test_dataset = None, None, None data_size = torch.cuda.LongTensor([0, 0, 0]) train_data, val_data, test_data = get_train_val_test_data_clean(args, tokenizer, train_dataset, dev_dataset, test_dataset) torch.distributed.broadcast(data_size, mpu.get_model_parallel_src_rank(), group=mpu.get_model_parallel_group()) args.data_size = data_size world_size = torch.distributed.get_world_size( group=mpu.get_data_parallel_group()) args.train_iters = args.data_size[0].item() // (world_size * args.batch_size) * args.num_epochs return train_data, val_data, test_data, [], args
null
18,308
from __future__ import absolute_import, division, print_function, unicode_literals import collections import os import six import unicodedata from io import open from ...utils import cached_path from ...utils.tokenization_utils import PreTrainedTokenizer, _is_control, _is_punctuation, _is_whitespace from ...utils.file_utils import logging The provided code snippet includes necessary dependencies for implementing the `load_vocab` function. Write a Python function `def load_vocab(vocab_file)` to solve the following problem: Loads a vocabulary file into a dictionary. Here is the function: def load_vocab(vocab_file): """Loads a vocabulary file into a dictionary.""" vocab = collections.OrderedDict() index = 0 with open(vocab_file, "r", encoding="utf-8") as reader: while True: token = reader.readline() if not token: break token = token.strip() vocab[token] = index index += 1 return vocab
Loads a vocabulary file into a dictionary.
18,309
from __future__ import absolute_import, division, print_function, unicode_literals import collections import os import six import unicodedata from io import open from ...utils import cached_path from ...utils.tokenization_utils import PreTrainedTokenizer, _is_control, _is_punctuation, _is_whitespace from ...utils.file_utils import logging The provided code snippet includes necessary dependencies for implementing the `whitespace_tokenize` function. Write a Python function `def whitespace_tokenize(text)` to solve the following problem: Runs basic whitespace cleaning and splitting on a piece of text. Here is the function: def whitespace_tokenize(text): """Runs basic whitespace cleaning and splitting on a piece of text.""" text = text.strip() if not text: return [] tokens = text.split() return tokens
Runs basic whitespace cleaning and splitting on a piece of text.
18,310
from __future__ import absolute_import, division, print_function, unicode_literals import collections import os import six import unicodedata from io import open from ...utils import cached_path from ...utils.tokenization_utils import PreTrainedTokenizer, _is_control, _is_punctuation, _is_whitespace from ...utils.file_utils import logging The provided code snippet includes necessary dependencies for implementing the `_is_whitespace` function. Write a Python function `def _is_whitespace(char)` to solve the following problem: Checks whether `chars` is a whitespace character. Here is the function: def _is_whitespace(char): """Checks whether `chars` is a whitespace character.""" # \t, \n, and \r are technically contorl characters but we treat them # as whitespace since they are generally considered as such. if char == " " or char == "\t" or char == "\n" or char == "\r": return True cat = unicodedata.category(char) if cat == "Zs": return True return False
Checks whether `chars` is a whitespace character.
18,311
from __future__ import absolute_import, division, print_function, unicode_literals import collections import os import six import unicodedata from io import open from ...utils import cached_path from ...utils.tokenization_utils import PreTrainedTokenizer, _is_control, _is_punctuation, _is_whitespace from ...utils.file_utils import logging The provided code snippet includes necessary dependencies for implementing the `_is_control` function. Write a Python function `def _is_control(char)` to solve the following problem: Checks whether `chars` is a control character. Here is the function: def _is_control(char): """Checks whether `chars` is a control character.""" # These are technically control characters but we count them as whitespace # characters. if char == "\t" or char == "\n" or char == "\r": return False cat = unicodedata.category(char) if cat.startswith("C"): return True return False
Checks whether `chars` is a control character.
18,312
from __future__ import absolute_import, division, print_function, unicode_literals import collections import os import six import unicodedata from io import open from ...utils import cached_path from ...utils.tokenization_utils import PreTrainedTokenizer, _is_control, _is_punctuation, _is_whitespace from ...utils.file_utils import logging The provided code snippet includes necessary dependencies for implementing the `_is_punctuation` function. Write a Python function `def _is_punctuation(char)` to solve the following problem: Checks whether `chars` is a punctuation character. Here is the function: def _is_punctuation(char): """Checks whether `chars` is a punctuation character.""" cp = ord(char) # We treat all non-letter/number ASCII as punctuation. # Characters such as "^", "$", and "`" are not in the Unicode # Punctuation class but we treat them as punctuation anyways, for # consistency. if ((cp >= 33 and cp <= 47) or (cp >= 58 and cp <= 64) or (cp >= 91 and cp <= 96) or (cp >= 123 and cp <= 126)): return True cat = unicodedata.category(char) if cat.startswith("P"): return True return False
Checks whether `chars` is a punctuation character.
18,313
from __future__ import absolute_import, division, print_function, unicode_literals import collections import os import six import unicodedata from io import open from ...utils import cached_path from ...utils.tokenization_utils import PreTrainedTokenizer, _is_control, _is_punctuation, _is_whitespace from ...utils.file_utils import logging The provided code snippet includes necessary dependencies for implementing the `printable_text` function. Write a Python function `def printable_text(text)` to solve the following problem: Returns text encoded in a way suitable for print or `tf.logging`. Here is the function: def printable_text(text): """Returns text encoded in a way suitable for print or `tf.logging`.""" # These functions want `str` for both Python2 and Python3, but in one case # it's a Unicode string and in the other it's a byte string. if six.PY3: if isinstance(text, str): return text elif isinstance(text, bytes): return text.decode("utf-8", "ignore") else: raise ValueError("Unsupported string type: %s" % (type(text))) elif six.PY2: if isinstance(text, str): return text elif isinstance(text, unicode): return text.encode("utf-8") else: raise ValueError("Unsupported string type: %s" % (type(text))) else: raise ValueError("Not running on Python2 or Python 3?")
Returns text encoded in a way suitable for print or `tf.logging`.
18,314
import os import json import torch import random import collections import logging import h5py import copy import torch.distributed as dist from torch.utils.data import Dataset, Subset from multiprocessing import Pool from itertools import repeat import multiprocessing as mp from .tokenization_plug import BertTokenizer, printable_text from sofa.utils import mpu, data_utils, print_rank_0 def configure_data(tokenizer): """add cmdline flags for configuring datasets""" # These are options that are used by data_utils, but are either # deprecated or not meant to be exposed to the command line user. # These options are intneded to be set in code by specific scripts. defaults = { 'world_size': 1, 'rank': -1, 'persist_state': 0, 'lazy': False, 'transpose': False, 'data_set_type': 'supervised', 'seq_length': 256, 'eval_seq_length': 256, 'samples_per_shard': 100 } return DataConfig(tokenizer, defaults=defaults) The provided code snippet includes necessary dependencies for implementing the `get_train_val_test_data` function. Write a Python function `def get_train_val_test_data(args)` to solve the following problem: Load the data on rank zero and boradcast number of tokens to all GPUS. Here is the function: def get_train_val_test_data(args): """Load the data on rank zero and boradcast number of tokens to all GPUS.""" (train_data, val_data, test_data) = (None, None, None) # Data loader only on rank 0 of each model parallel group. if mpu.get_model_parallel_rank() == 0: data_config = configure_data() data_config.set_defaults(data_set_type='BERT', transpose=False) (train_data, val_data, test_data), tokenizer = data_config.apply(args) before = tokenizer.num_tokens after = before multiple = args.make_vocab_size_divisible_by * \ mpu.get_model_parallel_world_size() while (after % multiple) != 0: after += 1 print_rank_0('> padded vocab (size: {}) with {} dummy ' 'tokens (new size: {})'.format( before, after - before, after)) # Need to broadcast num_tokens and num_type_tokens. token_counts = torch.cuda.LongTensor([after, tokenizer.num_type_tokens, int(args.do_train), int(args.do_valid), int(args.do_test)]) else: token_counts = torch.cuda.LongTensor([0, 0, 0, 0, 0]) # Broadcast num tokens. torch.distributed.broadcast(token_counts, mpu.get_model_parallel_src_rank(), group=mpu.get_model_parallel_group()) num_tokens = token_counts[0].item() num_type_tokens = token_counts[1].item() args.do_train = token_counts[2].item() args.do_valid = token_counts[3].item() args.do_test = token_counts[4].item() return train_data, val_data, test_data, num_tokens, num_type_tokens
Load the data on rank zero and boradcast number of tokens to all GPUS.
18,315
import os import json import torch import random import collections import logging import h5py import copy import torch.distributed as dist from torch.utils.data import Dataset, Subset from multiprocessing import Pool from itertools import repeat import multiprocessing as mp from .tokenization_plug import BertTokenizer, printable_text from sofa.utils import mpu, data_utils, print_rank_0 def make_data_loader(dataset, batch_size, args): def make_downstream_loaders(args, tokenizer, train, valid, test): world_size = torch.distributed.get_world_size( group=mpu.get_data_parallel_group()) batch_size = args.batch_size * world_size eval_batch_size = args.eval_batch_size * world_size tokenizer.num_tokens = len(tokenizer.vocab) tokenizer.num_type_tokens = 3 args.do_train = True args.do_valid = True args.do_test = True train = make_data_loader(train, batch_size, args) valid = make_data_loader(valid, eval_batch_size, args) shuffle = args.shuffle args.shuffle = False test = make_data_loader(test, eval_batch_size, args) args.shuffle = shuffle return (train, valid, test), tokenizer
null
18,316
import os import json import torch import random import collections import logging import h5py import copy import torch.distributed as dist from torch.utils.data import Dataset, Subset from multiprocessing import Pool from itertools import repeat import multiprocessing as mp from .tokenization_plug import BertTokenizer, printable_text from sofa.utils import mpu, data_utils, print_rank_0 class HDF5Dataset(Dataset): """HDF5 dataset""" def __init__(self, args, input_file, tokenizer, vocab_words, iter_per_epoch, is_training=True): self.oss_file = input_file #[dist.get_rank()] self.input_file = self.oss_file.split('/')[-1]+str(dist.get_rank()) if args.environ == 'jiuding' else self.oss_file self.input_json_file = self.input_file+'.json' if args.environ == 'jiuding' else self.oss_file.replace('token.', 'token.json') self.is_training = is_training self.args = args self.sent_to_doc = json.load(open(self.input_json_file,'r'))['dict'] self.total_len = len(self.sent_to_doc) self.vocab_words = vocab_words self.tokenizer = tokenizer self.iter_per_epoch = iter_per_epoch def __len__(self): return self.iter_per_epoch def remove_local_file(self): os.remove(self.input_file) os.remove(self.input_json_file) logger.info("Remove local token file & json file!") def __getitem__(self, index): with h5py.File(self.input_file, 'r') as all_documents: document_index = str(self.sent_to_doc[random.randint(0, self.total_len - 1)]) instance = create_instances_from_document( self.sent_to_doc, self.args, document_index, all_documents, self.vocab_words, random, self.tokenizer) feature = convert_instance_to_feature(self.args, instance, self.tokenizer) return feature def make_data_loader(dataset, batch_size, args): shuffle = args.shuffle if shuffle: #if not args.struct_bert_dataset and not args.palm_dataset: # sampler = data_utils.samplers.RandomSampler(dataset, replacement=True, num_samples=batch_size*args.train_iters) #else: if 1: sampler = data_utils.samplers.RandomSampler(dataset, replacement=False) else: sampler = torch.utils.data.SequentialSampler(dataset) world_size = torch.distributed.get_world_size( group=mpu.get_data_parallel_group()) rank = torch.distributed.get_rank(group=mpu.get_data_parallel_group()) distributed = world_size > 1 drop_last = distributed if not args.struct_bert_dataset and not args.palm_dataset and not args.image_dataset: if distributed: batch_sampler = data_utils.samplers.DistributedBatchSampler(sampler, batch_size, shuffle, #if not shuffle, than don't drop_last rank, world_size) else: batch_sampler = torch.utils.data.BatchSampler(sampler, batch_size, shuffle) #if not shuffle, than don't drop_last data_loader = torch.utils.data.DataLoader(dataset, batch_sampler=batch_sampler, num_workers=args.num_workers, pin_memory=True) else: _worker_init_fn = WorkerInitObj(args.seed + torch.distributed.get_rank()) data_loader = torch.utils.data.DataLoader(dataset, batch_size=batch_size, sampler=sampler, num_workers=args.num_workers, pin_memory=True, collate_fn=batchify if args.struct_bert_dataset else PalmBatchify, worker_init_fn=_worker_init_fn) return data_loader def get_split(args): """ Get dataset splits from comma separated string list """ splits = [] if args.split.find(',') != -1: splits = [float(s) for s in args.split.split(',')] elif args.split.find('/') != -1: splits = [float(s) for s in args.split.split('/')] else: splits = [float(args.split)] split_total = sum(splits) if split_total < 1.: splits.append(1-split_total) while len(splits) < 3: splits.append(0.) splits = splits[:3] if args.valid_data is not None: splits[1] = 0. if args.test_data is not None: splits[2] = 0. final_sum = sum(splits) return [s/final_sum for s in splits] def make_structbert_loaders(args, tokenizer): #world_size = torch.distributed.get_world_size( # group=mpu.get_data_parallel_group()) #batch_size = args.batch_size * world_size #we don't need multiple world_size because we don't use distributed batch sampler batch_size = args.batch_size eval_batch_size = batch_size if args.eval_batch_size is not None: eval_batch_size = args.eval_batch_size #* world_size seq_length = args.seq_length if seq_length < 0: seq_length = seq_length# * world_size eval_seq_length = args.eval_seq_length if eval_seq_length is not None and eval_seq_length < 0: eval_seq_length = eval_seq_length# * world_size split = get_split(args) tokenizer.num_tokens = len(tokenizer.vocab) tokenizer.num_type_tokens = 3 args.tokenizer = tokenizer args.cls_token, args.sep_token, args.mask_token = '[CLS]', '[SEP]', '[MASK]' args.vocab_words = list(tokenizer.vocab) #add structbert args #args.environ = 'local' args.dataset_has_lang_id = False args.one_sentence = False args.short_seq_prob = 0 args.ns_type = 3 args.jieba = False args.do_whole_word_mask = False args.masked_lm_prob = 0.15 args.do_mask_rate_range = False args.all_token_mlm = False args.predict_context_prob = 0 args.continue_mask_prob = 0 args.shuffle_order_prob = 0 args.tokenizer_type = 'bert' args.do_train = True args.do_valid = True args.do_test = False data_parallel_rank = torch.distributed.get_rank(group=mpu.get_data_parallel_group()) train = HDF5Dataset(args, args.sub_train_lst[data_parallel_rank], args.tokenizer, args.vocab_words, args.train_iters * args.gradient_accumulation_steps * args.batch_size // args.num_epochs, is_training=True) valid = Subset(train, list(range(args.eval_iters * eval_batch_size))) train = make_data_loader(train, batch_size, args) valid = make_data_loader(valid, eval_batch_size, args) return (train, valid, None), tokenizer
null
18,317
import os import json import torch import random import collections import logging import h5py import copy import torch.distributed as dist from torch.utils.data import Dataset, Subset from multiprocessing import Pool from itertools import repeat import multiprocessing as mp from .tokenization_plug import BertTokenizer, printable_text from sofa.utils import mpu, data_utils, print_rank_0 def make_data_loader(dataset, batch_size, args): shuffle = args.shuffle if shuffle: #if not args.struct_bert_dataset and not args.palm_dataset: # sampler = data_utils.samplers.RandomSampler(dataset, replacement=True, num_samples=batch_size*args.train_iters) #else: if 1: sampler = data_utils.samplers.RandomSampler(dataset, replacement=False) else: sampler = torch.utils.data.SequentialSampler(dataset) world_size = torch.distributed.get_world_size( group=mpu.get_data_parallel_group()) rank = torch.distributed.get_rank(group=mpu.get_data_parallel_group()) distributed = world_size > 1 drop_last = distributed if not args.struct_bert_dataset and not args.palm_dataset and not args.image_dataset: if distributed: batch_sampler = data_utils.samplers.DistributedBatchSampler(sampler, batch_size, shuffle, #if not shuffle, than don't drop_last rank, world_size) else: batch_sampler = torch.utils.data.BatchSampler(sampler, batch_size, shuffle) #if not shuffle, than don't drop_last data_loader = torch.utils.data.DataLoader(dataset, batch_sampler=batch_sampler, num_workers=args.num_workers, pin_memory=True) else: _worker_init_fn = WorkerInitObj(args.seed + torch.distributed.get_rank()) data_loader = torch.utils.data.DataLoader(dataset, batch_size=batch_size, sampler=sampler, num_workers=args.num_workers, pin_memory=True, collate_fn=batchify if args.struct_bert_dataset else PalmBatchify, worker_init_fn=_worker_init_fn) return data_loader def make_tfrecord_loaders(args): """Load train/val/test dataset from shuffled TFRecords""" #import data_utils.tf_dl data_set_args = {'batch_size': args.batch_size, 'max_seq_len': args.seq_length, 'max_preds_per_seq': args.max_preds_per_seq, 'train': True, 'num_workers': max(args.num_workers, 1), 'seed': args.seed + args.rank + 1, 'threaded_dl': args.num_workers > 0 } train = data_utils.tf_dl.TFRecordDataLoader(args.train_data, **data_set_args) data_set_args['train'] = False if args.eval_seq_length is not None: data_set_args['max_seq_len'] = args.eval_seq_length if args.eval_max_preds_per_seq is not None: data_set_args['max_preds_per_seq'] = args.eval_max_preds_per_seq valid = None if args.valid_data is not None: valid = data_utils.tf_dl.TFRecordDataLoader(args.valid_data, **data_set_args) test = None if args.test_data is not None: test = data_utils.tf_dl.TFRecordDataLoader(args.test_data, **data_set_args) tokenizer = data_utils.make_tokenizer(args.tokenizer_type, train, args.tokenizer_path, args.vocab_size, args.tokenizer_model_type, cache_dir=args.cache_dir) return (train, valid, test), tokenizer def get_split(args): """ Get dataset splits from comma separated string list """ splits = [] if args.split.find(',') != -1: splits = [float(s) for s in args.split.split(',')] elif args.split.find('/') != -1: splits = [float(s) for s in args.split.split('/')] else: splits = [float(args.split)] split_total = sum(splits) if split_total < 1.: splits.append(1-split_total) while len(splits) < 3: splits.append(0.) splits = splits[:3] if args.valid_data is not None: splits[1] = 0. if args.test_data is not None: splits[2] = 0. final_sum = sum(splits) return [s/final_sum for s in splits] The provided code snippet includes necessary dependencies for implementing the `make_loaders` function. Write a Python function `def make_loaders(args)` to solve the following problem: makes training/val/test Here is the function: def make_loaders(args): """makes training/val/test""" if args.use_tfrecords: return make_tfrecord_loaders(args) world_size = torch.distributed.get_world_size( group=mpu.get_data_parallel_group()) batch_size = args.batch_size * world_size eval_batch_size = batch_size if args.eval_batch_size is not None: eval_batch_size = args.eval_batch_size * world_size seq_length = args.seq_length if seq_length < 0: seq_length = seq_length * world_size eval_seq_length = args.eval_seq_length if eval_seq_length is not None and eval_seq_length < 0: eval_seq_length = eval_seq_length * world_size split = get_split(args) data_set_args = { 'path': args.train_data, 'seq_length': seq_length, 'lazy': args.lazy_loader, 'delim': args.delim, 'text_key': args.text_key, 'label_key': 'label', 'non_binary_cols': None, 'ds_type': args.data_set_type, 'split': split, 'loose': args.loose_json, 'tokenizer_type': args.tokenizer_type, 'tokenizer_model_path': args.tokenizer_path, 'vocab_size': args.vocab_size, 'model_type': args.tokenizer_model_type, 'cache_dir': args.cache_dir, 'max_preds_per_seq': args.max_preds_per_seq, 'presplit_sentences': args.presplit_sentences} eval_set_args = copy.copy(data_set_args) eval_set_args['split'] = [1.] # if optional eval args were set then replace their # equivalent values in the arg dict if eval_seq_length: eval_set_args['seq_length'] = eval_seq_length if args.eval_max_preds_per_seq: eval_set_args['max_preds_per_seq'] = args.eval_max_preds_per_seq if args.eval_text_key is not None: eval_set_args['text_key'] = args.eval_text_key # make datasets splits and tokenizer train = None valid = None test = None if args.train_data is not None: print(data_set_args) train, tokenizer = data_utils.make_dataset(**data_set_args) if data_utils.should_split(split): train, valid, test = train eval_set_args['tokenizer'] = tokenizer # make training and val dataset if necessary if valid is None and args.valid_data is not None: eval_set_args['path'] = args.valid_data valid, tokenizer = data_utils.make_dataset(**eval_set_args) eval_set_args['tokenizer'] = tokenizer if test is None and args.test_data is not None: eval_set_args['path'] = args.test_data test, tokenizer = data_utils.make_dataset(**eval_set_args) # wrap datasets with data loader if train is not None and args.batch_size > 0: train = make_data_loader(train, batch_size, args) args.do_train = True else: args.do_train = False eval_batch_size = eval_batch_size if eval_batch_size != 0 else batch_size if valid is not None: valid = make_data_loader(valid, eval_batch_size, args) args.do_valid = True else: args.do_valid = False if test is not None: test = make_data_loader(test, eval_batch_size, args) args.do_test = True else: args.do_test = False return (train, valid, test), tokenizer
makes training/val/test
18,318
import os import json import torch import random import collections import logging import h5py import copy import torch.distributed as dist from torch.utils.data import Dataset, Subset from multiprocessing import Pool from itertools import repeat import multiprocessing as mp from .tokenization_plug import BertTokenizer, printable_text from sofa.utils import mpu, data_utils, print_rank_0 class PalmHDF5Dataset(Dataset): """HDF5 dataset""" def __init__(self, args, input_file, tokenizer, vocab_words, iter_per_epoch, is_training=True): self.oss_file = input_file #[dist.get_rank()] self.input_file = self.oss_file.split('/')[-1]+str(dist.get_rank()) if args.environ == 'jiuding' else self.oss_file self.input_json_file = self.input_file+'.json' if args.environ == 'jiuding' else self.oss_file.replace('token.', 'token.json') self.is_training = is_training self.args = args self.sent_to_doc = json.load(open(self.input_json_file,'r'))['dict'] self.total_len = len(self.sent_to_doc) self.vocab_words = vocab_words self.tokenizer = tokenizer self.iter_per_epoch = iter_per_epoch def __len__(self): return self.iter_per_epoch def remove_local_file(self): os.remove(self.input_file) os.remove(self.input_json_file) logger.info("Remove local token file & json file!") def __getitem__(self, index): with h5py.File(self.input_file, 'r') as all_documents: document_index = str(self.sent_to_doc[random.randint(0, self.total_len - 1)]) instance, lenth = create_instances_from_document( self.args, document_index, all_documents, self.vocab_words, random, self.tokenizer, index) feature = convert_instance_to_feature(self.args, instance, self.tokenizer, lenth) return feature def make_data_loader(dataset, batch_size, args): shuffle = args.shuffle if shuffle: #if not args.struct_bert_dataset and not args.palm_dataset: # sampler = data_utils.samplers.RandomSampler(dataset, replacement=True, num_samples=batch_size*args.train_iters) #else: if 1: sampler = data_utils.samplers.RandomSampler(dataset, replacement=False) else: sampler = torch.utils.data.SequentialSampler(dataset) world_size = torch.distributed.get_world_size( group=mpu.get_data_parallel_group()) rank = torch.distributed.get_rank(group=mpu.get_data_parallel_group()) distributed = world_size > 1 drop_last = distributed if not args.struct_bert_dataset and not args.palm_dataset and not args.image_dataset: if distributed: batch_sampler = data_utils.samplers.DistributedBatchSampler(sampler, batch_size, shuffle, #if not shuffle, than don't drop_last rank, world_size) else: batch_sampler = torch.utils.data.BatchSampler(sampler, batch_size, shuffle) #if not shuffle, than don't drop_last data_loader = torch.utils.data.DataLoader(dataset, batch_sampler=batch_sampler, num_workers=args.num_workers, pin_memory=True) else: _worker_init_fn = WorkerInitObj(args.seed + torch.distributed.get_rank()) data_loader = torch.utils.data.DataLoader(dataset, batch_size=batch_size, sampler=sampler, num_workers=args.num_workers, pin_memory=True, collate_fn=batchify if args.struct_bert_dataset else PalmBatchify, worker_init_fn=_worker_init_fn) return data_loader def get_split(args): """ Get dataset splits from comma separated string list """ splits = [] if args.split.find(',') != -1: splits = [float(s) for s in args.split.split(',')] elif args.split.find('/') != -1: splits = [float(s) for s in args.split.split('/')] else: splits = [float(args.split)] split_total = sum(splits) if split_total < 1.: splits.append(1-split_total) while len(splits) < 3: splits.append(0.) splits = splits[:3] if args.valid_data is not None: splits[1] = 0. if args.test_data is not None: splits[2] = 0. final_sum = sum(splits) return [s/final_sum for s in splits] def make_palm_loaders(args, tokenizer): #world_size = torch.distributed.get_world_size( # group=mpu.get_data_parallel_group()) #batch_size = args.batch_size * world_size #we don't need multiple world_size because we don't use distributed batch sampler batch_size = args.batch_size eval_batch_size = batch_size if args.eval_batch_size is not None: eval_batch_size = args.eval_batch_size #* world_size seq_length = args.seq_length if seq_length < 0: seq_length = seq_length# * world_size eval_seq_length = args.eval_seq_length if eval_seq_length is not None and eval_seq_length < 0: eval_seq_length = eval_seq_length# * world_size split = get_split(args) tokenizer.num_tokens = len(tokenizer.vocab) tokenizer.num_type_tokens = 3 args.tokenizer = tokenizer args.cls_token, args.sep_token, args.mask_token = '[CLS]', '[SEP]', '[MASK]' args.bos_token, args.eos_token = '[CLS]', '[SEP]' args.vocab_words = list(tokenizer.vocab) #add palm args args.start_length = 30 args.tgt_length = 128 args.full_sent_prob = 0.3 #add structbert args args.environ = 'local' args.dataset_has_lang_id = False args.one_sentence = False args.short_seq_prob = 0 args.ns_type = 3 args.jieba = False args.do_whole_word_mask = False args.masked_lm_prob = 0.15 args.do_mask_rate_range = False args.all_token_mlm = False args.predict_context_prob = 0 args.continue_mask_prob = 0 args.shuffle_order_prob = 0 args.tokenizer_type = 'bert' args.do_train = True args.do_valid = True args.do_test = False data_parallel_rank = torch.distributed.get_rank(group=mpu.get_data_parallel_group()) train = PalmHDF5Dataset(args, args.sub_train_lst[data_parallel_rank], args.tokenizer, args.vocab_words, args.train_iters * args.gradient_accumulation_steps * args.batch_size // args.num_epochs, is_training=True) valid = Subset(train, list(range(args.eval_iters * eval_batch_size))) train = make_data_loader(train, batch_size, args) valid = make_data_loader(valid, eval_batch_size, args) return (train, valid, None), tokenizer
null
18,319
import os import json import torch import random import collections import logging import h5py import copy import torch.distributed as dist from torch.utils.data import Dataset, Subset from multiprocessing import Pool from itertools import repeat import multiprocessing as mp from .tokenization_plug import BertTokenizer, printable_text from sofa.utils import mpu, data_utils, print_rank_0 class TrainingInstance(object): """A single training instance (sentence pair).""" def __init__(self, tokens, segment_ids, masked_lm_positions, masked_lm_labels, next_sent_label): self.tokens = tokens self.segment_ids = segment_ids self.next_sent_label = next_sent_label self.masked_lm_positions = masked_lm_positions self.masked_lm_labels = masked_lm_labels def __str__(self): s = "" s += "tokens: %s\n" % (" ".join( [printable_text(x) for x in self.tokens])) s += "segment_ids: %s\n" % (" ".join([str(x) for x in self.segment_ids])) s += "next_sent_label: %s\n" % self.next_sent_label s += "masked_lm_positions: %s\n" % (" ".join( [str(x) for x in self.masked_lm_positions])) s += "masked_lm_labels: %s\n" % (" ".join( [printable_text(x) for x in self.masked_lm_labels])) s += "\n" return s def __repr__(self): return self.__str__() def truncate_seq_pair(tokens_a, tokens_b, max_num_tokens, rng): """Truncates a pair of sequences to a maximum sequence length.""" while True: total_length = len(tokens_a) + len(tokens_b) if total_length <= max_num_tokens: break trunc_tokens = tokens_a if len(tokens_a) > len(tokens_b) else tokens_b assert len(trunc_tokens) >= 1 # We want to sometimes truncate from the front and sometimes from the # back to add more randomness and avoid biases. if rng.random() < 0.5: del trunc_tokens[0] else: trunc_tokens.pop() def create_masked_lm_predictions(args, tokens, vocab_words, rng, tokenizer): """Creates the predictions for the masked LM objective.""" cand_indexes = [] special_indexes = set() if not args.jieba: for (i, token) in enumerate(tokens): if token == tokenizer.vocab[args.cls_token] or token == tokenizer.vocab[args.sep_token]: special_indexes.add(i) continue if args.do_whole_word_mask and len(cand_indexes) >= 1 and not tokenizer.convert_ids_to_tokens(int(token)).startswith("▁") and not tokenizer.convert_ids_to_tokens(int(token)).startswith("<") and not tokenizer.convert_ids_to_tokens(int(token)).startswith("Ġ"): cand_indexes[-1].append(i) else: cand_indexes.append([i]) else: raise NotImplementedError("Chinese wwm is not implemented.") rng.shuffle(cand_indexes) output_tokens = list(tokens) masked_lm = collections.namedtuple("masked_lm", ["index", "label"]) # pylint: disable=invalid-name num_to_predict = min(args.max_preds_per_seq, max(1, int(round(len(tokens) * args.masked_lm_prob)))) if args.do_mask_rate_range: num_to_predict = rng.randint(1, num_to_predict) masked_lms = [] covered_indexes = set() for index_set in cand_indexes: if len(masked_lms) >= num_to_predict: masked_lms = masked_lms[:num_to_predict] break # If adding a whole-word mask would exceed the maximum number of # predictions, then just skip this candidate. if len(masked_lms) + len(index_set) > num_to_predict: continue is_any_index_covered = False for index in index_set: if index in covered_indexes: is_any_index_covered = True break if is_any_index_covered: continue for index in index_set: covered_indexes.add(index) masked_token = None # 80% of the time, replace with [MASK] if args.all_token_mlm: masked_token = tokenizer.convert_tokens_to_ids([vocab_words[rng.randint(0, len(vocab_words) - 1)]])[0] else: if rng.random() < 0.8: masked_token = tokenizer.vocab[args.mask_token] else: # 10% of the time, keep original if rng.random() < 0.5: masked_token = tokens[index] # 10% of the time, replace with random word else: masked_token = tokenizer.convert_tokens_to_ids([vocab_words[rng.randint(0, len(vocab_words) - 1)]])[0] output_tokens[index] = masked_token token4predict = tokens[index] if args.predict_context_prob > 0.0: if rng.random() < args.predict_context_prob: ## predict context word instead if rng.random() < 0.5: ## use left word if index > 1: token4predict = tokens[index - 1] else: ## use right word if index < len(tokens) - 1: token4predict = tokens[index + 1] masked_lms.append(masked_lm(index=index, label=token4predict)) if args.continue_mask_prob > 0.0: for ii in [index - 1, index + 1]: if (ii <= 0 or ii >= len(tokens) or ii in special_indexes or ii in covered_indexes or rng.random() > args.continue_mask_prob): continue covered_indexes.add(ii) masked_token = None # 80% of the time, replace with [MASK] if args.all_token_mlm: masked_token = tokenizer.convert_tokens_to_ids([vocab_words[rng.randint(0, len(vocab_words) - 1)]])[0] else: if rng.random() < 0.8: masked_token = tokenizer.vocab[args.mask_token] else: # 10% of the time, keep original if rng.random() < 0.5: masked_token = tokens[ii] # 10% of the time, replace with random word else: masked_token = tokenizer.convert_tokens_to_ids([vocab_words[rng.randint(0, len(vocab_words) - 1)]])[0] output_tokens[ii] = masked_token masked_lms.append(masked_lm(index=ii, label=tokens[ii])) if args.shuffle_order_prob > 0.0: cand_indexes = sum(cand_indexes, []) rng.shuffle(cand_indexes) if rng.random() < args.shuffle_order_prob: for idx in cand_indexes: if idx < len(output_tokens) - 2 and rng.random() < 0.1: temp_tokens = output_tokens[idx:idx+3] rng.shuffle(temp_tokens) for i, token in enumerate(output_tokens[idx:idx+3]): if temp_tokens[i] != token and idx+i not in covered_indexes: masked_lms.append(masked_lm(index=idx+i, label=token)) covered_indexes.add(idx+i) if len(masked_lms) >= args.max_preds_per_seq: excess = len(masked_lms) - args.max_preds_per_seq masked_lms = masked_lms[:args.max_preds_per_seq] output_tokens[idx:idx+3] = temp_tokens[:3-excess] + output_tokens[idx:idx+excess] break output_tokens[idx:idx+3] = temp_tokens masked_lms = sorted(masked_lms, key=lambda x: x.index) masked_lm_positions = [] masked_lm_labels = [] for p in masked_lms: masked_lm_positions.append(p.index) masked_lm_labels.append(p.label) return (output_tokens, masked_lm_positions, masked_lm_labels) The provided code snippet includes necessary dependencies for implementing the `create_instances_from_document` function. Write a Python function `def create_instances_from_document(sent_to_doc, args, document_index, all_documents, vocab_words, rng, tokenizer)` to solve the following problem: Creates `TrainingInstance`s for a single document. Here is the function: def create_instances_from_document(sent_to_doc, args, document_index, all_documents, vocab_words, rng, tokenizer): """Creates `TrainingInstance`s for a single document.""" def split_doc(doc): #doc_piece = [] #for index in range(doc.shape[0]): # doc_piece.append(doc[index]) #return doc_piece return doc document = all_documents[document_index][:-1] document_piece = split_doc(document) if args.dataset_has_lang_id: document_piece = document_piece[1:] # Account for [CLS], [SEP], [SEP] max_num_tokens = args.seq_length - 3 if not args.one_sentence else args.seq_length - 2 # We *usually* want to fill up the entire sequence since we are padding # to `seq_length` anyways, so short sequences are generally wasted # computation. However, we *sometimes* # (i.e., short_seq_prob == 0.1 == 10% of the time) want to use shorter # sequences to minimize the mismatch between pre-training and fine-tuning. # The `target_seq_length` is just a rough target however, whereas # `seq_length` is a hard limit. target_seq_length = max_num_tokens if rng.random() < args.short_seq_prob: target_seq_length = rng.randint(2, max_num_tokens) # We DON'T just concatenate all of the tokens from a document into a long # sequence and choose an arbitrary split point because this would make the # next sentence prediction task too easy. Instead, we split the input into # segments "A" and "B" based on the actual "sentences" provided by the user # input. current_chunk = [] current_length = 0 i = rng.randint(0, len(document_piece) - 1) while i < len(document_piece): segment = document_piece[i] current_chunk.append(segment) current_length += len(segment) if i == len(document_piece) - 1 or current_length >= target_seq_length: if current_chunk: ## @bao if args.one_sentence: tokens_a = [] for chunk in current_chunk: tokens_a.extend(chunk) while len(tokens_a) > max_num_tokens: if rng.random() < 0.5: del tokens_a[0] else: tokens_a.pop() tokens = [] segment_ids = [] tokens.append(tokenizer.vocab[args.cls_token]) segment_ids.append(0) for token in tokens_a: tokens.append(token) segment_ids.append(0) tokens.append(tokenizer.vocab[args.sep_token]) segment_ids.append(0) assert len(tokens) <= args.seq_length, "length of tokens is %d"%len(tokens) if rng.random() < 0.5: if not args.no_nsp: args.shuffle_order_prob = 1.0 else: args.shuffle_order_prob = 0.0 next_sent_label = 1 else: args.shuffle_order_prob = 0.0 next_sent_label = 0 (tokens, masked_lm_positions, masked_lm_labels) = create_masked_lm_predictions(args, tokens, vocab_words, rng, tokenizer) instance = TrainingInstance( tokens=[x % len(tokenizer.vocab) for x in tokens], segment_ids=segment_ids, next_sent_label=next_sent_label, masked_lm_positions=masked_lm_positions, masked_lm_labels=[x % len(tokenizer.vocab) for x in masked_lm_labels] if masked_lm_labels is not None else masked_lm_labels) break # `a_end` is how many segments from `current_chunk` go into the `A` # (first) sentence. a_end = 1 if len(current_chunk) >= 2: a_end = rng.randint(1, len(current_chunk) - 1) tokens_a = [] for j in range(a_end): tokens_a.extend(current_chunk[j]) tokens_b = [] # Random next if len(current_chunk) == 1 or rng.random() < 1.0/args.ns_type: next_sent_label = 0 target_b_length = target_seq_length - len(tokens_a) # This should rarely go for more than one iteration for large # corpora. However, just to be careful, we try to make sure that # the random document is not the same as the document # we're processing. for _ in range(10): random_document_index = str(sent_to_doc[rng.randint(0, len(sent_to_doc) - 1)]) #random_document_index = str(rng.randint(0, len(all_documents) - 1)) if random_document_index != document_index: break random_document = all_documents[random_document_index][:-1] random_document_piece = split_doc(random_document) if args.dataset_has_lang_id: random_document_piece = random_document_piece[1:] random_start = rng.randint(0, len(random_document_piece) - 1) for j in range(random_start, len(random_document_piece)): tokens_b.extend(random_document_piece[j]) if len(tokens_b) >= target_b_length: break # We didn't actually use these segments so we "put them back" so # they don't go to waste. num_unused_segments = len(current_chunk) - a_end i -= num_unused_segments # Actual next else: for j in range(a_end, len(current_chunk)): tokens_b.extend(current_chunk[j]) if args.ns_type==2: next_sent_label = 1 elif args.ns_type==3: if rng.random() < 0.5: next_sent_label = 1 else: tokens_a, tokens_b = tokens_b, tokens_a next_sent_label = 2 elif args.ns_type==5: if len(current_chunk) >= 3 and rng.random() < 0.5: p1 = rng.randint(1, len(current_chunk) - 1) for _ in range(100): p2 = rng.randint(1, len(current_chunk) - 1) if p1 != p2: break start = min(p1, p2) end = max(p1, p2) tokens_a = [] for item in current_chunk[:start]: tokens_a.extend(item) tokens_b = [] for item in current_chunk[end:]: tokens_b.extend(item) if rng.random() < 0.5: next_sent_label = 3 else: tokens_a, tokens_b = tokens_b, tokens_a next_sent_label = 4 elif rng.random() < 0.5: next_sent_label = 1 else: tokens_a, tokens_b = tokens_b, tokens_a next_sent_label = 2 else: raise ValueError('Class type only support 2,3,5!') truncate_seq_pair(tokens_a, tokens_b, max_num_tokens, rng) assert len(tokens_a) >= 1, "length a: %d, length b: %d"%(len(tokens_a), len(tokens_b)) assert len(tokens_b) >= 1, "length a: %d, length b: %d"%(len(tokens_a), len(tokens_b)) tokens = [] segment_ids = [] tokens.append(tokenizer.vocab[args.cls_token]) segment_ids.append(0) for token in tokens_a: tokens.append(token) segment_ids.append(0) tokens.append(tokenizer.vocab[args.sep_token]) segment_ids.append(0) for token in tokens_b: tokens.append(token) segment_ids.append(1) tokens.append(tokenizer.vocab[args.sep_token]) segment_ids.append(1) (tokens, masked_lm_positions, masked_lm_labels) = create_masked_lm_predictions(args, tokens, vocab_words, rng, tokenizer) instance = TrainingInstance( tokens=[x % len(tokenizer.vocab) for x in tokens], segment_ids=segment_ids, next_sent_label=next_sent_label, masked_lm_positions=masked_lm_positions, masked_lm_labels=[x % len(tokenizer.vocab) for x in masked_lm_labels] if masked_lm_labels is not None else masked_lm_labels) break i += 1 return instance
Creates `TrainingInstance`s for a single document.
18,320
import os import json import torch import random import collections import logging import h5py import copy import torch.distributed as dist from torch.utils.data import Dataset, Subset from multiprocessing import Pool from itertools import repeat import multiprocessing as mp from .tokenization_plug import BertTokenizer, printable_text from sofa.utils import mpu, data_utils, print_rank_0 def convert_instance_to_feature(args, instance, tokenizer): input_ids = instance.tokens input_mask = [1] * len(input_ids) segment_ids = list(instance.segment_ids) assert len(input_ids) <= args.seq_length while len(input_ids) < args.seq_length: if args.tokenizer_type.lower() in ['xlmr', 'roberta']: padding_id = 1 elif args.tokenizer_type.lower() in ['bert']: padding_id = 0 else: raise ValueError('{} tokenizer not supported'.format(args.tokenizer_type)) input_ids.append(padding_id) input_mask.append(0) segment_ids.append(0) assert len(input_ids) == args.seq_length assert len(input_mask) == args.seq_length assert len(segment_ids) == args.seq_length masked_lm_positions = list(instance.masked_lm_positions) masked_lm_ids = instance.masked_lm_labels masked_lm_weights = [1.0] * len(masked_lm_ids) while len(masked_lm_positions) < args.max_preds_per_seq: masked_lm_positions.append(0) masked_lm_ids.append(0) masked_lm_weights.append(0.0) next_sentence_label = instance.next_sent_label feature = {} feature['input_ids'] = input_ids feature['input_mask'] = input_mask feature['segment_ids'] = segment_ids feature['masked_lm_positions'] = masked_lm_positions feature['masked_lm_ids'] = masked_lm_ids feature['masked_lm_weights'] = masked_lm_weights feature['next_sentence_labels'] = [next_sentence_label] return feature
null
18,321
import os import json import torch import random import collections import logging import h5py import copy import torch.distributed as dist from torch.utils.data import Dataset, Subset from multiprocessing import Pool from itertools import repeat import multiprocessing as mp from .tokenization_plug import BertTokenizer, printable_text from sofa.utils import mpu, data_utils, print_rank_0 class FeatureDataset(Dataset): """Squad dataset""" def __init__(self, features): self.features = features def __len__(self): return len(self.features) def __getitem__(self, index): feat = self.features[index] feat_dict = {'input_ids': feat.input_ids, 'input_mask': feat.input_mask, 'segment_ids': feat.segment_ids, 'label_id': feat.label_id, 'index': feat.index } return feat_dict #return self.features[index] def lengths(self): return [len(feature.input_ids) for feature in self.features] def get_train_val_test_data_clean(args, tokenizer, train, dev, test): (train_data, val_data, test_data) = (None, None, None) if mpu.get_model_parallel_rank() == 0: data_config = configure_data(tokenizer) data_config.set_defaults(data_set_type='BERT', transpose=False) (train_data, val_data, test_data), _ = data_config.apply(args, train, dev, test) return train_data, val_data, test_data def convert_examples_to_features(args, examples, label_lists, max_seq_length, tokenizer, index, max_index, is_training=False): """Loads a data file into a list of `InputBatch`s.""" label_map_lst = [] for label_list in label_lists: label_map = {} if len(label_list)!= 1: for (i, label) in enumerate(label_list): label_map[label] = i label_map_lst.append(label_map) pool = Pool(mp.cpu_count()) # logger.info('start tokenize') if args.task_type == TaskTypeName.SEQUENCE_LABELING or args.task_type == TaskTypeName.SEQUENCE_LABELING_CRF: worker = ner_examples_to_features_worker # elif args.task_type == TaskTypeName.MULTICHOICE_MRC: # worker = mrc_examples_to_features_worker else: worker = examples_to_features_worker features = pool.starmap(worker, zip(examples, repeat(max_seq_length), repeat(tokenizer), repeat(label_map_lst), repeat(index), repeat(max_index), repeat(is_training), repeat(args))) pool.close() pool.join() #features = [examples_to_features_worker(x, max_seq_length, tokenizer, label_map_lst, index, max_index, is_training, args) for x in examples] return features def get_few_shot_train_data(args, train_examples, labels): example_per_class = {} for label in labels: example_per_class[label] = [] for example in train_examples: example_per_class[example.label].append(example) sampled_train_examples = [] for label in labels: sampled_train_examples.extend(random.sample(example_per_class[label], args.few_shot_train_size_per_class)) print_rank_0('len(sampled_train_examples): {}'.format(len(sampled_train_examples))) return sampled_train_examples def data_preparation_nlu(tokenizer, processor, args): args.fast_train = False label_list = [] if mpu.get_model_parallel_rank() == 0: dev_examples = processor.get_dev_examples(args.dev_data) if args.dev_data else [] # should be none [] test_examples = processor.get_test_examples(args.test_data) if args.dev_data else [] # suppose to be [] if len(dev_examples) == 0: train_examples, dev_examples, label_list = processor.train_dev_split(args.train_data) else: train_examples = processor.get_train_examples(args.train_data) label_list = processor.get_labels() if args.few_shot and args.few_shot_train_size_per_class > 0: print_rank_0('Randomly sample a subset of train examples to train in few-shot learning setting') print_rank_0('few_shot_train_size: {}'.format(args.few_shot_train_size_per_class)) train_examples = get_few_shot_train_data(args, train_examples, label_list) train_features = convert_examples_to_features(args, train_examples, [label_list], args.seq_length, tokenizer, 0, 1, True) dev_features = convert_examples_to_features(args, dev_examples, [label_list], args.seq_length, tokenizer, 0, 1, True) test_features = convert_examples_to_features(args, test_examples, [label_list], args.seq_length, tokenizer, 0, 1, False) train_dataset = FeatureDataset(train_features) dev_dataset = FeatureDataset(dev_features) test_dataset = FeatureDataset(test_features) data_size = torch.cuda.LongTensor([len(train_dataset), len(dev_dataset), len(test_dataset)]) label_map = dict(enumerate(label_list)) label_map_list = [label_map] else: train_dataset, dev_dataset, test_dataset = None, None, None data_size = torch.cuda.LongTensor([0, 0, 0]) label_map_list = [None] torch.distributed.broadcast(data_size, mpu.get_model_parallel_src_rank(), group=mpu.get_model_parallel_group()) torch.distributed.broadcast_object_list(label_map_list, mpu.get_model_parallel_src_rank(), group=mpu.get_model_parallel_group()) args.num_of_classes = len(label_map_list[0].items()) # rank 0 has had the label_list if len(label_list) == 0: label_list = [None] * args.num_of_classes for key, value in label_map_list[0].items(): label_list[key] = value args.data_size = data_size train_data, val_data, test_data = get_train_val_test_data_clean(args, train_dataset, dev_dataset, test_dataset) world_size = torch.distributed.get_world_size( group=mpu.get_data_parallel_group()) args.train_iters = args.data_size[0].item() // (world_size * args.batch_size) * args.num_epochs return train_data, val_data, test_data, label_list, args
null
18,322
from __future__ import absolute_import, division, print_function, unicode_literals import os import copy import json import math import logging import tarfile import tempfile import shutil import torch from torch import nn import torch.nn.functional as F from torch.nn import CrossEntropyLoss from .configuration_plug import PlugNLUConfig, PlugNLGConfig from sofa.utils import mpu, cached_path import copy from deepspeed.utils.timer import SynchronizedWallClockTimer def normal_init_method(mean, std): def init_(tensor): return torch.nn.init.normal_(tensor, mean=mean, std=std) return init_
null
18,323
from __future__ import absolute_import, division, print_function, unicode_literals import os import copy import json import math import logging import tarfile import tempfile import shutil import torch from torch import nn import torch.nn.functional as F from torch.nn import CrossEntropyLoss from .configuration_plug import PlugNLUConfig, PlugNLGConfig from sofa.utils import mpu, cached_path import copy from deepspeed.utils.timer import SynchronizedWallClockTimer The provided code snippet includes necessary dependencies for implementing the `scaled_init_method` function. Write a Python function `def scaled_init_method(mean, std, num_layers)` to solve the following problem: Init method based on N(0, sigma/sqrt(2*num_layers). Here is the function: def scaled_init_method(mean, std, num_layers): """Init method based on N(0, sigma/sqrt(2*num_layers).""" std = std / math.sqrt(2.0 * num_layers) def init_(tensor): return torch.nn.init.normal_(tensor, mean=mean, std=std) return init_
Init method based on N(0, sigma/sqrt(2*num_layers).
18,324
from __future__ import absolute_import, division, print_function, unicode_literals import os import copy import json import math import logging import tarfile import tempfile import shutil import torch from torch import nn import torch.nn.functional as F from torch.nn import CrossEntropyLoss from .configuration_plug import PlugNLUConfig, PlugNLGConfig from sofa.utils import mpu, cached_path import copy from deepspeed.utils.timer import SynchronizedWallClockTimer if 1: print("Better speed can be achieved with apex installed from https://www.github.com/nvidia/apex.") The provided code snippet includes necessary dependencies for implementing the `load_tf_weights_in_bert` function. Write a Python function `def load_tf_weights_in_bert(model, tf_checkpoint_path)` to solve the following problem: Load tf checkpoints in a pytorch model Here is the function: def load_tf_weights_in_bert(model, tf_checkpoint_path): """ Load tf checkpoints in a pytorch model """ try: import re import numpy as np import tensorflow as tf except ImportError: print("Loading a TensorFlow models in PyTorch, requires TensorFlow to be installed. Please see " "https://www.tensorflow.org/install/ for installation instructions.") raise tf_path = os.path.abspath(tf_checkpoint_path) print("Converting TensorFlow checkpoint from {}".format(tf_path)) # Load weights from TF model init_vars = tf.train.list_variables(tf_path) names = [] arrays = [] for name, shape in init_vars: print("Loading TF weight {} with shape {}".format(name, shape)) array = tf.train.load_variable(tf_path, name) names.append(name) arrays.append(array) for name, array in zip(names, arrays): name = name.split('/') # adam_v and adam_m are variables used in AdamWeightDecayOptimizer to calculated m and v # which are not required for using pretrained model if any(n in ["adam_v", "adam_m"] for n in name): print("Skipping {}".format("/".join(name))) continue pointer = model for m_name in name: if re.fullmatch(r'[A-Za-z]+_\d+', m_name): l = re.split(r'_(\d+)', m_name) else: l = [m_name] if l[0] == 'kernel' or l[0] == 'gamma': pointer = getattr(pointer, 'weight') elif l[0] == 'output_bias' or l[0] == 'beta': pointer = getattr(pointer, 'bias') elif l[0] == 'output_weights': pointer = getattr(pointer, 'weight') else: pointer = getattr(pointer, l[0]) if len(l) >= 2: num = int(l[1]) pointer = pointer[num] if m_name[-11:] == '_embeddings': pointer = getattr(pointer, 'weight') elif m_name == 'kernel': array = np.transpose(array) try: assert pointer.shape == array.shape except AssertionError as e: e.args += (pointer.shape, array.shape) raise print("Initialize PyTorch weight {}".format(name)) pointer.data = torch.from_numpy(array) return model
Load tf checkpoints in a pytorch model
18,325
from __future__ import absolute_import, division, print_function, unicode_literals import os import copy import json import math import logging import tarfile import tempfile import shutil import torch from torch import nn import torch.nn.functional as F from torch.nn import CrossEntropyLoss from .configuration_plug import PlugNLUConfig, PlugNLGConfig from sofa.utils import mpu, cached_path import copy from deepspeed.utils.timer import SynchronizedWallClockTimer The provided code snippet includes necessary dependencies for implementing the `gelu` function. Write a Python function `def gelu(x)` to solve the following problem: Implementation of the gelu activation function. For information: OpenAI GPT's gelu is slightly different (and gives slightly different results): 0.5 * x * (1 + torch.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * torch.pow(x, 3)))) Here is the function: def gelu(x): """Implementation of the gelu activation function. For information: OpenAI GPT's gelu is slightly different (and gives slightly different results): 0.5 * x * (1 + torch.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * torch.pow(x, 3)))) """ return x * 0.5 * (1.0 + torch.erf(x / math.sqrt(2.0)))
Implementation of the gelu activation function. For information: OpenAI GPT's gelu is slightly different (and gives slightly different results): 0.5 * x * (1 + torch.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * torch.pow(x, 3))))
18,326
from __future__ import absolute_import, division, print_function, unicode_literals import os import copy import json import math import logging import tarfile import tempfile import shutil import torch from torch import nn import torch.nn.functional as F from torch.nn import CrossEntropyLoss from .configuration_plug import PlugNLUConfig, PlugNLGConfig from sofa.utils import mpu, cached_path import copy from deepspeed.utils.timer import SynchronizedWallClockTimer def swish(x): return x * torch.sigmoid(x)
null
18,327
import collections import os import unicodedata from typing import List, Optional, Tuple from ...utils.tokenization_utils import PreTrainedTokenizer, _is_control, _is_punctuation, _is_whitespace from ...utils.file_utils import logging The provided code snippet includes necessary dependencies for implementing the `load_vocab` function. Write a Python function `def load_vocab(vocab_file)` to solve the following problem: Loads a vocabulary file into a dictionary. Here is the function: def load_vocab(vocab_file): """Loads a vocabulary file into a dictionary.""" vocab = collections.OrderedDict() with open(vocab_file, "r", encoding="utf-8") as reader: tokens = reader.readlines() for index, token in enumerate(tokens): token = token.rstrip("\n") vocab[token] = index return vocab
Loads a vocabulary file into a dictionary.