Skip to content

Commit 3dc3bfe

Browse files
committed
lots of updates
1 parent 37bc337 commit 3dc3bfe

File tree

8 files changed

+257
-226
lines changed

8 files changed

+257
-226
lines changed

Programming/Remove_SRT_Timestamps.py

Lines changed: 0 additions & 46 deletions
This file was deleted.
Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
#!/usr/bin/env python3
2+
3+
import os
4+
import sys
5+
import argparse
6+
7+
def is_non_fixed(filename):
8+
"""
9+
Determine if the .srt file is 'non-fixed'.
10+
Non-fixed files end with '.en.srt' but do not end with '.en-fixed.srt'.
11+
"""
12+
return filename.lower().endswith('.en.srt') and not filename.lower().endswith('.en-fixed.srt')
13+
14+
def find_non_fixed_srt_files(directory):
15+
"""
16+
Find all .srt files in the directory that are not 'fixed'.
17+
"""
18+
try:
19+
all_files = os.listdir(directory)
20+
except Exception as e:
21+
print(f"Error accessing directory '{directory}': {e}")
22+
sys.exit(1)
23+
24+
non_fixed_files = [f for f in all_files if is_non_fixed(f)]
25+
return non_fixed_files
26+
27+
def delete_files(files, directory, dry_run=False):
28+
"""
29+
Delete the specified files from the directory.
30+
If dry_run is True, just print the files that would be deleted.
31+
"""
32+
if dry_run:
33+
print("\nDry Run: The following files would be deleted:")
34+
for f in files:
35+
print(f" - {f}")
36+
return
37+
38+
for f in files:
39+
file_path = os.path.join(directory, f)
40+
try:
41+
os.remove(file_path)
42+
print(f"Deleted: {f}")
43+
except Exception as e:
44+
print(f"Error deleting '{f}': {e}")
45+
46+
def main():
47+
parser = argparse.ArgumentParser(
48+
description="Delete non-fixed .srt files in a directory.\n\n"
49+
"Fixed files end with '.en-fixed.srt' and will be preserved.\n"
50+
"Non-fixed files end with '.en.srt' and will be deleted.",
51+
formatter_class=argparse.RawDescriptionHelpFormatter
52+
)
53+
parser.add_argument(
54+
'directory',
55+
nargs='?',
56+
default='.',
57+
help='Target directory (default: current directory)'
58+
)
59+
parser.add_argument(
60+
'--force',
61+
'-f',
62+
action='store_true',
63+
help='Force deletion without confirmation'
64+
)
65+
parser.add_argument(
66+
'--dry-run',
67+
'-d',
68+
action='store_true',
69+
help='Show files to be deleted without deleting them'
70+
)
71+
72+
args = parser.parse_args()
73+
target_dir = os.path.abspath(args.directory)
74+
75+
if not os.path.isdir(target_dir):
76+
print(f"Error: The directory '{target_dir}' does not exist or is not a directory.")
77+
sys.exit(1)
78+
79+
non_fixed_files = find_non_fixed_srt_files(target_dir)
80+
81+
if not non_fixed_files:
82+
print("No non-fixed .srt files found to delete.")
83+
sys.exit(0)
84+
85+
print(f"\nFound {len(non_fixed_files)} non-fixed .srt file(s) to delete in '{target_dir}':")
86+
for f in non_fixed_files:
87+
print(f" - {f}")
88+
89+
if args.dry_run:
90+
delete_files(non_fixed_files, target_dir, dry_run=True)
91+
sys.exit(0)
92+
93+
if not args.force:
94+
confirm = input("\nAre you sure you want to delete these files? (y/N): ").strip().lower()
95+
if confirm != 'y':
96+
print("Deletion canceled.")
97+
sys.exit(0)
98+
99+
delete_files(non_fixed_files, target_dir)
100+
101+
if __name__ == "__main__":
102+
main()

