Skip to content

Commit

Permalink
More linter
Browse files Browse the repository at this point in the history
  • Loading branch information
Audionut committed Aug 31, 2024
1 parent 6457df7 commit 7c46235
Show file tree
Hide file tree
Showing 16 changed files with 320 additions and 366 deletions.
2 changes: 1 addition & 1 deletion .flake8
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
[flake8]
max-line-length = 220
max-line-length = 1000
2 changes: 1 addition & 1 deletion .github/workflows/.flake8
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
[flake8]
max-line-length = 220
max-line-length = 500
7 changes: 4 additions & 3 deletions cogs/commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -317,7 +317,7 @@ async def send_embed_and_upload(self, ctx, meta):
embed.add_field(name="Links", value=f"[TMDB](https://www.themoviedb.org/{meta['category'].lower()}/{meta['tmdb']}){imdb}{tvdb}")
embed.add_field(name=f"{res} / {meta['type']}{tag}", value=f"```{meta['name']}```", inline=False)
if missing != []:
embed.add_field(name=f"POTENTIALLY MISSING INFORMATION:", value="\n".join(missing), inline=False)
embed.add_field(name="POTENTIALLY MISSING INFORMATION:", value="\n".join(missing), inline=False)
embed.set_thumbnail(url=f"https://image.tmdb.org/t/p/original{meta['poster']}")
embed.set_footer(text=meta['uuid'])
embed.set_author(name="L4G's Upload Assistant", url="https://github.com/Audionut/Upload-Assistant", icon_url="https://images2.imgbox.com/6e/da/dXfdgNYs_o.png")
Expand Down Expand Up @@ -380,7 +380,7 @@ def check(reaction, user):
await msg.clear_reactions()
await msg.edit(embed=timeout_embed)
return
except:
except Exception:
print("timeout after edit")
pass
except CancelException:
Expand Down Expand Up @@ -533,7 +533,7 @@ def check(reaction, user):
try:
await channel.send(f"{meta['uuid']} timed out")
meta['upload'] = False
except:
except Exception:
return
except CancelException:
await channel.send(f"{meta['title']} cancelled")
Expand All @@ -557,6 +557,7 @@ async def get_missing(self, meta):
missing.append(f"--{each}")
return missing


def setup(bot):
bot.add_cog(Commands(bot))

Expand Down
11 changes: 1 addition & 10 deletions discordbot.py
Original file line number Diff line number Diff line change
@@ -1,21 +1,18 @@
import asyncio
import datetime
import json
import logging
import configparser
from pathlib import Path

import discord
from discord.ext import commands




def config_load():
# Python Config
from data.config import config
return config


async def run():
"""
Where the bot gets started. If you wanted to create an database connection pool or other session for the bot to use,
Expand Down Expand Up @@ -75,7 +72,6 @@ async def load_all_extensions(self):
error = f'{extension}\n {type(e).__name__} : {e}'
print(f'failed to load extension {error}')
print('-' * 10)


async def on_ready(self):
"""
Expand All @@ -101,11 +97,6 @@ async def on_message(self, message):
return # ignore all bots
await self.process_commands(message)






if __name__ == '__main__':
logging.basicConfig(level=logging.INFO)

Expand Down
2 changes: 1 addition & 1 deletion src/bbcode.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ def clean_ptp_description(self, desc, is_disc):
# Re-place comparisons
if comp_placeholders != []:
for i, comp in enumerate(comp_placeholders):
comp = re.sub(r"\[\/?img[\s\S]*?\]", "",comp, flags=re.IGNORECASE)
comp = re.sub(r"\[\/?img[\s\S]*?\]", "", comp, flags=re.IGNORECASE)
desc = desc.replace(f"COMPARISON_PLACEHOLDER-{i} ", comp)

