def edit(path="/"): """Edit the given subtitle, or create a new one""" path = normalize_path(path) realpath = os.path.abspath(root_dir + path) data = {} title = ".".join(path.split("/")[-1].split(".")[:-2]) data["title"] = title data["path"] = path data["root"] = "/".join(path.split("/")[:-1]) data["breadCrumbs"] = listBreadCrumbs(path) if "shift" in request.values: # Shift subtitle try: s = float(request.values["shift"]) shift.shift(realpath, s) data["message"] = "File shifted by {}s.".format(s) except ValueError: pass elif "upload" in request.files: # Upload custom subtitle f = request.files["upload"] name = os.path.splitext(path.split("/")[-1])[0] data["message"] = 'The file "' + name + '.srt" has been uploaded' ext = os.path.splitext(f.filename)[1] target = os.path.splitext(realpath)[0] + ".srt" if ext == ".sub": # Convert .sub to .srt t = tempfile.NamedTemporaryFile() f.save(t.name) sub2srt.convert(t.name, target) data["message"] += " and converted to SRT format" else: f.save(target) os.chmod(target, 0o666) normalize_encoding(target) elif "auto" in request.values: # Download subtitle from OpenSubtitle try: folderPath = "/".join((root_dir + normalize_path(path)).split("/")[:-1]) opensubs.get_sub(root_dir + normalize_path(path)) except: logging.warning(traceback.format_exc()) data["message"] = "Could not download subtitles" # Subtitle content try: data["filecontent"] = open(realpath).read().replace("\n", "<br/>") data["sub_title"] = "Subtitle content" except: data["sub_title"] = "No subtitle" return flask.render_template("edit.html", **data)
def get_sub(path): (folderPath, filename) = os.path.split(path) title = '.'.join(filename.split('.')[:-2]) p = pathlib.Path(folderPath) movie = [str(x) for x in p.iterdir() if x.is_file() and x.suffix in movie_ext and x.name.startswith(title)][0]; raw_lang = path.split('.')[-2] lang = babel_dict[raw_lang] sub_dict = subliminal.api.download_best_subtitles([subliminal.video.scan_video(movie, subtitles=False)], {Language(lang)}) for (vid, subs) in sub_dict.items(): logging.info("Subs for %s" % (path,)) subliminal.api.save_subtitles(vid, subs) if raw_lang != lang_dict[raw_lang]: if not os.path.exists(folderPath + "/" + title + '.' + lang_dict[raw_lang] + '.srt'): raise FileNotFoundError else: target = folderPath + "/" + title + '.' + raw_lang + '.srt' os.rename(folderPath + "/" + title + '.' + lang_dict[raw_lang] + '.srt', target) os.chmod(target, 0o666); normalize_encoding(target)