Skip to content

Commit

Permalink
Lint Errors
Browse files Browse the repository at this point in the history
Lint cleaning
  • Loading branch information
GeoHaber committed Sep 17, 2024
1 parent ab0f12c commit cc7881b
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 90 deletions.
20 changes: 11 additions & 9 deletions FFMpeg.py
Original file line number Diff line number Diff line change
Expand Up @@ -288,15 +288,15 @@ def parse_frmat(input_file: str, mta_dta: Dict[str, any], de_bug: bool) -> Tuple

# XXX: Check for skip condition # XXX:
fnam, ext = os.path.splitext(os.path.basename(input_file))
name_good = fnam == title and ext == '.mp4'
# if not name_good:
good_fname = fnam == title and ext == '.mp4'
# if not good_fname:
# print(f" Ext:{ext}\t Fname:{fnam}\n Title:{title}")

summary_msg = f" |=Title|{title}|\n |>FRMT<|Size: {hm_sz(size)}|Bitrate: {hm_sz(glb_bitrate)}|Length: {hm_time(glb_vidolen)}|"
summary_msg += ''.join([f" {key}: {count}|" for key, count in stream_counts.items() if count != 0])
print(f"\033[96m{summary_msg}\033[0m")

f_skip = name_good and f_comment == Skip_key
f_skip = good_fname and f_comment == Skip_key
# de_bug = True
if f_skip:
print(" .Skip: Format")
Expand Down Expand Up @@ -880,10 +880,10 @@ def show_progrs(line_to, sy, de_bug=False):
if "N/A" in line_to:
return False

elif all(substr in line_to for substr in ["speed=", "fps=", "time="]):
elif all(substr in line_to for substr in ["fps=", "speed=", "size="]):
regx_val = {}
try:
# Use compiled regular expressions
regx_val = {}
for key, regex in regex_dict.items():
regx_val[key] = regex.search(line_to).group(1)

Expand All @@ -899,15 +899,17 @@ def show_progrs(line_to, sy, de_bug=False):
mints, secs = divmod(int(eta), 60)
hours, mints = divmod(mints, 60)
_eta = f"{hours:02d}:{mints:02d}:{secs:02d}"
_P = f"\r | {sy} |Size: {hm_sz(regx_val['size']):>7}|Frames: {int(regx_val['frame']):>6}|Fps: {fp_int:>3}|BitRate: {hm_sz(regx_val['bitrate']):>6}|Speed: {sp_float:>5}|ETA: {_eta:>8}| "
_P = f" | {sy} |Size: {hm_sz(regx_val['size']):>7}|Frames: {int(regx_val['frame']):>6}|Fps: {fp_int:>3}|BitRate: {hm_sz(regx_val['bitrate']):>6}|Speed: {sp_float:>5}|ETA: {_eta:>8}| \r"
if de_bug:
print(f"\n {line_to}\n | {sy} |Size: {hm_sz(regx_val['size']):>7}|Frames: {int(regx_val['frame']):>6}|Fps: {fp_int:>3}|BitRate: {hm_sz(regx_val['bitrate']):>6}|Speed: {sp_float:>5}|ETA: {_eta:>8}|")

except Exception as e:
msj = f"Exception in {msj}: {e} {line_to}"
msj = f"    {msj} Exeption: {e} in {line_to}"
print(msj)

elif any(substr in line_to for substr in ["muxing overhead:", "global headers:", "encoded"]):
_P = f"\r |<+>| Done: {line_to}"
elif any(substr in line_to for substr in ["muxing overhead:", "global headers:"]):
print(f"\n |<+>|Done: {line_to}")
return -1

sys.stderr.write(_P)
sys.stderr.flush()
Expand Down
73 changes: 2 additions & 71 deletions My_Utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -183,10 +183,8 @@ def measure_cpu_utilization(func):
@wraps(func)
def wrapper(*args, **kwargs):
cpu_count = psutil.cpu_count(logical=True)
strt_time = time.monotonic()
cpu_prcnt = psutil.cpu_percent(interval=0.1, percpu=True)
result = func(*args, **kwargs)
end_time = time.monotonic()
cpu_percnt = sum(cpu_prcnt) / cpu_count
return result, cpu_percnt, cpu_prcnt
return wrapper
Expand Down Expand Up @@ -590,7 +588,7 @@ def divd_strn(val: str ) -> float:

def vis_compr(string1, string2, no_match_c='|', match_c='='):
''' Visualy show diferences between sting1 graphx string2 '''
str_t = datetime.datetime.now()
str_t = TM.datetime.now()
message = sys._getframe().f_code.co_name + ':'
print(f" +{message}=: Start: {str_t:%T}")

Expand All @@ -615,19 +613,6 @@ def vis_compr(string1, string2, no_match_c='|', match_c='='):
#>=-------------------------------------------------------------------------=<#


def file_size(path):
# Return file/dir size (MB)
mb = 1 << 20 # bytes to MiB (1024 ** 2)
path = Path(path)
if path.is_file():
return path.stat().st_size / mb
elif path.is_dir():
return sum(f.stat().st_size for f in path.glob('**/*') if f.is_file()) / mb
else:
return 0.0
##>>============-------------------< End >------------------==============<<##