# Convert hides with multiple images to comparison
Expand Down
8 changes: 4 additions & 4 deletions src/discparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ async def get_bdinfo(self, discs, folder_id, base_dir, meta_discs):
console.print(f"[bold green]Scanning {path}")
proc = await asyncio.create_subprocess_exec('mono', f"{base_dir}/bin/BDInfo/BDInfo.exe", '-w', path, save_dir)
await proc.wait()
except:
except Exception:
console.print('[bold red]mono not found, please install mono')

elif sys.platform.startswith('win32'):
Expand Down Expand Up @@ -135,7 +135,7 @@ def parse_bdinfo(self, bdinfo_input, files, path):
bit_depth = split2[n+6].strip()
hdr_dv = split2[n+7].strip()
color = split2[n+8].strip()
except:
except Exception:
bit_depth = ""
hdr_dv = ""
color = ""
Expand Down Expand Up @@ -165,7 +165,7 @@ def parse_bdinfo(self, bdinfo_input, files, path):
fuckatmos = ""
try:
bit_depth = split2[n+5].strip()
except:
except Exception:
bit_depth = ""
bdinfo['audio'].append({
'language': split2[0].strip(),
Expand Down Expand Up @@ -200,7 +200,7 @@ def parse_bdinfo(self, bdinfo_input, files, path):
m2ts['file'] = bd_file
m2ts['length'] = bd_length
bdinfo['files'].append(m2ts)
except:
except Exception:
pass
return bdinfo

Expand Down
112 changes: 56 additions & 56 deletions src/prep.py
Original file line number Diff line number Diff line change
Expand Up @@ -714,13 +714,13 @@ def get_resolution(self, guess, folder_id, base_dir):
try:
width = mi['media']['track'][1]['Width']
height = mi['media']['track'][1]['Height']
except:
except Exception:
width = 0
height = 0
framerate = mi['media']['track'][1].get('FrameRate', '')
try:
scan = mi['media']['track'][1]['ScanType']
except:
except Exception:
scan = "Progressive"
if scan == "Progressive":
scan = "p"
Expand Down Expand Up @@ -777,7 +777,7 @@ def mi_resolution(self, res, guess, width, scan, height, actual_height):
if resolution is None:
try:
resolution = guess['screen_size']
except:
except Exception:
width_map = {
'3840p': '2160p',
'2560p': '1550p',
Expand Down Expand Up @@ -879,39 +879,39 @@ def disc_screenshots(self, filename, bdinfo, folder_id, base_dir, use_vs, image_
"[cyan]{task.completed}/{task.total}",
TimeRemainingColumn()
) as progress:
screen_task = progress.add_task("[green]Saving Screens...", total=num_screens + 1)
ss_times = []
for i in range(num_screens + 1):
image = f"{base_dir}/tmp/{folder_id}/{filename}-{i}.png"
try:
ss_times = self.valid_ss_time(ss_times, num_screens+1, length)
(
ffmpeg
.input(file, ss=ss_times[-1], skip_frame=keyframe)
.output(image, vframes=1, pix_fmt="rgb24")
.overwrite_output()
.global_args('-loglevel', loglevel)
.run(quiet=debug)
)
except Exception:
console.print(traceback.format_exc())

self.optimize_images(image)
if os.path.getsize(Path(image)) <= 31000000 and self.img_host == "imgbb":
i += 1
elif os.path.getsize(Path(image)) <= 10000000 and self.img_host in ["imgbox", 'pixhost']:
i += 1
elif os.path.getsize(Path(image)) <= 75000:
console.print("[bold yellow]Image is incredibly small, retaking")
time.sleep(1)
elif self.img_host == "ptpimg":
i += 1
elif self.img_host == "lensdump":
i += 1
else:
console.print("[red]Image too large for your image host, retaking")
time.sleep(1)
progress.advance(screen_task)
screen_task = progress.add_task("[green]Saving Screens...", total=num_screens + 1)
ss_times = []
for i in range(num_screens + 1):
image = f"{base_dir}/tmp/{folder_id}/{filename}-{i}.png"
try:
ss_times = self.valid_ss_time(ss_times, num_screens+1, length)
(
ffmpeg
.input(file, ss=ss_times[-1], skip_frame=keyframe)
.output(image, vframes=1, pix_fmt="rgb24")
.overwrite_output()
.global_args('-loglevel', loglevel)
.run(quiet=debug)
)
except Exception:
console.print(traceback.format_exc())

self.optimize_images(image)
if os.path.getsize(Path(image)) <= 31000000 and self.img_host == "imgbb":
i += 1
elif os.path.getsize(Path(image)) <= 10000000 and self.img_host in ["imgbox", 'pixhost']:
i += 1
elif os.path.getsize(Path(image)) <= 75000:
console.print("[bold yellow]Image is incredibly small, retaking")
time.sleep(1)
elif self.img_host == "ptpimg":
i += 1
elif self.img_host == "lensdump":
i += 1
else:
console.print("[red]Image too large for your image host, retaking")
time.sleep(1)
progress.advance(screen_task)
# remove smallest image
smallest = ""
smallestsize = 99 ** 99
Expand Down Expand Up @@ -1194,7 +1194,7 @@ def optimize_images(self, image):
oxipng.optimize(image, level=6)
else:
oxipng.optimize(image, level=3)
except:
except Exception:
pass
return

Expand Down Expand Up @@ -1319,7 +1319,7 @@ async def tmdb_other_meta(self, meta):
meta = await self.get_tmdb_id(guessit(title, {"excludes": ["country", "language"]})['title'], meta['search_year'], meta)
if meta['tmdb'] == "0":
meta = await self.get_tmdb_id(title, "", meta, meta['category'])
except:
except Exception:
if meta.get('mode', 'discord') == 'cli':
console.print("[bold red]Unable to find tmdb entry. Exiting.")
exit()
Expand Down Expand Up @@ -1441,7 +1441,7 @@ def get_keywords(self, tmdb_info):
keywords = [f"{keyword['name'].replace(',', ' ')}" for keyword in tmdb_keywords.get('keywords')]
elif tmdb_keywords.get('results') is not None:
keywords = [f"{keyword['name'].replace(',', ' ')}" for keyword in tmdb_keywords.get('results')]
return(', '.join(keywords))
return(', '.join (keywords))
else:
return ''

Expand All @@ -1450,7 +1450,7 @@ def get_genres(self, tmdb_info):
tmdb_genres = tmdb_info.get('genres', [])
if tmdb_genres is not []:
genres = [f"{genre['name'].replace(',', ' ')}" for genre in tmdb_genres]
return(', '.join(genres))
return(', '.join (genres))
else:
return ''

Expand Down Expand Up @@ -1553,7 +1553,7 @@ def get_romaji(self, tmdb_name, mal):
response = requests.post(url, json={'query': query, 'variables': variables})
json = response.json()
media = json['data']['Page']['media']
except:
except Exception:
console.print('[red]Failed to get anime specific info from anilist. Continuing without it...')
media = []
if media not in (None, []):
Expand Down Expand Up @@ -1628,10 +1628,10 @@ def get_audio_v2(self, mi, meta, bdinfo):
channels = mi['media']['track'][track_num]['Channels']
try:
channel_layout = mi['media']['track'][track_num]['ChannelLayout']
except:
except Exception:
try:
channel_layout = mi['media']['track'][track_num]['ChannelLayout_Original']
except:
except Exception:
channel_layout = ""

# Ensure channel_layout is not None or an empty string before iterating
Expand Down Expand Up @@ -1789,7 +1789,7 @@ def get_tag(self, video, meta):
try:
tag = guessit(video)['release_group']
tag = f"-{tag}"
except:
except Exception:
tag = ""
if tag == "-":
tag = ""
Expand All @@ -1801,10 +1801,10 @@ def get_source(self, type, video, path, is_disc, meta):
try:
try:
source = guessit(video)['source']
except:
except Exception:
try:
source = guessit(path)['source']
except:
except Exception:
source = "BluRay"
if meta.get('manual_source', None):
source = meta['manual_source']
Expand All @@ -1824,14 +1824,14 @@ def get_source(self, type, video, path, is_disc, meta):
system = track.standard
if system not in ("PAL", "NTSC"):
raise WeirdSystem
except:
except Exception:
try:
other = guessit(video)['other']
if "PAL" in other:
system = "PAL"
elif "NTSC" in other:
system = "NTSC"
except:
except Exception:
system = ""
finally:
if system is None:
Expand Down Expand Up @@ -1861,7 +1861,7 @@ def get_uhd(self, type, guess, resolution, path):
try:
source = guess['Source']
other = guess['Other']
except:
except Exception:
source = ""
other = ""
uhd = ""
Expand Down Expand Up @@ -1889,7 +1889,7 @@ def get_hdr(self, mi, bdinfo):
try:
if bdinfo['video'][1]['hdr_dv'] == "Dolby Vision":
dv = "DV"
except:
except Exception:
pass
else:
video_track = mi['media']['track'][1]
Expand All @@ -1909,13 +1909,13 @@ def get_hdr(self, mi, bdinfo):
hdr = "HLG"
if hdr != "HLG" and "BT.2020 (10-bit)" in transfer_characteristics:
hdr = "WCG"
except:
except Exception:
pass

try:
if "Dolby Vision" in video_track.get('HDR_Format', '') or "Dolby Vision" in video_track.get('HDR_Format_String', ''):
dv = "DV"
except:
except Exception:
pass

hdr = f"{dv} {hdr}".strip()
Expand Down Expand Up @@ -2016,7 +2016,7 @@ def get_video_encode(self, mi, type, bdinfo):
if mi['media']['track'][1].get('Encoded_Library_Settings', None):
has_encode_settings = True
bit_depth = mi['media']['track'][1].get('BitDepth', '0')
except:
except Exception:
format = bdinfo['video'][0]['codec']
format_profile = bdinfo['video'][0]['profile']
if type in ("ENCODE", "WEBRIP"): # ENCODE or WEBRIP
Expand Down Expand Up @@ -2493,7 +2493,7 @@ async def get_name(self, meta):
elif type == "HDTV": # HDTV
name = f"{title} {alt_title} {year} {edition} {repack} {resolution} {source} {audio} {video_encode}"
potential_missing = []
elif meta['category'] == "TV": #T V SPECIFIC
elif meta['category'] == "TV": # TV SPECIFIC
if type == "DISC": # Disk
if meta['is_disc'] == 'BDMV':
name = f"{title} {year} {alt_title} {season}{episode} {three_d} {edition} {repack} {resolution} {region} {uhd} {source} {hdr} {video_codec} {audio}"
Expand Down Expand Up @@ -2525,7 +2525,7 @@ async def get_name(self, meta):

try:
name = ' '.join(name.split())
except:
except Exception:
console.print("[bold red]Unable to generate name. Please re-run and correct any of the following args if needed.")
console.print(f"--category [yellow]{meta['category']}")
console.print(f"--type [yellow]{meta['type']}")
Expand Down Expand Up @@ -2966,7 +2966,7 @@ async def package(self, meta):
poster = poster[0]
generic.write(f"TMDB Poster: {poster.get('raw_url', poster.get('img_url'))}\n")
meta['rehosted_poster'] = poster.get('raw_url', poster.get('img_url'))
with open (f"{meta['base_dir']}/tmp/{meta['uuid']}/meta.json", 'w') as metafile:
with open(f"{meta['base_dir']}/tmp/{meta['uuid']}/meta.json", 'w') as metafile:
json.dump(meta, metafile, indent=4)
metafile.close()
else:
Expand Down
Loading

0 comments on commit 7c46235

Please sign in to comment.