Programming/ollama.py

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
import subprocess
2+
import time
3+
from pathlib import Path
4+
5+
def get_process_status(process_name):
6+
try:
7+
# Check if any process with the given name is running
8+
result = subprocess.run(["pgrep", "-f", process_name], capture_output=True, text=True)
9+
return len(result.stdout.strip().split("\n")) > 0
10+
except subprocess.CalledProcessError:
11+
return False
12+
13+
def start_service(command):
14+
try:
15+
print(f"Starting {command[0]}...")
16+
process = subprocess.Popen(
17+
command,
18+
stdout=subprocess.PIPE,
19+
stderr=subprocess.PIPE,
20+
text=True,
21+
universal_newlines=True
22+
)
23+
time.sleep(2) # Give the service time to start
24+
return process
25+
except Exception as e:
26+
print(f"Error starting {command[0]}: {e}")
27+
return None
28+
29+
def stop_service(process):
30+
try:
31+
print(f"Stopping {process.args[0]}...")
32+
process.terminate()
33+
# Wait for the process to terminate
34+
process.wait(timeout=5)
35+
if process.returncode == 0:
36+
print(f"{process.args[0]} stopped successfully.")
37+
else:
38+
print(f"{process.args[0]} did not stop gracefully.")
39+
except Exception as e:
40+
print(f"Error stopping {process.args[0]}: {e}")
41+
42+
def main():
43+
# Initialize processes
44+
ollama_process = None
45+
openwebui_process = None
46+
47+
try:
48+
# Start Ollama if not running
49+
if not get_process_status("ollama"):
50+
ollama_process = start_service(["ollama", "serve"])
51+
if ollama_process is None:
52+
return
53+
54+
# Start OpenWebUI if not running
55+
if not get_process_status("openwebui"):
56+
openwebui_process = start_service(["openwebui", "start"])
57+
if openwebui_process is None:
58+
return
59+
60+
print("\nServices are running.")
61+
print(f"Ollama status: {'running' if ollama_process else 'stopped'}")
62+
print(f"OpenWebUI status: {'running' if openwebui_process else 'stopped'}")
63+
64+
# Wait for user input to stop
65+
input("\nPress Enter to stop the services...")
66+
67+
# Stop services gracefully
68+
if ollama_process:
69+
stop_service(ollama_process)
70+
if openwebui_process:
71+
stop_service(openwebui_process)
72+
73+
except Exception as e:
74+
print(f"Error: {e}")
75+
76+
if __name__ == "__main__":
77+
main()

Programming/pandasheet.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
import sys
2+
import pandas as pd
3+
import os
4+
5+
def csv_to_excel():
6+
if len(sys.argv) < 2:
7+
print("Usage: python pandasheet.py <input_file.csv>")
8+
sys.exit(1)
9+
10+
input_csv = sys.argv[1]
11+
output_excel = os.path.splitext(input_csv)[0] + '.xlsx'
12+
13+
try:
14+
# Read CSV file
15+
df = pd.read_csv(input_csv)
16+
17+
# Write to Excel
18+
df.to_excel(output_excel, index=False)
19+
print(f"Successfully converted '{input_csv}' to '{output_excel}'")
20+
21+
except Exception as e:
22+
print(f"Error: {str(e)}")
23+
sys.exit(1)
24+
25+
if __name__ == "__main__":
26+
csv_to_excel()

Programming/srtcleanup.py

Lines changed: 35 additions & 91 deletions
Original file line numberDiff line numberDiff line change
@@ -1,102 +1,46 @@
1-
#!/usr/bin/env python3
2-
3-
import os
1+
import re
42
import sys
5-
import argparse
6-
7-
def is_non_fixed(filename):
8-
"""
9-
Determine if the .srt file is 'non-fixed'.
10-
Non-fixed files end with '.en.srt' but do not end with '.en-fixed.srt'.
11-
"""
12-
return filename.lower().endswith('.en.srt') and not filename.lower().endswith('.en-fixed.srt')
13-
14-
def find_non_fixed_srt_files(directory):
15-
"""
16-
Find all .srt files in the directory that are not 'fixed'.
17-
"""
18-
try:
19-
all_files = os.listdir(directory)
20-
except Exception as e:
21-
print(f"Error accessing directory '{directory}': {e}")
22-
sys.exit(1)
23-
24-
non_fixed_files = [f for f in all_files if is_non_fixed(f)]
25-
return non_fixed_files
26-
27-
def delete_files(files, directory, dry_run=False):
28-
"""
29-
Delete the specified files from the directory.
30-
If dry_run is True, just print the files that would be deleted.
31-
"""
32-
if dry_run:
33-
print("\nDry Run: The following files would be deleted:")
34-
for f in files:
35-
print(f" - {f}")
36-
return
37-
38-
for f in files:
39-
file_path = os.path.join(directory, f)
40-
try:
41-
os.remove(file_path)
42-
print(f"Deleted: {f}")
43-
except Exception as e:
44-
print(f"Error deleting '{f}': {e}")
3+
from pathlib import Path
4+
import shutil
5+
6+
def remove_timestamps_and_line_numbers(input_file, output_file):
7+
# Regex pattern to match timestamp lines
8+
timestamp_pattern = re.compile(r'^\d{2}:\d{2}:\d{2},\d{3} --> \d{2}:\d{2}:\d{2},\d{3}$')
9+
# Regex pattern to match line numbers
10+
line_number_pattern = re.compile(r'^\d+$')
11+
12+
with open(input_file, 'r', encoding='utf-8') as infile, open(output_file, 'w', encoding='utf-8') as outfile:
13+
for line in infile:
14+
line = line.strip()
15+
# Skip timestamp lines and line numbers, write all others
16+
if not timestamp_pattern.match(line) and not line_number_pattern.match(line) and line != '':
17+
outfile.write(line + '\n')
4518

