Skip to content

Commit 829ef22

Browse files
committed
multi file
1 parent 1af6584 commit 829ef22

File tree

1 file changed

+19
-11
lines changed

1 file changed

+19
-11
lines changed

pdf_auto_renamer.py

Lines changed: 19 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
import requests
88
dotenv.load_dotenv()
99

10-
import better_exceptions; better_exceptions.hook()
10+
# import better_exceptions; better_exceptions.hook()
1111
from ratelimiter import RateLimiter
1212
import google.generativeai as genai
1313
import os
@@ -20,15 +20,22 @@
2020
# model = genai.GenerativeModel('gemini-1.0-pro-latest')
2121

2222
@RateLimiter(max_calls=14, period=60)
23-
def gen_content(c): return model.generate_content(c)
23+
def gen_content(c):
24+
return model.generate_content(c)
2425

2526
@click.command()
26-
@click.argument('file')
27+
@click.argument('files', required=True, nargs=-1)
2728
@click.option('--folder-for-context', default=None, help='Folder for additional context')
2829
@click.option('--extra-instructions', default='', help='Extra instructions')
29-
def main(file, folder_for_context, extra_instructions):
30-
if not os.path.exists(file):
31-
raise FileNotFoundError(f"File {file} does not exist.")
30+
def main(files, folder_for_context, extra_instructions):
31+
for file in files:
32+
if not os.path.exists(file):
33+
raise FileNotFoundError(f"File {file} does not exist.")
34+
for file in files:
35+
auto_rename(file, folder_for_context, extra_instructions)
36+
print("Done.")
37+
38+
def auto_rename(file, folder_for_context, extra_instructions):
3239
reader = PdfReader(file)
3340
base_dir, filename = os.path.split(os.path.abspath(file))
3441
pdf_text = '\n\n'.join(p.extract_text() for p in reader.pages)
@@ -45,12 +52,13 @@ def main(file, folder_for_context, extra_instructions):
4552
f'Here is the file contents, use it as context to create the file name: \n```\n{pdf_text}\n```' +
4653
'In the end of your response, emit a json {"new_name": ...}'
4754
)
48-
chat = model.start_chat()
49-
response = chat.send_message(query)
55+
response = gen_content(query)
5056
try:
51-
match = re.search(r'```json.*?(\{.*\}).*?```', response.text, flags=re.MULTILINE | re.DOTALL)
52-
new_name = json.loads(match.group(1).strip())['new_name']
53-
print(f'Renaming to {new_name!r}')
57+
match = re.search(r'\{\s*"new_name":.*?\}', response.text, flags=re.MULTILINE | re.DOTALL)
58+
new_name = json.loads(match.group(0).strip())['new_name']
59+
if not re.match(r'[^<>:"/\\|?*]+', new_name):
60+
raise ValueError(f"Invalid filename: {new_name}")
61+
print(f'Renaming from {filename!r} to {new_name!r}')
5462
os.rename(file, os.path.join(base_dir, new_name))
5563
except Exception as e:
5664
print(e)

0 commit comments

Comments
 (0)