7
7
import requests
8
8
dotenv .load_dotenv ()
9
9
10
- import better_exceptions ; better_exceptions .hook ()
10
+ # import better_exceptions; better_exceptions.hook()
11
11
from ratelimiter import RateLimiter
12
12
import google .generativeai as genai
13
13
import os
20
20
# model = genai.GenerativeModel('gemini-1.0-pro-latest')
21
21
22
22
@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 )
24
25
25
26
@click .command ()
26
- @click .argument ('file' )
27
+ @click .argument ('files' , required = True , nargs = - 1 )
27
28
@click .option ('--folder-for-context' , default = None , help = 'Folder for additional context' )
28
29
@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 ):
32
39
reader = PdfReader (file )
33
40
base_dir , filename = os .path .split (os .path .abspath (file ))
34
41
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):
45
52
f'Here is the file contents, use it as context to create the file name: \n ```\n { pdf_text } \n ```' +
46
53
'In the end of your response, emit a json {"new_name": ...}'
47
54
)
48
- chat = model .start_chat ()
49
- response = chat .send_message (query )
55
+ response = gen_content (query )
50
56
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} ' )
54
62
os .rename (file , os .path .join (base_dir , new_name ))
55
63
except Exception as e :
56
64
print (e )
0 commit comments