def print_alighned(list: str) -> None :
'''
print a formated table with the {list} values provided
Expand Down Expand Up @@ -711,30 +696,6 @@ def safe_options(strm, opts ):
return safe
##==============------------------- End -------------------==============##

def parse_from_to(strm, dictio, de_bug=True):
msj = sys._getframe().f_code.co_name
resul = {}
try:
resul = {k: (int(strm[k]) if type(dictio[k]) == int else
float(strm[k]) if type(dictio[k]) == float else
dict(strm[k]) if type(dictio[k]) == dict else
strm[k])
for k in dictio.keys() if k in strm}
except Exception as e:
logging.exception(f"Error {e}", exc_info=True, stack_info=True, extra=msj)
msj = f'\n{len(strm)}\n{strm}\n{len(resul)}\n{resul}'
print(msj)
Traceback.print_exc()
input("An error occurred.")

if len(resul) > 1:
return tuple(resul.values())
elif len(resul) == 1:
return next(iter(resul.values()))
else:
return None
##==============------------------- End -------------------==============##

def Trace(message: str, exception: Exception, debug: bool = False) -> None:
"""Prints a traceback and debug info for a given exception"""
max_chars = 42
Expand Down Expand Up @@ -779,7 +740,7 @@ def Trace(message: str, exception: Exception, debug: bool = False) -> None:
def res_chk(folder='.'):
msj = sys._getframe().f_code.co_name
print("=" * 60)
print(datetime.datetime.now().strftime('\n%a:%b:%Y %T %p'))
print(TM.datetime.now().strftime('\n%a:%b:%Y %T %p'))
print('\n:>', msj)
print(os.getcwd())

Expand Down Expand Up @@ -854,33 +815,3 @@ def calculate_total_bits(width, height, pixel_format):
total_bits = width * height * bpp
print(f"Total bits for a frame with pixel format '{pixel_format}': {total_bits}")
return total_bits
'''
import numpy as np
import matplotlib.pyplot as plt
# Define the x values (base) ranging from 1 to 10
x_values = np.linspace(1, 10, 500)
# Calculate the corresponding y values for each exponent (0.7, 0.5, 0.3)
y_values_07 = x_values ** 0.7
y_values_05 = x_values ** 0.5
y_values_03 = x_values ** 0.3
# Plot the graphs
plt.figure(figsize=(10, 6))
plt.plot(x_values, y_values_07, label='y = x^0.7', color='b')
plt.plot(x_values, y_values_05, label='y = x^0.5', color='g')
plt.plot(x_values, y_values_03, label='y = x^0.3', color='r')
plt.xlabel('x (Base)')
plt.ylabel('y (Result)')
plt.title('Graphs of y = x^0.7, y = x^0.5, and y = x^0.3')
plt.legend()
plt.grid(True)
plt.show()
# Evaluate which number is bigger
result_07 = 10 ** 0.7
result_05 = 10 ** 0.5
result_03 = 10 ** 0.3
(result_07, result_05, result_03)
'''
24 changes: 14 additions & 10 deletions Trans_code.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,12 +83,12 @@ def perform_clustering(data: List[List[float]], _lst: List[List]) -> None:

@perf_monitor
def clean_up(input_file: str, output_file: str, skip_it: bool, debug: bool) -> int:
function_name = sys._getframe().f_code.co_name
msj = sys._getframe().f_code.co_name

if skip_it:
return 0

print(f" +{function_name} Start: {time.strftime('%H:%M:%S')}")
print(f" +{msj} Start: {time.strftime('%H:%M:%S')}")

try:
if not os.path.exists(input_file):
Expand All @@ -108,25 +108,29 @@ def clean_up(input_file: str, output_file: str, skip_it: bool, debug: bool) -> i

ratio = round (100 * ((output_file_size - input_file_size) / input_file_size), 2)
extra = "+Biger" if ratio > 0 else ("=Same" if (input_file_size - output_file_size) == 0 else "-Lost")
msg = f" Size Was: {hm_sz(input_file_size)} Is: {hm_sz(output_file_size)} {extra}: {hm_sz(abs(input_file_size - output_file_size))} {ratio}%"
sv_ms = f" Size Was: {hm_sz(input_file_size)} Is: {hm_sz(output_file_size)} {extra}: {hm_sz(abs(input_file_size - output_file_size))} {ratio}%"

final_output_file = input_file if input_file.endswith('.mp4') else input_file.rsplit('.', 1)[0] + '.mp4'
temp_file = input_file + "_Delete_.old"
os.rename(input_file, temp_file)
shutil.move(output_file, final_output_file)

if not debug:
os.remove(temp_file)

print(msg)
# debug = True
if debug:
confirm = input(f" Are you sure you want to delete {temp_file}? (y/n): ")
if confirm.lower() != "y":
print(" Deletion canceled.")
return input_file_size - output_file_size # Return here to stop further execution

print(sv_ms)
os.remove(temp_file)
return input_file_size - output_file_size

except (FileNotFoundError, PermissionError) as e:
print(f"Error accessing file: {e}")
print(f" {msj} Error accessing file: {e}")
except Exception as e:
print(f"An error occurred: {e}")
input ("WTF")
print(f" {msj} An error occurred: {e}")
input(f"? {msj} WTF ?")

return -1

Expand Down

0 comments on commit cc7881b

Please sign in to comment.