wangzhibo
2025-07-31 b2f1162b79f319438dc49767873b0d185fdb1618
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import threading
from datetime import datetime
from pathlib import Path
from auto_media_publisher.modifiers.rewriter.docx_rewriter_gemini import GeminiDocxRewriter  # 根据你的路径修改
import random
import time
 
class DocxRewriteWorkerThread(threading.Thread):
    def __init__(self, input_dir, output_dir, interval_minutes=10, rewrite_style="random"):
        super().__init__()
        self.input_dir = Path(input_dir)
        self.output_dir = Path(output_dir)
        self.interval = interval_minutes * 60  # 转换成秒
        self.rewriter = GeminiDocxRewriter(rewrite_style=rewrite_style)
        self.stop_event = threading.Event()
 
    def stop(self):
        self.stop_event.set()
 
    def run(self):
        while not self.stop_event.is_set():
            print(f"[DocxRewriteThread] Scanning for .docx files at {datetime.now().isoformat()}")
            for docx_path in self.input_dir.rglob("*.docx"):
                try:
                    rel_path = docx_path.relative_to(self.input_dir)
                    timestamp_prefix = datetime.now().strftime("%Y%m%d%H%M%S")
                    new_filename = f"{timestamp_prefix}_{docx_path.name}"
                    output_path = self.output_dir / rel_path.parent / new_filename
 
                    output_path.parent.mkdir(parents=True, exist_ok=True)
                    
                    print(f"[DocxRewriteThread] Rewriting: {docx_path}")
                    self.rewriter.rewrite(str(docx_path), str(output_path))
 
                    sleep_duration = random.uniform(10, 15)  # 秒
                    print(f"[DocxRewriteThread] Sleeping for {sleep_duration:.1f}s to avoid rate limit.")
                    time.sleep(sleep_duration)
 
                except Exception as e:
                    print(f"[DocxRewriteThread] Failed to process {docx_path}: {e}")
                
 
            print(f"[DocxRewriteThread] Waiting for {self.interval // 60} minutes...")
            self.stop_event.wait(self.interval)