4619
def main():
47-
parser = argparse.ArgumentParser(
48-
description="Delete non-fixed .srt files in a directory.\n\n"
49-
"Fixed files end with '.en-fixed.srt' and will be preserved.\n"
50-
"Non-fixed files end with '.en.srt' and will be deleted.",
51-
formatter_class=argparse.RawDescriptionHelpFormatter
52-
)
53-
parser.add_argument(
54-
'directory',
55-
nargs='?',
56-
default='.',
57-
help='Target directory (default: current directory)'
58-
)
59-
parser.add_argument(
60-
'--force',
61-
'-f',
62-
action='store_true',
63-
help='Force deletion without confirmation'
64-
)
65-
parser.add_argument(
66-
'--dry-run',
67-
'-d',
68-
action='store_true',
69-
help='Show files to be deleted without deleting them'
70-
)
71-
72-
args = parser.parse_args()
73-
target_dir = os.path.abspath(args.directory)
74-
75-
if not os.path.isdir(target_dir):
76-
print(f"Error: The directory '{target_dir}' does not exist or is not a directory.")
20+
if len(sys.argv) < 2:
21+
print("Usage: drag and drop SRT files onto this script.")
7722
sys.exit(1)
7823

79-
non_fixed_files = find_non_fixed_srt_files(target_dir)
80-
81-
if not non_fixed_files:
82-
print("No non-fixed .srt files found to delete.")
83-
sys.exit(0)
24+
for input_path in sys.argv[1:]:
25+
input_file = Path(input_path)
26+
if not input_file.exists() or input_file.suffix.lower() != '.srt':
27+
print(f"Skipping invalid file: {input_path}")
28+
continue
8429

85-
print(f"\nFound {len(non_fixed_files)} non-fixed .srt file(s) to delete in '{target_dir}':")
86-
for f in non_fixed_files:
87-
print(f" - {f}")
30+
# Create output folder in the same directory as the input file
31+
output_folder = input_file.parent / "no_timestamps"
32+
output_folder.mkdir(exist_ok=True)
8833

89-
if args.dry_run:
90-
delete_files(non_fixed_files, target_dir, dry_run=True)
91-
sys.exit(0)
34+
output_file = input_file.with_name(f"{input_file.stem}_no_timestamps{input_file.suffix}")
35+
print(f"Processing: {input_file} -> {output_file}")
9236

93-
if not args.force:
94-
confirm = input("\nAre you sure you want to delete these files? (y/N): ").strip().lower()
95-
if confirm != 'y':
96-
print("Deletion canceled.")
97-
sys.exit(0)
98-
99-
delete_files(non_fixed_files, target_dir)
37+
try:
38+
remove_timestamps_and_line_numbers(input_file, output_file)
39+
# Move the processed file to the output folder
40+
shutil.move(output_file, output_folder / output_file.name)
41+
print(f"Processed and moved to: {output_folder / output_file.name}")
42+
except Exception as e:
43+
print(f"Error processing {input_file}: {e}")
10044

10145
if __name__ == "__main__":
10246
main()

0 commit comments

Comments
 (0)