rmodiucf commited on
Commit
c05c47b
·
verified ·
1 Parent(s): 3f060fe

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. turing_archive/gemini_pipeline/turing_archive/delilah/compile_latex.py +163 -0
  2. turing_archive/gemini_pipeline/turing_archive/delilah/failed_compilations.txt +11 -0
  3. turing_archive/gemini_pipeline/turing_archive/delilah/process.py +157 -0
  4. turing_archive/gemini_pipeline/turing_archive/delilah/process_two_pass.py +377 -0
  5. turing_archive/gemini_pipeline/turing_archive/delilah/process_two_pass_gemini_flash.py +193 -0
  6. turing_archive/gemini_pipeline/turing_archive/delilah/processing_trace.log +0 -0
  7. turing_archive/gemini_pipeline/turing_archive/kings_patricia/compile_latex.py +163 -0
  8. turing_archive/gemini_pipeline/turing_archive/kings_patricia/failed_compilations.txt +0 -0
  9. turing_archive/gemini_pipeline/turing_archive/kings_patricia/process.py +157 -0
  10. turing_archive/gemini_pipeline/turing_archive/kings_patricia/process_two_pass.py +377 -0
  11. turing_archive/gemini_pipeline/turing_archive/kings_patricia/processing_trace.log +0 -0
  12. turing_archive/gemini_pipeline/turing_archive/mother_correspondance/compile_latex.py +163 -0
  13. turing_archive/gemini_pipeline/turing_archive/mother_correspondance/failed_compilations.txt +2 -0
  14. turing_archive/gemini_pipeline/turing_archive/mother_correspondance/process.py +157 -0
  15. turing_archive/gemini_pipeline/turing_archive/mother_correspondance/process_two_pass.py +377 -0
  16. turing_archive/gemini_pipeline/turing_archive/mother_correspondance/process_two_pass_gemini_flash.py +193 -0
  17. turing_archive/gemini_pipeline/turing_archive/mother_correspondance/processing_trace.log +873 -0
  18. turing_archive/gemini_pipeline/turing_archive/personal_documents/compile_latex.py +163 -0
  19. turing_archive/gemini_pipeline/turing_archive/personal_documents/failed_compilations.txt +4 -0
  20. turing_archive/gemini_pipeline/turing_archive/personal_documents/process.py +157 -0
  21. turing_archive/gemini_pipeline/turing_archive/personal_documents/process_two_pass.py +377 -0
  22. turing_archive/gemini_pipeline/turing_archive/personal_documents/process_two_pass_gemini_flash.py +193 -0
  23. turing_archive/gemini_pipeline/turing_archive/personal_documents/processing_trace.log +0 -0
  24. turing_archive/gemini_pipeline/turing_archive/processed/unpublished_drafts/processed/amt-c-6-to-10-1.pdf +0 -0
  25. turing_archive/gemini_pipeline/turing_archive/publications/compile_latex.py +163 -0
  26. turing_archive/gemini_pipeline/turing_archive/publications/failed_compilations.txt +0 -0
  27. turing_archive/gemini_pipeline/turing_archive/publications/process.py +157 -0
  28. turing_archive/gemini_pipeline/turing_archive/publications/process_two_pass.py +377 -0
  29. turing_archive/gemini_pipeline/turing_archive/publications/process_two_pass_gemini_flash.py +193 -0
  30. turing_archive/gemini_pipeline/turing_archive/publications/processing_trace.log +0 -0
  31. turing_archive/gemini_pipeline/turing_archive/publications/texput.log +22 -0
  32. turing_archive/gemini_pipeline/turing_archive/unpublished_drafts/compile_latex.py +163 -0
  33. turing_archive/gemini_pipeline/turing_archive/unpublished_drafts/failed_compilations.txt +7 -0
  34. turing_archive/gemini_pipeline/turing_archive/unpublished_drafts/process.py +157 -0
  35. turing_archive/gemini_pipeline/turing_archive/unpublished_drafts/process_two_pass.py +377 -0
  36. turing_archive/gemini_pipeline/turing_archive/unpublished_drafts/processing_trace.log +0 -0
  37. turing_archive/gemini_pipeline/turing_net/c04/085.gif +3 -0
  38. turing_archive/gemini_pipeline/turing_net/c04/088.gif +3 -0
  39. turing_archive/gemini_pipeline/turing_net/c04/091.gif +3 -0
  40. turing_archive/gemini_pipeline/turing_net/c04/094.gif +3 -0
  41. turing_archive/gemini_pipeline/turing_net/c04/095.gif +3 -0
  42. turing_archive/gemini_pipeline/turing_net/c04/096.gif +3 -0
  43. turing_archive/gemini_pipeline/turing_net/c04/097.gif +3 -0
  44. turing_archive/gemini_pipeline/turing_net/c04/098.gif +3 -0
  45. turing_archive/gemini_pipeline/turing_net/c04/099.gif +3 -0
  46. turing_archive/gemini_pipeline/turing_net/c04/100.gif +3 -0
  47. turing_archive/gemini_pipeline/turing_net/c04/101.gif +3 -0
  48. turing_archive/gemini_pipeline/turing_net/c04/102.gif +3 -0
  49. turing_archive/gemini_pipeline/turing_net/c04/103.gif +3 -0
  50. turing_archive/gemini_pipeline/turing_net/c04/104.gif +3 -0
turing_archive/gemini_pipeline/turing_archive/delilah/compile_latex.py ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import subprocess
3
+ import logging
4
+ from multiprocessing import Pool
5
+
6
+ # ==========================================
7
+ # Logging & Configuration Setup
8
+ # ==========================================
9
+ logging.basicConfig(
10
+ level=logging.INFO,
11
+ format='%(asctime)s [%(levelname)s] %(message)s'
12
+ )
13
+
14
+ PROCESSED_DIR = "./processed_pdfs"
15
+ TOTAL_CORES = os.cpu_count() or 1
16
+ MAX_CONCURRENT_COMPILATIONS = max(1, TOTAL_CORES - 1)
17
+ ERROR_LOG_FILE = "failed_compilations.txt" # <-- Name of your persistent error list
18
+
19
+ def compile_single_tex(dir_name):
20
+ """Worker function executed by independent CPU cores."""
21
+ target_dir = os.path.join(PROCESSED_DIR, dir_name)
22
+ tex_file = "manuscript.tex"
23
+ tex_path = os.path.join(target_dir, tex_file)
24
+
25
+ if not os.path.exists(tex_path):
26
+ return None
27
+
28
+ logging.info(f"[{dir_name}] Launching XeLaTeX compilation...")
29
+
30
+ cmd = [
31
+ "xelatex",
32
+ "-interaction=nonstopmode",
33
+ "-file-line-error",
34
+ tex_file
35
+ ]
36
+
37
+ try:
38
+ result = subprocess.run(
39
+ cmd,
40
+ cwd=target_dir,
41
+ stdout=subprocess.PIPE,
42
+ stderr=subprocess.PIPE,
43
+ text=True,
44
+ check=True
45
+ )
46
+ logging.info(f"[{dir_name}] SUCCESS. PDF compiled successfully.")
47
+ return {
48
+ "dir": dir_name,
49
+ "status": "SUCCESS",
50
+ "full_output": result.stdout,
51
+ "errors": []
52
+ }
53
+
54
+ except subprocess.CalledProcessError as e:
55
+ logging.error(f"[{dir_name}] FAILED. Engine encountered compilation syntax bugs.")
56
+
57
+ error_summary = []
58
+ for line in e.stdout.splitlines():
59
+ if "error" in line.lower() or "fatal" in line.lower() or line.startswith("!"):
60
+ error_summary.append(line.strip())
61
+
62
+ if not error_summary:
63
+ error_summary = [e.stderr.strip() if e.stderr else "Non-zero exit status thrown by engine."]
64
+
65
+ return {
66
+ "dir": dir_name,
67
+ "status": "FAILED",
68
+ "full_output": e.stdout,
69
+ "errors": error_summary
70
+ }
71
+ except Exception as e:
72
+ logging.error(f"[{dir_name}] SYSTEM CALL ERROR: {e}")
73
+ return {
74
+ "dir": dir_name,
75
+ "status": "SYSTEM_ERROR",
76
+ "full_output": "",
77
+ "errors": [str(e)]
78
+ }
79
+
80
+ def main():
81
+ if not os.path.exists(PROCESSED_DIR):
82
+ print(f"Error: The target directory '{PROCESSED_DIR}' does not exist.")
83
+ return
84
+
85
+ all_contents = os.listdir(PROCESSED_DIR)
86
+ sub_dirs = [d for d in all_contents if os.path.isdir(os.path.join(PROCESSED_DIR, d))]
87
+
88
+ if not sub_dirs:
89
+ print(f"No sub-directories detected inside '{PROCESSED_DIR}'.")
90
+ return
91
+
92
+ print(f"System detected {TOTAL_CORES} cores.")
93
+ print(f"Spawning {MAX_CONCURRENT_COMPILATIONS} parallel XeLaTeX compilation engines across folders...\n")
94
+
95
+ pool = Pool(processes=MAX_CONCURRENT_COMPILATIONS)
96
+ try:
97
+ results = [r for r in pool.map(compile_single_tex, sub_dirs) if r is not None]
98
+ finally:
99
+ pool.close()
100
+ pool.join()
101
+
102
+ # ==========================================
103
+ # Final Reporting & Full Log Aggregation
104
+ # ==========================================
105
+ print("\n" + "="*60)
106
+ print(" DETAILED XELATEX OUTPUTS & ENGINE LOGS ")
107
+ print("="*60)
108
+
109
+ for res in results:
110
+ print(f"\n📂 FOLDER DATASTREAM: {res['dir']}")
111
+ print(f"Status: {'✅ SUCCESS' if res['status'] == 'SUCCESS' else '❌ FAILED'}")
112
+ print("-" * 40)
113
+
114
+ if res['status'] == 'SUCCESS':
115
+ summary_lines = [l for l in res['full_output'].splitlines() if "Output written on" in l or "pages" in l]
116
+ if summary_lines:
117
+ for sl in summary_lines:
118
+ print(f" {sl}")
119
+ else:
120
+ print(" Document compiled successfully. (Log output compressed)")
121
+ else:
122
+ print("🛑 Engine Syntax Errors Triggered:")
123
+ for err in res['errors'][:8]:
124
+ print(f" -> {err}")
125
+
126
+ print("\n📋 Last 15 Lines of Raw Engine Context Log:")
127
+ raw_lines = res['full_output'].splitlines()
128
+ for line in raw_lines[-15:]:
129
+ print(f" | {line}")
130
+ print("-" * 60)
131
+
132
+ # ==========================================
133
+ # PERSISTENT STORAGE WRITEBACK (New Addition)
134
+ # ==========================================
135
+ failures = [r for r in results if r["status"] != "SUCCESS"]
136
+
137
+ if failures:
138
+ try:
139
+ with open(ERROR_LOG_FILE, "w", encoding="utf-8") as f:
140
+ f.write("=== FAILED COMPILATIONS MANIFEST ===\n")
141
+ f.write(f"The following folders triggered XeLaTeX layout exceptions:\n\n")
142
+ for fail in failures:
143
+ f.write(f"📁 {fail['dir']}\n")
144
+ f.write(f" Primary Error: {fail['errors'][0] if fail['errors'] else 'Unknown layout bug'}\n\n")
145
+ print(f"\n💾 Saved persistent manifest of broken runs to: {ERROR_LOG_FILE}")
146
+ except Exception as file_err:
147
+ print(f"\n⚠️ System failed to write tracking manifest to disk: {file_err}")
148
+ else:
149
+ # If a subsequent run passes completely clean, purge the old error file
150
+ if os.path.exists(ERROR_LOG_FILE):
151
+ os.remove(ERROR_LOG_FILE)
152
+
153
+ # Global Stats Banner
154
+ print("\n" + "="*60)
155
+ print(" COMPILATION METRICS ")
156
+ print("="*60)
157
+ print(f"Total Folders Processed: {len(results)}")
158
+ print(f"Flawless Conversions: {len(results) - len(failures)}")
159
+ print(f"Syntax/Layout Failures: {len(failures)}")
160
+ print("="*60)
161
+
162
+ if __name__ == "__main__":
163
+ main()
turing_archive/gemini_pipeline/turing_archive/delilah/failed_compilations.txt ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ === FAILED COMPILATIONS MANIFEST ===
2
+ The following folders triggered XeLaTeX layout exceptions:
3
+ too difficult, redo, not all pages were done
4
+
5
+ 📁 h-1-1-351
6
+ Primary Error: ./manuscript.tex:92: Package graphics Error: Division by 0.
7
+
8
+ too difficult, redo, not all pages were done
9
+ 📁 amt-h-1-3-353
10
+ Primary Error: ./manuscript.tex:42: Package graphics Error: Division by 0.
11
+
turing_archive/gemini_pipeline/turing_archive/delilah/process.py ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # processes and tries to compile latex.
2
+ # issue is that latex is not great,
3
+ # and i need a new way to generate that latex.
4
+ import os
5
+ import shutil
6
+ import subprocess
7
+ import logging
8
+ import re
9
+ from multiprocessing import Pool
10
+ from pdf2image import convert_from_path
11
+ from google import genai
12
+ from tenacity import retry, stop_after_attempt, wait_exponential
13
+
14
+ # ==========================================
15
+ # 1. Logging Setup
16
+ # ==========================================
17
+ logging.basicConfig(
18
+ level=logging.INFO,
19
+ format='%(asctime)s [%(levelname)s] %(message)s',
20
+ handlers=[logging.FileHandler("processing_trace.log"), logging.StreamHandler()]
21
+ )
22
+
23
+ def log(msg, filename):
24
+ logging.info(f"[{filename}] {msg}")
25
+
26
+ # ==========================================
27
+ # 2. Configuration
28
+ # ==========================================
29
+ API_KEY = "AIzaSyACloyikx6S1JqZfk3daRG9XTGwTMSWn7E"
30
+ MODEL_NAME = 'gemini-2.5-flash-lite'
31
+ MAX_CONCURRENT_FILES = 6
32
+ INPUT_DIR = "."
33
+ OUTPUT_DIR = "./processed_pdfs"
34
+ WORK_DIR = "./workspace"
35
+
36
+ LATEX_TEMPLATE = r"""\documentclass[11pt,a4paper]{{article}}
37
+ \usepackage[utf8]{{inputenc}}
38
+ \usepackage{{amsmath, amssymb, amsfonts}}
39
+ \usepackage{{graphicx}}
40
+ \usepackage{{xcolor}}
41
+ \usepackage[normalem]{{ulem}}
42
+ \usepackage{{cancel}}
43
+ \usepackage{{enumitem}}
44
+ \usepackage{{geometry}}
45
+ \geometry{{margin=1in}}
46
+ \begin{{document}}
47
+ {}
48
+ \end{{document}}
49
+ """
50
+
51
+ def clean_output(text):
52
+ # 1. Remove markdown code blocks
53
+ text = re.sub(r"```latex", "", text, flags=re.IGNORECASE)
54
+ text = re.sub(r"```", "", text, flags=re.IGNORECASE)
55
+
56
+ # 2. Aggressively strip preamble commands
57
+ text = re.sub(r"\\documentclass.*", "", text)
58
+ text = re.sub(r"\\usepackage\{.*?\}", "", text)
59
+ text = re.sub(r"\\begin\{document\}", "", text)
60
+ text = re.sub(r"\\end\{document\}", "", text)
61
+
62
+ # 3. Strip structural quote commands if they cause nesting issues
63
+ text = text.replace(r"\begin{quote}", "").replace(r"\end{quote}", "")
64
+
65
+ # 4. Fix common broken LaTeX syntax generated by LLMs
66
+ text = text.replace(r"&", r"\&") # Escape alignment tabs
67
+ text = re.sub(r"\\left(?![^{])", "", text) # Remove dangling left
68
+ text = re.sub(r"\\right(?![^{])", "", text) # Remove dangling right
69
+
70
+ return text.strip()
71
+
72
+ def init_worker(api_key):
73
+ global client
74
+ client = genai.Client(api_key=api_key)
75
+
76
+ @retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=2, max=10))
77
+ def call_gemini_with_retry(img, prompt):
78
+ return client.models.generate_content(
79
+ model=MODEL_NAME,
80
+ contents=[img, prompt]
81
+ )
82
+
83
+ def process_single_pdf(pdf_filename):
84
+ if pdf_filename.startswith("processed_"):
85
+ return
86
+
87
+ pdf_base = os.path.splitext(pdf_filename)[0]
88
+ workspace = os.path.join(WORK_DIR, pdf_base)
89
+ figures_dir = os.path.join(workspace, "figures")
90
+ os.makedirs(figures_dir, exist_ok=True)
91
+
92
+ log("Initializing workspace.", pdf_filename)
93
+
94
+ try:
95
+ pages = convert_from_path(pdf_filename, dpi=200)
96
+ except Exception as e:
97
+ log(f"FAILED during extraction: {e}", pdf_filename)
98
+ return
99
+
100
+ latex_content = ""
101
+
102
+ for i, page_img in enumerate(pages):
103
+ img_name = f"page_{i+1}.png"
104
+ img_path = os.path.join(figures_dir, img_name)
105
+ page_img.save(img_path, "PNG")
106
+
107
+ log(f"Transcribing page {i+1}/{len(pages)}.", pdf_filename)
108
+
109
+ # Strict prompt to prevent boilerplate hallucination
110
+ prompt = (
111
+ "Transcribe this handwritten math page into LaTeX. "
112
+ "Output ONLY the LaTeX body content. "
113
+ "DO NOT include: \\usepackage, \\documentclass, \\begin{document}, \\end{document}. "
114
+ "Ensure all math is properly closed with '$' or environment tags. "
115
+ )
116
+
117
+ try:
118
+ response = call_gemini_with_retry(page_img, prompt)
119
+ # Use \par instead of quote to avoid nested environment errors
120
+ latex_content += f"""\\subsection*{{Page {i+1}}}
121
+ \\includegraphics[width=0.6\\textwidth]{{figures/{img_name}}}
122
+ \\par {clean_output(response.text)} \\newpage\n"""
123
+ except Exception as e:
124
+ log(f"FAILED page {i+1} after retries: {e}", pdf_filename)
125
+ latex_content += f"\\subsection*{{Page {i+1}}} \\par \\textit{{Transcription failed.}} \\newpage\n"
126
+
127
+ tex_path = os.path.join(workspace, "manuscript.tex")
128
+ with open(tex_path, "w", encoding="utf-8") as f:
129
+ f.write(LATEX_TEMPLATE.format(latex_content))
130
+
131
+ log("Compiling with XeLaTeX.", pdf_filename)
132
+ try:
133
+ # Run twice to resolve references
134
+ for _ in range(2):
135
+ subprocess.run(["xelatex", "-interaction=nonstopmode", "manuscript.tex"],
136
+ cwd=workspace, stdout=subprocess.DEVNULL)
137
+
138
+ if os.path.exists(os.path.join(workspace, "manuscript.pdf")):
139
+ shutil.move(os.path.join(workspace, "manuscript.pdf"),
140
+ os.path.join(OUTPUT_DIR, f"processed_{pdf_filename}"))
141
+ log("SUCCESS.", pdf_filename)
142
+ else:
143
+ log("COMPILATION FAILED: No PDF produced.", pdf_filename)
144
+ except Exception as e:
145
+ log(f"SYSTEM ERROR: {e}", pdf_filename)
146
+
147
+ def main():
148
+ os.makedirs(OUTPUT_DIR, exist_ok=True)
149
+ os.makedirs(WORK_DIR, exist_ok=True)
150
+
151
+ files = ['amt-c-11-to20-5.pdf']
152
+ print(f"Processing {len(files)} files...")
153
+ with Pool(processes=MAX_CONCURRENT_FILES, initializer=init_worker, initargs=(API_KEY,)) as pool:
154
+ pool.map(process_single_pdf, files)
155
+
156
+ if __name__ == "__main__":
157
+ main()
turing_archive/gemini_pipeline/turing_archive/delilah/process_two_pass.py ADDED
@@ -0,0 +1,377 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import shutil
3
+ import subprocess
4
+ import logging
5
+ import re
6
+ from multiprocessing import Pool
7
+ from pdf2image import convert_from_path
8
+ from google import genai
9
+ from google.genai import types
10
+ from tenacity import retry, stop_after_attempt, wait_exponential,wait_random_exponential
11
+
12
+ # ==========================================
13
+ # 1. Logging Setup
14
+ # ==========================================
15
+ logging.basicConfig(
16
+ level=logging.INFO,
17
+ format='%(asctime)s [%(levelname)s] %(message)s',
18
+ handlers=[logging.FileHandler("processing_trace.log"), logging.StreamHandler()]
19
+ )
20
+
21
+ def log(msg, filename):
22
+ logging.info(f"[{filename}] {msg}")
23
+
24
+ # ==========================================
25
+ # 2. Configuration
26
+ # ==========================================
27
+ API_KEY = "AIzaSyACloyikx6S1JqZfk3daRG9XTGwTMSWn7E"
28
+ TRANSCRIPTION_MODEL = 'gemini-2.5-flash-lite' # Fast and cheap for page images
29
+ REFINEMENT_MODEL = 'gemini-2.5-pro' # Deep reasoning for structural math cleanup
30
+ MAX_CONCURRENT_FILES = 6
31
+ INPUT_DIR = "."
32
+ OUTPUT_DIR = "./processed_pdfs"
33
+ WORK_DIR = "./workspace"
34
+
35
+ LATEX_TEMPLATE = r"""\documentclass[11pt,a4paper]{{article}}
36
+ \usepackage[utf8]{{inputenc}}
37
+ \usepackage{{amsmath, amssymb, amsfonts}}
38
+ \usepackage{{graphicx}}
39
+ \usepackage{{xcolor}}
40
+ \usepackage[normalem]{{ulem}}
41
+ \usepackage{{cancel}}
42
+ \usepackage{{enumitem}}
43
+ \usepackage{{geometry}}
44
+ \geometry{{margin=1in}}
45
+ \begin{{document}}
46
+ {}
47
+ \end{{document}}
48
+ """
49
+
50
+ def clean_output(text):
51
+ if not text:
52
+ return ""
53
+ # 1. Remove markdown code blocks
54
+ text = re.sub(r"```latex", "", text, flags=re.IGNORECASE)
55
+ text = re.sub(r"```", "", text, flags=re.IGNORECASE)
56
+
57
+ # 2. Aggressively strip preamble commands
58
+ text = re.sub(r"\\documentclass.*", "", text)
59
+ text = re.sub(r"\\usepackage\{.*?\}", "", text)
60
+ text = re.sub(r"\\begin\{document\}", "", text)
61
+ text = re.sub(r"\\end\{document\}", "", text)
62
+
63
+ # 3. Strip structural quote commands if they cause nesting issues
64
+ text = text.replace(r"\begin{quote}", "").replace(r"\end{quote}", "")
65
+
66
+ return text.strip()
67
+
68
+ def init_worker(api_key):
69
+ global client
70
+ client = genai.Client(api_key=api_key)
71
+
72
+ @retry(
73
+ stop=stop_after_attempt(7),
74
+ wait=wait_random_exponential(multiplier=2, min=15, max=65),
75
+ before_sleep=lambda retry_state: logging.warning(
76
+ f"Rate limit hit (429). Retrying in {retry_state.next_action.sleep:.2f} seconds... (Attempt {retry_state.attempt_number}/7)"
77
+ )
78
+ )
79
+ def call_gemini_with_retry(contents, prompt, is_image=True):
80
+ if is_image:
81
+ return client.models.generate_content(
82
+ model=TRANSCRIPTION_MODEL,
83
+ contents=[contents, prompt]
84
+ )
85
+ else:
86
+ # Standardize text requests and route them to the stronger PRO model
87
+ combined_payload = f"{prompt}\n\nINPUT TEXT TO REFINE:\n{contents}"
88
+ return client.models.generate_content(
89
+ model=REFINEMENT_MODEL,
90
+ contents=combined_payload
91
+ )
92
+
93
+ def process_single_pdf(pdf_filename):
94
+ if pdf_filename.startswith("processed_"):
95
+ return
96
+
97
+ pdf_base = os.path.splitext(pdf_filename)[0]
98
+ workspace = os.path.join(WORK_DIR, pdf_base)
99
+ figures_dir = os.path.join(workspace, "figures")
100
+ os.makedirs(figures_dir, exist_ok=True)
101
+
102
+ log("Initializing workspace.", pdf_filename)
103
+
104
+ try:
105
+ pages = convert_from_path(pdf_filename, dpi=150)
106
+ except Exception as e:
107
+ log(f"FAILED during extraction: {e}", pdf_filename)
108
+ return
109
+
110
+ raw_latex_body = ""
111
+
112
+ # PASS 1: Sequential Page Transcriptions (Using Flash-Lite)
113
+ for i, page_img in enumerate(pages):
114
+ img_name = f"page_{i+1}.png"
115
+ img_path = os.path.join(figures_dir, img_name)
116
+ page_img.save(img_path, "PNG")
117
+
118
+ log(f"Transcribing page {i+1}/{len(pages)} (Pass 1 - Flash-Lite).", pdf_filename)
119
+
120
+ prompt = (
121
+ "Transcribe this handwritten math page into LaTeX. "
122
+ "Output ONLY the LaTeX body content. "
123
+ "DO NOT include: \\usepackage, \\documentclass, \\begin{document}, or \\end{document}. "
124
+ "Ensure all math is properly closed with '$' or environment tags. "
125
+ )
126
+
127
+ try:
128
+ response = call_gemini_with_retry(page_img, prompt, is_image=True)
129
+ cleaned_page = clean_output(response.text)
130
+
131
+ raw_latex_body += f"""\\subsection*{{Page {i+1}}}
132
+ \\includegraphics[width=0.6\\textwidth]{{figures/{img_name}}}
133
+ \\par {cleaned_page} \\newpage\n"""
134
+ except Exception as e:
135
+ log(f"FAILED page {i+1} during Pass 1: {e}", pdf_filename)
136
+ raw_latex_body += f"\\subsection*{{Page {i+1}}} \\par \\textit{{Transcription failed.}} \\newpage\n"
137
+
138
+ # PASS 2: Global Document Refinement (Using Pro - No Compilation)
139
+ log("Refining full document syntax (Pass 2 - Gemini Pro).", pdf_filename)
140
+ refinement_prompt = (
141
+ "You are an expert LaTeX proofreader. Review the provided input document containing multi-page transcription math. "
142
+ "Fix common compilation bugs globally: ensure all math inline or display environments match, "
143
+ "ensure all braces are closed correctly, convert unmatched or dangling \\left/\\right markers into generic formatting "
144
+ "like standard parenthesis if necessary, and escape naked '&' markers outside of tables or matrices. "
145
+ "DO NOT delete the actual mathematical text or sentences under any circumstance. "
146
+ "Preserve the structural page breaks (\\newpage) and image macros intact. "
147
+ "Output ONLY the corrected body markup text without any markdown or code wrappers."
148
+ )
149
+
150
+ try:
151
+ refinement_response = call_gemini_with_retry(raw_latex_body, refinement_prompt, is_image=False)
152
+ final_latex_body = clean_output(refinement_response.text)
153
+ except Exception as e:
154
+ log(f"Refinement Pass 2 failed. Falling back to Pass 1 content. Error: {e}", pdf_filename)
155
+ final_latex_body = raw_latex_body
156
+
157
+ # Assemble into standard file structure
158
+ tex_path = os.path.join(workspace, "manuscript.tex")
159
+ with open(tex_path, "w", encoding="utf-8") as f:
160
+ f.write(LATEX_TEMPLATE.format(final_latex_body))
161
+
162
+ log("Saving output files to destination without compiling.", pdf_filename)
163
+ try:
164
+ final_dest_dir = os.path.join(OUTPUT_DIR, pdf_base)
165
+ if os.path.exists(final_dest_dir):
166
+ shutil.rmtree(final_dest_dir)
167
+
168
+ shutil.copytree(workspace, final_dest_dir)
169
+ log(f"SUCCESS. Content directory saved at {final_dest_dir}", pdf_filename)
170
+ except Exception as e:
171
+ log(f"SYSTEM COPY ERROR: {e}", pdf_filename)
172
+
173
+ def main():
174
+ os.makedirs(OUTPUT_DIR, exist_ok=True)
175
+ os.makedirs(WORK_DIR, exist_ok=True)
176
+
177
+ #files = ['amt-c-11-to20-5.pdf']
178
+ #detect all files
179
+ files = [f for f in os.listdir(INPUT_DIR) if f.endswith('.pdf') and not f.startswith("processed_")]
180
+ print(f"Processing {len(files)} files with Dual-Pass Reflection (Hybrid Flash-Lite / Pro)...")
181
+
182
+ pool = Pool(processes=MAX_CONCURRENT_FILES, initializer=init_worker, initargs=(API_KEY,))
183
+ try:
184
+ pool.map(process_single_pdf, files)
185
+ finally:
186
+ pool.close()
187
+ pool.join()
188
+
189
+ print("All file processing steps have successfully completed.")
190
+
191
+ if __name__ == "__main__":
192
+ main()
193
+
194
+ # import os
195
+ # import shutil
196
+ # import subprocess
197
+ # import logging
198
+ # import re
199
+ # from multiprocessing import Pool
200
+ # from pdf2image import convert_from_path
201
+ # from google import genai
202
+ # from google.genai import types
203
+ # from tenacity import retry, stop_after_attempt, wait_exponential
204
+
205
+ # # ==========================================
206
+ # # 1. Logging Setup
207
+ # # ==========================================
208
+ # logging.basicConfig(
209
+ # level=logging.INFO,
210
+ # format='%(asctime)s [%(levelname)s] %(message)s',
211
+ # handlers=[logging.FileHandler("processing_trace.log"), logging.StreamHandler()]
212
+ # )
213
+
214
+ # def log(msg, filename):
215
+ # logging.info(f"[{filename}] {msg}")
216
+
217
+ # # ==========================================
218
+ # # 2. Configuration
219
+ # # ==========================================
220
+ # API_KEY = "AIzaSyACloyikx6S1JqZfk3daRG9XTGwTMSWn7E"
221
+ # MODEL_NAME = 'gemini-2.5-flash-lite'
222
+ # MAX_CONCURRENT_FILES = 6
223
+ # INPUT_DIR = "."
224
+ # OUTPUT_DIR = "./processed_pdfs"
225
+ # WORK_DIR = "./workspace"
226
+
227
+ # LATEX_TEMPLATE = r"""\documentclass[11pt,a4paper]{{article}}
228
+ # \usepackage[utf8]{{inputenc}}
229
+ # \usepackage{{amsmath, amssymb, amsfonts}}
230
+ # \usepackage{{graphicx}}
231
+ # \usepackage{{xcolor}}
232
+ # \usepackage[normalem]{{ulem}}
233
+ # \usepackage{{cancel}}
234
+ # \usepackage{{enumitem}}
235
+ # \usepackage{{geometry}}
236
+ # \geometry{{margin=1in}}
237
+ # \begin{{document}}
238
+ # {}
239
+ # \end{{document}}
240
+ # """
241
+
242
+ # def clean_output(text):
243
+ # if not text:
244
+ # return ""
245
+ # # 1. Remove markdown code blocks
246
+ # text = re.sub(r"```latex", "", text, flags=re.IGNORECASE)
247
+ # text = re.sub(r"```", "", text, flags=re.IGNORECASE)
248
+
249
+ # # 2. Aggressively strip preamble commands
250
+ # text = re.sub(r"\\documentclass.*", "", text)
251
+ # text = re.sub(r"\\usepackage\{.*?\}", "", text)
252
+ # text = re.sub(r"\\begin\{document\}", "", text)
253
+ # text = re.sub(r"\\end\{document\}", "", text)
254
+
255
+ # # 3. Strip structural quote commands if they cause nesting issues
256
+ # text = text.replace(r"\begin{quote}", "").replace(r"\end{quote}", "")
257
+
258
+ # return text.strip()
259
+
260
+ # def init_worker(api_key):
261
+ # global client
262
+ # client = genai.Client(api_key=api_key)
263
+
264
+ # @retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=2, max=10))
265
+ # def call_gemini_with_retry(contents, prompt, is_image=True):
266
+ # if is_image:
267
+ # return client.models.generate_content(
268
+ # model=MODEL_NAME,
269
+ # contents=[contents, prompt]
270
+ # )
271
+ # else:
272
+ # # Standardize non-image generation requests using a single explicit text configuration payload
273
+ # combined_payload = f"{prompt}\n\nINPUT TEXT TO REFINE:\n{contents}"
274
+ # return client.models.generate_content(
275
+ # model=MODEL_NAME,
276
+ # contents=combined_payload
277
+ # )
278
+
279
+ # def process_single_pdf(pdf_filename):
280
+ # if pdf_filename.startswith("processed_"):
281
+ # return
282
+
283
+ # pdf_base = os.path.splitext(pdf_filename)[0]
284
+ # workspace = os.path.join(WORK_DIR, pdf_base)
285
+ # figures_dir = os.path.join(workspace, "figures")
286
+ # os.makedirs(figures_dir, exist_ok=True)
287
+
288
+ # log("Initializing workspace.", pdf_filename)
289
+
290
+ # try:
291
+ # pages = convert_from_path(pdf_filename, dpi=150)
292
+ # except Exception as e:
293
+ # log(f"FAILED during extraction: {e}", pdf_filename)
294
+ # return
295
+
296
+ # raw_latex_body = ""
297
+
298
+ # # PASS 1: Sequential Page Transcriptions
299
+ # for i, page_img in enumerate(pages):
300
+ # img_name = f"page_{i+1}.png"
301
+ # img_path = os.path.join(figures_dir, img_name)
302
+ # page_img.save(img_path, "PNG")
303
+
304
+ # log(f"Transcribing page {i+1}/{len(pages)} (Pass 1).", pdf_filename)
305
+
306
+ # prompt = (
307
+ # "Transcribe this handwritten math page into LaTeX. "
308
+ # "Output ONLY the LaTeX body content. "
309
+ # "DO NOT include: \\usepackage, \\documentclass, \\begin{document}, or \\end{document}. "
310
+ # "Ensure all math is properly closed with '$' or environment tags. "
311
+ # )
312
+
313
+ # try:
314
+ # response = call_gemini_with_retry(page_img, prompt, is_image=True)
315
+ # cleaned_page = clean_output(response.text)
316
+
317
+ # raw_latex_body += f"""\\subsection*{{Page {i+1}}}
318
+ # \\includegraphics[width=0.6\\textwidth]{{figures/{img_name}}}
319
+ # \\par {cleaned_page} \\newpage\n"""
320
+ # except Exception as e:
321
+ # log(f"FAILED page {i+1} during Pass 1: {e}", pdf_filename)
322
+ # raw_latex_body += f"\\subsection*{{Page {i+1}}} \\par \\textit{{Transcription failed.}} \\newpage\n"
323
+
324
+ # # PASS 2: Global Document Refinement (No Compilation)
325
+ # log("Refining full document syntax (Pass 2).", pdf_filename)
326
+ # refinement_prompt = (
327
+ # "You are an expert LaTeX proofreader. Review the provided input document containing multi-page transcription math. "
328
+ # "Fix common compilation bugs globally: ensure all math inline or display environments match, "
329
+ # "ensure all braces are closed correctly, convert unmatched or dangling \\left/\\right markers into generic formatting "
330
+ # "like standard parenthesis if necessary, and escape naked '&' markers outside of tables or matrices. "
331
+ # "DO NOT delete the actual mathematical text or sentences under any circumstance. "
332
+ # "Preserve the structural page breaks (\\newpage) and image macros intact. "
333
+ # "Output ONLY the corrected body markup text without any markdown or code wrappers."
334
+ # )
335
+
336
+ # try:
337
+ # refinement_response = call_gemini_with_retry(raw_latex_body, refinement_prompt, is_image=False)
338
+ # final_latex_body = clean_output(refinement_response.text)
339
+ # except Exception as e:
340
+ # log(f"Refinement Pass 2 failed. Falling back to Pass 1 content. Error: {e}", pdf_filename)
341
+ # final_latex_body = raw_latex_body
342
+
343
+ # # Assemble into standard file structure
344
+ # tex_path = os.path.join(workspace, "manuscript.tex")
345
+ # with open(tex_path, "w", encoding="utf-8") as f:
346
+ # f.write(LATEX_TEMPLATE.format(final_latex_body))
347
+
348
+ # log("Saving output files to destination without compiling.", pdf_filename)
349
+ # try:
350
+ # final_dest_dir = os.path.join(OUTPUT_DIR, pdf_base)
351
+ # if os.path.exists(final_dest_dir):
352
+ # shutil.rmtree(final_dest_dir)
353
+
354
+ # shutil.copytree(workspace, final_dest_dir)
355
+ # log(f"SUCCESS. Content directory saved at {final_dest_dir}", pdf_filename)
356
+ # except Exception as e:
357
+ # log(f"SYSTEM COPY ERROR: {e}", pdf_filename)
358
+
359
+ # def main():
360
+ # os.makedirs(OUTPUT_DIR, exist_ok=True)
361
+ # os.makedirs(WORK_DIR, exist_ok=True)
362
+
363
+ # files = ['amt-c-11-to20-5.pdf']
364
+ # print(f"Processing {len(files)} files with Dual-Pass Reflection...")
365
+
366
+ # # Explicitly managing the pool lifecycle ensures complete structural teardown upon map exit
367
+ # pool = Pool(processes=MAX_CONCURRENT_FILES, initializer=init_worker, initargs=(API_KEY,))
368
+ # try:
369
+ # pool.map(process_single_pdf, files)
370
+ # finally:
371
+ # pool.close()
372
+ # pool.join()
373
+
374
+ # print("All file processing steps have successfully completed.")
375
+
376
+ # if __name__ == "__main__":
377
+ # main()
turing_archive/gemini_pipeline/turing_archive/delilah/process_two_pass_gemini_flash.py ADDED
@@ -0,0 +1,193 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import shutil
3
+ import subprocess
4
+ import logging
5
+ import re
6
+ from multiprocessing import Pool
7
+ from pdf2image import convert_from_path
8
+ from google import genai
9
+ from google.genai import types
10
+ from tenacity import retry, stop_after_attempt, wait_exponential,wait_random_exponential
11
+
12
+ # ==========================================
13
+ # 1. Logging Setup
14
+ # ==========================================
15
+ logging.basicConfig(
16
+ level=logging.INFO,
17
+ format='%(asctime)s [%(levelname)s] %(message)s',
18
+ handlers=[logging.FileHandler("processing_trace.log"), logging.StreamHandler()]
19
+ )
20
+
21
+ def log(msg, filename):
22
+ logging.info(f"[{filename}] {msg}")
23
+
24
+ # ==========================================
25
+ # 2. Configuration
26
+ # ==========================================
27
+ API_KEY = "AIzaSyACloyikx6S1JqZfk3daRG9XTGwTMSWn7E"
28
+ TRANSCRIPTION_MODEL = 'gemini-2.5-flash' # Fast and cheap for page images
29
+ REFINEMENT_MODEL = 'gemini-2.5-pro' # Deep reasoning for structural math cleanup
30
+ MAX_CONCURRENT_FILES = 6
31
+ INPUT_DIR = "."
32
+ OUTPUT_DIR = "./processed_pdfs"
33
+ WORK_DIR = "./workspace"
34
+
35
+ LATEX_TEMPLATE = r"""\documentclass[11pt,a4paper]{{article}}
36
+ \usepackage[utf8]{{inputenc}}
37
+ \usepackage{{amsmath, amssymb, amsfonts}}
38
+ \usepackage{{graphicx}}
39
+ \usepackage{{xcolor}}
40
+ \usepackage[normalem]{{ulem}}
41
+ \usepackage{{cancel}}
42
+ \usepackage{{enumitem}}
43
+ \usepackage{{geometry}}
44
+ \geometry{{margin=1in}}
45
+ \begin{{document}}
46
+ {}
47
+ \end{{document}}
48
+ """
49
+
50
+ def clean_output(text):
51
+ if not text:
52
+ return ""
53
+ # 1. Remove markdown code blocks
54
+ text = re.sub(r"```latex", "", text, flags=re.IGNORECASE)
55
+ text = re.sub(r"```", "", text, flags=re.IGNORECASE)
56
+
57
+ # 2. Aggressively strip preamble commands
58
+ text = re.sub(r"\\documentclass.*", "", text)
59
+ text = re.sub(r"\\usepackage\{.*?\}", "", text)
60
+ text = re.sub(r"\\begin\{document\}", "", text)
61
+ text = re.sub(r"\\end\{document\}", "", text)
62
+
63
+ # 3. Strip structural quote commands if they cause nesting issues
64
+ text = text.replace(r"\begin{quote}", "").replace(r"\end{quote}", "")
65
+
66
+ return text.strip()
67
+
68
+ def init_worker(api_key):
69
+ global client
70
+ client = genai.Client(api_key=api_key)
71
+
72
+ @retry(
73
+ stop=stop_after_attempt(7),
74
+ wait=wait_random_exponential(multiplier=2, min=15, max=65),
75
+ before_sleep=lambda retry_state: logging.warning(
76
+ f"Rate limit hit (429). Retrying in {retry_state.next_action.sleep:.2f} seconds... (Attempt {retry_state.attempt_number}/7)"
77
+ )
78
+ )
79
+ def call_gemini_with_retry(contents, prompt, is_image=True):
80
+ if is_image:
81
+ return client.models.generate_content(
82
+ model=TRANSCRIPTION_MODEL,
83
+ contents=[contents, prompt]
84
+ )
85
+ else:
86
+ # Standardize text requests and route them to the stronger PRO model
87
+ combined_payload = f"{prompt}\n\nINPUT TEXT TO REFINE:\n{contents}"
88
+ return client.models.generate_content(
89
+ model=REFINEMENT_MODEL,
90
+ contents=combined_payload
91
+ )
92
+
93
+ def process_single_pdf(pdf_filename):
94
+ if pdf_filename.startswith("processed_"):
95
+ return
96
+
97
+ pdf_base = os.path.splitext(pdf_filename)[0]
98
+ workspace = os.path.join(WORK_DIR, pdf_base)
99
+ figures_dir = os.path.join(workspace, "figures")
100
+ os.makedirs(figures_dir, exist_ok=True)
101
+
102
+ log("Initializing workspace.", pdf_filename)
103
+
104
+ try:
105
+ pages = convert_from_path(pdf_filename, dpi=150)
106
+ except Exception as e:
107
+ log(f"FAILED during extraction: {e}", pdf_filename)
108
+ return
109
+
110
+ raw_latex_body = ""
111
+
112
+ # PASS 1: Sequential Page Transcriptions (Using Flash-Lite)
113
+ for i, page_img in enumerate(pages):
114
+ img_name = f"page_{i+1}.png"
115
+ img_path = os.path.join(figures_dir, img_name)
116
+ page_img.save(img_path, "PNG")
117
+
118
+ log(f"Transcribing page {i+1}/{len(pages)} (Pass 1 - Flash).", pdf_filename)
119
+
120
+ prompt = (
121
+ "Transcribe this handwritten math page into LaTeX. "
122
+ "Output ONLY the LaTeX body content. "
123
+ "DO NOT include: \\usepackage, \\documentclass, \\begin{document}, or \\end{document}. "
124
+ "Ensure all math is properly closed with '$' or environment tags. "
125
+ )
126
+
127
+ try:
128
+ response = call_gemini_with_retry(page_img, prompt, is_image=True)
129
+ cleaned_page = clean_output(response.text)
130
+
131
+ raw_latex_body += f"""\\subsection*{{Page {i+1}}}
132
+ \\includegraphics[width=0.6\\textwidth]{{figures/{img_name}}}
133
+ \\par {cleaned_page} \\newpage\n"""
134
+ except Exception as e:
135
+ log(f"FAILED page {i+1} during Pass 1: {e}", pdf_filename)
136
+ raw_latex_body += f"\\subsection*{{Page {i+1}}} \\par \\textit{{Transcription failed.}} \\newpage\n"
137
+
138
+ # PASS 2: Global Document Refinement (Using Pro - No Compilation)
139
+ log("Refining full document syntax (Pass 2 - Gemini Pro).", pdf_filename)
140
+ refinement_prompt = (
141
+ "You are an expert LaTeX proofreader. Review the provided input document containing multi-page transcription math. "
142
+ "Fix common compilation bugs globally: ensure all math inline or display environments match, "
143
+ "ensure all braces are closed correctly, convert unmatched or dangling \\left/\\right markers into generic formatting "
144
+ "like standard parenthesis if necessary, and escape naked '&' markers outside of tables or matrices. "
145
+ "DO NOT delete the actual mathematical text or sentences under any circumstance. "
146
+ "Preserve the structural page breaks (\\newpage) and image macros intact. "
147
+ "Output ONLY the corrected body markup text without any markdown or code wrappers."
148
+ )
149
+
150
+ try:
151
+ refinement_response = call_gemini_with_retry(raw_latex_body, refinement_prompt, is_image=False)
152
+ final_latex_body = clean_output(refinement_response.text)
153
+ except Exception as e:
154
+ log(f"Refinement Pass 2 failed. Falling back to Pass 1 content. Error: {e}", pdf_filename)
155
+ final_latex_body = raw_latex_body
156
+
157
+ # Assemble into standard file structure
158
+ tex_path = os.path.join(workspace, "manuscript.tex")
159
+ with open(tex_path, "w", encoding="utf-8") as f:
160
+ f.write(LATEX_TEMPLATE.format(final_latex_body))
161
+
162
+ log("Saving output files to destination without compiling.", pdf_filename)
163
+ try:
164
+ final_dest_dir = os.path.join(OUTPUT_DIR, pdf_base)
165
+ if os.path.exists(final_dest_dir):
166
+ shutil.rmtree(final_dest_dir)
167
+
168
+ shutil.copytree(workspace, final_dest_dir)
169
+ log(f"SUCCESS. Content directory saved at {final_dest_dir}", pdf_filename)
170
+ except Exception as e:
171
+ log(f"SYSTEM COPY ERROR: {e}", pdf_filename)
172
+
173
+ def main():
174
+ os.makedirs(OUTPUT_DIR, exist_ok=True)
175
+ os.makedirs(WORK_DIR, exist_ok=True)
176
+
177
+ #files = ['amt-c-11-to20-5.pdf']
178
+ #detect all files
179
+ # files = [f for f in os.listdir(INPUT_DIR) if f.endswith('.pdf') and not f.startswith("processed_")]
180
+ files = ['h-1-1-351.pdf','amt-h-1-3-353.pdf']
181
+ print(f"Processing {len(files)} files with Dual-Pass Reflection (Hybrid Flash-Lite / Pro)...")
182
+
183
+ pool = Pool(processes=MAX_CONCURRENT_FILES, initializer=init_worker, initargs=(API_KEY,))
184
+ try:
185
+ pool.map(process_single_pdf, files)
186
+ finally:
187
+ pool.close()
188
+ pool.join()
189
+
190
+ print("All file processing steps have successfully completed.")
191
+
192
+ if __name__ == "__main__":
193
+ main()
turing_archive/gemini_pipeline/turing_archive/delilah/processing_trace.log ADDED
The diff for this file is too large to render. See raw diff
 
turing_archive/gemini_pipeline/turing_archive/kings_patricia/compile_latex.py ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import subprocess
3
+ import logging
4
+ from multiprocessing import Pool
5
+
6
+ # ==========================================
7
+ # Logging & Configuration Setup
8
+ # ==========================================
9
+ logging.basicConfig(
10
+ level=logging.INFO,
11
+ format='%(asctime)s [%(levelname)s] %(message)s'
12
+ )
13
+
14
+ PROCESSED_DIR = "./processed_pdfs"
15
+ TOTAL_CORES = os.cpu_count() or 1
16
+ MAX_CONCURRENT_COMPILATIONS = max(1, TOTAL_CORES - 1)
17
+ ERROR_LOG_FILE = "failed_compilations.txt" # <-- Name of your persistent error list
18
+
19
+ def compile_single_tex(dir_name):
20
+ """Worker function executed by independent CPU cores."""
21
+ target_dir = os.path.join(PROCESSED_DIR, dir_name)
22
+ tex_file = "manuscript.tex"
23
+ tex_path = os.path.join(target_dir, tex_file)
24
+
25
+ if not os.path.exists(tex_path):
26
+ return None
27
+
28
+ logging.info(f"[{dir_name}] Launching XeLaTeX compilation...")
29
+
30
+ cmd = [
31
+ "xelatex",
32
+ "-interaction=nonstopmode",
33
+ "-file-line-error",
34
+ tex_file
35
+ ]
36
+
37
+ try:
38
+ result = subprocess.run(
39
+ cmd,
40
+ cwd=target_dir,
41
+ stdout=subprocess.PIPE,
42
+ stderr=subprocess.PIPE,
43
+ text=True,
44
+ check=True
45
+ )
46
+ logging.info(f"[{dir_name}] SUCCESS. PDF compiled successfully.")
47
+ return {
48
+ "dir": dir_name,
49
+ "status": "SUCCESS",
50
+ "full_output": result.stdout,
51
+ "errors": []
52
+ }
53
+
54
+ except subprocess.CalledProcessError as e:
55
+ logging.error(f"[{dir_name}] FAILED. Engine encountered compilation syntax bugs.")
56
+
57
+ error_summary = []
58
+ for line in e.stdout.splitlines():
59
+ if "error" in line.lower() or "fatal" in line.lower() or line.startswith("!"):
60
+ error_summary.append(line.strip())
61
+
62
+ if not error_summary:
63
+ error_summary = [e.stderr.strip() if e.stderr else "Non-zero exit status thrown by engine."]
64
+
65
+ return {
66
+ "dir": dir_name,
67
+ "status": "FAILED",
68
+ "full_output": e.stdout,
69
+ "errors": error_summary
70
+ }
71
+ except Exception as e:
72
+ logging.error(f"[{dir_name}] SYSTEM CALL ERROR: {e}")
73
+ return {
74
+ "dir": dir_name,
75
+ "status": "SYSTEM_ERROR",
76
+ "full_output": "",
77
+ "errors": [str(e)]
78
+ }
79
+
80
+ def main():
81
+ if not os.path.exists(PROCESSED_DIR):
82
+ print(f"Error: The target directory '{PROCESSED_DIR}' does not exist.")
83
+ return
84
+
85
+ all_contents = os.listdir(PROCESSED_DIR)
86
+ sub_dirs = [d for d in all_contents if os.path.isdir(os.path.join(PROCESSED_DIR, d))]
87
+
88
+ if not sub_dirs:
89
+ print(f"No sub-directories detected inside '{PROCESSED_DIR}'.")
90
+ return
91
+
92
+ print(f"System detected {TOTAL_CORES} cores.")
93
+ print(f"Spawning {MAX_CONCURRENT_COMPILATIONS} parallel XeLaTeX compilation engines across folders...\n")
94
+
95
+ pool = Pool(processes=MAX_CONCURRENT_COMPILATIONS)
96
+ try:
97
+ results = [r for r in pool.map(compile_single_tex, sub_dirs) if r is not None]
98
+ finally:
99
+ pool.close()
100
+ pool.join()
101
+
102
+ # ==========================================
103
+ # Final Reporting & Full Log Aggregation
104
+ # ==========================================
105
+ print("\n" + "="*60)
106
+ print(" DETAILED XELATEX OUTPUTS & ENGINE LOGS ")
107
+ print("="*60)
108
+
109
+ for res in results:
110
+ print(f"\n📂 FOLDER DATASTREAM: {res['dir']}")
111
+ print(f"Status: {'✅ SUCCESS' if res['status'] == 'SUCCESS' else '❌ FAILED'}")
112
+ print("-" * 40)
113
+
114
+ if res['status'] == 'SUCCESS':
115
+ summary_lines = [l for l in res['full_output'].splitlines() if "Output written on" in l or "pages" in l]
116
+ if summary_lines:
117
+ for sl in summary_lines:
118
+ print(f" {sl}")
119
+ else:
120
+ print(" Document compiled successfully. (Log output compressed)")
121
+ else:
122
+ print("🛑 Engine Syntax Errors Triggered:")
123
+ for err in res['errors'][:8]:
124
+ print(f" -> {err}")
125
+
126
+ print("\n📋 Last 15 Lines of Raw Engine Context Log:")
127
+ raw_lines = res['full_output'].splitlines()
128
+ for line in raw_lines[-15:]:
129
+ print(f" | {line}")
130
+ print("-" * 60)
131
+
132
+ # ==========================================
133
+ # PERSISTENT STORAGE WRITEBACK (New Addition)
134
+ # ==========================================
135
+ failures = [r for r in results if r["status"] != "SUCCESS"]
136
+
137
+ if failures:
138
+ try:
139
+ with open(ERROR_LOG_FILE, "w", encoding="utf-8") as f:
140
+ f.write("=== FAILED COMPILATIONS MANIFEST ===\n")
141
+ f.write(f"The following folders triggered XeLaTeX layout exceptions:\n\n")
142
+ for fail in failures:
143
+ f.write(f"📁 {fail['dir']}\n")
144
+ f.write(f" Primary Error: {fail['errors'][0] if fail['errors'] else 'Unknown layout bug'}\n\n")
145
+ print(f"\n💾 Saved persistent manifest of broken runs to: {ERROR_LOG_FILE}")
146
+ except Exception as file_err:
147
+ print(f"\n⚠️ System failed to write tracking manifest to disk: {file_err}")
148
+ else:
149
+ # If a subsequent run passes completely clean, purge the old error file
150
+ if os.path.exists(ERROR_LOG_FILE):
151
+ os.remove(ERROR_LOG_FILE)
152
+
153
+ # Global Stats Banner
154
+ print("\n" + "="*60)
155
+ print(" COMPILATION METRICS ")
156
+ print("="*60)
157
+ print(f"Total Folders Processed: {len(results)}")
158
+ print(f"Flawless Conversions: {len(results) - len(failures)}")
159
+ print(f"Syntax/Layout Failures: {len(failures)}")
160
+ print("="*60)
161
+
162
+ if __name__ == "__main__":
163
+ main()
turing_archive/gemini_pipeline/turing_archive/kings_patricia/failed_compilations.txt ADDED
File without changes
turing_archive/gemini_pipeline/turing_archive/kings_patricia/process.py ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # processes and tries to compile latex.
2
+ # issue is that latex is not great,
3
+ # and i need a new way to generate that latex.
4
+ import os
5
+ import shutil
6
+ import subprocess
7
+ import logging
8
+ import re
9
+ from multiprocessing import Pool
10
+ from pdf2image import convert_from_path
11
+ from google import genai
12
+ from tenacity import retry, stop_after_attempt, wait_exponential
13
+
14
+ # ==========================================
15
+ # 1. Logging Setup
16
+ # ==========================================
17
+ logging.basicConfig(
18
+ level=logging.INFO,
19
+ format='%(asctime)s [%(levelname)s] %(message)s',
20
+ handlers=[logging.FileHandler("processing_trace.log"), logging.StreamHandler()]
21
+ )
22
+
23
+ def log(msg, filename):
24
+ logging.info(f"[{filename}] {msg}")
25
+
26
+ # ==========================================
27
+ # 2. Configuration
28
+ # ==========================================
29
+ API_KEY = "AIzaSyACloyikx6S1JqZfk3daRG9XTGwTMSWn7E"
30
+ MODEL_NAME = 'gemini-2.5-flash-lite'
31
+ MAX_CONCURRENT_FILES = 6
32
+ INPUT_DIR = "."
33
+ OUTPUT_DIR = "./processed_pdfs"
34
+ WORK_DIR = "./workspace"
35
+
36
+ LATEX_TEMPLATE = r"""\documentclass[11pt,a4paper]{{article}}
37
+ \usepackage[utf8]{{inputenc}}
38
+ \usepackage{{amsmath, amssymb, amsfonts}}
39
+ \usepackage{{graphicx}}
40
+ \usepackage{{xcolor}}
41
+ \usepackage[normalem]{{ulem}}
42
+ \usepackage{{cancel}}
43
+ \usepackage{{enumitem}}
44
+ \usepackage{{geometry}}
45
+ \geometry{{margin=1in}}
46
+ \begin{{document}}
47
+ {}
48
+ \end{{document}}
49
+ """
50
+
51
+ def clean_output(text):
52
+ # 1. Remove markdown code blocks
53
+ text = re.sub(r"```latex", "", text, flags=re.IGNORECASE)
54
+ text = re.sub(r"```", "", text, flags=re.IGNORECASE)
55
+
56
+ # 2. Aggressively strip preamble commands
57
+ text = re.sub(r"\\documentclass.*", "", text)
58
+ text = re.sub(r"\\usepackage\{.*?\}", "", text)
59
+ text = re.sub(r"\\begin\{document\}", "", text)
60
+ text = re.sub(r"\\end\{document\}", "", text)
61
+
62
+ # 3. Strip structural quote commands if they cause nesting issues
63
+ text = text.replace(r"\begin{quote}", "").replace(r"\end{quote}", "")
64
+
65
+ # 4. Fix common broken LaTeX syntax generated by LLMs
66
+ text = text.replace(r"&", r"\&") # Escape alignment tabs
67
+ text = re.sub(r"\\left(?![^{])", "", text) # Remove dangling left
68
+ text = re.sub(r"\\right(?![^{])", "", text) # Remove dangling right
69
+
70
+ return text.strip()
71
+
72
+ def init_worker(api_key):
73
+ global client
74
+ client = genai.Client(api_key=api_key)
75
+
76
+ @retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=2, max=10))
77
+ def call_gemini_with_retry(img, prompt):
78
+ return client.models.generate_content(
79
+ model=MODEL_NAME,
80
+ contents=[img, prompt]
81
+ )
82
+
83
+ def process_single_pdf(pdf_filename):
84
+ if pdf_filename.startswith("processed_"):
85
+ return
86
+
87
+ pdf_base = os.path.splitext(pdf_filename)[0]
88
+ workspace = os.path.join(WORK_DIR, pdf_base)
89
+ figures_dir = os.path.join(workspace, "figures")
90
+ os.makedirs(figures_dir, exist_ok=True)
91
+
92
+ log("Initializing workspace.", pdf_filename)
93
+
94
+ try:
95
+ pages = convert_from_path(pdf_filename, dpi=200)
96
+ except Exception as e:
97
+ log(f"FAILED during extraction: {e}", pdf_filename)
98
+ return
99
+
100
+ latex_content = ""
101
+
102
+ for i, page_img in enumerate(pages):
103
+ img_name = f"page_{i+1}.png"
104
+ img_path = os.path.join(figures_dir, img_name)
105
+ page_img.save(img_path, "PNG")
106
+
107
+ log(f"Transcribing page {i+1}/{len(pages)}.", pdf_filename)
108
+
109
+ # Strict prompt to prevent boilerplate hallucination
110
+ prompt = (
111
+ "Transcribe this handwritten math page into LaTeX. "
112
+ "Output ONLY the LaTeX body content. "
113
+ "DO NOT include: \\usepackage, \\documentclass, \\begin{document}, \\end{document}. "
114
+ "Ensure all math is properly closed with '$' or environment tags. "
115
+ )
116
+
117
+ try:
118
+ response = call_gemini_with_retry(page_img, prompt)
119
+ # Use \par instead of quote to avoid nested environment errors
120
+ latex_content += f"""\\subsection*{{Page {i+1}}}
121
+ \\includegraphics[width=0.6\\textwidth]{{figures/{img_name}}}
122
+ \\par {clean_output(response.text)} \\newpage\n"""
123
+ except Exception as e:
124
+ log(f"FAILED page {i+1} after retries: {e}", pdf_filename)
125
+ latex_content += f"\\subsection*{{Page {i+1}}} \\par \\textit{{Transcription failed.}} \\newpage\n"
126
+
127
+ tex_path = os.path.join(workspace, "manuscript.tex")
128
+ with open(tex_path, "w", encoding="utf-8") as f:
129
+ f.write(LATEX_TEMPLATE.format(latex_content))
130
+
131
+ log("Compiling with XeLaTeX.", pdf_filename)
132
+ try:
133
+ # Run twice to resolve references
134
+ for _ in range(2):
135
+ subprocess.run(["xelatex", "-interaction=nonstopmode", "manuscript.tex"],
136
+ cwd=workspace, stdout=subprocess.DEVNULL)
137
+
138
+ if os.path.exists(os.path.join(workspace, "manuscript.pdf")):
139
+ shutil.move(os.path.join(workspace, "manuscript.pdf"),
140
+ os.path.join(OUTPUT_DIR, f"processed_{pdf_filename}"))
141
+ log("SUCCESS.", pdf_filename)
142
+ else:
143
+ log("COMPILATION FAILED: No PDF produced.", pdf_filename)
144
+ except Exception as e:
145
+ log(f"SYSTEM ERROR: {e}", pdf_filename)
146
+
147
+ def main():
148
+ os.makedirs(OUTPUT_DIR, exist_ok=True)
149
+ os.makedirs(WORK_DIR, exist_ok=True)
150
+
151
+ files = ['amt-c-11-to20-5.pdf']
152
+ print(f"Processing {len(files)} files...")
153
+ with Pool(processes=MAX_CONCURRENT_FILES, initializer=init_worker, initargs=(API_KEY,)) as pool:
154
+ pool.map(process_single_pdf, files)
155
+
156
+ if __name__ == "__main__":
157
+ main()
turing_archive/gemini_pipeline/turing_archive/kings_patricia/process_two_pass.py ADDED
@@ -0,0 +1,377 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import shutil
3
+ import subprocess
4
+ import logging
5
+ import re
6
+ from multiprocessing import Pool
7
+ from pdf2image import convert_from_path
8
+ from google import genai
9
+ from google.genai import types
10
+ from tenacity import retry, stop_after_attempt, wait_exponential,wait_random_exponential
11
+
12
+ # ==========================================
13
+ # 1. Logging Setup
14
+ # ==========================================
15
+ logging.basicConfig(
16
+ level=logging.INFO,
17
+ format='%(asctime)s [%(levelname)s] %(message)s',
18
+ handlers=[logging.FileHandler("processing_trace.log"), logging.StreamHandler()]
19
+ )
20
+
21
+ def log(msg, filename):
22
+ logging.info(f"[{filename}] {msg}")
23
+
24
+ # ==========================================
25
+ # 2. Configuration
26
+ # ==========================================
27
+ API_KEY = "AIzaSyACloyikx6S1JqZfk3daRG9XTGwTMSWn7E"
28
+ TRANSCRIPTION_MODEL = 'gemini-2.5-flash-lite' # Fast and cheap for page images
29
+ REFINEMENT_MODEL = 'gemini-2.5-pro' # Deep reasoning for structural math cleanup
30
+ MAX_CONCURRENT_FILES = 6
31
+ INPUT_DIR = "."
32
+ OUTPUT_DIR = "./processed_pdfs"
33
+ WORK_DIR = "./workspace"
34
+
35
+ LATEX_TEMPLATE = r"""\documentclass[11pt,a4paper]{{article}}
36
+ \usepackage[utf8]{{inputenc}}
37
+ \usepackage{{amsmath, amssymb, amsfonts}}
38
+ \usepackage{{graphicx}}
39
+ \usepackage{{xcolor}}
40
+ \usepackage[normalem]{{ulem}}
41
+ \usepackage{{cancel}}
42
+ \usepackage{{enumitem}}
43
+ \usepackage{{geometry}}
44
+ \geometry{{margin=1in}}
45
+ \begin{{document}}
46
+ {}
47
+ \end{{document}}
48
+ """
49
+
50
+ def clean_output(text):
51
+ if not text:
52
+ return ""
53
+ # 1. Remove markdown code blocks
54
+ text = re.sub(r"```latex", "", text, flags=re.IGNORECASE)
55
+ text = re.sub(r"```", "", text, flags=re.IGNORECASE)
56
+
57
+ # 2. Aggressively strip preamble commands
58
+ text = re.sub(r"\\documentclass.*", "", text)
59
+ text = re.sub(r"\\usepackage\{.*?\}", "", text)
60
+ text = re.sub(r"\\begin\{document\}", "", text)
61
+ text = re.sub(r"\\end\{document\}", "", text)
62
+
63
+ # 3. Strip structural quote commands if they cause nesting issues
64
+ text = text.replace(r"\begin{quote}", "").replace(r"\end{quote}", "")
65
+
66
+ return text.strip()
67
+
68
+ def init_worker(api_key):
69
+ global client
70
+ client = genai.Client(api_key=api_key)
71
+
72
+ @retry(
73
+ stop=stop_after_attempt(7),
74
+ wait=wait_random_exponential(multiplier=2, min=15, max=65),
75
+ before_sleep=lambda retry_state: logging.warning(
76
+ f"Rate limit hit (429). Retrying in {retry_state.next_action.sleep:.2f} seconds... (Attempt {retry_state.attempt_number}/7)"
77
+ )
78
+ )
79
+ def call_gemini_with_retry(contents, prompt, is_image=True):
80
+ if is_image:
81
+ return client.models.generate_content(
82
+ model=TRANSCRIPTION_MODEL,
83
+ contents=[contents, prompt]
84
+ )
85
+ else:
86
+ # Standardize text requests and route them to the stronger PRO model
87
+ combined_payload = f"{prompt}\n\nINPUT TEXT TO REFINE:\n{contents}"
88
+ return client.models.generate_content(
89
+ model=REFINEMENT_MODEL,
90
+ contents=combined_payload
91
+ )
92
+
93
+ def process_single_pdf(pdf_filename):
94
+ if pdf_filename.startswith("processed_"):
95
+ return
96
+
97
+ pdf_base = os.path.splitext(pdf_filename)[0]
98
+ workspace = os.path.join(WORK_DIR, pdf_base)
99
+ figures_dir = os.path.join(workspace, "figures")
100
+ os.makedirs(figures_dir, exist_ok=True)
101
+
102
+ log("Initializing workspace.", pdf_filename)
103
+
104
+ try:
105
+ pages = convert_from_path(pdf_filename, dpi=150)
106
+ except Exception as e:
107
+ log(f"FAILED during extraction: {e}", pdf_filename)
108
+ return
109
+
110
+ raw_latex_body = ""
111
+
112
+ # PASS 1: Sequential Page Transcriptions (Using Flash-Lite)
113
+ for i, page_img in enumerate(pages):
114
+ img_name = f"page_{i+1}.png"
115
+ img_path = os.path.join(figures_dir, img_name)
116
+ page_img.save(img_path, "PNG")
117
+
118
+ log(f"Transcribing page {i+1}/{len(pages)} (Pass 1 - Flash-Lite).", pdf_filename)
119
+
120
+ prompt = (
121
+ "Transcribe this handwritten math page into LaTeX. "
122
+ "Output ONLY the LaTeX body content. "
123
+ "DO NOT include: \\usepackage, \\documentclass, \\begin{document}, or \\end{document}. "
124
+ "Ensure all math is properly closed with '$' or environment tags. "
125
+ )
126
+
127
+ try:
128
+ response = call_gemini_with_retry(page_img, prompt, is_image=True)
129
+ cleaned_page = clean_output(response.text)
130
+
131
+ raw_latex_body += f"""\\subsection*{{Page {i+1}}}
132
+ \\includegraphics[width=0.6\\textwidth]{{figures/{img_name}}}
133
+ \\par {cleaned_page} \\newpage\n"""
134
+ except Exception as e:
135
+ log(f"FAILED page {i+1} during Pass 1: {e}", pdf_filename)
136
+ raw_latex_body += f"\\subsection*{{Page {i+1}}} \\par \\textit{{Transcription failed.}} \\newpage\n"
137
+
138
+ # PASS 2: Global Document Refinement (Using Pro - No Compilation)
139
+ log("Refining full document syntax (Pass 2 - Gemini Pro).", pdf_filename)
140
+ refinement_prompt = (
141
+ "You are an expert LaTeX proofreader. Review the provided input document containing multi-page transcription math. "
142
+ "Fix common compilation bugs globally: ensure all math inline or display environments match, "
143
+ "ensure all braces are closed correctly, convert unmatched or dangling \\left/\\right markers into generic formatting "
144
+ "like standard parenthesis if necessary, and escape naked '&' markers outside of tables or matrices. "
145
+ "DO NOT delete the actual mathematical text or sentences under any circumstance. "
146
+ "Preserve the structural page breaks (\\newpage) and image macros intact. "
147
+ "Output ONLY the corrected body markup text without any markdown or code wrappers."
148
+ )
149
+
150
+ try:
151
+ refinement_response = call_gemini_with_retry(raw_latex_body, refinement_prompt, is_image=False)
152
+ final_latex_body = clean_output(refinement_response.text)
153
+ except Exception as e:
154
+ log(f"Refinement Pass 2 failed. Falling back to Pass 1 content. Error: {e}", pdf_filename)
155
+ final_latex_body = raw_latex_body
156
+
157
+ # Assemble into standard file structure
158
+ tex_path = os.path.join(workspace, "manuscript.tex")
159
+ with open(tex_path, "w", encoding="utf-8") as f:
160
+ f.write(LATEX_TEMPLATE.format(final_latex_body))
161
+
162
+ log("Saving output files to destination without compiling.", pdf_filename)
163
+ try:
164
+ final_dest_dir = os.path.join(OUTPUT_DIR, pdf_base)
165
+ if os.path.exists(final_dest_dir):
166
+ shutil.rmtree(final_dest_dir)
167
+
168
+ shutil.copytree(workspace, final_dest_dir)
169
+ log(f"SUCCESS. Content directory saved at {final_dest_dir}", pdf_filename)
170
+ except Exception as e:
171
+ log(f"SYSTEM COPY ERROR: {e}", pdf_filename)
172
+
173
+ def main():
174
+ os.makedirs(OUTPUT_DIR, exist_ok=True)
175
+ os.makedirs(WORK_DIR, exist_ok=True)
176
+
177
+ #files = ['amt-c-11-to20-5.pdf']
178
+ #detect all files
179
+ files = [f for f in os.listdir(INPUT_DIR) if f.endswith('.pdf') and not f.startswith("processed_")]
180
+ print(f"Processing {len(files)} files with Dual-Pass Reflection (Hybrid Flash-Lite / Pro)...")
181
+
182
+ pool = Pool(processes=MAX_CONCURRENT_FILES, initializer=init_worker, initargs=(API_KEY,))
183
+ try:
184
+ pool.map(process_single_pdf, files)
185
+ finally:
186
+ pool.close()
187
+ pool.join()
188
+
189
+ print("All file processing steps have successfully completed.")
190
+
191
+ if __name__ == "__main__":
192
+ main()
193
+
194
+ # import os
195
+ # import shutil
196
+ # import subprocess
197
+ # import logging
198
+ # import re
199
+ # from multiprocessing import Pool
200
+ # from pdf2image import convert_from_path
201
+ # from google import genai
202
+ # from google.genai import types
203
+ # from tenacity import retry, stop_after_attempt, wait_exponential
204
+
205
+ # # ==========================================
206
+ # # 1. Logging Setup
207
+ # # ==========================================
208
+ # logging.basicConfig(
209
+ # level=logging.INFO,
210
+ # format='%(asctime)s [%(levelname)s] %(message)s',
211
+ # handlers=[logging.FileHandler("processing_trace.log"), logging.StreamHandler()]
212
+ # )
213
+
214
+ # def log(msg, filename):
215
+ # logging.info(f"[{filename}] {msg}")
216
+
217
+ # # ==========================================
218
+ # # 2. Configuration
219
+ # # ==========================================
220
+ # API_KEY = "AIzaSyACloyikx6S1JqZfk3daRG9XTGwTMSWn7E"
221
+ # MODEL_NAME = 'gemini-2.5-flash-lite'
222
+ # MAX_CONCURRENT_FILES = 6
223
+ # INPUT_DIR = "."
224
+ # OUTPUT_DIR = "./processed_pdfs"
225
+ # WORK_DIR = "./workspace"
226
+
227
+ # LATEX_TEMPLATE = r"""\documentclass[11pt,a4paper]{{article}}
228
+ # \usepackage[utf8]{{inputenc}}
229
+ # \usepackage{{amsmath, amssymb, amsfonts}}
230
+ # \usepackage{{graphicx}}
231
+ # \usepackage{{xcolor}}
232
+ # \usepackage[normalem]{{ulem}}
233
+ # \usepackage{{cancel}}
234
+ # \usepackage{{enumitem}}
235
+ # \usepackage{{geometry}}
236
+ # \geometry{{margin=1in}}
237
+ # \begin{{document}}
238
+ # {}
239
+ # \end{{document}}
240
+ # """
241
+
242
+ # def clean_output(text):
243
+ # if not text:
244
+ # return ""
245
+ # # 1. Remove markdown code blocks
246
+ # text = re.sub(r"```latex", "", text, flags=re.IGNORECASE)
247
+ # text = re.sub(r"```", "", text, flags=re.IGNORECASE)
248
+
249
+ # # 2. Aggressively strip preamble commands
250
+ # text = re.sub(r"\\documentclass.*", "", text)
251
+ # text = re.sub(r"\\usepackage\{.*?\}", "", text)
252
+ # text = re.sub(r"\\begin\{document\}", "", text)
253
+ # text = re.sub(r"\\end\{document\}", "", text)
254
+
255
+ # # 3. Strip structural quote commands if they cause nesting issues
256
+ # text = text.replace(r"\begin{quote}", "").replace(r"\end{quote}", "")
257
+
258
+ # return text.strip()
259
+
260
+ # def init_worker(api_key):
261
+ # global client
262
+ # client = genai.Client(api_key=api_key)
263
+
264
+ # @retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=2, max=10))
265
+ # def call_gemini_with_retry(contents, prompt, is_image=True):
266
+ # if is_image:
267
+ # return client.models.generate_content(
268
+ # model=MODEL_NAME,
269
+ # contents=[contents, prompt]
270
+ # )
271
+ # else:
272
+ # # Standardize non-image generation requests using a single explicit text configuration payload
273
+ # combined_payload = f"{prompt}\n\nINPUT TEXT TO REFINE:\n{contents}"
274
+ # return client.models.generate_content(
275
+ # model=MODEL_NAME,
276
+ # contents=combined_payload
277
+ # )
278
+
279
+ # def process_single_pdf(pdf_filename):
280
+ # if pdf_filename.startswith("processed_"):
281
+ # return
282
+
283
+ # pdf_base = os.path.splitext(pdf_filename)[0]
284
+ # workspace = os.path.join(WORK_DIR, pdf_base)
285
+ # figures_dir = os.path.join(workspace, "figures")
286
+ # os.makedirs(figures_dir, exist_ok=True)
287
+
288
+ # log("Initializing workspace.", pdf_filename)
289
+
290
+ # try:
291
+ # pages = convert_from_path(pdf_filename, dpi=150)
292
+ # except Exception as e:
293
+ # log(f"FAILED during extraction: {e}", pdf_filename)
294
+ # return
295
+
296
+ # raw_latex_body = ""
297
+
298
+ # # PASS 1: Sequential Page Transcriptions
299
+ # for i, page_img in enumerate(pages):
300
+ # img_name = f"page_{i+1}.png"
301
+ # img_path = os.path.join(figures_dir, img_name)
302
+ # page_img.save(img_path, "PNG")
303
+
304
+ # log(f"Transcribing page {i+1}/{len(pages)} (Pass 1).", pdf_filename)
305
+
306
+ # prompt = (
307
+ # "Transcribe this handwritten math page into LaTeX. "
308
+ # "Output ONLY the LaTeX body content. "
309
+ # "DO NOT include: \\usepackage, \\documentclass, \\begin{document}, or \\end{document}. "
310
+ # "Ensure all math is properly closed with '$' or environment tags. "
311
+ # )
312
+
313
+ # try:
314
+ # response = call_gemini_with_retry(page_img, prompt, is_image=True)
315
+ # cleaned_page = clean_output(response.text)
316
+
317
+ # raw_latex_body += f"""\\subsection*{{Page {i+1}}}
318
+ # \\includegraphics[width=0.6\\textwidth]{{figures/{img_name}}}
319
+ # \\par {cleaned_page} \\newpage\n"""
320
+ # except Exception as e:
321
+ # log(f"FAILED page {i+1} during Pass 1: {e}", pdf_filename)
322
+ # raw_latex_body += f"\\subsection*{{Page {i+1}}} \\par \\textit{{Transcription failed.}} \\newpage\n"
323
+
324
+ # # PASS 2: Global Document Refinement (No Compilation)
325
+ # log("Refining full document syntax (Pass 2).", pdf_filename)
326
+ # refinement_prompt = (
327
+ # "You are an expert LaTeX proofreader. Review the provided input document containing multi-page transcription math. "
328
+ # "Fix common compilation bugs globally: ensure all math inline or display environments match, "
329
+ # "ensure all braces are closed correctly, convert unmatched or dangling \\left/\\right markers into generic formatting "
330
+ # "like standard parenthesis if necessary, and escape naked '&' markers outside of tables or matrices. "
331
+ # "DO NOT delete the actual mathematical text or sentences under any circumstance. "
332
+ # "Preserve the structural page breaks (\\newpage) and image macros intact. "
333
+ # "Output ONLY the corrected body markup text without any markdown or code wrappers."
334
+ # )
335
+
336
+ # try:
337
+ # refinement_response = call_gemini_with_retry(raw_latex_body, refinement_prompt, is_image=False)
338
+ # final_latex_body = clean_output(refinement_response.text)
339
+ # except Exception as e:
340
+ # log(f"Refinement Pass 2 failed. Falling back to Pass 1 content. Error: {e}", pdf_filename)
341
+ # final_latex_body = raw_latex_body
342
+
343
+ # # Assemble into standard file structure
344
+ # tex_path = os.path.join(workspace, "manuscript.tex")
345
+ # with open(tex_path, "w", encoding="utf-8") as f:
346
+ # f.write(LATEX_TEMPLATE.format(final_latex_body))
347
+
348
+ # log("Saving output files to destination without compiling.", pdf_filename)
349
+ # try:
350
+ # final_dest_dir = os.path.join(OUTPUT_DIR, pdf_base)
351
+ # if os.path.exists(final_dest_dir):
352
+ # shutil.rmtree(final_dest_dir)
353
+
354
+ # shutil.copytree(workspace, final_dest_dir)
355
+ # log(f"SUCCESS. Content directory saved at {final_dest_dir}", pdf_filename)
356
+ # except Exception as e:
357
+ # log(f"SYSTEM COPY ERROR: {e}", pdf_filename)
358
+
359
+ # def main():
360
+ # os.makedirs(OUTPUT_DIR, exist_ok=True)
361
+ # os.makedirs(WORK_DIR, exist_ok=True)
362
+
363
+ # files = ['amt-c-11-to20-5.pdf']
364
+ # print(f"Processing {len(files)} files with Dual-Pass Reflection...")
365
+
366
+ # # Explicitly managing the pool lifecycle ensures complete structural teardown upon map exit
367
+ # pool = Pool(processes=MAX_CONCURRENT_FILES, initializer=init_worker, initargs=(API_KEY,))
368
+ # try:
369
+ # pool.map(process_single_pdf, files)
370
+ # finally:
371
+ # pool.close()
372
+ # pool.join()
373
+
374
+ # print("All file processing steps have successfully completed.")
375
+
376
+ # if __name__ == "__main__":
377
+ # main()
turing_archive/gemini_pipeline/turing_archive/kings_patricia/processing_trace.log ADDED
The diff for this file is too large to render. See raw diff
 
turing_archive/gemini_pipeline/turing_archive/mother_correspondance/compile_latex.py ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import subprocess
3
+ import logging
4
+ from multiprocessing import Pool
5
+
6
+ # ==========================================
7
+ # Logging & Configuration Setup
8
+ # ==========================================
9
+ logging.basicConfig(
10
+ level=logging.INFO,
11
+ format='%(asctime)s [%(levelname)s] %(message)s'
12
+ )
13
+
14
+ PROCESSED_DIR = "./processed_pdfs"
15
+ TOTAL_CORES = os.cpu_count() or 1
16
+ MAX_CONCURRENT_COMPILATIONS = max(1, TOTAL_CORES - 1)
17
+ ERROR_LOG_FILE = "failed_compilations.txt" # <-- Name of your persistent error list
18
+
19
+ def compile_single_tex(dir_name):
20
+ """Worker function executed by independent CPU cores."""
21
+ target_dir = os.path.join(PROCESSED_DIR, dir_name)
22
+ tex_file = "manuscript.tex"
23
+ tex_path = os.path.join(target_dir, tex_file)
24
+
25
+ if not os.path.exists(tex_path):
26
+ return None
27
+
28
+ logging.info(f"[{dir_name}] Launching XeLaTeX compilation...")
29
+
30
+ cmd = [
31
+ "xelatex",
32
+ "-interaction=nonstopmode",
33
+ "-file-line-error",
34
+ tex_file
35
+ ]
36
+
37
+ try:
38
+ result = subprocess.run(
39
+ cmd,
40
+ cwd=target_dir,
41
+ stdout=subprocess.PIPE,
42
+ stderr=subprocess.PIPE,
43
+ text=True,
44
+ check=True
45
+ )
46
+ logging.info(f"[{dir_name}] SUCCESS. PDF compiled successfully.")
47
+ return {
48
+ "dir": dir_name,
49
+ "status": "SUCCESS",
50
+ "full_output": result.stdout,
51
+ "errors": []
52
+ }
53
+
54
+ except subprocess.CalledProcessError as e:
55
+ logging.error(f"[{dir_name}] FAILED. Engine encountered compilation syntax bugs.")
56
+
57
+ error_summary = []
58
+ for line in e.stdout.splitlines():
59
+ if "error" in line.lower() or "fatal" in line.lower() or line.startswith("!"):
60
+ error_summary.append(line.strip())
61
+
62
+ if not error_summary:
63
+ error_summary = [e.stderr.strip() if e.stderr else "Non-zero exit status thrown by engine."]
64
+
65
+ return {
66
+ "dir": dir_name,
67
+ "status": "FAILED",
68
+ "full_output": e.stdout,
69
+ "errors": error_summary
70
+ }
71
+ except Exception as e:
72
+ logging.error(f"[{dir_name}] SYSTEM CALL ERROR: {e}")
73
+ return {
74
+ "dir": dir_name,
75
+ "status": "SYSTEM_ERROR",
76
+ "full_output": "",
77
+ "errors": [str(e)]
78
+ }
79
+
80
+ def main():
81
+ if not os.path.exists(PROCESSED_DIR):
82
+ print(f"Error: The target directory '{PROCESSED_DIR}' does not exist.")
83
+ return
84
+
85
+ all_contents = os.listdir(PROCESSED_DIR)
86
+ sub_dirs = [d for d in all_contents if os.path.isdir(os.path.join(PROCESSED_DIR, d))]
87
+
88
+ if not sub_dirs:
89
+ print(f"No sub-directories detected inside '{PROCESSED_DIR}'.")
90
+ return
91
+
92
+ print(f"System detected {TOTAL_CORES} cores.")
93
+ print(f"Spawning {MAX_CONCURRENT_COMPILATIONS} parallel XeLaTeX compilation engines across folders...\n")
94
+
95
+ pool = Pool(processes=MAX_CONCURRENT_COMPILATIONS)
96
+ try:
97
+ results = [r for r in pool.map(compile_single_tex, sub_dirs) if r is not None]
98
+ finally:
99
+ pool.close()
100
+ pool.join()
101
+
102
+ # ==========================================
103
+ # Final Reporting & Full Log Aggregation
104
+ # ==========================================
105
+ print("\n" + "="*60)
106
+ print(" DETAILED XELATEX OUTPUTS & ENGINE LOGS ")
107
+ print("="*60)
108
+
109
+ for res in results:
110
+ print(f"\n📂 FOLDER DATASTREAM: {res['dir']}")
111
+ print(f"Status: {'✅ SUCCESS' if res['status'] == 'SUCCESS' else '❌ FAILED'}")
112
+ print("-" * 40)
113
+
114
+ if res['status'] == 'SUCCESS':
115
+ summary_lines = [l for l in res['full_output'].splitlines() if "Output written on" in l or "pages" in l]
116
+ if summary_lines:
117
+ for sl in summary_lines:
118
+ print(f" {sl}")
119
+ else:
120
+ print(" Document compiled successfully. (Log output compressed)")
121
+ else:
122
+ print("🛑 Engine Syntax Errors Triggered:")
123
+ for err in res['errors'][:8]:
124
+ print(f" -> {err}")
125
+
126
+ print("\n📋 Last 15 Lines of Raw Engine Context Log:")
127
+ raw_lines = res['full_output'].splitlines()
128
+ for line in raw_lines[-15:]:
129
+ print(f" | {line}")
130
+ print("-" * 60)
131
+
132
+ # ==========================================
133
+ # PERSISTENT STORAGE WRITEBACK (New Addition)
134
+ # ==========================================
135
+ failures = [r for r in results if r["status"] != "SUCCESS"]
136
+
137
+ if failures:
138
+ try:
139
+ with open(ERROR_LOG_FILE, "w", encoding="utf-8") as f:
140
+ f.write("=== FAILED COMPILATIONS MANIFEST ===\n")
141
+ f.write(f"The following folders triggered XeLaTeX layout exceptions:\n\n")
142
+ for fail in failures:
143
+ f.write(f"📁 {fail['dir']}\n")
144
+ f.write(f" Primary Error: {fail['errors'][0] if fail['errors'] else 'Unknown layout bug'}\n\n")
145
+ print(f"\n💾 Saved persistent manifest of broken runs to: {ERROR_LOG_FILE}")
146
+ except Exception as file_err:
147
+ print(f"\n⚠️ System failed to write tracking manifest to disk: {file_err}")
148
+ else:
149
+ # If a subsequent run passes completely clean, purge the old error file
150
+ if os.path.exists(ERROR_LOG_FILE):
151
+ os.remove(ERROR_LOG_FILE)
152
+
153
+ # Global Stats Banner
154
+ print("\n" + "="*60)
155
+ print(" COMPILATION METRICS ")
156
+ print("="*60)
157
+ print(f"Total Folders Processed: {len(results)}")
158
+ print(f"Flawless Conversions: {len(results) - len(failures)}")
159
+ print(f"Syntax/Layout Failures: {len(failures)}")
160
+ print("="*60)
161
+
162
+ if __name__ == "__main__":
163
+ main()
turing_archive/gemini_pipeline/turing_archive/mother_correspondance/failed_compilations.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ === FAILED COMPILATIONS MANIFEST ===
2
+ The following folders triggered XeLaTeX layout exceptions:
turing_archive/gemini_pipeline/turing_archive/mother_correspondance/process.py ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # processes and tries to compile latex.
2
+ # issue is that latex is not great,
3
+ # and i need a new way to generate that latex.
4
+ import os
5
+ import shutil
6
+ import subprocess
7
+ import logging
8
+ import re
9
+ from multiprocessing import Pool
10
+ from pdf2image import convert_from_path
11
+ from google import genai
12
+ from tenacity import retry, stop_after_attempt, wait_exponential
13
+
14
+ # ==========================================
15
+ # 1. Logging Setup
16
+ # ==========================================
17
+ logging.basicConfig(
18
+ level=logging.INFO,
19
+ format='%(asctime)s [%(levelname)s] %(message)s',
20
+ handlers=[logging.FileHandler("processing_trace.log"), logging.StreamHandler()]
21
+ )
22
+
23
+ def log(msg, filename):
24
+ logging.info(f"[{filename}] {msg}")
25
+
26
+ # ==========================================
27
+ # 2. Configuration
28
+ # ==========================================
29
+ API_KEY = "AIzaSyACloyikx6S1JqZfk3daRG9XTGwTMSWn7E"
30
+ MODEL_NAME = 'gemini-2.5-flash-lite'
31
+ MAX_CONCURRENT_FILES = 6
32
+ INPUT_DIR = "."
33
+ OUTPUT_DIR = "./processed_pdfs"
34
+ WORK_DIR = "./workspace"
35
+
36
+ LATEX_TEMPLATE = r"""\documentclass[11pt,a4paper]{{article}}
37
+ \usepackage[utf8]{{inputenc}}
38
+ \usepackage{{amsmath, amssymb, amsfonts}}
39
+ \usepackage{{graphicx}}
40
+ \usepackage{{xcolor}}
41
+ \usepackage[normalem]{{ulem}}
42
+ \usepackage{{cancel}}
43
+ \usepackage{{enumitem}}
44
+ \usepackage{{geometry}}
45
+ \geometry{{margin=1in}}
46
+ \begin{{document}}
47
+ {}
48
+ \end{{document}}
49
+ """
50
+
51
+ def clean_output(text):
52
+ # 1. Remove markdown code blocks
53
+ text = re.sub(r"```latex", "", text, flags=re.IGNORECASE)
54
+ text = re.sub(r"```", "", text, flags=re.IGNORECASE)
55
+
56
+ # 2. Aggressively strip preamble commands
57
+ text = re.sub(r"\\documentclass.*", "", text)
58
+ text = re.sub(r"\\usepackage\{.*?\}", "", text)
59
+ text = re.sub(r"\\begin\{document\}", "", text)
60
+ text = re.sub(r"\\end\{document\}", "", text)
61
+
62
+ # 3. Strip structural quote commands if they cause nesting issues
63
+ text = text.replace(r"\begin{quote}", "").replace(r"\end{quote}", "")
64
+
65
+ # 4. Fix common broken LaTeX syntax generated by LLMs
66
+ text = text.replace(r"&", r"\&") # Escape alignment tabs
67
+ text = re.sub(r"\\left(?![^{])", "", text) # Remove dangling left
68
+ text = re.sub(r"\\right(?![^{])", "", text) # Remove dangling right
69
+
70
+ return text.strip()
71
+
72
+ def init_worker(api_key):
73
+ global client
74
+ client = genai.Client(api_key=api_key)
75
+
76
+ @retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=2, max=10))
77
+ def call_gemini_with_retry(img, prompt):
78
+ return client.models.generate_content(
79
+ model=MODEL_NAME,
80
+ contents=[img, prompt]
81
+ )
82
+
83
+ def process_single_pdf(pdf_filename):
84
+ if pdf_filename.startswith("processed_"):
85
+ return
86
+
87
+ pdf_base = os.path.splitext(pdf_filename)[0]
88
+ workspace = os.path.join(WORK_DIR, pdf_base)
89
+ figures_dir = os.path.join(workspace, "figures")
90
+ os.makedirs(figures_dir, exist_ok=True)
91
+
92
+ log("Initializing workspace.", pdf_filename)
93
+
94
+ try:
95
+ pages = convert_from_path(pdf_filename, dpi=200)
96
+ except Exception as e:
97
+ log(f"FAILED during extraction: {e}", pdf_filename)
98
+ return
99
+
100
+ latex_content = ""
101
+
102
+ for i, page_img in enumerate(pages):
103
+ img_name = f"page_{i+1}.png"
104
+ img_path = os.path.join(figures_dir, img_name)
105
+ page_img.save(img_path, "PNG")
106
+
107
+ log(f"Transcribing page {i+1}/{len(pages)}.", pdf_filename)
108
+
109
+ # Strict prompt to prevent boilerplate hallucination
110
+ prompt = (
111
+ "Transcribe this handwritten math page into LaTeX. "
112
+ "Output ONLY the LaTeX body content. "
113
+ "DO NOT include: \\usepackage, \\documentclass, \\begin{document}, \\end{document}. "
114
+ "Ensure all math is properly closed with '$' or environment tags. "
115
+ )
116
+
117
+ try:
118
+ response = call_gemini_with_retry(page_img, prompt)
119
+ # Use \par instead of quote to avoid nested environment errors
120
+ latex_content += f"""\\subsection*{{Page {i+1}}}
121
+ \\includegraphics[width=0.6\\textwidth]{{figures/{img_name}}}
122
+ \\par {clean_output(response.text)} \\newpage\n"""
123
+ except Exception as e:
124
+ log(f"FAILED page {i+1} after retries: {e}", pdf_filename)
125
+ latex_content += f"\\subsection*{{Page {i+1}}} \\par \\textit{{Transcription failed.}} \\newpage\n"
126
+
127
+ tex_path = os.path.join(workspace, "manuscript.tex")
128
+ with open(tex_path, "w", encoding="utf-8") as f:
129
+ f.write(LATEX_TEMPLATE.format(latex_content))
130
+
131
+ log("Compiling with XeLaTeX.", pdf_filename)
132
+ try:
133
+ # Run twice to resolve references
134
+ for _ in range(2):
135
+ subprocess.run(["xelatex", "-interaction=nonstopmode", "manuscript.tex"],
136
+ cwd=workspace, stdout=subprocess.DEVNULL)
137
+
138
+ if os.path.exists(os.path.join(workspace, "manuscript.pdf")):
139
+ shutil.move(os.path.join(workspace, "manuscript.pdf"),
140
+ os.path.join(OUTPUT_DIR, f"processed_{pdf_filename}"))
141
+ log("SUCCESS.", pdf_filename)
142
+ else:
143
+ log("COMPILATION FAILED: No PDF produced.", pdf_filename)
144
+ except Exception as e:
145
+ log(f"SYSTEM ERROR: {e}", pdf_filename)
146
+
147
+ def main():
148
+ os.makedirs(OUTPUT_DIR, exist_ok=True)
149
+ os.makedirs(WORK_DIR, exist_ok=True)
150
+
151
+ files = ['amt-c-11-to20-5.pdf']
152
+ print(f"Processing {len(files)} files...")
153
+ with Pool(processes=MAX_CONCURRENT_FILES, initializer=init_worker, initargs=(API_KEY,)) as pool:
154
+ pool.map(process_single_pdf, files)
155
+
156
+ if __name__ == "__main__":
157
+ main()
turing_archive/gemini_pipeline/turing_archive/mother_correspondance/process_two_pass.py ADDED
@@ -0,0 +1,377 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import shutil
3
+ import subprocess
4
+ import logging
5
+ import re
6
+ from multiprocessing import Pool
7
+ from pdf2image import convert_from_path
8
+ from google import genai
9
+ from google.genai import types
10
+ from tenacity import retry, stop_after_attempt, wait_exponential,wait_random_exponential
11
+
12
+ # ==========================================
13
+ # 1. Logging Setup
14
+ # ==========================================
15
+ logging.basicConfig(
16
+ level=logging.INFO,
17
+ format='%(asctime)s [%(levelname)s] %(message)s',
18
+ handlers=[logging.FileHandler("processing_trace.log"), logging.StreamHandler()]
19
+ )
20
+
21
+ def log(msg, filename):
22
+ logging.info(f"[{filename}] {msg}")
23
+
24
+ # ==========================================
25
+ # 2. Configuration
26
+ # ==========================================
27
+ API_KEY = "AIzaSyACloyikx6S1JqZfk3daRG9XTGwTMSWn7E"
28
+ TRANSCRIPTION_MODEL = 'gemini-2.5-flash-lite' # Fast and cheap for page images
29
+ REFINEMENT_MODEL = 'gemini-2.5-pro' # Deep reasoning for structural math cleanup
30
+ MAX_CONCURRENT_FILES = 6
31
+ INPUT_DIR = "."
32
+ OUTPUT_DIR = "./processed_pdfs"
33
+ WORK_DIR = "./workspace"
34
+
35
+ LATEX_TEMPLATE = r"""\documentclass[11pt,a4paper]{{article}}
36
+ \usepackage[utf8]{{inputenc}}
37
+ \usepackage{{amsmath, amssymb, amsfonts}}
38
+ \usepackage{{graphicx}}
39
+ \usepackage{{xcolor}}
40
+ \usepackage[normalem]{{ulem}}
41
+ \usepackage{{cancel}}
42
+ \usepackage{{enumitem}}
43
+ \usepackage{{geometry}}
44
+ \geometry{{margin=1in}}
45
+ \begin{{document}}
46
+ {}
47
+ \end{{document}}
48
+ """
49
+
50
+ def clean_output(text):
51
+ if not text:
52
+ return ""
53
+ # 1. Remove markdown code blocks
54
+ text = re.sub(r"```latex", "", text, flags=re.IGNORECASE)
55
+ text = re.sub(r"```", "", text, flags=re.IGNORECASE)
56
+
57
+ # 2. Aggressively strip preamble commands
58
+ text = re.sub(r"\\documentclass.*", "", text)
59
+ text = re.sub(r"\\usepackage\{.*?\}", "", text)
60
+ text = re.sub(r"\\begin\{document\}", "", text)
61
+ text = re.sub(r"\\end\{document\}", "", text)
62
+
63
+ # 3. Strip structural quote commands if they cause nesting issues
64
+ text = text.replace(r"\begin{quote}", "").replace(r"\end{quote}", "")
65
+
66
+ return text.strip()
67
+
68
+ def init_worker(api_key):
69
+ global client
70
+ client = genai.Client(api_key=api_key)
71
+
72
+ @retry(
73
+ stop=stop_after_attempt(7),
74
+ wait=wait_random_exponential(multiplier=2, min=15, max=65),
75
+ before_sleep=lambda retry_state: logging.warning(
76
+ f"Rate limit hit (429). Retrying in {retry_state.next_action.sleep:.2f} seconds... (Attempt {retry_state.attempt_number}/7)"
77
+ )
78
+ )
79
+ def call_gemini_with_retry(contents, prompt, is_image=True):
80
+ if is_image:
81
+ return client.models.generate_content(
82
+ model=TRANSCRIPTION_MODEL,
83
+ contents=[contents, prompt]
84
+ )
85
+ else:
86
+ # Standardize text requests and route them to the stronger PRO model
87
+ combined_payload = f"{prompt}\n\nINPUT TEXT TO REFINE:\n{contents}"
88
+ return client.models.generate_content(
89
+ model=REFINEMENT_MODEL,
90
+ contents=combined_payload
91
+ )
92
+
93
+ def process_single_pdf(pdf_filename):
94
+ if pdf_filename.startswith("processed_"):
95
+ return
96
+
97
+ pdf_base = os.path.splitext(pdf_filename)[0]
98
+ workspace = os.path.join(WORK_DIR, pdf_base)
99
+ figures_dir = os.path.join(workspace, "figures")
100
+ os.makedirs(figures_dir, exist_ok=True)
101
+
102
+ log("Initializing workspace.", pdf_filename)
103
+
104
+ try:
105
+ pages = convert_from_path(pdf_filename, dpi=150)
106
+ except Exception as e:
107
+ log(f"FAILED during extraction: {e}", pdf_filename)
108
+ return
109
+
110
+ raw_latex_body = ""
111
+
112
+ # PASS 1: Sequential Page Transcriptions (Using Flash-Lite)
113
+ for i, page_img in enumerate(pages):
114
+ img_name = f"page_{i+1}.png"
115
+ img_path = os.path.join(figures_dir, img_name)
116
+ page_img.save(img_path, "PNG")
117
+
118
+ log(f"Transcribing page {i+1}/{len(pages)} (Pass 1 - Flash-Lite).", pdf_filename)
119
+
120
+ prompt = (
121
+ "Transcribe this handwritten math page into LaTeX. "
122
+ "Output ONLY the LaTeX body content. "
123
+ "DO NOT include: \\usepackage, \\documentclass, \\begin{document}, or \\end{document}. "
124
+ "Ensure all math is properly closed with '$' or environment tags. "
125
+ )
126
+
127
+ try:
128
+ response = call_gemini_with_retry(page_img, prompt, is_image=True)
129
+ cleaned_page = clean_output(response.text)
130
+
131
+ raw_latex_body += f"""\\subsection*{{Page {i+1}}}
132
+ \\includegraphics[width=0.6\\textwidth]{{figures/{img_name}}}
133
+ \\par {cleaned_page} \\newpage\n"""
134
+ except Exception as e:
135
+ log(f"FAILED page {i+1} during Pass 1: {e}", pdf_filename)
136
+ raw_latex_body += f"\\subsection*{{Page {i+1}}} \\par \\textit{{Transcription failed.}} \\newpage\n"
137
+
138
+ # PASS 2: Global Document Refinement (Using Pro - No Compilation)
139
+ log("Refining full document syntax (Pass 2 - Gemini Pro).", pdf_filename)
140
+ refinement_prompt = (
141
+ "You are an expert LaTeX proofreader. Review the provided input document containing multi-page transcription math. "
142
+ "Fix common compilation bugs globally: ensure all math inline or display environments match, "
143
+ "ensure all braces are closed correctly, convert unmatched or dangling \\left/\\right markers into generic formatting "
144
+ "like standard parenthesis if necessary, and escape naked '&' markers outside of tables or matrices. "
145
+ "DO NOT delete the actual mathematical text or sentences under any circumstance. "
146
+ "Preserve the structural page breaks (\\newpage) and image macros intact. "
147
+ "Output ONLY the corrected body markup text without any markdown or code wrappers."
148
+ )
149
+
150
+ try:
151
+ refinement_response = call_gemini_with_retry(raw_latex_body, refinement_prompt, is_image=False)
152
+ final_latex_body = clean_output(refinement_response.text)
153
+ except Exception as e:
154
+ log(f"Refinement Pass 2 failed. Falling back to Pass 1 content. Error: {e}", pdf_filename)
155
+ final_latex_body = raw_latex_body
156
+
157
+ # Assemble into standard file structure
158
+ tex_path = os.path.join(workspace, "manuscript.tex")
159
+ with open(tex_path, "w", encoding="utf-8") as f:
160
+ f.write(LATEX_TEMPLATE.format(final_latex_body))
161
+
162
+ log("Saving output files to destination without compiling.", pdf_filename)
163
+ try:
164
+ final_dest_dir = os.path.join(OUTPUT_DIR, pdf_base)
165
+ if os.path.exists(final_dest_dir):
166
+ shutil.rmtree(final_dest_dir)
167
+
168
+ shutil.copytree(workspace, final_dest_dir)
169
+ log(f"SUCCESS. Content directory saved at {final_dest_dir}", pdf_filename)
170
+ except Exception as e:
171
+ log(f"SYSTEM COPY ERROR: {e}", pdf_filename)
172
+
173
+ def main():
174
+ os.makedirs(OUTPUT_DIR, exist_ok=True)
175
+ os.makedirs(WORK_DIR, exist_ok=True)
176
+
177
+ #files = ['amt-c-11-to20-5.pdf']
178
+ #detect all files
179
+ files = [f for f in os.listdir(INPUT_DIR) if f.endswith('.pdf') and not f.startswith("processed_")]
180
+ print(f"Processing {len(files)} files with Dual-Pass Reflection (Hybrid Flash-Lite / Pro)...")
181
+
182
+ pool = Pool(processes=MAX_CONCURRENT_FILES, initializer=init_worker, initargs=(API_KEY,))
183
+ try:
184
+ pool.map(process_single_pdf, files)
185
+ finally:
186
+ pool.close()
187
+ pool.join()
188
+
189
+ print("All file processing steps have successfully completed.")
190
+
191
+ if __name__ == "__main__":
192
+ main()
193
+
194
+ # import os
195
+ # import shutil
196
+ # import subprocess
197
+ # import logging
198
+ # import re
199
+ # from multiprocessing import Pool
200
+ # from pdf2image import convert_from_path
201
+ # from google import genai
202
+ # from google.genai import types
203
+ # from tenacity import retry, stop_after_attempt, wait_exponential
204
+
205
+ # # ==========================================
206
+ # # 1. Logging Setup
207
+ # # ==========================================
208
+ # logging.basicConfig(
209
+ # level=logging.INFO,
210
+ # format='%(asctime)s [%(levelname)s] %(message)s',
211
+ # handlers=[logging.FileHandler("processing_trace.log"), logging.StreamHandler()]
212
+ # )
213
+
214
+ # def log(msg, filename):
215
+ # logging.info(f"[{filename}] {msg}")
216
+
217
+ # # ==========================================
218
+ # # 2. Configuration
219
+ # # ==========================================
220
+ # API_KEY = "AIzaSyACloyikx6S1JqZfk3daRG9XTGwTMSWn7E"
221
+ # MODEL_NAME = 'gemini-2.5-flash-lite'
222
+ # MAX_CONCURRENT_FILES = 6
223
+ # INPUT_DIR = "."
224
+ # OUTPUT_DIR = "./processed_pdfs"
225
+ # WORK_DIR = "./workspace"
226
+
227
+ # LATEX_TEMPLATE = r"""\documentclass[11pt,a4paper]{{article}}
228
+ # \usepackage[utf8]{{inputenc}}
229
+ # \usepackage{{amsmath, amssymb, amsfonts}}
230
+ # \usepackage{{graphicx}}
231
+ # \usepackage{{xcolor}}
232
+ # \usepackage[normalem]{{ulem}}
233
+ # \usepackage{{cancel}}
234
+ # \usepackage{{enumitem}}
235
+ # \usepackage{{geometry}}
236
+ # \geometry{{margin=1in}}
237
+ # \begin{{document}}
238
+ # {}
239
+ # \end{{document}}
240
+ # """
241
+
242
+ # def clean_output(text):
243
+ # if not text:
244
+ # return ""
245
+ # # 1. Remove markdown code blocks
246
+ # text = re.sub(r"```latex", "", text, flags=re.IGNORECASE)
247
+ # text = re.sub(r"```", "", text, flags=re.IGNORECASE)
248
+
249
+ # # 2. Aggressively strip preamble commands
250
+ # text = re.sub(r"\\documentclass.*", "", text)
251
+ # text = re.sub(r"\\usepackage\{.*?\}", "", text)
252
+ # text = re.sub(r"\\begin\{document\}", "", text)
253
+ # text = re.sub(r"\\end\{document\}", "", text)
254
+
255
+ # # 3. Strip structural quote commands if they cause nesting issues
256
+ # text = text.replace(r"\begin{quote}", "").replace(r"\end{quote}", "")
257
+
258
+ # return text.strip()
259
+
260
+ # def init_worker(api_key):
261
+ # global client
262
+ # client = genai.Client(api_key=api_key)
263
+
264
+ # @retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=2, max=10))
265
+ # def call_gemini_with_retry(contents, prompt, is_image=True):
266
+ # if is_image:
267
+ # return client.models.generate_content(
268
+ # model=MODEL_NAME,
269
+ # contents=[contents, prompt]
270
+ # )
271
+ # else:
272
+ # # Standardize non-image generation requests using a single explicit text configuration payload
273
+ # combined_payload = f"{prompt}\n\nINPUT TEXT TO REFINE:\n{contents}"
274
+ # return client.models.generate_content(
275
+ # model=MODEL_NAME,
276
+ # contents=combined_payload
277
+ # )
278
+
279
+ # def process_single_pdf(pdf_filename):
280
+ # if pdf_filename.startswith("processed_"):
281
+ # return
282
+
283
+ # pdf_base = os.path.splitext(pdf_filename)[0]
284
+ # workspace = os.path.join(WORK_DIR, pdf_base)
285
+ # figures_dir = os.path.join(workspace, "figures")
286
+ # os.makedirs(figures_dir, exist_ok=True)
287
+
288
+ # log("Initializing workspace.", pdf_filename)
289
+
290
+ # try:
291
+ # pages = convert_from_path(pdf_filename, dpi=150)
292
+ # except Exception as e:
293
+ # log(f"FAILED during extraction: {e}", pdf_filename)
294
+ # return
295
+
296
+ # raw_latex_body = ""
297
+
298
+ # # PASS 1: Sequential Page Transcriptions
299
+ # for i, page_img in enumerate(pages):
300
+ # img_name = f"page_{i+1}.png"
301
+ # img_path = os.path.join(figures_dir, img_name)
302
+ # page_img.save(img_path, "PNG")
303
+
304
+ # log(f"Transcribing page {i+1}/{len(pages)} (Pass 1).", pdf_filename)
305
+
306
+ # prompt = (
307
+ # "Transcribe this handwritten math page into LaTeX. "
308
+ # "Output ONLY the LaTeX body content. "
309
+ # "DO NOT include: \\usepackage, \\documentclass, \\begin{document}, or \\end{document}. "
310
+ # "Ensure all math is properly closed with '$' or environment tags. "
311
+ # )
312
+
313
+ # try:
314
+ # response = call_gemini_with_retry(page_img, prompt, is_image=True)
315
+ # cleaned_page = clean_output(response.text)
316
+
317
+ # raw_latex_body += f"""\\subsection*{{Page {i+1}}}
318
+ # \\includegraphics[width=0.6\\textwidth]{{figures/{img_name}}}
319
+ # \\par {cleaned_page} \\newpage\n"""
320
+ # except Exception as e:
321
+ # log(f"FAILED page {i+1} during Pass 1: {e}", pdf_filename)
322
+ # raw_latex_body += f"\\subsection*{{Page {i+1}}} \\par \\textit{{Transcription failed.}} \\newpage\n"
323
+
324
+ # # PASS 2: Global Document Refinement (No Compilation)
325
+ # log("Refining full document syntax (Pass 2).", pdf_filename)
326
+ # refinement_prompt = (
327
+ # "You are an expert LaTeX proofreader. Review the provided input document containing multi-page transcription math. "
328
+ # "Fix common compilation bugs globally: ensure all math inline or display environments match, "
329
+ # "ensure all braces are closed correctly, convert unmatched or dangling \\left/\\right markers into generic formatting "
330
+ # "like standard parenthesis if necessary, and escape naked '&' markers outside of tables or matrices. "
331
+ # "DO NOT delete the actual mathematical text or sentences under any circumstance. "
332
+ # "Preserve the structural page breaks (\\newpage) and image macros intact. "
333
+ # "Output ONLY the corrected body markup text without any markdown or code wrappers."
334
+ # )
335
+
336
+ # try:
337
+ # refinement_response = call_gemini_with_retry(raw_latex_body, refinement_prompt, is_image=False)
338
+ # final_latex_body = clean_output(refinement_response.text)
339
+ # except Exception as e:
340
+ # log(f"Refinement Pass 2 failed. Falling back to Pass 1 content. Error: {e}", pdf_filename)
341
+ # final_latex_body = raw_latex_body
342
+
343
+ # # Assemble into standard file structure
344
+ # tex_path = os.path.join(workspace, "manuscript.tex")
345
+ # with open(tex_path, "w", encoding="utf-8") as f:
346
+ # f.write(LATEX_TEMPLATE.format(final_latex_body))
347
+
348
+ # log("Saving output files to destination without compiling.", pdf_filename)
349
+ # try:
350
+ # final_dest_dir = os.path.join(OUTPUT_DIR, pdf_base)
351
+ # if os.path.exists(final_dest_dir):
352
+ # shutil.rmtree(final_dest_dir)
353
+
354
+ # shutil.copytree(workspace, final_dest_dir)
355
+ # log(f"SUCCESS. Content directory saved at {final_dest_dir}", pdf_filename)
356
+ # except Exception as e:
357
+ # log(f"SYSTEM COPY ERROR: {e}", pdf_filename)
358
+
359
+ # def main():
360
+ # os.makedirs(OUTPUT_DIR, exist_ok=True)
361
+ # os.makedirs(WORK_DIR, exist_ok=True)
362
+
363
+ # files = ['amt-c-11-to20-5.pdf']
364
+ # print(f"Processing {len(files)} files with Dual-Pass Reflection...")
365
+
366
+ # # Explicitly managing the pool lifecycle ensures complete structural teardown upon map exit
367
+ # pool = Pool(processes=MAX_CONCURRENT_FILES, initializer=init_worker, initargs=(API_KEY,))
368
+ # try:
369
+ # pool.map(process_single_pdf, files)
370
+ # finally:
371
+ # pool.close()
372
+ # pool.join()
373
+
374
+ # print("All file processing steps have successfully completed.")
375
+
376
+ # if __name__ == "__main__":
377
+ # main()
turing_archive/gemini_pipeline/turing_archive/mother_correspondance/process_two_pass_gemini_flash.py ADDED
@@ -0,0 +1,193 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import shutil
3
+ import subprocess
4
+ import logging
5
+ import re
6
+ from multiprocessing import Pool
7
+ from pdf2image import convert_from_path
8
+ from google import genai
9
+ from google.genai import types
10
+ from tenacity import retry, stop_after_attempt, wait_exponential,wait_random_exponential
11
+
12
+ # ==========================================
13
+ # 1. Logging Setup
14
+ # ==========================================
15
+ logging.basicConfig(
16
+ level=logging.INFO,
17
+ format='%(asctime)s [%(levelname)s] %(message)s',
18
+ handlers=[logging.FileHandler("processing_trace.log"), logging.StreamHandler()]
19
+ )
20
+
21
+ def log(msg, filename):
22
+ logging.info(f"[{filename}] {msg}")
23
+
24
+ # ==========================================
25
+ # 2. Configuration
26
+ # ==========================================
27
+ API_KEY = "AIzaSyACloyikx6S1JqZfk3daRG9XTGwTMSWn7E"
28
+ TRANSCRIPTION_MODEL = 'gemini-2.5-flash' # Fast and cheap for page images
29
+ REFINEMENT_MODEL = 'gemini-2.5-pro' # Deep reasoning for structural math cleanup
30
+ MAX_CONCURRENT_FILES = 6
31
+ INPUT_DIR = "."
32
+ OUTPUT_DIR = "./processed_pdfs"
33
+ WORK_DIR = "./workspace"
34
+
35
+ LATEX_TEMPLATE = r"""\documentclass[11pt,a4paper]{{article}}
36
+ \usepackage[utf8]{{inputenc}}
37
+ \usepackage{{amsmath, amssymb, amsfonts}}
38
+ \usepackage{{graphicx}}
39
+ \usepackage{{xcolor}}
40
+ \usepackage[normalem]{{ulem}}
41
+ \usepackage{{cancel}}
42
+ \usepackage{{enumitem}}
43
+ \usepackage{{geometry}}
44
+ \geometry{{margin=1in}}
45
+ \begin{{document}}
46
+ {}
47
+ \end{{document}}
48
+ """
49
+
50
+ def clean_output(text):
51
+ if not text:
52
+ return ""
53
+ # 1. Remove markdown code blocks
54
+ text = re.sub(r"```latex", "", text, flags=re.IGNORECASE)
55
+ text = re.sub(r"```", "", text, flags=re.IGNORECASE)
56
+
57
+ # 2. Aggressively strip preamble commands
58
+ text = re.sub(r"\\documentclass.*", "", text)
59
+ text = re.sub(r"\\usepackage\{.*?\}", "", text)
60
+ text = re.sub(r"\\begin\{document\}", "", text)
61
+ text = re.sub(r"\\end\{document\}", "", text)
62
+
63
+ # 3. Strip structural quote commands if they cause nesting issues
64
+ text = text.replace(r"\begin{quote}", "").replace(r"\end{quote}", "")
65
+
66
+ return text.strip()
67
+
68
+ def init_worker(api_key):
69
+ global client
70
+ client = genai.Client(api_key=api_key)
71
+
72
+ @retry(
73
+ stop=stop_after_attempt(7),
74
+ wait=wait_random_exponential(multiplier=2, min=15, max=65),
75
+ before_sleep=lambda retry_state: logging.warning(
76
+ f"Rate limit hit (429). Retrying in {retry_state.next_action.sleep:.2f} seconds... (Attempt {retry_state.attempt_number}/7)"
77
+ )
78
+ )
79
+ def call_gemini_with_retry(contents, prompt, is_image=True):
80
+ if is_image:
81
+ return client.models.generate_content(
82
+ model=TRANSCRIPTION_MODEL,
83
+ contents=[contents, prompt]
84
+ )
85
+ else:
86
+ # Standardize text requests and route them to the stronger PRO model
87
+ combined_payload = f"{prompt}\n\nINPUT TEXT TO REFINE:\n{contents}"
88
+ return client.models.generate_content(
89
+ model=REFINEMENT_MODEL,
90
+ contents=combined_payload
91
+ )
92
+
93
+ def process_single_pdf(pdf_filename):
94
+ if pdf_filename.startswith("processed_"):
95
+ return
96
+
97
+ pdf_base = os.path.splitext(pdf_filename)[0]
98
+ workspace = os.path.join(WORK_DIR, pdf_base)
99
+ figures_dir = os.path.join(workspace, "figures")
100
+ os.makedirs(figures_dir, exist_ok=True)
101
+
102
+ log("Initializing workspace.", pdf_filename)
103
+
104
+ try:
105
+ pages = convert_from_path(pdf_filename, dpi=150)
106
+ except Exception as e:
107
+ log(f"FAILED during extraction: {e}", pdf_filename)
108
+ return
109
+
110
+ raw_latex_body = ""
111
+
112
+ # PASS 1: Sequential Page Transcriptions (Using Flash-Lite)
113
+ for i, page_img in enumerate(pages):
114
+ img_name = f"page_{i+1}.png"
115
+ img_path = os.path.join(figures_dir, img_name)
116
+ page_img.save(img_path, "PNG")
117
+
118
+ log(f"Transcribing page {i+1}/{len(pages)} (Pass 1 - Flash).", pdf_filename)
119
+
120
+ prompt = (
121
+ "Transcribe this handwritten math page into LaTeX. "
122
+ "Output ONLY the LaTeX body content. "
123
+ "DO NOT include: \\usepackage, \\documentclass, \\begin{document}, or \\end{document}. "
124
+ "Ensure all math is properly closed with '$' or environment tags. "
125
+ )
126
+
127
+ try:
128
+ response = call_gemini_with_retry(page_img, prompt, is_image=True)
129
+ cleaned_page = clean_output(response.text)
130
+
131
+ raw_latex_body += f"""\\subsection*{{Page {i+1}}}
132
+ \\includegraphics[width=0.6\\textwidth]{{figures/{img_name}}}
133
+ \\par {cleaned_page} \\newpage\n"""
134
+ except Exception as e:
135
+ log(f"FAILED page {i+1} during Pass 1: {e}", pdf_filename)
136
+ raw_latex_body += f"\\subsection*{{Page {i+1}}} \\par \\textit{{Transcription failed.}} \\newpage\n"
137
+
138
+ # PASS 2: Global Document Refinement (Using Pro - No Compilation)
139
+ log("Refining full document syntax (Pass 2 - Gemini Pro).", pdf_filename)
140
+ refinement_prompt = (
141
+ "You are an expert LaTeX proofreader. Review the provided input document containing multi-page transcription math. "
142
+ "Fix common compilation bugs globally: ensure all math inline or display environments match, "
143
+ "ensure all braces are closed correctly, convert unmatched or dangling \\left/\\right markers into generic formatting "
144
+ "like standard parenthesis if necessary, and escape naked '&' markers outside of tables or matrices. "
145
+ "DO NOT delete the actual mathematical text or sentences under any circumstance. "
146
+ "Preserve the structural page breaks (\\newpage) and image macros intact. "
147
+ "Output ONLY the corrected body markup text without any markdown or code wrappers."
148
+ )
149
+
150
+ try:
151
+ refinement_response = call_gemini_with_retry(raw_latex_body, refinement_prompt, is_image=False)
152
+ final_latex_body = clean_output(refinement_response.text)
153
+ except Exception as e:
154
+ log(f"Refinement Pass 2 failed. Falling back to Pass 1 content. Error: {e}", pdf_filename)
155
+ final_latex_body = raw_latex_body
156
+
157
+ # Assemble into standard file structure
158
+ tex_path = os.path.join(workspace, "manuscript.tex")
159
+ with open(tex_path, "w", encoding="utf-8") as f:
160
+ f.write(LATEX_TEMPLATE.format(final_latex_body))
161
+
162
+ log("Saving output files to destination without compiling.", pdf_filename)
163
+ try:
164
+ final_dest_dir = os.path.join(OUTPUT_DIR, pdf_base)
165
+ if os.path.exists(final_dest_dir):
166
+ shutil.rmtree(final_dest_dir)
167
+
168
+ shutil.copytree(workspace, final_dest_dir)
169
+ log(f"SUCCESS. Content directory saved at {final_dest_dir}", pdf_filename)
170
+ except Exception as e:
171
+ log(f"SYSTEM COPY ERROR: {e}", pdf_filename)
172
+
173
+ def main():
174
+ os.makedirs(OUTPUT_DIR, exist_ok=True)
175
+ os.makedirs(WORK_DIR, exist_ok=True)
176
+
177
+ #files = ['amt-c-11-to20-5.pdf']
178
+ #detect all files
179
+ # files = [f for f in os.listdir(INPUT_DIR) if f.endswith('.pdf') and not f.startswith("processed_")]
180
+ files = ['amt-b-16-30-17.pdf','amt-b-31-57-3.pdf']
181
+ print(f"Processing {len(files)} files with Dual-Pass Reflection (Hybrid Flash-Lite / Pro)...")
182
+
183
+ pool = Pool(processes=MAX_CONCURRENT_FILES, initializer=init_worker, initargs=(API_KEY,))
184
+ try:
185
+ pool.map(process_single_pdf, files)
186
+ finally:
187
+ pool.close()
188
+ pool.join()
189
+
190
+ print("All file processing steps have successfully completed.")
191
+
192
+ if __name__ == "__main__":
193
+ main()
turing_archive/gemini_pipeline/turing_archive/mother_correspondance/processing_trace.log ADDED
@@ -0,0 +1,873 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 2026-06-13 20:13:47,504 [INFO] [amt-d-11.pdf] Initializing workspace.
2
+ 2026-06-13 20:13:47,506 [INFO] [amt-d-13.pdf] Initializing workspace.
3
+ 2026-06-13 20:13:47,506 [INFO] [amt-d-15.pdf] Initializing workspace.
4
+ 2026-06-13 20:13:47,508 [INFO] [amt-d-17.pdf] Initializing workspace.
5
+ 2026-06-13 20:13:47,509 [INFO] [amt-d-19.pdf] Initializing workspace.
6
+ 2026-06-13 20:13:47,509 [INFO] [amt-d-21.pdf] Initializing workspace.
7
+ 2026-06-13 20:13:47,958 [INFO] [amt-d-21.pdf] Transcribing page 1/2 (Pass 1 - Flash-Lite).
8
+ 2026-06-13 20:13:47,959 [INFO] AFC is enabled with max remote calls: 10.
9
+ 2026-06-13 20:13:48,092 [INFO] [amt-d-11.pdf] Transcribing page 1/1 (Pass 1 - Flash-Lite).
10
+ 2026-06-13 20:13:48,092 [INFO] AFC is enabled with max remote calls: 10.
11
+ 2026-06-13 20:13:48,149 [INFO] [amt-d-15.pdf] Transcribing page 1/3 (Pass 1 - Flash-Lite).
12
+ 2026-06-13 20:13:48,149 [INFO] AFC is enabled with max remote calls: 10.
13
+ 2026-06-13 20:13:48,420 [INFO] [amt-d-17.pdf] Transcribing page 1/10 (Pass 1 - Flash-Lite).
14
+ 2026-06-13 20:13:48,420 [INFO] AFC is enabled with max remote calls: 10.
15
+ 2026-06-13 20:13:48,443 [INFO] [amt-d-13.pdf] Transcribing page 1/8 (Pass 1 - Flash-Lite).
16
+ 2026-06-13 20:13:48,443 [INFO] AFC is enabled with max remote calls: 10.
17
+ 2026-06-13 20:13:48,698 [INFO] [amt-d-19.pdf] Transcribing page 1/14 (Pass 1 - Flash-Lite).
18
+ 2026-06-13 20:13:48,699 [INFO] AFC is enabled with max remote calls: 10.
19
+ 2026-06-13 20:13:50,581 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
20
+ 2026-06-13 20:13:50,756 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
21
+ 2026-06-13 20:13:51,058 [INFO] [amt-d-17.pdf] Transcribing page 2/10 (Pass 1 - Flash-Lite).
22
+ 2026-06-13 20:13:51,058 [INFO] AFC is enabled with max remote calls: 10.
23
+ 2026-06-13 20:13:51,095 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
24
+ 2026-06-13 20:13:51,095 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
25
+ 2026-06-13 20:13:51,347 [INFO] [amt-d-21.pdf] Transcribing page 2/2 (Pass 1 - Flash-Lite).
26
+ 2026-06-13 20:13:51,349 [INFO] AFC is enabled with max remote calls: 10.
27
+ 2026-06-13 20:13:51,378 [INFO] [amt-d-19.pdf] Transcribing page 2/14 (Pass 1 - Flash-Lite).
28
+ 2026-06-13 20:13:51,379 [INFO] AFC is enabled with max remote calls: 10.
29
+ 2026-06-13 20:13:51,495 [INFO] [amt-d-13.pdf] Transcribing page 2/8 (Pass 1 - Flash-Lite).
30
+ 2026-06-13 20:13:51,495 [INFO] AFC is enabled with max remote calls: 10.
31
+ 2026-06-13 20:13:53,288 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
32
+ 2026-06-13 20:13:53,533 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
33
+ 2026-06-13 20:13:53,536 [INFO] [amt-d-11.pdf] Refining full document syntax (Pass 2 - Gemini Pro).
34
+ 2026-06-13 20:13:53,536 [INFO] AFC is enabled with max remote calls: 10.
35
+ 2026-06-13 20:13:53,577 [INFO] [amt-d-15.pdf] Transcribing page 2/3 (Pass 1 - Flash-Lite).
36
+ 2026-06-13 20:13:53,577 [INFO] AFC is enabled with max remote calls: 10.
37
+ 2026-06-13 20:13:53,589 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
38
+ 2026-06-13 20:13:53,857 [INFO] [amt-d-19.pdf] Transcribing page 3/14 (Pass 1 - Flash-Lite).
39
+ 2026-06-13 20:13:53,858 [INFO] AFC is enabled with max remote calls: 10.
40
+ 2026-06-13 20:13:53,881 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
41
+ 2026-06-13 20:13:54,166 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
42
+ 2026-06-13 20:13:54,251 [INFO] [amt-d-17.pdf] Transcribing page 3/10 (Pass 1 - Flash-Lite).
43
+ 2026-06-13 20:13:54,251 [INFO] AFC is enabled with max remote calls: 10.
44
+ 2026-06-13 20:13:54,497 [INFO] [amt-d-13.pdf] Transcribing page 3/8 (Pass 1 - Flash-Lite).
45
+ 2026-06-13 20:13:54,497 [INFO] AFC is enabled with max remote calls: 10.
46
+ 2026-06-13 20:13:54,795 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
47
+ 2026-06-13 20:13:54,799 [INFO] [amt-d-21.pdf] Refining full document syntax (Pass 2 - Gemini Pro).
48
+ 2026-06-13 20:13:54,799 [INFO] AFC is enabled with max remote calls: 10.
49
+ 2026-06-13 20:13:55,868 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
50
+ 2026-06-13 20:13:55,916 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
51
+ 2026-06-13 20:13:56,197 [INFO] [amt-d-19.pdf] Transcribing page 4/14 (Pass 1 - Flash-Lite).
52
+ 2026-06-13 20:13:56,198 [INFO] AFC is enabled with max remote calls: 10.
53
+ 2026-06-13 20:13:56,224 [INFO] [amt-d-15.pdf] Transcribing page 3/3 (Pass 1 - Flash-Lite).
54
+ 2026-06-13 20:13:56,224 [INFO] AFC is enabled with max remote calls: 10.
55
+ 2026-06-13 20:13:56,983 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
56
+ 2026-06-13 20:13:57,345 [INFO] [amt-d-13.pdf] Transcribing page 4/8 (Pass 1 - Flash-Lite).
57
+ 2026-06-13 20:13:57,346 [INFO] AFC is enabled with max remote calls: 10.
58
+ 2026-06-13 20:13:58,063 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
59
+ 2026-06-13 20:13:58,336 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
60
+ 2026-06-13 20:13:58,338 [INFO] [amt-d-15.pdf] Refining full document syntax (Pass 2 - Gemini Pro).
61
+ 2026-06-13 20:13:58,339 [INFO] AFC is enabled with max remote calls: 10.
62
+ 2026-06-13 20:13:58,419 [INFO] [amt-d-17.pdf] Transcribing page 4/10 (Pass 1 - Flash-Lite).
63
+ 2026-06-13 20:13:58,419 [INFO] AFC is enabled with max remote calls: 10.
64
+ 2026-06-13 20:13:59,499 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
65
+ 2026-06-13 20:13:59,762 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
66
+ 2026-06-13 20:13:59,832 [INFO] [amt-d-19.pdf] Transcribing page 5/14 (Pass 1 - Flash-Lite).
67
+ 2026-06-13 20:13:59,832 [INFO] AFC is enabled with max remote calls: 10.
68
+ 2026-06-13 20:14:00,248 [INFO] [amt-d-13.pdf] Transcribing page 5/8 (Pass 1 - Flash-Lite).
69
+ 2026-06-13 20:14:00,248 [INFO] AFC is enabled with max remote calls: 10.
70
+ 2026-06-13 20:14:02,319 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
71
+ 2026-06-13 20:14:02,643 [INFO] [amt-d-19.pdf] Transcribing page 6/14 (Pass 1 - Flash-Lite).
72
+ 2026-06-13 20:14:02,643 [INFO] AFC is enabled with max remote calls: 10.
73
+ 2026-06-13 20:14:03,279 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
74
+ 2026-06-13 20:14:03,750 [INFO] [amt-d-13.pdf] Transcribing page 6/8 (Pass 1 - Flash-Lite).
75
+ 2026-06-13 20:14:03,751 [INFO] AFC is enabled with max remote calls: 10.
76
+ 2026-06-13 20:14:05,456 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
77
+ 2026-06-13 20:14:05,760 [INFO] [amt-d-19.pdf] Transcribing page 7/14 (Pass 1 - Flash-Lite).
78
+ 2026-06-13 20:14:05,760 [INFO] AFC is enabled with max remote calls: 10.
79
+ 2026-06-13 20:14:06,533 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
80
+ 2026-06-13 20:14:06,607 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-pro:generateContent "HTTP/1.1 200 OK"
81
+ 2026-06-13 20:14:06,610 [INFO] [amt-d-21.pdf] Saving output files to destination without compiling.
82
+ 2026-06-13 20:14:06,614 [INFO] [amt-d-21.pdf] SUCCESS. Content directory saved at ./processed_pdfs/amt-d-21
83
+ 2026-06-13 20:14:06,615 [INFO] [amt-d-23.pdf] Initializing workspace.
84
+ 2026-06-13 20:14:06,820 [INFO] [amt-d-17.pdf] Transcribing page 5/10 (Pass 1 - Flash-Lite).
85
+ 2026-06-13 20:14:06,820 [INFO] AFC is enabled with max remote calls: 10.
86
+ 2026-06-13 20:14:07,103 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
87
+ 2026-06-13 20:14:07,512 [INFO] [amt-d-13.pdf] Transcribing page 7/8 (Pass 1 - Flash-Lite).
88
+ 2026-06-13 20:14:07,512 [INFO] AFC is enabled with max remote calls: 10.
89
+ 2026-06-13 20:14:07,579 [INFO] [amt-d-23.pdf] Transcribing page 1/8 (Pass 1 - Flash-Lite).
90
+ 2026-06-13 20:14:07,579 [INFO] AFC is enabled with max remote calls: 10.
91
+ 2026-06-13 20:14:08,550 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
92
+ 2026-06-13 20:14:08,835 [INFO] [amt-d-19.pdf] Transcribing page 8/14 (Pass 1 - Flash-Lite).
93
+ 2026-06-13 20:14:08,835 [INFO] AFC is enabled with max remote calls: 10.
94
+ 2026-06-13 20:14:09,404 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
95
+ 2026-06-13 20:14:09,698 [INFO] [amt-d-17.pdf] Transcribing page 6/10 (Pass 1 - Flash-Lite).
96
+ 2026-06-13 20:14:09,698 [INFO] AFC is enabled with max remote calls: 10.
97
+ 2026-06-13 20:14:10,203 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
98
+ 2026-06-13 20:14:10,654 [INFO] [amt-d-13.pdf] Transcribing page 8/8 (Pass 1 - Flash-Lite).
99
+ 2026-06-13 20:14:10,654 [INFO] AFC is enabled with max remote calls: 10.
100
+ 2026-06-13 20:14:10,893 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
101
+ 2026-06-13 20:14:11,075 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
102
+ 2026-06-13 20:14:11,384 [INFO] [amt-d-19.pdf] Transcribing page 9/14 (Pass 1 - Flash-Lite).
103
+ 2026-06-13 20:14:11,384 [INFO] AFC is enabled with max remote calls: 10.
104
+ 2026-06-13 20:14:11,424 [INFO] [amt-d-23.pdf] Transcribing page 2/8 (Pass 1 - Flash-Lite).
105
+ 2026-06-13 20:14:11,425 [INFO] AFC is enabled with max remote calls: 10.
106
+ 2026-06-13 20:14:12,543 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
107
+ 2026-06-13 20:14:12,859 [INFO] [amt-d-17.pdf] Transcribing page 7/10 (Pass 1 - Flash-Lite).
108
+ 2026-06-13 20:14:12,860 [INFO] AFC is enabled with max remote calls: 10.
109
+ 2026-06-13 20:14:13,319 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
110
+ 2026-06-13 20:14:13,321 [INFO] [amt-d-13.pdf] Refining full document syntax (Pass 2 - Gemini Pro).
111
+ 2026-06-13 20:14:13,322 [INFO] AFC is enabled with max remote calls: 10.
112
+ 2026-06-13 20:14:13,874 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
113
+ 2026-06-13 20:14:13,914 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
114
+ 2026-06-13 20:14:14,215 [INFO] [amt-d-19.pdf] Transcribing page 10/14 (Pass 1 - Flash-Lite).
115
+ 2026-06-13 20:14:14,215 [INFO] AFC is enabled with max remote calls: 10.
116
+ 2026-06-13 20:14:14,481 [INFO] [amt-d-23.pdf] Transcribing page 3/8 (Pass 1 - Flash-Lite).
117
+ 2026-06-13 20:14:14,481 [INFO] AFC is enabled with max remote calls: 10.
118
+ 2026-06-13 20:14:15,363 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
119
+ 2026-06-13 20:14:15,738 [INFO] [amt-d-17.pdf] Transcribing page 8/10 (Pass 1 - Flash-Lite).
120
+ 2026-06-13 20:14:15,738 [INFO] AFC is enabled with max remote calls: 10.
121
+ 2026-06-13 20:14:16,260 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
122
+ 2026-06-13 20:14:16,650 [INFO] [amt-d-19.pdf] Transcribing page 11/14 (Pass 1 - Flash-Lite).
123
+ 2026-06-13 20:14:16,650 [INFO] AFC is enabled with max remote calls: 10.
124
+ 2026-06-13 20:14:17,618 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
125
+ 2026-06-13 20:14:18,252 [INFO] [amt-d-23.pdf] Transcribing page 4/8 (Pass 1 - Flash-Lite).
126
+ 2026-06-13 20:14:18,252 [INFO] AFC is enabled with max remote calls: 10.
127
+ 2026-06-13 20:14:18,678 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
128
+ 2026-06-13 20:14:18,945 [INFO] [amt-d-17.pdf] Transcribing page 9/10 (Pass 1 - Flash-Lite).
129
+ 2026-06-13 20:14:18,946 [INFO] AFC is enabled with max remote calls: 10.
130
+ 2026-06-13 20:14:21,250 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
131
+ 2026-06-13 20:14:21,589 [INFO] [amt-d-19.pdf] Transcribing page 12/14 (Pass 1 - Flash-Lite).
132
+ 2026-06-13 20:14:21,589 [INFO] AFC is enabled with max remote calls: 10.
133
+ 2026-06-13 20:14:21,640 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
134
+ 2026-06-13 20:14:21,913 [INFO] [amt-d-17.pdf] Transcribing page 10/10 (Pass 1 - Flash-Lite).
135
+ 2026-06-13 20:14:21,914 [INFO] AFC is enabled with max remote calls: 10.
136
+ 2026-06-13 20:14:22,055 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
137
+ 2026-06-13 20:14:22,371 [INFO] [amt-d-23.pdf] Transcribing page 5/8 (Pass 1 - Flash-Lite).
138
+ 2026-06-13 20:14:22,371 [INFO] AFC is enabled with max remote calls: 10.
139
+ 2026-06-13 20:14:23,789 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
140
+ 2026-06-13 20:14:23,790 [INFO] [amt-d-17.pdf] Refining full document syntax (Pass 2 - Gemini Pro).
141
+ 2026-06-13 20:14:23,791 [INFO] AFC is enabled with max remote calls: 10.
142
+ 2026-06-13 20:14:24,025 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
143
+ 2026-06-13 20:14:24,357 [INFO] [amt-d-19.pdf] Transcribing page 13/14 (Pass 1 - Flash-Lite).
144
+ 2026-06-13 20:14:24,358 [INFO] AFC is enabled with max remote calls: 10.
145
+ 2026-06-13 20:14:24,659 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
146
+ 2026-06-13 20:14:24,973 [INFO] [amt-d-23.pdf] Transcribing page 6/8 (Pass 1 - Flash-Lite).
147
+ 2026-06-13 20:14:24,974 [INFO] AFC is enabled with max remote calls: 10.
148
+ 2026-06-13 20:14:26,719 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
149
+ 2026-06-13 20:14:27,044 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
150
+ 2026-06-13 20:14:27,065 [INFO] [amt-d-19.pdf] Transcribing page 14/14 (Pass 1 - Flash-Lite).
151
+ 2026-06-13 20:14:27,065 [INFO] AFC is enabled with max remote calls: 10.
152
+ 2026-06-13 20:14:27,347 [INFO] [amt-d-23.pdf] Transcribing page 7/8 (Pass 1 - Flash-Lite).
153
+ 2026-06-13 20:14:27,347 [INFO] AFC is enabled with max remote calls: 10.
154
+ 2026-06-13 20:14:29,286 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
155
+ 2026-06-13 20:14:29,289 [INFO] [amt-d-19.pdf] Refining full document syntax (Pass 2 - Gemini Pro).
156
+ 2026-06-13 20:14:29,289 [INFO] AFC is enabled with max remote calls: 10.
157
+ 2026-06-13 20:14:29,917 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
158
+ 2026-06-13 20:14:30,472 [INFO] [amt-d-23.pdf] Transcribing page 8/8 (Pass 1 - Flash-Lite).
159
+ 2026-06-13 20:14:30,472 [INFO] AFC is enabled with max remote calls: 10.
160
+ 2026-06-13 20:14:33,122 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
161
+ 2026-06-13 20:14:33,125 [INFO] [amt-d-23.pdf] Refining full document syntax (Pass 2 - Gemini Pro).
162
+ 2026-06-13 20:14:33,125 [INFO] AFC is enabled with max remote calls: 10.
163
+ 2026-06-13 20:14:35,140 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-pro:generateContent "HTTP/1.1 200 OK"
164
+ 2026-06-13 20:14:35,145 [INFO] [amt-d-15.pdf] Saving output files to destination without compiling.
165
+ 2026-06-13 20:14:35,147 [INFO] [amt-d-15.pdf] SUCCESS. Content directory saved at ./processed_pdfs/amt-d-15
166
+ 2026-06-13 20:14:35,147 [INFO] [amt-d-25.pdf] Initializing workspace.
167
+ 2026-06-13 20:14:36,375 [INFO] [amt-d-25.pdf] Transcribing page 1/5 (Pass 1 - Flash-Lite).
168
+ 2026-06-13 20:14:36,375 [INFO] AFC is enabled with max remote calls: 10.
169
+ 2026-06-13 20:14:37,366 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-pro:generateContent "HTTP/1.1 200 OK"
170
+ 2026-06-13 20:14:37,382 [INFO] [amt-d-11.pdf] Saving output files to destination without compiling.
171
+ 2026-06-13 20:14:37,383 [INFO] [amt-d-11.pdf] SUCCESS. Content directory saved at ./processed_pdfs/amt-d-11
172
+ 2026-06-13 20:14:37,384 [INFO] [amt-d-27.pdf] Initializing workspace.
173
+ 2026-06-13 20:14:37,969 [INFO] [amt-d-27.pdf] Transcribing page 1/2 (Pass 1 - Flash-Lite).
174
+ 2026-06-13 20:14:37,969 [INFO] AFC is enabled with max remote calls: 10.
175
+ 2026-06-13 20:14:39,992 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
176
+ 2026-06-13 20:14:40,831 [INFO] [amt-d-25.pdf] Transcribing page 2/5 (Pass 1 - Flash-Lite).
177
+ 2026-06-13 20:14:40,832 [INFO] AFC is enabled with max remote calls: 10.
178
+ 2026-06-13 20:14:40,878 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
179
+ 2026-06-13 20:14:41,324 [INFO] [amt-d-27.pdf] Transcribing page 2/2 (Pass 1 - Flash-Lite).
180
+ 2026-06-13 20:14:41,324 [INFO] AFC is enabled with max remote calls: 10.
181
+ 2026-06-13 20:14:44,019 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
182
+ 2026-06-13 20:14:44,022 [INFO] [amt-d-27.pdf] Refining full document syntax (Pass 2 - Gemini Pro).
183
+ 2026-06-13 20:14:44,022 [INFO] AFC is enabled with max remote calls: 10.
184
+ 2026-06-13 20:14:45,052 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
185
+ 2026-06-13 20:14:45,729 [INFO] [amt-d-25.pdf] Transcribing page 3/5 (Pass 1 - Flash-Lite).
186
+ 2026-06-13 20:14:45,730 [INFO] AFC is enabled with max remote calls: 10.
187
+ 2026-06-13 20:14:49,017 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
188
+ 2026-06-13 20:14:49,744 [INFO] [amt-d-25.pdf] Transcribing page 4/5 (Pass 1 - Flash-Lite).
189
+ 2026-06-13 20:14:49,744 [INFO] AFC is enabled with max remote calls: 10.
190
+ 2026-06-13 20:14:52,658 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
191
+ 2026-06-13 20:14:53,104 [INFO] [amt-d-25.pdf] Transcribing page 5/5 (Pass 1 - Flash-Lite).
192
+ 2026-06-13 20:14:53,104 [INFO] AFC is enabled with max remote calls: 10.
193
+ 2026-06-13 20:14:54,011 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-pro:generateContent "HTTP/1.1 200 OK"
194
+ 2026-06-13 20:14:54,016 [INFO] [amt-d-13.pdf] Saving output files to destination without compiling.
195
+ 2026-06-13 20:14:54,023 [INFO] [amt-d-13.pdf] SUCCESS. Content directory saved at ./processed_pdfs/amt-d-13
196
+ 2026-06-13 20:14:54,028 [INFO] [amt-d-29.pdf] Initializing workspace.
197
+ 2026-06-13 20:14:54,731 [INFO] [amt-d-29.pdf] Transcribing page 1/4 (Pass 1 - Flash-Lite).
198
+ 2026-06-13 20:14:54,731 [INFO] AFC is enabled with max remote calls: 10.
199
+ 2026-06-13 20:14:55,107 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
200
+ 2026-06-13 20:14:55,109 [INFO] [amt-d-25.pdf] Refining full document syntax (Pass 2 - Gemini Pro).
201
+ 2026-06-13 20:14:55,110 [INFO] AFC is enabled with max remote calls: 10.
202
+ 2026-06-13 20:14:57,223 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
203
+ 2026-06-13 20:14:57,643 [INFO] [amt-d-29.pdf] Transcribing page 2/4 (Pass 1 - Flash-Lite).
204
+ 2026-06-13 20:14:57,644 [INFO] AFC is enabled with max remote calls: 10.
205
+ 2026-06-13 20:14:59,639 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-pro:generateContent "HTTP/1.1 200 OK"
206
+ 2026-06-13 20:14:59,642 [INFO] [amt-d-27.pdf] Saving output files to destination without compiling.
207
+ 2026-06-13 20:14:59,643 [INFO] [amt-d-27.pdf] SUCCESS. Content directory saved at ./processed_pdfs/amt-d-27
208
+ 2026-06-13 20:14:59,644 [INFO] [amt-d-3.pdf] Initializing workspace.
209
+ 2026-06-13 20:15:00,290 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
210
+ 2026-06-13 20:15:00,891 [INFO] [amt-d-29.pdf] Transcribing page 3/4 (Pass 1 - Flash-Lite).
211
+ 2026-06-13 20:15:00,892 [INFO] AFC is enabled with max remote calls: 10.
212
+ 2026-06-13 20:15:02,176 [INFO] [amt-d-3.pdf] Transcribing page 1/34 (Pass 1 - Flash-Lite).
213
+ 2026-06-13 20:15:02,176 [INFO] AFC is enabled with max remote calls: 10.
214
+ 2026-06-13 20:15:03,726 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
215
+ 2026-06-13 20:15:04,292 [INFO] [amt-d-29.pdf] Transcribing page 4/4 (Pass 1 - Flash-Lite).
216
+ 2026-06-13 20:15:04,293 [INFO] AFC is enabled with max remote calls: 10.
217
+ 2026-06-13 20:15:04,716 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
218
+ 2026-06-13 20:15:05,089 [INFO] [amt-d-3.pdf] Transcribing page 2/34 (Pass 1 - Flash-Lite).
219
+ 2026-06-13 20:15:05,089 [INFO] AFC is enabled with max remote calls: 10.
220
+ 2026-06-13 20:15:07,575 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-pro:generateContent "HTTP/1.1 200 OK"
221
+ 2026-06-13 20:15:07,578 [INFO] [amt-d-17.pdf] Saving output files to destination without compiling.
222
+ 2026-06-13 20:15:07,584 [INFO] [amt-d-17.pdf] SUCCESS. Content directory saved at ./processed_pdfs/amt-d-17
223
+ 2026-06-13 20:15:07,589 [INFO] [amt-d-31.pdf] Initializing workspace.
224
+ 2026-06-13 20:15:07,636 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
225
+ 2026-06-13 20:15:07,641 [INFO] [amt-d-29.pdf] Refining full document syntax (Pass 2 - Gemini Pro).
226
+ 2026-06-13 20:15:07,641 [INFO] AFC is enabled with max remote calls: 10.
227
+ 2026-06-13 20:15:08,061 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
228
+ 2026-06-13 20:15:08,443 [INFO] [amt-d-3.pdf] Transcribing page 3/34 (Pass 1 - Flash-Lite).
229
+ 2026-06-13 20:15:08,443 [INFO] AFC is enabled with max remote calls: 10.
230
+ 2026-06-13 20:15:11,067 [INFO] [amt-d-31.pdf] Transcribing page 1/51 (Pass 1 - Flash-Lite).
231
+ 2026-06-13 20:15:11,067 [INFO] AFC is enabled with max remote calls: 10.
232
+ 2026-06-13 20:15:11,657 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
233
+ 2026-06-13 20:15:11,980 [INFO] [amt-d-3.pdf] Transcribing page 4/34 (Pass 1 - Flash-Lite).
234
+ 2026-06-13 20:15:11,981 [INFO] AFC is enabled with max remote calls: 10.
235
+ 2026-06-13 20:15:13,385 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
236
+ 2026-06-13 20:15:13,782 [INFO] [amt-d-31.pdf] Transcribing page 2/51 (Pass 1 - Flash-Lite).
237
+ 2026-06-13 20:15:13,782 [INFO] AFC is enabled with max remote calls: 10.
238
+ 2026-06-13 20:15:14,642 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
239
+ 2026-06-13 20:15:15,005 [INFO] [amt-d-3.pdf] Transcribing page 5/34 (Pass 1 - Flash-Lite).
240
+ 2026-06-13 20:15:15,006 [INFO] AFC is enabled with max remote calls: 10.
241
+ 2026-06-13 20:15:16,808 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
242
+ 2026-06-13 20:15:17,250 [INFO] [amt-d-31.pdf] Transcribing page 3/51 (Pass 1 - Flash-Lite).
243
+ 2026-06-13 20:15:17,251 [INFO] AFC is enabled with max remote calls: 10.
244
+ 2026-06-13 20:15:17,634 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
245
+ 2026-06-13 20:15:17,993 [INFO] [amt-d-3.pdf] Transcribing page 6/34 (Pass 1 - Flash-Lite).
246
+ 2026-06-13 20:15:17,993 [INFO] AFC is enabled with max remote calls: 10.
247
+ 2026-06-13 20:15:20,245 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
248
+ 2026-06-13 20:15:20,655 [INFO] [amt-d-31.pdf] Transcribing page 4/51 (Pass 1 - Flash-Lite).
249
+ 2026-06-13 20:15:20,655 [INFO] AFC is enabled with max remote calls: 10.
250
+ 2026-06-13 20:15:20,770 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
251
+ 2026-06-13 20:15:21,112 [INFO] [amt-d-3.pdf] Transcribing page 7/34 (Pass 1 - Flash-Lite).
252
+ 2026-06-13 20:15:21,112 [INFO] AFC is enabled with max remote calls: 10.
253
+ 2026-06-13 20:15:23,610 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
254
+ 2026-06-13 20:15:23,658 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
255
+ 2026-06-13 20:15:23,966 [INFO] [amt-d-3.pdf] Transcribing page 8/34 (Pass 1 - Flash-Lite).
256
+ 2026-06-13 20:15:23,966 [INFO] AFC is enabled with max remote calls: 10.
257
+ 2026-06-13 20:15:24,098 [INFO] [amt-d-31.pdf] Transcribing page 5/51 (Pass 1 - Flash-Lite).
258
+ 2026-06-13 20:15:24,098 [INFO] AFC is enabled with max remote calls: 10.
259
+ 2026-06-13 20:15:26,458 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
260
+ 2026-06-13 20:15:26,746 [INFO] [amt-d-3.pdf] Transcribing page 9/34 (Pass 1 - Flash-Lite).
261
+ 2026-06-13 20:15:26,746 [INFO] AFC is enabled with max remote calls: 10.
262
+ 2026-06-13 20:15:27,460 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
263
+ 2026-06-13 20:15:27,875 [INFO] [amt-d-31.pdf] Transcribing page 6/51 (Pass 1 - Flash-Lite).
264
+ 2026-06-13 20:15:27,875 [INFO] AFC is enabled with max remote calls: 10.
265
+ 2026-06-13 20:15:29,214 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
266
+ 2026-06-13 20:15:29,456 [INFO] [amt-d-3.pdf] Transcribing page 10/34 (Pass 1 - Flash-Lite).
267
+ 2026-06-13 20:15:29,456 [INFO] AFC is enabled with max remote calls: 10.
268
+ 2026-06-13 20:15:29,519 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-pro:generateContent "HTTP/1.1 200 OK"
269
+ 2026-06-13 20:15:29,524 [INFO] [amt-d-19.pdf] Saving output files to destination without compiling.
270
+ 2026-06-13 20:15:29,532 [INFO] [amt-d-19.pdf] SUCCESS. Content directory saved at ./processed_pdfs/amt-d-19
271
+ 2026-06-13 20:15:29,538 [INFO] [amt-d-33.pdf] Initializing workspace.
272
+ 2026-06-13 20:15:30,397 [INFO] [amt-d-33.pdf] Transcribing page 1/3 (Pass 1 - Flash-Lite).
273
+ 2026-06-13 20:15:30,397 [INFO] AFC is enabled with max remote calls: 10.
274
+ 2026-06-13 20:15:31,161 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
275
+ 2026-06-13 20:15:31,672 [INFO] [amt-d-31.pdf] Transcribing page 7/51 (Pass 1 - Flash-Lite).
276
+ 2026-06-13 20:15:31,672 [INFO] AFC is enabled with max remote calls: 10.
277
+ 2026-06-13 20:15:32,192 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
278
+ 2026-06-13 20:15:32,519 [INFO] [amt-d-3.pdf] Transcribing page 11/34 (Pass 1 - Flash-Lite).
279
+ 2026-06-13 20:15:32,519 [INFO] AFC is enabled with max remote calls: 10.
280
+ 2026-06-13 20:15:33,666 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
281
+ 2026-06-13 20:15:34,002 [INFO] [amt-d-33.pdf] Transcribing page 2/3 (Pass 1 - Flash-Lite).
282
+ 2026-06-13 20:15:34,002 [INFO] AFC is enabled with max remote calls: 10.
283
+ 2026-06-13 20:15:34,317 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-pro:generateContent "HTTP/1.1 200 OK"
284
+ 2026-06-13 20:15:34,321 [INFO] [amt-d-29.pdf] Saving output files to destination without compiling.
285
+ 2026-06-13 20:15:34,324 [INFO] [amt-d-29.pdf] SUCCESS. Content directory saved at ./processed_pdfs/amt-d-29
286
+ 2026-06-13 20:15:34,324 [INFO] [amt-d-35.pdf] Initializing workspace.
287
+ 2026-06-13 20:15:34,630 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
288
+ 2026-06-13 20:15:35,177 [INFO] [amt-d-31.pdf] Transcribing page 8/51 (Pass 1 - Flash-Lite).
289
+ 2026-06-13 20:15:35,177 [INFO] AFC is enabled with max remote calls: 10.
290
+ 2026-06-13 20:15:35,662 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
291
+ 2026-06-13 20:15:35,797 [INFO] [amt-d-35.pdf] Transcribing page 1/13 (Pass 1 - Flash-Lite).
292
+ 2026-06-13 20:15:35,798 [INFO] AFC is enabled with max remote calls: 10.
293
+ 2026-06-13 20:15:35,948 [INFO] [amt-d-3.pdf] Transcribing page 12/34 (Pass 1 - Flash-Lite).
294
+ 2026-06-13 20:15:35,948 [INFO] AFC is enabled with max remote calls: 10.
295
+ 2026-06-13 20:15:36,384 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
296
+ 2026-06-13 20:15:36,739 [INFO] [amt-d-33.pdf] Transcribing page 3/3 (Pass 1 - Flash-Lite).
297
+ 2026-06-13 20:15:36,739 [INFO] AFC is enabled with max remote calls: 10.
298
+ 2026-06-13 20:15:38,637 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
299
+ 2026-06-13 20:15:38,665 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
300
+ 2026-06-13 20:15:38,838 [INFO] [amt-d-3.pdf] Transcribing page 13/34 (Pass 1 - Flash-Lite).
301
+ 2026-06-13 20:15:38,839 [INFO] AFC is enabled with max remote calls: 10.
302
+ 2026-06-13 20:15:38,979 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
303
+ 2026-06-13 20:15:38,981 [INFO] [amt-d-33.pdf] Refining full document syntax (Pass 2 - Gemini Pro).
304
+ 2026-06-13 20:15:38,981 [INFO] AFC is enabled with max remote calls: 10.
305
+ 2026-06-13 20:15:39,158 [INFO] [amt-d-35.pdf] Transcribing page 2/13 (Pass 1 - Flash-Lite).
306
+ 2026-06-13 20:15:39,158 [INFO] AFC is enabled with max remote calls: 10.
307
+ 2026-06-13 20:15:39,317 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
308
+ 2026-06-13 20:15:39,831 [INFO] [amt-d-31.pdf] Transcribing page 9/51 (Pass 1 - Flash-Lite).
309
+ 2026-06-13 20:15:39,832 [INFO] AFC is enabled with max remote calls: 10.
310
+ 2026-06-13 20:15:40,680 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
311
+ 2026-06-13 20:15:40,902 [INFO] [amt-d-3.pdf] Transcribing page 14/34 (Pass 1 - Flash-Lite).
312
+ 2026-06-13 20:15:40,903 [INFO] AFC is enabled with max remote calls: 10.
313
+ 2026-06-13 20:15:42,270 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
314
+ 2026-06-13 20:15:42,757 [INFO] [amt-d-35.pdf] Transcribing page 3/13 (Pass 1 - Flash-Lite).
315
+ 2026-06-13 20:15:42,758 [INFO] AFC is enabled with max remote calls: 10.
316
+ 2026-06-13 20:15:43,489 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
317
+ 2026-06-13 20:15:43,567 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
318
+ 2026-06-13 20:15:43,749 [INFO] [amt-d-3.pdf] Transcribing page 15/34 (Pass 1 - Flash-Lite).
319
+ 2026-06-13 20:15:43,750 [INFO] AFC is enabled with max remote calls: 10.
320
+ 2026-06-13 20:15:44,128 [INFO] [amt-d-31.pdf] Transcribing page 10/51 (Pass 1 - Flash-Lite).
321
+ 2026-06-13 20:15:44,128 [INFO] AFC is enabled with max remote calls: 10.
322
+ 2026-06-13 20:15:45,115 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-pro:generateContent "HTTP/1.1 200 OK"
323
+ 2026-06-13 20:15:45,119 [INFO] [amt-d-23.pdf] Saving output files to destination without compiling.
324
+ 2026-06-13 20:15:45,127 [INFO] [amt-d-23.pdf] SUCCESS. Content directory saved at ./processed_pdfs/amt-d-23
325
+ 2026-06-13 20:15:45,130 [INFO] [amt-d-5.pdf] Initializing workspace.
326
+ 2026-06-13 20:15:45,475 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
327
+ 2026-06-13 20:15:45,935 [INFO] [amt-d-35.pdf] Transcribing page 4/13 (Pass 1 - Flash-Lite).
328
+ 2026-06-13 20:15:45,935 [INFO] AFC is enabled with max remote calls: 10.
329
+ 2026-06-13 20:15:46,017 [INFO] [amt-d-5.pdf] Transcribing page 1/6 (Pass 1 - Flash-Lite).
330
+ 2026-06-13 20:15:46,017 [INFO] AFC is enabled with max remote calls: 10.
331
+ 2026-06-13 20:15:46,553 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
332
+ 2026-06-13 20:15:46,779 [INFO] [amt-d-3.pdf] Transcribing page 16/34 (Pass 1 - Flash-Lite).
333
+ 2026-06-13 20:15:46,779 [INFO] AFC is enabled with max remote calls: 10.
334
+ 2026-06-13 20:15:47,700 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
335
+ 2026-06-13 20:15:48,214 [INFO] [amt-d-31.pdf] Transcribing page 11/51 (Pass 1 - Flash-Lite).
336
+ 2026-06-13 20:15:48,214 [INFO] AFC is enabled with max remote calls: 10.
337
+ 2026-06-13 20:15:48,629 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
338
+ 2026-06-13 20:15:48,887 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
339
+ 2026-06-13 20:15:49,093 [INFO] [amt-d-35.pdf] Transcribing page 5/13 (Pass 1 - Flash-Lite).
340
+ 2026-06-13 20:15:49,093 [INFO] AFC is enabled with max remote calls: 10.
341
+ 2026-06-13 20:15:49,410 [INFO] [amt-d-5.pdf] Transcribing page 2/6 (Pass 1 - Flash-Lite).
342
+ 2026-06-13 20:15:49,410 [INFO] AFC is enabled with max remote calls: 10.
343
+ 2026-06-13 20:15:50,709 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
344
+ 2026-06-13 20:15:50,975 [INFO] [amt-d-3.pdf] Transcribing page 17/34 (Pass 1 - Flash-Lite).
345
+ 2026-06-13 20:15:50,975 [INFO] AFC is enabled with max remote calls: 10.
346
+ 2026-06-13 20:15:51,641 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
347
+ 2026-06-13 20:15:51,883 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
348
+ 2026-06-13 20:15:52,106 [INFO] [amt-d-31.pdf] Transcribing page 12/51 (Pass 1 - Flash-Lite).
349
+ 2026-06-13 20:15:52,106 [INFO] AFC is enabled with max remote calls: 10.
350
+ 2026-06-13 20:15:52,383 [INFO] [amt-d-35.pdf] Transcribing page 6/13 (Pass 1 - Flash-Lite).
351
+ 2026-06-13 20:15:52,384 [INFO] AFC is enabled with max remote calls: 10.
352
+ 2026-06-13 20:15:52,654 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
353
+ 2026-06-13 20:15:53,175 [INFO] [amt-d-5.pdf] Transcribing page 3/6 (Pass 1 - Flash-Lite).
354
+ 2026-06-13 20:15:53,175 [INFO] AFC is enabled with max remote calls: 10.
355
+ 2026-06-13 20:15:54,053 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
356
+ 2026-06-13 20:15:54,339 [INFO] [amt-d-3.pdf] Transcribing page 18/34 (Pass 1 - Flash-Lite).
357
+ 2026-06-13 20:15:54,339 [INFO] AFC is enabled with max remote calls: 10.
358
+ 2026-06-13 20:15:54,356 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-pro:generateContent "HTTP/1.1 200 OK"
359
+ 2026-06-13 20:15:54,362 [INFO] [amt-d-25.pdf] Saving output files to destination without compiling.
360
+ 2026-06-13 20:15:54,367 [INFO] [amt-d-25.pdf] SUCCESS. Content directory saved at ./processed_pdfs/amt-d-25
361
+ 2026-06-13 20:15:54,367 [INFO] [amt-d-7.pdf] Initializing workspace.
362
+ 2026-06-13 20:15:55,277 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
363
+ 2026-06-13 20:15:55,396 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
364
+ 2026-06-13 20:15:55,789 [INFO] [amt-d-31.pdf] Transcribing page 13/51 (Pass 1 - Flash-Lite).
365
+ 2026-06-13 20:15:55,789 [INFO] AFC is enabled with max remote calls: 10.
366
+ 2026-06-13 20:15:55,884 [INFO] [amt-d-35.pdf] Transcribing page 7/13 (Pass 1 - Flash-Lite).
367
+ 2026-06-13 20:15:55,885 [INFO] AFC is enabled with max remote calls: 10.
368
+ 2026-06-13 20:15:56,221 [INFO] [amt-d-7.pdf] Transcribing page 1/20 (Pass 1 - Flash-Lite).
369
+ 2026-06-13 20:15:56,221 [INFO] AFC is enabled with max remote calls: 10.
370
+ 2026-06-13 20:15:56,448 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
371
+ 2026-06-13 20:15:56,935 [INFO] [amt-d-5.pdf] Transcribing page 4/6 (Pass 1 - Flash-Lite).
372
+ 2026-06-13 20:15:56,935 [INFO] AFC is enabled with max remote calls: 10.
373
+ 2026-06-13 20:15:58,276 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
374
+ 2026-06-13 20:15:58,668 [INFO] [amt-d-3.pdf] Transcribing page 19/34 (Pass 1 - Flash-Lite).
375
+ 2026-06-13 20:15:58,668 [INFO] AFC is enabled with max remote calls: 10.
376
+ 2026-06-13 20:15:58,668 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
377
+ 2026-06-13 20:15:58,872 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
378
+ 2026-06-13 20:15:58,902 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
379
+ 2026-06-13 20:15:59,167 [INFO] [amt-d-35.pdf] Transcribing page 8/13 (Pass 1 - Flash-Lite).
380
+ 2026-06-13 20:15:59,167 [INFO] AFC is enabled with max remote calls: 10.
381
+ 2026-06-13 20:15:59,375 [INFO] [amt-d-31.pdf] Transcribing page 14/51 (Pass 1 - Flash-Lite).
382
+ 2026-06-13 20:15:59,375 [INFO] AFC is enabled with max remote calls: 10.
383
+ 2026-06-13 20:15:59,463 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-pro:generateContent "HTTP/1.1 200 OK"
384
+ 2026-06-13 20:15:59,467 [INFO] [amt-d-33.pdf] Saving output files to destination without compiling.
385
+ 2026-06-13 20:15:59,470 [INFO] [amt-d-33.pdf] SUCCESS. Content directory saved at ./processed_pdfs/amt-d-33
386
+ 2026-06-13 20:15:59,470 [INFO] [amt-d-9.pdf] Initializing workspace.
387
+ 2026-06-13 20:15:59,757 [INFO] [amt-d-7.pdf] Transcribing page 2/20 (Pass 1 - Flash-Lite).
388
+ 2026-06-13 20:15:59,757 [INFO] AFC is enabled with max remote calls: 10.
389
+ 2026-06-13 20:15:59,888 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
390
+ 2026-06-13 20:16:00,445 [INFO] [amt-d-5.pdf] Transcribing page 5/6 (Pass 1 - Flash-Lite).
391
+ 2026-06-13 20:16:00,445 [INFO] AFC is enabled with max remote calls: 10.
392
+ 2026-06-13 20:16:01,695 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
393
+ 2026-06-13 20:16:01,717 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
394
+ 2026-06-13 20:16:02,018 [INFO] [amt-d-3.pdf] Transcribing page 20/34 (Pass 1 - Flash-Lite).
395
+ 2026-06-13 20:16:02,018 [INFO] AFC is enabled with max remote calls: 10.
396
+ 2026-06-13 20:16:02,149 [INFO] [amt-d-35.pdf] Transcribing page 9/13 (Pass 1 - Flash-Lite).
397
+ 2026-06-13 20:16:02,149 [INFO] AFC is enabled with max remote calls: 10.
398
+ 2026-06-13 20:16:02,848 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
399
+ 2026-06-13 20:16:03,324 [INFO] [amt-d-31.pdf] Transcribing page 15/51 (Pass 1 - Flash-Lite).
400
+ 2026-06-13 20:16:03,324 [INFO] AFC is enabled with max remote calls: 10.
401
+ 2026-06-13 20:16:03,348 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
402
+ 2026-06-13 20:16:04,039 [INFO] [amt-d-9.pdf] Transcribing page 1/67 (Pass 1 - Flash-Lite).
403
+ 2026-06-13 20:16:04,040 [INFO] AFC is enabled with max remote calls: 10.
404
+ 2026-06-13 20:16:04,320 [INFO] [amt-d-7.pdf] Transcribing page 3/20 (Pass 1 - Flash-Lite).
405
+ 2026-06-13 20:16:04,320 [INFO] AFC is enabled with max remote calls: 10.
406
+ 2026-06-13 20:16:04,819 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
407
+ 2026-06-13 20:16:04,992 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
408
+ 2026-06-13 20:16:05,121 [INFO] [amt-d-3.pdf] Transcribing page 21/34 (Pass 1 - Flash-Lite).
409
+ 2026-06-13 20:16:05,121 [INFO] AFC is enabled with max remote calls: 10.
410
+ 2026-06-13 20:16:05,448 [INFO] [amt-d-35.pdf] Transcribing page 10/13 (Pass 1 - Flash-Lite).
411
+ 2026-06-13 20:16:05,449 [INFO] AFC is enabled with max remote calls: 10.
412
+ 2026-06-13 20:16:06,755 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
413
+ 2026-06-13 20:16:07,204 [INFO] [amt-d-31.pdf] Transcribing page 16/51 (Pass 1 - Flash-Lite).
414
+ 2026-06-13 20:16:07,204 [INFO] AFC is enabled with max remote calls: 10.
415
+ 2026-06-13 20:16:07,679 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
416
+ 2026-06-13 20:16:07,954 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
417
+ 2026-06-13 20:16:08,054 [INFO] [amt-d-9.pdf] Transcribing page 2/67 (Pass 1 - Flash-Lite).
418
+ 2026-06-13 20:16:08,054 [INFO] AFC is enabled with max remote calls: 10.
419
+ 2026-06-13 20:16:08,174 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
420
+ 2026-06-13 20:16:08,228 [INFO] [amt-d-3.pdf] Transcribing page 22/34 (Pass 1 - Flash-Lite).
421
+ 2026-06-13 20:16:08,228 [INFO] AFC is enabled with max remote calls: 10.
422
+ 2026-06-13 20:16:08,464 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
423
+ 2026-06-13 20:16:08,856 [INFO] [amt-d-7.pdf] Transcribing page 4/20 (Pass 1 - Flash-Lite).
424
+ 2026-06-13 20:16:08,856 [INFO] AFC is enabled with max remote calls: 10.
425
+ 2026-06-13 20:16:08,918 [INFO] [amt-d-35.pdf] Transcribing page 11/13 (Pass 1 - Flash-Lite).
426
+ 2026-06-13 20:16:08,919 [INFO] AFC is enabled with max remote calls: 10.
427
+ 2026-06-13 20:16:10,923 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
428
+ 2026-06-13 20:16:10,934 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
429
+ 2026-06-13 20:16:11,308 [INFO] [amt-d-9.pdf] Transcribing page 3/67 (Pass 1 - Flash-Lite).
430
+ 2026-06-13 20:16:11,308 [INFO] AFC is enabled with max remote calls: 10.
431
+ 2026-06-13 20:16:11,312 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
432
+ 2026-06-13 20:16:11,415 [INFO] [amt-d-31.pdf] Transcribing page 17/51 (Pass 1 - Flash-Lite).
433
+ 2026-06-13 20:16:11,415 [INFO] AFC is enabled with max remote calls: 10.
434
+ 2026-06-13 20:16:11,457 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
435
+ 2026-06-13 20:16:11,647 [INFO] [amt-d-3.pdf] Transcribing page 23/34 (Pass 1 - Flash-Lite).
436
+ 2026-06-13 20:16:11,647 [INFO] AFC is enabled with max remote calls: 10.
437
+ 2026-06-13 20:16:11,725 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
438
+ 2026-06-13 20:16:11,938 [INFO] [amt-d-35.pdf] Transcribing page 12/13 (Pass 1 - Flash-Lite).
439
+ 2026-06-13 20:16:11,938 [INFO] AFC is enabled with max remote calls: 10.
440
+ 2026-06-13 20:16:12,400 [INFO] [amt-d-7.pdf] Transcribing page 5/20 (Pass 1 - Flash-Lite).
441
+ 2026-06-13 20:16:12,401 [INFO] AFC is enabled with max remote calls: 10.
442
+ 2026-06-13 20:16:13,867 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
443
+ 2026-06-13 20:16:14,279 [INFO] [amt-d-9.pdf] Transcribing page 4/67 (Pass 1 - Flash-Lite).
444
+ 2026-06-13 20:16:14,279 [INFO] AFC is enabled with max remote calls: 10.
445
+ 2026-06-13 20:16:14,491 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
446
+ 2026-06-13 20:16:14,492 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
447
+ 2026-06-13 20:16:14,776 [INFO] [amt-d-3.pdf] Transcribing page 24/34 (Pass 1 - Flash-Lite).
448
+ 2026-06-13 20:16:14,776 [INFO] AFC is enabled with max remote calls: 10.
449
+ 2026-06-13 20:16:14,800 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
450
+ 2026-06-13 20:16:15,032 [INFO] [amt-d-35.pdf] Transcribing page 13/13 (Pass 1 - Flash-Lite).
451
+ 2026-06-13 20:16:15,033 [INFO] AFC is enabled with max remote calls: 10.
452
+ 2026-06-13 20:16:15,232 [INFO] [amt-d-31.pdf] Transcribing page 18/51 (Pass 1 - Flash-Lite).
453
+ 2026-06-13 20:16:15,232 [INFO] AFC is enabled with max remote calls: 10.
454
+ 2026-06-13 20:16:15,850 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
455
+ 2026-06-13 20:16:16,282 [INFO] [amt-d-7.pdf] Transcribing page 6/20 (Pass 1 - Flash-Lite).
456
+ 2026-06-13 20:16:16,282 [INFO] AFC is enabled with max remote calls: 10.
457
+ 2026-06-13 20:16:16,634 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
458
+ 2026-06-13 20:16:16,995 [INFO] [amt-d-9.pdf] Transcribing page 5/67 (Pass 1 - Flash-Lite).
459
+ 2026-06-13 20:16:16,995 [INFO] AFC is enabled with max remote calls: 10.
460
+ 2026-06-13 20:16:17,582 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
461
+ 2026-06-13 20:16:17,585 [INFO] [amt-d-35.pdf] Refining full document syntax (Pass 2 - Gemini Pro).
462
+ 2026-06-13 20:16:17,586 [INFO] AFC is enabled with max remote calls: 10.
463
+ 2026-06-13 20:16:17,749 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
464
+ 2026-06-13 20:16:17,879 [INFO] [amt-d-3.pdf] Transcribing page 25/34 (Pass 1 - Flash-Lite).
465
+ 2026-06-13 20:16:17,879 [INFO] AFC is enabled with max remote calls: 10.
466
+ 2026-06-13 20:16:18,585 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
467
+ 2026-06-13 20:16:18,900 [INFO] [amt-d-31.pdf] Transcribing page 19/51 (Pass 1 - Flash-Lite).
468
+ 2026-06-13 20:16:18,901 [INFO] AFC is enabled with max remote calls: 10.
469
+ 2026-06-13 20:16:19,437 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
470
+ 2026-06-13 20:16:19,665 [INFO] [amt-d-3.pdf] Transcribing page 26/34 (Pass 1 - Flash-Lite).
471
+ 2026-06-13 20:16:19,666 [INFO] AFC is enabled with max remote calls: 10.
472
+ 2026-06-13 20:16:19,874 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
473
+ 2026-06-13 20:16:20,189 [INFO] [amt-d-9.pdf] Transcribing page 6/67 (Pass 1 - Flash-Lite).
474
+ 2026-06-13 20:16:20,189 [INFO] AFC is enabled with max remote calls: 10.
475
+ 2026-06-13 20:16:20,197 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
476
+ 2026-06-13 20:16:20,800 [INFO] [amt-d-7.pdf] Transcribing page 7/20 (Pass 1 - Flash-Lite).
477
+ 2026-06-13 20:16:20,800 [INFO] AFC is enabled with max remote calls: 10.
478
+ 2026-06-13 20:16:21,279 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
479
+ 2026-06-13 20:16:21,654 [INFO] [amt-d-31.pdf] Transcribing page 20/51 (Pass 1 - Flash-Lite).
480
+ 2026-06-13 20:16:21,655 [INFO] AFC is enabled with max remote calls: 10.
481
+ 2026-06-13 20:16:21,944 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
482
+ 2026-06-13 20:16:22,177 [INFO] [amt-d-3.pdf] Transcribing page 27/34 (Pass 1 - Flash-Lite).
483
+ 2026-06-13 20:16:22,177 [INFO] AFC is enabled with max remote calls: 10.
484
+ 2026-06-13 20:16:23,212 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
485
+ 2026-06-13 20:16:23,590 [INFO] [amt-d-9.pdf] Transcribing page 7/67 (Pass 1 - Flash-Lite).
486
+ 2026-06-13 20:16:23,590 [INFO] AFC is enabled with max remote calls: 10.
487
+ 2026-06-13 20:16:24,426 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
488
+ 2026-06-13 20:16:24,497 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
489
+ 2026-06-13 20:16:24,750 [INFO] [amt-d-3.pdf] Transcribing page 28/34 (Pass 1 - Flash-Lite).
490
+ 2026-06-13 20:16:24,750 [INFO] AFC is enabled with max remote calls: 10.
491
+ 2026-06-13 20:16:24,930 [INFO] [amt-d-31.pdf] Transcribing page 21/51 (Pass 1 - Flash-Lite).
492
+ 2026-06-13 20:16:24,930 [INFO] AFC is enabled with max remote calls: 10.
493
+ 2026-06-13 20:16:25,947 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
494
+ 2026-06-13 20:16:26,502 [INFO] [amt-d-7.pdf] Transcribing page 8/20 (Pass 1 - Flash-Lite).
495
+ 2026-06-13 20:16:26,503 [INFO] AFC is enabled with max remote calls: 10.
496
+ 2026-06-13 20:16:27,041 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
497
+ 2026-06-13 20:16:27,449 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
498
+ 2026-06-13 20:16:27,465 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
499
+ 2026-06-13 20:16:27,578 [INFO] [amt-d-9.pdf] Transcribing page 8/67 (Pass 1 - Flash-Lite).
500
+ 2026-06-13 20:16:27,579 [INFO] AFC is enabled with max remote calls: 10.
501
+ 2026-06-13 20:16:27,898 [INFO] [amt-d-3.pdf] Transcribing page 29/34 (Pass 1 - Flash-Lite).
502
+ 2026-06-13 20:16:27,898 [INFO] AFC is enabled with max remote calls: 10.
503
+ 2026-06-13 20:16:27,935 [INFO] [amt-d-31.pdf] Transcribing page 22/51 (Pass 1 - Flash-Lite).
504
+ 2026-06-13 20:16:27,936 [INFO] AFC is enabled with max remote calls: 10.
505
+ 2026-06-13 20:16:30,108 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
506
+ 2026-06-13 20:16:30,632 [INFO] [amt-d-7.pdf] Transcribing page 9/20 (Pass 1 - Flash-Lite).
507
+ 2026-06-13 20:16:30,633 [INFO] AFC is enabled with max remote calls: 10.
508
+ 2026-06-13 20:16:30,951 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
509
+ 2026-06-13 20:16:31,154 [INFO] [amt-d-3.pdf] Transcribing page 30/34 (Pass 1 - Flash-Lite).
510
+ 2026-06-13 20:16:31,154 [INFO] AFC is enabled with max remote calls: 10.
511
+ 2026-06-13 20:16:31,542 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
512
+ 2026-06-13 20:16:31,831 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
513
+ 2026-06-13 20:16:32,105 [INFO] [amt-d-9.pdf] Transcribing page 9/67 (Pass 1 - Flash-Lite).
514
+ 2026-06-13 20:16:32,105 [INFO] AFC is enabled with max remote calls: 10.
515
+ 2026-06-13 20:16:32,297 [INFO] [amt-d-31.pdf] Transcribing page 23/51 (Pass 1 - Flash-Lite).
516
+ 2026-06-13 20:16:32,297 [INFO] AFC is enabled with max remote calls: 10.
517
+ 2026-06-13 20:16:33,733 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
518
+ 2026-06-13 20:16:34,140 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
519
+ 2026-06-13 20:16:34,224 [INFO] [amt-d-3.pdf] Transcribing page 31/34 (Pass 1 - Flash-Lite).
520
+ 2026-06-13 20:16:34,224 [INFO] AFC is enabled with max remote calls: 10.
521
+ 2026-06-13 20:16:34,668 [INFO] [amt-d-7.pdf] Transcribing page 10/20 (Pass 1 - Flash-Lite).
522
+ 2026-06-13 20:16:34,668 [INFO] AFC is enabled with max remote calls: 10.
523
+ 2026-06-13 20:16:35,620 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
524
+ 2026-06-13 20:16:35,899 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
525
+ 2026-06-13 20:16:36,121 [INFO] [amt-d-31.pdf] Transcribing page 24/51 (Pass 1 - Flash-Lite).
526
+ 2026-06-13 20:16:36,122 [INFO] AFC is enabled with max remote calls: 10.
527
+ 2026-06-13 20:16:36,443 [INFO] [amt-d-9.pdf] Transcribing page 10/67 (Pass 1 - Flash-Lite).
528
+ 2026-06-13 20:16:36,443 [INFO] AFC is enabled with max remote calls: 10.
529
+ 2026-06-13 20:16:37,930 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
530
+ 2026-06-13 20:16:38,096 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
531
+ 2026-06-13 20:16:38,282 [INFO] [amt-d-3.pdf] Transcribing page 32/34 (Pass 1 - Flash-Lite).
532
+ 2026-06-13 20:16:38,282 [INFO] AFC is enabled with max remote calls: 10.
533
+ 2026-06-13 20:16:38,660 [INFO] [amt-d-7.pdf] Transcribing page 11/20 (Pass 1 - Flash-Lite).
534
+ 2026-06-13 20:16:38,661 [INFO] AFC is enabled with max remote calls: 10.
535
+ 2026-06-13 20:16:40,382 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
536
+ 2026-06-13 20:16:40,508 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
537
+ 2026-06-13 20:16:40,818 [INFO] [amt-d-31.pdf] Transcribing page 25/51 (Pass 1 - Flash-Lite).
538
+ 2026-06-13 20:16:40,818 [INFO] AFC is enabled with max remote calls: 10.
539
+ 2026-06-13 20:16:41,050 [INFO] [amt-d-9.pdf] Transcribing page 11/67 (Pass 1 - Flash-Lite).
540
+ 2026-06-13 20:16:41,050 [INFO] AFC is enabled with max remote calls: 10.
541
+ 2026-06-13 20:16:41,313 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
542
+ 2026-06-13 20:16:41,468 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
543
+ 2026-06-13 20:16:41,814 [INFO] [amt-d-3.pdf] Transcribing page 33/34 (Pass 1 - Flash-Lite).
544
+ 2026-06-13 20:16:41,814 [INFO] AFC is enabled with max remote calls: 10.
545
+ 2026-06-13 20:16:41,883 [INFO] [amt-d-7.pdf] Transcribing page 12/20 (Pass 1 - Flash-Lite).
546
+ 2026-06-13 20:16:41,883 [INFO] AFC is enabled with max remote calls: 10.
547
+ 2026-06-13 20:16:43,801 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
548
+ 2026-06-13 20:16:44,201 [INFO] [amt-d-31.pdf] Transcribing page 26/51 (Pass 1 - Flash-Lite).
549
+ 2026-06-13 20:16:44,201 [INFO] AFC is enabled with max remote calls: 10.
550
+ 2026-06-13 20:16:44,506 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
551
+ 2026-06-13 20:16:44,570 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
552
+ 2026-06-13 20:16:44,828 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
553
+ 2026-06-13 20:16:44,865 [INFO] [amt-d-7.pdf] Transcribing page 13/20 (Pass 1 - Flash-Lite).
554
+ 2026-06-13 20:16:44,865 [INFO] AFC is enabled with max remote calls: 10.
555
+ 2026-06-13 20:16:45,048 [INFO] [amt-d-3.pdf] Transcribing page 34/34 (Pass 1 - Flash-Lite).
556
+ 2026-06-13 20:16:45,048 [INFO] AFC is enabled with max remote calls: 10.
557
+ 2026-06-13 20:16:45,155 [INFO] [amt-d-9.pdf] Transcribing page 12/67 (Pass 1 - Flash-Lite).
558
+ 2026-06-13 20:16:45,155 [INFO] AFC is enabled with max remote calls: 10.
559
+ 2026-06-13 20:16:46,928 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
560
+ 2026-06-13 20:16:47,294 [INFO] [amt-d-7.pdf] Transcribing page 14/20 (Pass 1 - Flash-Lite).
561
+ 2026-06-13 20:16:47,295 [INFO] AFC is enabled with max remote calls: 10.
562
+ 2026-06-13 20:16:47,432 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
563
+ 2026-06-13 20:16:47,821 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
564
+ 2026-06-13 20:16:47,887 [INFO] [amt-d-31.pdf] Transcribing page 27/51 (Pass 1 - Flash-Lite).
565
+ 2026-06-13 20:16:47,887 [INFO] AFC is enabled with max remote calls: 10.
566
+ 2026-06-13 20:16:48,178 [INFO] [amt-d-9.pdf] Transcribing page 13/67 (Pass 1 - Flash-Lite).
567
+ 2026-06-13 20:16:48,178 [INFO] AFC is enabled with max remote calls: 10.
568
+ 2026-06-13 20:16:48,984 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
569
+ 2026-06-13 20:16:48,986 [INFO] [amt-d-3.pdf] Refining full document syntax (Pass 2 - Gemini Pro).
570
+ 2026-06-13 20:16:48,986 [INFO] AFC is enabled with max remote calls: 10.
571
+ 2026-06-13 20:16:49,245 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
572
+ 2026-06-13 20:16:49,615 [INFO] [amt-d-7.pdf] Transcribing page 15/20 (Pass 1 - Flash-Lite).
573
+ 2026-06-13 20:16:49,615 [INFO] AFC is enabled with max remote calls: 10.
574
+ 2026-06-13 20:16:50,400 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
575
+ 2026-06-13 20:16:50,716 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
576
+ 2026-06-13 20:16:50,787 [INFO] [amt-d-9.pdf] Transcribing page 14/67 (Pass 1 - Flash-Lite).
577
+ 2026-06-13 20:16:50,788 [INFO] AFC is enabled with max remote calls: 10.
578
+ 2026-06-13 20:16:51,116 [INFO] [amt-d-31.pdf] Transcribing page 28/51 (Pass 1 - Flash-Lite).
579
+ 2026-06-13 20:16:51,116 [INFO] AFC is enabled with max remote calls: 10.
580
+ 2026-06-13 20:16:51,880 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
581
+ 2026-06-13 20:16:52,230 [INFO] [amt-d-7.pdf] Transcribing page 16/20 (Pass 1 - Flash-Lite).
582
+ 2026-06-13 20:16:52,230 [INFO] AFC is enabled with max remote calls: 10.
583
+ 2026-06-13 20:16:53,728 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
584
+ 2026-06-13 20:16:54,230 [INFO] [amt-d-9.pdf] Transcribing page 15/67 (Pass 1 - Flash-Lite).
585
+ 2026-06-13 20:16:54,231 [INFO] AFC is enabled with max remote calls: 10.
586
+ 2026-06-13 20:16:54,762 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
587
+ 2026-06-13 20:16:55,136 [INFO] [amt-d-7.pdf] Transcribing page 17/20 (Pass 1 - Flash-Lite).
588
+ 2026-06-13 20:16:55,136 [INFO] AFC is enabled with max remote calls: 10.
589
+ 2026-06-13 20:16:55,186 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-pro:generateContent "HTTP/1.1 200 OK"
590
+ 2026-06-13 20:16:55,190 [INFO] [amt-d-35.pdf] Saving output files to destination without compiling.
591
+ 2026-06-13 20:16:55,204 [INFO] [amt-d-35.pdf] SUCCESS. Content directory saved at ./processed_pdfs/amt-d-35
592
+ 2026-06-13 20:16:55,204 [INFO] [d-19-336.pdf] Initializing workspace.
593
+ 2026-06-13 20:16:55,813 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
594
+ 2026-06-13 20:16:56,099 [INFO] [d-19-336.pdf] Transcribing page 1/4 (Pass 1 - Flash-Lite).
595
+ 2026-06-13 20:16:56,100 [INFO] AFC is enabled with max remote calls: 10.
596
+ 2026-06-13 20:16:56,245 [INFO] [amt-d-31.pdf] Transcribing page 29/51 (Pass 1 - Flash-Lite).
597
+ 2026-06-13 20:16:56,245 [INFO] AFC is enabled with max remote calls: 10.
598
+ 2026-06-13 20:16:56,974 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
599
+ 2026-06-13 20:16:57,242 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
600
+ 2026-06-13 20:16:57,461 [INFO] [amt-d-9.pdf] Transcribing page 16/67 (Pass 1 - Flash-Lite).
601
+ 2026-06-13 20:16:57,461 [INFO] AFC is enabled with max remote calls: 10.
602
+ 2026-06-13 20:16:57,632 [INFO] [amt-d-7.pdf] Transcribing page 18/20 (Pass 1 - Flash-Lite).
603
+ 2026-06-13 20:16:57,632 [INFO] AFC is enabled with max remote calls: 10.
604
+ 2026-06-13 20:16:58,843 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
605
+ 2026-06-13 20:16:59,283 [INFO] [amt-d-31.pdf] Transcribing page 30/51 (Pass 1 - Flash-Lite).
606
+ 2026-06-13 20:16:59,283 [INFO] AFC is enabled with max remote calls: 10.
607
+ 2026-06-13 20:17:00,088 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
608
+ 2026-06-13 20:17:00,089 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
609
+ 2026-06-13 20:17:00,405 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
610
+ 2026-06-13 20:17:00,594 [INFO] [amt-d-9.pdf] Transcribing page 17/67 (Pass 1 - Flash-Lite).
611
+ 2026-06-13 20:17:00,594 [INFO] AFC is enabled with max remote calls: 10.
612
+ 2026-06-13 20:17:00,711 [INFO] [amt-d-7.pdf] Transcribing page 19/20 (Pass 1 - Flash-Lite).
613
+ 2026-06-13 20:17:00,711 [INFO] AFC is enabled with max remote calls: 10.
614
+ 2026-06-13 20:17:00,986 [INFO] [d-19-336.pdf] Transcribing page 2/4 (Pass 1 - Flash-Lite).
615
+ 2026-06-13 20:17:00,987 [INFO] AFC is enabled with max remote calls: 10.
616
+ 2026-06-13 20:17:02,352 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
617
+ 2026-06-13 20:17:02,808 [INFO] [amt-d-31.pdf] Transcribing page 31/51 (Pass 1 - Flash-Lite).
618
+ 2026-06-13 20:17:02,809 [INFO] AFC is enabled with max remote calls: 10.
619
+ 2026-06-13 20:17:03,309 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
620
+ 2026-06-13 20:17:03,817 [INFO] [amt-d-9.pdf] Transcribing page 18/67 (Pass 1 - Flash-Lite).
621
+ 2026-06-13 20:17:03,817 [INFO] AFC is enabled with max remote calls: 10.
622
+ 2026-06-13 20:17:04,667 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
623
+ 2026-06-13 20:17:04,681 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
624
+ 2026-06-13 20:17:05,317 [INFO] [amt-d-7.pdf] Transcribing page 20/20 (Pass 1 - Flash-Lite).
625
+ 2026-06-13 20:17:05,317 [INFO] AFC is enabled with max remote calls: 10.
626
+ 2026-06-13 20:17:05,467 [INFO] [d-19-336.pdf] Transcribing page 3/4 (Pass 1 - Flash-Lite).
627
+ 2026-06-13 20:17:05,468 [INFO] AFC is enabled with max remote calls: 10.
628
+ 2026-06-13 20:17:05,843 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
629
+ 2026-06-13 20:17:06,258 [INFO] [amt-d-31.pdf] Transcribing page 32/51 (Pass 1 - Flash-Lite).
630
+ 2026-06-13 20:17:06,258 [INFO] AFC is enabled with max remote calls: 10.
631
+ 2026-06-13 20:17:06,798 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
632
+ 2026-06-13 20:17:07,286 [INFO] [amt-d-9.pdf] Transcribing page 19/67 (Pass 1 - Flash-Lite).
633
+ 2026-06-13 20:17:07,286 [INFO] AFC is enabled with max remote calls: 10.
634
+ 2026-06-13 20:17:08,411 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
635
+ 2026-06-13 20:17:09,109 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
636
+ 2026-06-13 20:17:09,113 [INFO] [amt-d-7.pdf] Refining full document syntax (Pass 2 - Gemini Pro).
637
+ 2026-06-13 20:17:09,113 [INFO] AFC is enabled with max remote calls: 10.
638
+ 2026-06-13 20:17:09,263 [INFO] [d-19-336.pdf] Transcribing page 4/4 (Pass 1 - Flash-Lite).
639
+ 2026-06-13 20:17:09,264 [INFO] AFC is enabled with max remote calls: 10.
640
+ 2026-06-13 20:17:09,849 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
641
+ 2026-06-13 20:17:10,292 [INFO] [amt-d-31.pdf] Transcribing page 33/51 (Pass 1 - Flash-Lite).
642
+ 2026-06-13 20:17:10,292 [INFO] AFC is enabled with max remote calls: 10.
643
+ 2026-06-13 20:17:10,341 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
644
+ 2026-06-13 20:17:10,873 [INFO] [amt-d-9.pdf] Transcribing page 20/67 (Pass 1 - Flash-Lite).
645
+ 2026-06-13 20:17:10,873 [INFO] AFC is enabled with max remote calls: 10.
646
+ 2026-06-13 20:17:13,413 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
647
+ 2026-06-13 20:17:13,450 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
648
+ 2026-06-13 20:17:13,847 [INFO] [amt-d-31.pdf] Transcribing page 34/51 (Pass 1 - Flash-Lite).
649
+ 2026-06-13 20:17:13,847 [INFO] AFC is enabled with max remote calls: 10.
650
+ 2026-06-13 20:17:13,937 [INFO] [amt-d-9.pdf] Transcribing page 21/67 (Pass 1 - Flash-Lite).
651
+ 2026-06-13 20:17:13,938 [INFO] AFC is enabled with max remote calls: 10.
652
+ 2026-06-13 20:17:16,429 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
653
+ 2026-06-13 20:17:16,856 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
654
+ 2026-06-13 20:17:16,879 [INFO] [amt-d-9.pdf] Transcribing page 22/67 (Pass 1 - Flash-Lite).
655
+ 2026-06-13 20:17:16,880 [INFO] AFC is enabled with max remote calls: 10.
656
+ 2026-06-13 20:17:17,300 [INFO] [amt-d-31.pdf] Transcribing page 35/51 (Pass 1 - Flash-Lite).
657
+ 2026-06-13 20:17:17,300 [INFO] AFC is enabled with max remote calls: 10.
658
+ 2026-06-13 20:17:19,842 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
659
+ 2026-06-13 20:17:20,272 [INFO] [amt-d-9.pdf] Transcribing page 23/67 (Pass 1 - Flash-Lite).
660
+ 2026-06-13 20:17:20,273 [INFO] AFC is enabled with max remote calls: 10.
661
+ 2026-06-13 20:17:20,513 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
662
+ 2026-06-13 20:17:20,985 [INFO] [amt-d-31.pdf] Transcribing page 36/51 (Pass 1 - Flash-Lite).
663
+ 2026-06-13 20:17:20,985 [INFO] AFC is enabled with max remote calls: 10.
664
+ 2026-06-13 20:17:23,096 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
665
+ 2026-06-13 20:17:23,610 [INFO] [amt-d-9.pdf] Transcribing page 24/67 (Pass 1 - Flash-Lite).
666
+ 2026-06-13 20:17:23,610 [INFO] AFC is enabled with max remote calls: 10.
667
+ 2026-06-13 20:17:24,216 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
668
+ 2026-06-13 20:17:24,694 [INFO] [amt-d-31.pdf] Transcribing page 37/51 (Pass 1 - Flash-Lite).
669
+ 2026-06-13 20:17:24,694 [INFO] AFC is enabled with max remote calls: 10.
670
+ 2026-06-13 20:17:26,100 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
671
+ 2026-06-13 20:17:26,623 [INFO] [amt-d-9.pdf] Transcribing page 25/67 (Pass 1 - Flash-Lite).
672
+ 2026-06-13 20:17:26,623 [INFO] AFC is enabled with max remote calls: 10.
673
+ 2026-06-13 20:17:27,891 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
674
+ 2026-06-13 20:17:28,327 [INFO] [amt-d-31.pdf] Transcribing page 38/51 (Pass 1 - Flash-Lite).
675
+ 2026-06-13 20:17:28,327 [INFO] AFC is enabled with max remote calls: 10.
676
+ 2026-06-13 20:17:30,552 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
677
+ 2026-06-13 20:17:31,075 [INFO] [amt-d-9.pdf] Transcribing page 26/67 (Pass 1 - Flash-Lite).
678
+ 2026-06-13 20:17:31,075 [INFO] AFC is enabled with max remote calls: 10.
679
+ 2026-06-13 20:17:31,853 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
680
+ 2026-06-13 20:17:32,367 [INFO] [amt-d-31.pdf] Transcribing page 39/51 (Pass 1 - Flash-Lite).
681
+ 2026-06-13 20:17:32,367 [INFO] AFC is enabled with max remote calls: 10.
682
+ 2026-06-13 20:17:34,685 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
683
+ 2026-06-13 20:17:35,192 [INFO] [amt-d-9.pdf] Transcribing page 27/67 (Pass 1 - Flash-Lite).
684
+ 2026-06-13 20:17:35,192 [INFO] AFC is enabled with max remote calls: 10.
685
+ 2026-06-13 20:17:35,791 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
686
+ 2026-06-13 20:17:36,219 [INFO] [amt-d-31.pdf] Transcribing page 40/51 (Pass 1 - Flash-Lite).
687
+ 2026-06-13 20:17:36,220 [INFO] AFC is enabled with max remote calls: 10.
688
+ 2026-06-13 20:17:38,231 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
689
+ 2026-06-13 20:17:38,796 [INFO] [amt-d-9.pdf] Transcribing page 28/67 (Pass 1 - Flash-Lite).
690
+ 2026-06-13 20:17:38,796 [INFO] AFC is enabled with max remote calls: 10.
691
+ 2026-06-13 20:17:40,296 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
692
+ 2026-06-13 20:17:40,735 [INFO] [amt-d-31.pdf] Transcribing page 41/51 (Pass 1 - Flash-Lite).
693
+ 2026-06-13 20:17:40,735 [INFO] AFC is enabled with max remote calls: 10.
694
+ 2026-06-13 20:17:41,326 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
695
+ 2026-06-13 20:17:41,896 [INFO] [amt-d-9.pdf] Transcribing page 29/67 (Pass 1 - Flash-Lite).
696
+ 2026-06-13 20:17:41,897 [INFO] AFC is enabled with max remote calls: 10.
697
+ 2026-06-13 20:17:44,166 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
698
+ 2026-06-13 20:17:44,539 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
699
+ 2026-06-13 20:17:44,663 [INFO] [amt-d-31.pdf] Transcribing page 42/51 (Pass 1 - Flash-Lite).
700
+ 2026-06-13 20:17:44,663 [INFO] AFC is enabled with max remote calls: 10.
701
+ 2026-06-13 20:17:45,120 [INFO] [amt-d-9.pdf] Transcribing page 30/67 (Pass 1 - Flash-Lite).
702
+ 2026-06-13 20:17:45,120 [INFO] AFC is enabled with max remote calls: 10.
703
+ 2026-06-13 20:17:47,872 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
704
+ 2026-06-13 20:17:48,016 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
705
+ 2026-06-13 20:17:48,425 [INFO] [amt-d-9.pdf] Transcribing page 31/67 (Pass 1 - Flash-Lite).
706
+ 2026-06-13 20:17:48,425 [INFO] AFC is enabled with max remote calls: 10.
707
+ 2026-06-13 20:17:48,499 [INFO] [amt-d-31.pdf] Transcribing page 43/51 (Pass 1 - Flash-Lite).
708
+ 2026-06-13 20:17:48,499 [INFO] AFC is enabled with max remote calls: 10.
709
+ 2026-06-13 20:17:51,266 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
710
+ 2026-06-13 20:17:51,813 [INFO] [amt-d-9.pdf] Transcribing page 32/67 (Pass 1 - Flash-Lite).
711
+ 2026-06-13 20:17:51,813 [INFO] AFC is enabled with max remote calls: 10.
712
+ 2026-06-13 20:17:52,385 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
713
+ 2026-06-13 20:17:52,819 [INFO] [amt-d-31.pdf] Transcribing page 44/51 (Pass 1 - Flash-Lite).
714
+ 2026-06-13 20:17:52,819 [INFO] AFC is enabled with max remote calls: 10.
715
+ 2026-06-13 20:17:54,914 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
716
+ 2026-06-13 20:17:55,459 [INFO] [amt-d-9.pdf] Transcribing page 33/67 (Pass 1 - Flash-Lite).
717
+ 2026-06-13 20:17:55,459 [INFO] AFC is enabled with max remote calls: 10.
718
+ 2026-06-13 20:17:56,259 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
719
+ 2026-06-13 20:17:56,676 [INFO] [amt-d-31.pdf] Transcribing page 45/51 (Pass 1 - Flash-Lite).
720
+ 2026-06-13 20:17:56,676 [INFO] AFC is enabled with max remote calls: 10.
721
+ 2026-06-13 20:17:58,195 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
722
+ 2026-06-13 20:17:58,770 [INFO] [amt-d-9.pdf] Transcribing page 34/67 (Pass 1 - Flash-Lite).
723
+ 2026-06-13 20:17:58,771 [INFO] AFC is enabled with max remote calls: 10.
724
+ 2026-06-13 20:18:00,236 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
725
+ 2026-06-13 20:18:00,664 [INFO] [amt-d-31.pdf] Transcribing page 46/51 (Pass 1 - Flash-Lite).
726
+ 2026-06-13 20:18:00,664 [INFO] AFC is enabled with max remote calls: 10.
727
+ 2026-06-13 20:18:01,740 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
728
+ 2026-06-13 20:18:02,276 [INFO] [amt-d-9.pdf] Transcribing page 35/67 (Pass 1 - Flash-Lite).
729
+ 2026-06-13 20:18:02,276 [INFO] AFC is enabled with max remote calls: 10.
730
+ 2026-06-13 20:18:04,103 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
731
+ 2026-06-13 20:18:04,619 [INFO] [amt-d-31.pdf] Transcribing page 47/51 (Pass 1 - Flash-Lite).
732
+ 2026-06-13 20:18:04,619 [INFO] AFC is enabled with max remote calls: 10.
733
+ 2026-06-13 20:18:05,059 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
734
+ 2026-06-13 20:18:05,576 [INFO] [amt-d-9.pdf] Transcribing page 36/67 (Pass 1 - Flash-Lite).
735
+ 2026-06-13 20:18:05,576 [INFO] AFC is enabled with max remote calls: 10.
736
+ 2026-06-13 20:18:07,566 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
737
+ 2026-06-13 20:18:08,154 [INFO] [amt-d-31.pdf] Transcribing page 48/51 (Pass 1 - Flash-Lite).
738
+ 2026-06-13 20:18:08,154 [INFO] AFC is enabled with max remote calls: 10.
739
+ 2026-06-13 20:18:08,862 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
740
+ 2026-06-13 20:18:09,419 [INFO] [amt-d-9.pdf] Transcribing page 37/67 (Pass 1 - Flash-Lite).
741
+ 2026-06-13 20:18:09,419 [INFO] AFC is enabled with max remote calls: 10.
742
+ 2026-06-13 20:18:11,548 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
743
+ 2026-06-13 20:18:12,045 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
744
+ 2026-06-13 20:18:12,064 [INFO] [amt-d-31.pdf] Transcribing page 49/51 (Pass 1 - Flash-Lite).
745
+ 2026-06-13 20:18:12,064 [INFO] AFC is enabled with max remote calls: 10.
746
+ 2026-06-13 20:18:12,592 [INFO] [amt-d-9.pdf] Transcribing page 38/67 (Pass 1 - Flash-Lite).
747
+ 2026-06-13 20:18:12,593 [INFO] AFC is enabled with max remote calls: 10.
748
+ 2026-06-13 20:18:14,933 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
749
+ 2026-06-13 20:18:15,326 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
750
+ 2026-06-13 20:18:15,440 [INFO] [amt-d-31.pdf] Transcribing page 50/51 (Pass 1 - Flash-Lite).
751
+ 2026-06-13 20:18:15,440 [INFO] AFC is enabled with max remote calls: 10.
752
+ 2026-06-13 20:18:15,733 [INFO] [amt-d-9.pdf] Transcribing page 39/67 (Pass 1 - Flash-Lite).
753
+ 2026-06-13 20:18:15,733 [INFO] AFC is enabled with max remote calls: 10.
754
+ 2026-06-13 20:18:17,905 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
755
+ 2026-06-13 20:18:18,351 [INFO] [amt-d-31.pdf] Transcribing page 51/51 (Pass 1 - Flash-Lite).
756
+ 2026-06-13 20:18:18,351 [INFO] AFC is enabled with max remote calls: 10.
757
+ 2026-06-13 20:18:19,299 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
758
+ 2026-06-13 20:18:19,801 [INFO] [amt-d-9.pdf] Transcribing page 40/67 (Pass 1 - Flash-Lite).
759
+ 2026-06-13 20:18:19,801 [INFO] AFC is enabled with max remote calls: 10.
760
+ 2026-06-13 20:18:20,924 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
761
+ 2026-06-13 20:18:20,927 [INFO] [amt-d-31.pdf] Refining full document syntax (Pass 2 - Gemini Pro).
762
+ 2026-06-13 20:18:20,927 [INFO] AFC is enabled with max remote calls: 10.
763
+ 2026-06-13 20:18:22,113 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
764
+ 2026-06-13 20:18:22,386 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
765
+ 2026-06-13 20:18:22,584 [INFO] [amt-d-5.pdf] Transcribing page 6/6 (Pass 1 - Flash-Lite).
766
+ 2026-06-13 20:18:22,584 [INFO] AFC is enabled with max remote calls: 10.
767
+ 2026-06-13 20:18:22,888 [INFO] [amt-d-9.pdf] Transcribing page 41/67 (Pass 1 - Flash-Lite).
768
+ 2026-06-13 20:18:22,889 [INFO] AFC is enabled with max remote calls: 10.
769
+ 2026-06-13 20:18:25,254 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
770
+ 2026-06-13 20:18:25,257 [INFO] [amt-d-5.pdf] Refining full document syntax (Pass 2 - Gemini Pro).
771
+ 2026-06-13 20:18:25,257 [INFO] AFC is enabled with max remote calls: 10.
772
+ 2026-06-13 20:18:25,466 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
773
+ 2026-06-13 20:18:25,969 [INFO] [amt-d-9.pdf] Transcribing page 42/67 (Pass 1 - Flash-Lite).
774
+ 2026-06-13 20:18:25,969 [INFO] AFC is enabled with max remote calls: 10.
775
+ 2026-06-13 20:18:28,746 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
776
+ 2026-06-13 20:18:29,253 [INFO] [amt-d-9.pdf] Transcribing page 43/67 (Pass 1 - Flash-Lite).
777
+ 2026-06-13 20:18:29,253 [INFO] AFC is enabled with max remote calls: 10.
778
+ 2026-06-13 20:18:32,235 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
779
+ 2026-06-13 20:18:32,761 [INFO] [amt-d-9.pdf] Transcribing page 44/67 (Pass 1 - Flash-Lite).
780
+ 2026-06-13 20:18:32,762 [INFO] AFC is enabled with max remote calls: 10.
781
+ 2026-06-13 20:18:35,200 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-pro:generateContent "HTTP/1.1 200 OK"
782
+ 2026-06-13 20:18:35,204 [INFO] [amt-d-5.pdf] Saving output files to destination without compiling.
783
+ 2026-06-13 20:18:35,233 [INFO] [amt-d-5.pdf] SUCCESS. Content directory saved at ./processed_pdfs/amt-d-5
784
+ 2026-06-13 20:18:35,517 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
785
+ 2026-06-13 20:18:36,071 [INFO] [amt-d-9.pdf] Transcribing page 45/67 (Pass 1 - Flash-Lite).
786
+ 2026-06-13 20:18:36,071 [INFO] AFC is enabled with max remote calls: 10.
787
+ 2026-06-13 20:18:39,037 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
788
+ 2026-06-13 20:18:39,533 [INFO] [amt-d-9.pdf] Transcribing page 46/67 (Pass 1 - Flash-Lite).
789
+ 2026-06-13 20:18:39,533 [INFO] AFC is enabled with max remote calls: 10.
790
+ 2026-06-13 20:18:42,183 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
791
+ 2026-06-13 20:18:42,673 [INFO] [amt-d-9.pdf] Transcribing page 47/67 (Pass 1 - Flash-Lite).
792
+ 2026-06-13 20:18:42,673 [INFO] AFC is enabled with max remote calls: 10.
793
+ 2026-06-13 20:18:44,851 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
794
+ 2026-06-13 20:18:45,176 [INFO] [amt-d-9.pdf] Transcribing page 48/67 (Pass 1 - Flash-Lite).
795
+ 2026-06-13 20:18:45,176 [INFO] AFC is enabled with max remote calls: 10.
796
+ 2026-06-13 20:18:47,112 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
797
+ 2026-06-13 20:18:47,417 [INFO] [amt-d-9.pdf] Transcribing page 49/67 (Pass 1 - Flash-Lite).
798
+ 2026-06-13 20:18:47,418 [INFO] AFC is enabled with max remote calls: 10.
799
+ 2026-06-13 20:18:49,538 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
800
+ 2026-06-13 20:18:49,991 [INFO] [amt-d-9.pdf] Transcribing page 50/67 (Pass 1 - Flash-Lite).
801
+ 2026-06-13 20:18:49,991 [INFO] AFC is enabled with max remote calls: 10.
802
+ 2026-06-13 20:18:55,071 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
803
+ 2026-06-13 20:18:55,558 [INFO] [amt-d-9.pdf] Transcribing page 51/67 (Pass 1 - Flash-Lite).
804
+ 2026-06-13 20:18:55,558 [INFO] AFC is enabled with max remote calls: 10.
805
+ 2026-06-13 20:18:59,791 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
806
+ 2026-06-13 20:19:00,305 [INFO] [amt-d-9.pdf] Transcribing page 52/67 (Pass 1 - Flash-Lite).
807
+ 2026-06-13 20:19:00,305 [INFO] AFC is enabled with max remote calls: 10.
808
+ 2026-06-13 20:19:03,084 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
809
+ 2026-06-13 20:19:03,562 [INFO] [amt-d-9.pdf] Transcribing page 53/67 (Pass 1 - Flash-Lite).
810
+ 2026-06-13 20:19:03,563 [INFO] AFC is enabled with max remote calls: 10.
811
+ 2026-06-13 20:19:07,093 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
812
+ 2026-06-13 20:19:07,566 [INFO] [amt-d-9.pdf] Transcribing page 54/67 (Pass 1 - Flash-Lite).
813
+ 2026-06-13 20:19:07,566 [INFO] AFC is enabled with max remote calls: 10.
814
+ 2026-06-13 20:19:10,543 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
815
+ 2026-06-13 20:19:10,991 [INFO] [amt-d-9.pdf] Transcribing page 55/67 (Pass 1 - Flash-Lite).
816
+ 2026-06-13 20:19:10,991 [INFO] AFC is enabled with max remote calls: 10.
817
+ 2026-06-13 20:19:14,255 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
818
+ 2026-06-13 20:19:14,691 [INFO] [amt-d-9.pdf] Transcribing page 56/67 (Pass 1 - Flash-Lite).
819
+ 2026-06-13 20:19:14,691 [INFO] AFC is enabled with max remote calls: 10.
820
+ 2026-06-13 20:19:17,383 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
821
+ 2026-06-13 20:19:17,910 [INFO] [amt-d-9.pdf] Transcribing page 57/67 (Pass 1 - Flash-Lite).
822
+ 2026-06-13 20:19:17,910 [INFO] AFC is enabled with max remote calls: 10.
823
+ 2026-06-13 20:19:20,979 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
824
+ 2026-06-13 20:19:21,213 [INFO] [amt-d-9.pdf] Transcribing page 58/67 (Pass 1 - Flash-Lite).
825
+ 2026-06-13 20:19:21,214 [INFO] AFC is enabled with max remote calls: 10.
826
+ 2026-06-13 20:19:23,429 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
827
+ 2026-06-13 20:19:23,662 [INFO] [amt-d-9.pdf] Transcribing page 59/67 (Pass 1 - Flash-Lite).
828
+ 2026-06-13 20:19:23,662 [INFO] AFC is enabled with max remote calls: 10.
829
+ 2026-06-13 20:19:26,657 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
830
+ 2026-06-13 20:19:26,898 [INFO] [amt-d-9.pdf] Transcribing page 60/67 (Pass 1 - Flash-Lite).
831
+ 2026-06-13 20:19:26,898 [INFO] AFC is enabled with max remote calls: 10.
832
+ 2026-06-13 20:19:27,332 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-pro:generateContent "HTTP/1.1 200 OK"
833
+ 2026-06-13 20:19:27,338 [INFO] [amt-d-3.pdf] Saving output files to destination without compiling.
834
+ 2026-06-13 20:19:27,359 [INFO] [amt-d-3.pdf] SUCCESS. Content directory saved at ./processed_pdfs/amt-d-3
835
+ 2026-06-13 20:19:29,237 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
836
+ 2026-06-13 20:19:29,464 [INFO] [amt-d-9.pdf] Transcribing page 61/67 (Pass 1 - Flash-Lite).
837
+ 2026-06-13 20:19:29,464 [INFO] AFC is enabled with max remote calls: 10.
838
+ 2026-06-13 20:19:31,944 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
839
+ 2026-06-13 20:19:32,153 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-pro:generateContent "HTTP/1.1 200 OK"
840
+ 2026-06-13 20:19:32,158 [INFO] [amt-d-7.pdf] Saving output files to destination without compiling.
841
+ 2026-06-13 20:19:32,175 [INFO] [amt-d-7.pdf] SUCCESS. Content directory saved at ./processed_pdfs/amt-d-7
842
+ 2026-06-13 20:19:32,342 [INFO] [amt-d-9.pdf] Transcribing page 62/67 (Pass 1 - Flash-Lite).
843
+ 2026-06-13 20:19:32,342 [INFO] AFC is enabled with max remote calls: 10.
844
+ 2026-06-13 20:19:34,795 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
845
+ 2026-06-13 20:19:35,184 [INFO] [amt-d-9.pdf] Transcribing page 63/67 (Pass 1 - Flash-Lite).
846
+ 2026-06-13 20:19:35,185 [INFO] AFC is enabled with max remote calls: 10.
847
+ 2026-06-13 20:19:37,505 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
848
+ 2026-06-13 20:19:37,867 [INFO] [amt-d-9.pdf] Transcribing page 64/67 (Pass 1 - Flash-Lite).
849
+ 2026-06-13 20:19:37,868 [INFO] AFC is enabled with max remote calls: 10.
850
+ 2026-06-13 20:19:42,205 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
851
+ 2026-06-13 20:19:42,656 [INFO] [amt-d-9.pdf] Transcribing page 65/67 (Pass 1 - Flash-Lite).
852
+ 2026-06-13 20:19:42,656 [INFO] AFC is enabled with max remote calls: 10.
853
+ 2026-06-13 20:19:45,449 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
854
+ 2026-06-13 20:19:45,898 [INFO] [amt-d-9.pdf] Transcribing page 66/67 (Pass 1 - Flash-Lite).
855
+ 2026-06-13 20:19:45,898 [INFO] AFC is enabled with max remote calls: 10.
856
+ 2026-06-13 20:19:48,544 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
857
+ 2026-06-13 20:19:49,052 [INFO] [amt-d-9.pdf] Transcribing page 67/67 (Pass 1 - Flash-Lite).
858
+ 2026-06-13 20:19:49,053 [INFO] AFC is enabled with max remote calls: 10.
859
+ 2026-06-13 20:19:51,535 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
860
+ 2026-06-13 20:19:51,537 [INFO] [amt-d-9.pdf] Refining full document syntax (Pass 2 - Gemini Pro).
861
+ 2026-06-13 20:19:51,537 [INFO] AFC is enabled with max remote calls: 10.
862
+ 2026-06-13 20:19:53,567 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent "HTTP/1.1 200 OK"
863
+ 2026-06-13 20:19:53,576 [INFO] [d-19-336.pdf] Refining full document syntax (Pass 2 - Gemini Pro).
864
+ 2026-06-13 20:19:53,576 [INFO] AFC is enabled with max remote calls: 10.
865
+ 2026-06-13 20:21:48,868 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-pro:generateContent "HTTP/1.1 200 OK"
866
+ 2026-06-13 20:21:48,881 [INFO] [amt-d-31.pdf] Saving output files to destination without compiling.
867
+ 2026-06-13 20:21:48,913 [INFO] [amt-d-31.pdf] SUCCESS. Content directory saved at ./processed_pdfs/amt-d-31
868
+ 2026-06-13 20:22:19,082 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-pro:generateContent "HTTP/1.1 200 OK"
869
+ 2026-06-13 20:22:19,088 [INFO] [d-19-336.pdf] Saving output files to destination without compiling.
870
+ 2026-06-13 20:22:19,093 [INFO] [d-19-336.pdf] SUCCESS. Content directory saved at ./processed_pdfs/d-19-336
871
+ 2026-06-13 20:23:09,449 [INFO] HTTP Request: POST https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-pro:generateContent "HTTP/1.1 200 OK"
872
+ 2026-06-13 20:23:09,479 [INFO] [amt-d-9.pdf] Saving output files to destination without compiling.
873
+ 2026-06-13 20:23:09,542 [INFO] [amt-d-9.pdf] SUCCESS. Content directory saved at ./processed_pdfs/amt-d-9
turing_archive/gemini_pipeline/turing_archive/personal_documents/compile_latex.py ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import subprocess
3
+ import logging
4
+ from multiprocessing import Pool
5
+
6
+ # ==========================================
7
+ # Logging & Configuration Setup
8
+ # ==========================================
9
+ logging.basicConfig(
10
+ level=logging.INFO,
11
+ format='%(asctime)s [%(levelname)s] %(message)s'
12
+ )
13
+
14
+ PROCESSED_DIR = "./processed_pdfs"
15
+ TOTAL_CORES = os.cpu_count() or 1
16
+ MAX_CONCURRENT_COMPILATIONS = max(1, TOTAL_CORES - 1)
17
+ ERROR_LOG_FILE = "failed_compilations.txt" # <-- Name of your persistent error list
18
+
19
+ def compile_single_tex(dir_name):
20
+ """Worker function executed by independent CPU cores."""
21
+ target_dir = os.path.join(PROCESSED_DIR, dir_name)
22
+ tex_file = "manuscript.tex"
23
+ tex_path = os.path.join(target_dir, tex_file)
24
+
25
+ if not os.path.exists(tex_path):
26
+ return None
27
+
28
+ logging.info(f"[{dir_name}] Launching XeLaTeX compilation...")
29
+
30
+ cmd = [
31
+ "xelatex",
32
+ "-interaction=nonstopmode",
33
+ "-file-line-error",
34
+ tex_file
35
+ ]
36
+
37
+ try:
38
+ result = subprocess.run(
39
+ cmd,
40
+ cwd=target_dir,
41
+ stdout=subprocess.PIPE,
42
+ stderr=subprocess.PIPE,
43
+ text=True,
44
+ check=True
45
+ )
46
+ logging.info(f"[{dir_name}] SUCCESS. PDF compiled successfully.")
47
+ return {
48
+ "dir": dir_name,
49
+ "status": "SUCCESS",
50
+ "full_output": result.stdout,
51
+ "errors": []
52
+ }
53
+
54
+ except subprocess.CalledProcessError as e:
55
+ logging.error(f"[{dir_name}] FAILED. Engine encountered compilation syntax bugs.")
56
+
57
+ error_summary = []
58
+ for line in e.stdout.splitlines():
59
+ if "error" in line.lower() or "fatal" in line.lower() or line.startswith("!"):
60
+ error_summary.append(line.strip())
61
+
62
+ if not error_summary:
63
+ error_summary = [e.stderr.strip() if e.stderr else "Non-zero exit status thrown by engine."]
64
+
65
+ return {
66
+ "dir": dir_name,
67
+ "status": "FAILED",
68
+ "full_output": e.stdout,
69
+ "errors": error_summary
70
+ }
71
+ except Exception as e:
72
+ logging.error(f"[{dir_name}] SYSTEM CALL ERROR: {e}")
73
+ return {
74
+ "dir": dir_name,
75
+ "status": "SYSTEM_ERROR",
76
+ "full_output": "",
77
+ "errors": [str(e)]
78
+ }
79
+
80
+ def main():
81
+ if not os.path.exists(PROCESSED_DIR):
82
+ print(f"Error: The target directory '{PROCESSED_DIR}' does not exist.")
83
+ return
84
+
85
+ all_contents = os.listdir(PROCESSED_DIR)
86
+ sub_dirs = [d for d in all_contents if os.path.isdir(os.path.join(PROCESSED_DIR, d))]
87
+
88
+ if not sub_dirs:
89
+ print(f"No sub-directories detected inside '{PROCESSED_DIR}'.")
90
+ return
91
+
92
+ print(f"System detected {TOTAL_CORES} cores.")
93
+ print(f"Spawning {MAX_CONCURRENT_COMPILATIONS} parallel XeLaTeX compilation engines across folders...\n")
94
+
95
+ pool = Pool(processes=MAX_CONCURRENT_COMPILATIONS)
96
+ try:
97
+ results = [r for r in pool.map(compile_single_tex, sub_dirs) if r is not None]
98
+ finally:
99
+ pool.close()
100
+ pool.join()
101
+
102
+ # ==========================================
103
+ # Final Reporting & Full Log Aggregation
104
+ # ==========================================
105
+ print("\n" + "="*60)
106
+ print(" DETAILED XELATEX OUTPUTS & ENGINE LOGS ")
107
+ print("="*60)
108
+
109
+ for res in results:
110
+ print(f"\n📂 FOLDER DATASTREAM: {res['dir']}")
111
+ print(f"Status: {'✅ SUCCESS' if res['status'] == 'SUCCESS' else '❌ FAILED'}")
112
+ print("-" * 40)
113
+
114
+ if res['status'] == 'SUCCESS':
115
+ summary_lines = [l for l in res['full_output'].splitlines() if "Output written on" in l or "pages" in l]
116
+ if summary_lines:
117
+ for sl in summary_lines:
118
+ print(f" {sl}")
119
+ else:
120
+ print(" Document compiled successfully. (Log output compressed)")
121
+ else:
122
+ print("🛑 Engine Syntax Errors Triggered:")
123
+ for err in res['errors'][:8]:
124
+ print(f" -> {err}")
125
+
126
+ print("\n📋 Last 15 Lines of Raw Engine Context Log:")
127
+ raw_lines = res['full_output'].splitlines()
128
+ for line in raw_lines[-15:]:
129
+ print(f" | {line}")
130
+ print("-" * 60)
131
+
132
+ # ==========================================
133
+ # PERSISTENT STORAGE WRITEBACK (New Addition)
134
+ # ==========================================
135
+ failures = [r for r in results if r["status"] != "SUCCESS"]
136
+
137
+ if failures:
138
+ try:
139
+ with open(ERROR_LOG_FILE, "w", encoding="utf-8") as f:
140
+ f.write("=== FAILED COMPILATIONS MANIFEST ===\n")
141
+ f.write(f"The following folders triggered XeLaTeX layout exceptions:\n\n")
142
+ for fail in failures:
143
+ f.write(f"📁 {fail['dir']}\n")
144
+ f.write(f" Primary Error: {fail['errors'][0] if fail['errors'] else 'Unknown layout bug'}\n\n")
145
+ print(f"\n💾 Saved persistent manifest of broken runs to: {ERROR_LOG_FILE}")
146
+ except Exception as file_err:
147
+ print(f"\n⚠️ System failed to write tracking manifest to disk: {file_err}")
148
+ else:
149
+ # If a subsequent run passes completely clean, purge the old error file
150
+ if os.path.exists(ERROR_LOG_FILE):
151
+ os.remove(ERROR_LOG_FILE)
152
+
153
+ # Global Stats Banner
154
+ print("\n" + "="*60)
155
+ print(" COMPILATION METRICS ")
156
+ print("="*60)
157
+ print(f"Total Folders Processed: {len(results)}")
158
+ print(f"Flawless Conversions: {len(results) - len(failures)}")
159
+ print(f"Syntax/Layout Failures: {len(failures)}")
160
+ print("="*60)
161
+
162
+ if __name__ == "__main__":
163
+ main()
turing_archive/gemini_pipeline/turing_archive/personal_documents/failed_compilations.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ === FAILED COMPILATIONS MANIFEST ===
2
+ The following folders triggered XeLaTeX layout exceptions:
3
+
4
+ No output PDF file written.
turing_archive/gemini_pipeline/turing_archive/personal_documents/process.py ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # processes and tries to compile latex.
2
+ # issue is that latex is not great,
3
+ # and i need a new way to generate that latex.
4
+ import os
5
+ import shutil
6
+ import subprocess
7
+ import logging
8
+ import re
9
+ from multiprocessing import Pool
10
+ from pdf2image import convert_from_path
11
+ from google import genai
12
+ from tenacity import retry, stop_after_attempt, wait_exponential
13
+
14
+ # ==========================================
15
+ # 1. Logging Setup
16
+ # ==========================================
17
+ logging.basicConfig(
18
+ level=logging.INFO,
19
+ format='%(asctime)s [%(levelname)s] %(message)s',
20
+ handlers=[logging.FileHandler("processing_trace.log"), logging.StreamHandler()]
21
+ )
22
+
23
+ def log(msg, filename):
24
+ logging.info(f"[{filename}] {msg}")
25
+
26
+ # ==========================================
27
+ # 2. Configuration
28
+ # ==========================================
29
+ API_KEY = "AIzaSyACloyikx6S1JqZfk3daRG9XTGwTMSWn7E"
30
+ MODEL_NAME = 'gemini-2.5-flash-lite'
31
+ MAX_CONCURRENT_FILES = 6
32
+ INPUT_DIR = "."
33
+ OUTPUT_DIR = "./processed_pdfs"
34
+ WORK_DIR = "./workspace"
35
+
36
+ LATEX_TEMPLATE = r"""\documentclass[11pt,a4paper]{{article}}
37
+ \usepackage[utf8]{{inputenc}}
38
+ \usepackage{{amsmath, amssymb, amsfonts}}
39
+ \usepackage{{graphicx}}
40
+ \usepackage{{xcolor}}
41
+ \usepackage[normalem]{{ulem}}
42
+ \usepackage{{cancel}}
43
+ \usepackage{{enumitem}}
44
+ \usepackage{{geometry}}
45
+ \geometry{{margin=1in}}
46
+ \begin{{document}}
47
+ {}
48
+ \end{{document}}
49
+ """
50
+
51
+ def clean_output(text):
52
+ # 1. Remove markdown code blocks
53
+ text = re.sub(r"```latex", "", text, flags=re.IGNORECASE)
54
+ text = re.sub(r"```", "", text, flags=re.IGNORECASE)
55
+
56
+ # 2. Aggressively strip preamble commands
57
+ text = re.sub(r"\\documentclass.*", "", text)
58
+ text = re.sub(r"\\usepackage\{.*?\}", "", text)
59
+ text = re.sub(r"\\begin\{document\}", "", text)
60
+ text = re.sub(r"\\end\{document\}", "", text)
61
+
62
+ # 3. Strip structural quote commands if they cause nesting issues
63
+ text = text.replace(r"\begin{quote}", "").replace(r"\end{quote}", "")
64
+
65
+ # 4. Fix common broken LaTeX syntax generated by LLMs
66
+ text = text.replace(r"&", r"\&") # Escape alignment tabs
67
+ text = re.sub(r"\\left(?![^{])", "", text) # Remove dangling left
68
+ text = re.sub(r"\\right(?![^{])", "", text) # Remove dangling right
69
+
70
+ return text.strip()
71
+
72
+ def init_worker(api_key):
73
+ global client
74
+ client = genai.Client(api_key=api_key)
75
+
76
+ @retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=2, max=10))
77
+ def call_gemini_with_retry(img, prompt):
78
+ return client.models.generate_content(
79
+ model=MODEL_NAME,
80
+ contents=[img, prompt]
81
+ )
82
+
83
+ def process_single_pdf(pdf_filename):
84
+ if pdf_filename.startswith("processed_"):
85
+ return
86
+
87
+ pdf_base = os.path.splitext(pdf_filename)[0]
88
+ workspace = os.path.join(WORK_DIR, pdf_base)
89
+ figures_dir = os.path.join(workspace, "figures")
90
+ os.makedirs(figures_dir, exist_ok=True)
91
+
92
+ log("Initializing workspace.", pdf_filename)
93
+
94
+ try:
95
+ pages = convert_from_path(pdf_filename, dpi=200)
96
+ except Exception as e:
97
+ log(f"FAILED during extraction: {e}", pdf_filename)
98
+ return
99
+
100
+ latex_content = ""
101
+
102
+ for i, page_img in enumerate(pages):
103
+ img_name = f"page_{i+1}.png"
104
+ img_path = os.path.join(figures_dir, img_name)
105
+ page_img.save(img_path, "PNG")
106
+
107
+ log(f"Transcribing page {i+1}/{len(pages)}.", pdf_filename)
108
+
109
+ # Strict prompt to prevent boilerplate hallucination
110
+ prompt = (
111
+ "Transcribe this handwritten math page into LaTeX. "
112
+ "Output ONLY the LaTeX body content. "
113
+ "DO NOT include: \\usepackage, \\documentclass, \\begin{document}, \\end{document}. "
114
+ "Ensure all math is properly closed with '$' or environment tags. "
115
+ )
116
+
117
+ try:
118
+ response = call_gemini_with_retry(page_img, prompt)
119
+ # Use \par instead of quote to avoid nested environment errors
120
+ latex_content += f"""\\subsection*{{Page {i+1}}}
121
+ \\includegraphics[width=0.6\\textwidth]{{figures/{img_name}}}
122
+ \\par {clean_output(response.text)} \\newpage\n"""
123
+ except Exception as e:
124
+ log(f"FAILED page {i+1} after retries: {e}", pdf_filename)
125
+ latex_content += f"\\subsection*{{Page {i+1}}} \\par \\textit{{Transcription failed.}} \\newpage\n"
126
+
127
+ tex_path = os.path.join(workspace, "manuscript.tex")
128
+ with open(tex_path, "w", encoding="utf-8") as f:
129
+ f.write(LATEX_TEMPLATE.format(latex_content))
130
+
131
+ log("Compiling with XeLaTeX.", pdf_filename)
132
+ try:
133
+ # Run twice to resolve references
134
+ for _ in range(2):
135
+ subprocess.run(["xelatex", "-interaction=nonstopmode", "manuscript.tex"],
136
+ cwd=workspace, stdout=subprocess.DEVNULL)
137
+
138
+ if os.path.exists(os.path.join(workspace, "manuscript.pdf")):
139
+ shutil.move(os.path.join(workspace, "manuscript.pdf"),
140
+ os.path.join(OUTPUT_DIR, f"processed_{pdf_filename}"))
141
+ log("SUCCESS.", pdf_filename)
142
+ else:
143
+ log("COMPILATION FAILED: No PDF produced.", pdf_filename)
144
+ except Exception as e:
145
+ log(f"SYSTEM ERROR: {e}", pdf_filename)
146
+
147
+ def main():
148
+ os.makedirs(OUTPUT_DIR, exist_ok=True)
149
+ os.makedirs(WORK_DIR, exist_ok=True)
150
+
151
+ files = ['amt-c-11-to20-5.pdf']
152
+ print(f"Processing {len(files)} files...")
153
+ with Pool(processes=MAX_CONCURRENT_FILES, initializer=init_worker, initargs=(API_KEY,)) as pool:
154
+ pool.map(process_single_pdf, files)
155
+
156
+ if __name__ == "__main__":
157
+ main()
turing_archive/gemini_pipeline/turing_archive/personal_documents/process_two_pass.py ADDED
@@ -0,0 +1,377 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import shutil
3
+ import subprocess
4
+ import logging
5
+ import re
6
+ from multiprocessing import Pool
7
+ from pdf2image import convert_from_path
8
+ from google import genai
9
+ from google.genai import types
10
+ from tenacity import retry, stop_after_attempt, wait_exponential,wait_random_exponential
11
+
12
+ # ==========================================
13
+ # 1. Logging Setup
14
+ # ==========================================
15
+ logging.basicConfig(
16
+ level=logging.INFO,
17
+ format='%(asctime)s [%(levelname)s] %(message)s',
18
+ handlers=[logging.FileHandler("processing_trace.log"), logging.StreamHandler()]
19
+ )
20
+
21
+ def log(msg, filename):
22
+ logging.info(f"[{filename}] {msg}")
23
+
24
+ # ==========================================
25
+ # 2. Configuration
26
+ # ==========================================
27
+ API_KEY = "AIzaSyACloyikx6S1JqZfk3daRG9XTGwTMSWn7E"
28
+ TRANSCRIPTION_MODEL = 'gemini-2.5-flash-lite' # Fast and cheap for page images
29
+ REFINEMENT_MODEL = 'gemini-2.5-pro' # Deep reasoning for structural math cleanup
30
+ MAX_CONCURRENT_FILES = 6
31
+ INPUT_DIR = "."
32
+ OUTPUT_DIR = "./processed_pdfs"
33
+ WORK_DIR = "./workspace"
34
+
35
+ LATEX_TEMPLATE = r"""\documentclass[11pt,a4paper]{{article}}
36
+ \usepackage[utf8]{{inputenc}}
37
+ \usepackage{{amsmath, amssymb, amsfonts}}
38
+ \usepackage{{graphicx}}
39
+ \usepackage{{xcolor}}
40
+ \usepackage[normalem]{{ulem}}
41
+ \usepackage{{cancel}}
42
+ \usepackage{{enumitem}}
43
+ \usepackage{{geometry}}
44
+ \geometry{{margin=1in}}
45
+ \begin{{document}}
46
+ {}
47
+ \end{{document}}
48
+ """
49
+
50
+ def clean_output(text):
51
+ if not text:
52
+ return ""
53
+ # 1. Remove markdown code blocks
54
+ text = re.sub(r"```latex", "", text, flags=re.IGNORECASE)
55
+ text = re.sub(r"```", "", text, flags=re.IGNORECASE)
56
+
57
+ # 2. Aggressively strip preamble commands
58
+ text = re.sub(r"\\documentclass.*", "", text)
59
+ text = re.sub(r"\\usepackage\{.*?\}", "", text)
60
+ text = re.sub(r"\\begin\{document\}", "", text)
61
+ text = re.sub(r"\\end\{document\}", "", text)
62
+
63
+ # 3. Strip structural quote commands if they cause nesting issues
64
+ text = text.replace(r"\begin{quote}", "").replace(r"\end{quote}", "")
65
+
66
+ return text.strip()
67
+
68
+ def init_worker(api_key):
69
+ global client
70
+ client = genai.Client(api_key=api_key)
71
+
72
+ @retry(
73
+ stop=stop_after_attempt(7),
74
+ wait=wait_random_exponential(multiplier=2, min=15, max=65),
75
+ before_sleep=lambda retry_state: logging.warning(
76
+ f"Rate limit hit (429). Retrying in {retry_state.next_action.sleep:.2f} seconds... (Attempt {retry_state.attempt_number}/7)"
77
+ )
78
+ )
79
+ def call_gemini_with_retry(contents, prompt, is_image=True):
80
+ if is_image:
81
+ return client.models.generate_content(
82
+ model=TRANSCRIPTION_MODEL,
83
+ contents=[contents, prompt]
84
+ )
85
+ else:
86
+ # Standardize text requests and route them to the stronger PRO model
87
+ combined_payload = f"{prompt}\n\nINPUT TEXT TO REFINE:\n{contents}"
88
+ return client.models.generate_content(
89
+ model=REFINEMENT_MODEL,
90
+ contents=combined_payload
91
+ )
92
+
93
+ def process_single_pdf(pdf_filename):
94
+ if pdf_filename.startswith("processed_"):
95
+ return
96
+
97
+ pdf_base = os.path.splitext(pdf_filename)[0]
98
+ workspace = os.path.join(WORK_DIR, pdf_base)
99
+ figures_dir = os.path.join(workspace, "figures")
100
+ os.makedirs(figures_dir, exist_ok=True)
101
+
102
+ log("Initializing workspace.", pdf_filename)
103
+
104
+ try:
105
+ pages = convert_from_path(pdf_filename, dpi=150)
106
+ except Exception as e:
107
+ log(f"FAILED during extraction: {e}", pdf_filename)
108
+ return
109
+
110
+ raw_latex_body = ""
111
+
112
+ # PASS 1: Sequential Page Transcriptions (Using Flash-Lite)
113
+ for i, page_img in enumerate(pages):
114
+ img_name = f"page_{i+1}.png"
115
+ img_path = os.path.join(figures_dir, img_name)
116
+ page_img.save(img_path, "PNG")
117
+
118
+ log(f"Transcribing page {i+1}/{len(pages)} (Pass 1 - Flash-Lite).", pdf_filename)
119
+
120
+ prompt = (
121
+ "Transcribe this handwritten math page into LaTeX. "
122
+ "Output ONLY the LaTeX body content. "
123
+ "DO NOT include: \\usepackage, \\documentclass, \\begin{document}, or \\end{document}. "
124
+ "Ensure all math is properly closed with '$' or environment tags. "
125
+ )
126
+
127
+ try:
128
+ response = call_gemini_with_retry(page_img, prompt, is_image=True)
129
+ cleaned_page = clean_output(response.text)
130
+
131
+ raw_latex_body += f"""\\subsection*{{Page {i+1}}}
132
+ \\includegraphics[width=0.6\\textwidth]{{figures/{img_name}}}
133
+ \\par {cleaned_page} \\newpage\n"""
134
+ except Exception as e:
135
+ log(f"FAILED page {i+1} during Pass 1: {e}", pdf_filename)
136
+ raw_latex_body += f"\\subsection*{{Page {i+1}}} \\par \\textit{{Transcription failed.}} \\newpage\n"
137
+
138
+ # PASS 2: Global Document Refinement (Using Pro - No Compilation)
139
+ log("Refining full document syntax (Pass 2 - Gemini Pro).", pdf_filename)
140
+ refinement_prompt = (
141
+ "You are an expert LaTeX proofreader. Review the provided input document containing multi-page transcription math. "
142
+ "Fix common compilation bugs globally: ensure all math inline or display environments match, "
143
+ "ensure all braces are closed correctly, convert unmatched or dangling \\left/\\right markers into generic formatting "
144
+ "like standard parenthesis if necessary, and escape naked '&' markers outside of tables or matrices. "
145
+ "DO NOT delete the actual mathematical text or sentences under any circumstance. "
146
+ "Preserve the structural page breaks (\\newpage) and image macros intact. "
147
+ "Output ONLY the corrected body markup text without any markdown or code wrappers."
148
+ )
149
+
150
+ try:
151
+ refinement_response = call_gemini_with_retry(raw_latex_body, refinement_prompt, is_image=False)
152
+ final_latex_body = clean_output(refinement_response.text)
153
+ except Exception as e:
154
+ log(f"Refinement Pass 2 failed. Falling back to Pass 1 content. Error: {e}", pdf_filename)
155
+ final_latex_body = raw_latex_body
156
+
157
+ # Assemble into standard file structure
158
+ tex_path = os.path.join(workspace, "manuscript.tex")
159
+ with open(tex_path, "w", encoding="utf-8") as f:
160
+ f.write(LATEX_TEMPLATE.format(final_latex_body))
161
+
162
+ log("Saving output files to destination without compiling.", pdf_filename)
163
+ try:
164
+ final_dest_dir = os.path.join(OUTPUT_DIR, pdf_base)
165
+ if os.path.exists(final_dest_dir):
166
+ shutil.rmtree(final_dest_dir)
167
+
168
+ shutil.copytree(workspace, final_dest_dir)
169
+ log(f"SUCCESS. Content directory saved at {final_dest_dir}", pdf_filename)
170
+ except Exception as e:
171
+ log(f"SYSTEM COPY ERROR: {e}", pdf_filename)
172
+
173
+ def main():
174
+ os.makedirs(OUTPUT_DIR, exist_ok=True)
175
+ os.makedirs(WORK_DIR, exist_ok=True)
176
+
177
+ #files = ['amt-c-11-to20-5.pdf']
178
+ #detect all files
179
+ files = [f for f in os.listdir(INPUT_DIR) if f.endswith('.pdf') and not f.startswith("processed_")]
180
+ print(f"Processing {len(files)} files with Dual-Pass Reflection (Hybrid Flash-Lite / Pro)...")
181
+
182
+ pool = Pool(processes=MAX_CONCURRENT_FILES, initializer=init_worker, initargs=(API_KEY,))
183
+ try:
184
+ pool.map(process_single_pdf, files)
185
+ finally:
186
+ pool.close()
187
+ pool.join()
188
+
189
+ print("All file processing steps have successfully completed.")
190
+
191
+ if __name__ == "__main__":
192
+ main()
193
+
194
+ # import os
195
+ # import shutil
196
+ # import subprocess
197
+ # import logging
198
+ # import re
199
+ # from multiprocessing import Pool
200
+ # from pdf2image import convert_from_path
201
+ # from google import genai
202
+ # from google.genai import types
203
+ # from tenacity import retry, stop_after_attempt, wait_exponential
204
+
205
+ # # ==========================================
206
+ # # 1. Logging Setup
207
+ # # ==========================================
208
+ # logging.basicConfig(
209
+ # level=logging.INFO,
210
+ # format='%(asctime)s [%(levelname)s] %(message)s',
211
+ # handlers=[logging.FileHandler("processing_trace.log"), logging.StreamHandler()]
212
+ # )
213
+
214
+ # def log(msg, filename):
215
+ # logging.info(f"[{filename}] {msg}")
216
+
217
+ # # ==========================================
218
+ # # 2. Configuration
219
+ # # ==========================================
220
+ # API_KEY = "AIzaSyACloyikx6S1JqZfk3daRG9XTGwTMSWn7E"
221
+ # MODEL_NAME = 'gemini-2.5-flash-lite'
222
+ # MAX_CONCURRENT_FILES = 6
223
+ # INPUT_DIR = "."
224
+ # OUTPUT_DIR = "./processed_pdfs"
225
+ # WORK_DIR = "./workspace"
226
+
227
+ # LATEX_TEMPLATE = r"""\documentclass[11pt,a4paper]{{article}}
228
+ # \usepackage[utf8]{{inputenc}}
229
+ # \usepackage{{amsmath, amssymb, amsfonts}}
230
+ # \usepackage{{graphicx}}
231
+ # \usepackage{{xcolor}}
232
+ # \usepackage[normalem]{{ulem}}
233
+ # \usepackage{{cancel}}
234
+ # \usepackage{{enumitem}}
235
+ # \usepackage{{geometry}}
236
+ # \geometry{{margin=1in}}
237
+ # \begin{{document}}
238
+ # {}
239
+ # \end{{document}}
240
+ # """
241
+
242
+ # def clean_output(text):
243
+ # if not text:
244
+ # return ""
245
+ # # 1. Remove markdown code blocks
246
+ # text = re.sub(r"```latex", "", text, flags=re.IGNORECASE)
247
+ # text = re.sub(r"```", "", text, flags=re.IGNORECASE)
248
+
249
+ # # 2. Aggressively strip preamble commands
250
+ # text = re.sub(r"\\documentclass.*", "", text)
251
+ # text = re.sub(r"\\usepackage\{.*?\}", "", text)
252
+ # text = re.sub(r"\\begin\{document\}", "", text)
253
+ # text = re.sub(r"\\end\{document\}", "", text)
254
+
255
+ # # 3. Strip structural quote commands if they cause nesting issues
256
+ # text = text.replace(r"\begin{quote}", "").replace(r"\end{quote}", "")
257
+
258
+ # return text.strip()
259
+
260
+ # def init_worker(api_key):
261
+ # global client
262
+ # client = genai.Client(api_key=api_key)
263
+
264
+ # @retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=2, max=10))
265
+ # def call_gemini_with_retry(contents, prompt, is_image=True):
266
+ # if is_image:
267
+ # return client.models.generate_content(
268
+ # model=MODEL_NAME,
269
+ # contents=[contents, prompt]
270
+ # )
271
+ # else:
272
+ # # Standardize non-image generation requests using a single explicit text configuration payload
273
+ # combined_payload = f"{prompt}\n\nINPUT TEXT TO REFINE:\n{contents}"
274
+ # return client.models.generate_content(
275
+ # model=MODEL_NAME,
276
+ # contents=combined_payload
277
+ # )
278
+
279
+ # def process_single_pdf(pdf_filename):
280
+ # if pdf_filename.startswith("processed_"):
281
+ # return
282
+
283
+ # pdf_base = os.path.splitext(pdf_filename)[0]
284
+ # workspace = os.path.join(WORK_DIR, pdf_base)
285
+ # figures_dir = os.path.join(workspace, "figures")
286
+ # os.makedirs(figures_dir, exist_ok=True)
287
+
288
+ # log("Initializing workspace.", pdf_filename)
289
+
290
+ # try:
291
+ # pages = convert_from_path(pdf_filename, dpi=150)
292
+ # except Exception as e:
293
+ # log(f"FAILED during extraction: {e}", pdf_filename)
294
+ # return
295
+
296
+ # raw_latex_body = ""
297
+
298
+ # # PASS 1: Sequential Page Transcriptions
299
+ # for i, page_img in enumerate(pages):
300
+ # img_name = f"page_{i+1}.png"
301
+ # img_path = os.path.join(figures_dir, img_name)
302
+ # page_img.save(img_path, "PNG")
303
+
304
+ # log(f"Transcribing page {i+1}/{len(pages)} (Pass 1).", pdf_filename)
305
+
306
+ # prompt = (
307
+ # "Transcribe this handwritten math page into LaTeX. "
308
+ # "Output ONLY the LaTeX body content. "
309
+ # "DO NOT include: \\usepackage, \\documentclass, \\begin{document}, or \\end{document}. "
310
+ # "Ensure all math is properly closed with '$' or environment tags. "
311
+ # )
312
+
313
+ # try:
314
+ # response = call_gemini_with_retry(page_img, prompt, is_image=True)
315
+ # cleaned_page = clean_output(response.text)
316
+
317
+ # raw_latex_body += f"""\\subsection*{{Page {i+1}}}
318
+ # \\includegraphics[width=0.6\\textwidth]{{figures/{img_name}}}
319
+ # \\par {cleaned_page} \\newpage\n"""
320
+ # except Exception as e:
321
+ # log(f"FAILED page {i+1} during Pass 1: {e}", pdf_filename)
322
+ # raw_latex_body += f"\\subsection*{{Page {i+1}}} \\par \\textit{{Transcription failed.}} \\newpage\n"
323
+
324
+ # # PASS 2: Global Document Refinement (No Compilation)
325
+ # log("Refining full document syntax (Pass 2).", pdf_filename)
326
+ # refinement_prompt = (
327
+ # "You are an expert LaTeX proofreader. Review the provided input document containing multi-page transcription math. "
328
+ # "Fix common compilation bugs globally: ensure all math inline or display environments match, "
329
+ # "ensure all braces are closed correctly, convert unmatched or dangling \\left/\\right markers into generic formatting "
330
+ # "like standard parenthesis if necessary, and escape naked '&' markers outside of tables or matrices. "
331
+ # "DO NOT delete the actual mathematical text or sentences under any circumstance. "
332
+ # "Preserve the structural page breaks (\\newpage) and image macros intact. "
333
+ # "Output ONLY the corrected body markup text without any markdown or code wrappers."
334
+ # )
335
+
336
+ # try:
337
+ # refinement_response = call_gemini_with_retry(raw_latex_body, refinement_prompt, is_image=False)
338
+ # final_latex_body = clean_output(refinement_response.text)
339
+ # except Exception as e:
340
+ # log(f"Refinement Pass 2 failed. Falling back to Pass 1 content. Error: {e}", pdf_filename)
341
+ # final_latex_body = raw_latex_body
342
+
343
+ # # Assemble into standard file structure
344
+ # tex_path = os.path.join(workspace, "manuscript.tex")
345
+ # with open(tex_path, "w", encoding="utf-8") as f:
346
+ # f.write(LATEX_TEMPLATE.format(final_latex_body))
347
+
348
+ # log("Saving output files to destination without compiling.", pdf_filename)
349
+ # try:
350
+ # final_dest_dir = os.path.join(OUTPUT_DIR, pdf_base)
351
+ # if os.path.exists(final_dest_dir):
352
+ # shutil.rmtree(final_dest_dir)
353
+
354
+ # shutil.copytree(workspace, final_dest_dir)
355
+ # log(f"SUCCESS. Content directory saved at {final_dest_dir}", pdf_filename)
356
+ # except Exception as e:
357
+ # log(f"SYSTEM COPY ERROR: {e}", pdf_filename)
358
+
359
+ # def main():
360
+ # os.makedirs(OUTPUT_DIR, exist_ok=True)
361
+ # os.makedirs(WORK_DIR, exist_ok=True)
362
+
363
+ # files = ['amt-c-11-to20-5.pdf']
364
+ # print(f"Processing {len(files)} files with Dual-Pass Reflection...")
365
+
366
+ # # Explicitly managing the pool lifecycle ensures complete structural teardown upon map exit
367
+ # pool = Pool(processes=MAX_CONCURRENT_FILES, initializer=init_worker, initargs=(API_KEY,))
368
+ # try:
369
+ # pool.map(process_single_pdf, files)
370
+ # finally:
371
+ # pool.close()
372
+ # pool.join()
373
+
374
+ # print("All file processing steps have successfully completed.")
375
+
376
+ # if __name__ == "__main__":
377
+ # main()
turing_archive/gemini_pipeline/turing_archive/personal_documents/process_two_pass_gemini_flash.py ADDED
@@ -0,0 +1,193 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import shutil
3
+ import subprocess
4
+ import logging
5
+ import re
6
+ from multiprocessing import Pool
7
+ from pdf2image import convert_from_path
8
+ from google import genai
9
+ from google.genai import types
10
+ from tenacity import retry, stop_after_attempt, wait_exponential,wait_random_exponential
11
+
12
+ # ==========================================
13
+ # 1. Logging Setup
14
+ # ==========================================
15
+ logging.basicConfig(
16
+ level=logging.INFO,
17
+ format='%(asctime)s [%(levelname)s] %(message)s',
18
+ handlers=[logging.FileHandler("processing_trace.log"), logging.StreamHandler()]
19
+ )
20
+
21
+ def log(msg, filename):
22
+ logging.info(f"[{filename}] {msg}")
23
+
24
+ # ==========================================
25
+ # 2. Configuration
26
+ # ==========================================
27
+ API_KEY = "AIzaSyACloyikx6S1JqZfk3daRG9XTGwTMSWn7E"
28
+ TRANSCRIPTION_MODEL = 'gemini-2.5-flash' # Fast and cheap for page images
29
+ REFINEMENT_MODEL = 'gemini-2.5-pro' # Deep reasoning for structural math cleanup
30
+ MAX_CONCURRENT_FILES = 6
31
+ INPUT_DIR = "."
32
+ OUTPUT_DIR = "./processed_pdfs"
33
+ WORK_DIR = "./workspace"
34
+
35
+ LATEX_TEMPLATE = r"""\documentclass[11pt,a4paper]{{article}}
36
+ \usepackage[utf8]{{inputenc}}
37
+ \usepackage{{amsmath, amssymb, amsfonts}}
38
+ \usepackage{{graphicx}}
39
+ \usepackage{{xcolor}}
40
+ \usepackage[normalem]{{ulem}}
41
+ \usepackage{{cancel}}
42
+ \usepackage{{enumitem}}
43
+ \usepackage{{geometry}}
44
+ \geometry{{margin=1in}}
45
+ \begin{{document}}
46
+ {}
47
+ \end{{document}}
48
+ """
49
+
50
+ def clean_output(text):
51
+ if not text:
52
+ return ""
53
+ # 1. Remove markdown code blocks
54
+ text = re.sub(r"```latex", "", text, flags=re.IGNORECASE)
55
+ text = re.sub(r"```", "", text, flags=re.IGNORECASE)
56
+
57
+ # 2. Aggressively strip preamble commands
58
+ text = re.sub(r"\\documentclass.*", "", text)
59
+ text = re.sub(r"\\usepackage\{.*?\}", "", text)
60
+ text = re.sub(r"\\begin\{document\}", "", text)
61
+ text = re.sub(r"\\end\{document\}", "", text)
62
+
63
+ # 3. Strip structural quote commands if they cause nesting issues
64
+ text = text.replace(r"\begin{quote}", "").replace(r"\end{quote}", "")
65
+
66
+ return text.strip()
67
+
68
+ def init_worker(api_key):
69
+ global client
70
+ client = genai.Client(api_key=api_key)
71
+
72
+ @retry(
73
+ stop=stop_after_attempt(7),
74
+ wait=wait_random_exponential(multiplier=2, min=15, max=65),
75
+ before_sleep=lambda retry_state: logging.warning(
76
+ f"Rate limit hit (429). Retrying in {retry_state.next_action.sleep:.2f} seconds... (Attempt {retry_state.attempt_number}/7)"
77
+ )
78
+ )
79
+ def call_gemini_with_retry(contents, prompt, is_image=True):
80
+ if is_image:
81
+ return client.models.generate_content(
82
+ model=TRANSCRIPTION_MODEL,
83
+ contents=[contents, prompt]
84
+ )
85
+ else:
86
+ # Standardize text requests and route them to the stronger PRO model
87
+ combined_payload = f"{prompt}\n\nINPUT TEXT TO REFINE:\n{contents}"
88
+ return client.models.generate_content(
89
+ model=REFINEMENT_MODEL,
90
+ contents=combined_payload
91
+ )
92
+
93
+ def process_single_pdf(pdf_filename):
94
+ if pdf_filename.startswith("processed_"):
95
+ return
96
+
97
+ pdf_base = os.path.splitext(pdf_filename)[0]
98
+ workspace = os.path.join(WORK_DIR, pdf_base)
99
+ figures_dir = os.path.join(workspace, "figures")
100
+ os.makedirs(figures_dir, exist_ok=True)
101
+
102
+ log("Initializing workspace.", pdf_filename)
103
+
104
+ try:
105
+ pages = convert_from_path(pdf_filename, dpi=150)
106
+ except Exception as e:
107
+ log(f"FAILED during extraction: {e}", pdf_filename)
108
+ return
109
+
110
+ raw_latex_body = ""
111
+
112
+ # PASS 1: Sequential Page Transcriptions (Using Flash-Lite)
113
+ for i, page_img in enumerate(pages):
114
+ img_name = f"page_{i+1}.png"
115
+ img_path = os.path.join(figures_dir, img_name)
116
+ page_img.save(img_path, "PNG")
117
+
118
+ log(f"Transcribing page {i+1}/{len(pages)} (Pass 1 - Flash).", pdf_filename)
119
+
120
+ prompt = (
121
+ "Transcribe this handwritten math page into LaTeX. "
122
+ "Output ONLY the LaTeX body content. "
123
+ "DO NOT include: \\usepackage, \\documentclass, \\begin{document}, or \\end{document}. "
124
+ "Ensure all math is properly closed with '$' or environment tags. "
125
+ )
126
+
127
+ try:
128
+ response = call_gemini_with_retry(page_img, prompt, is_image=True)
129
+ cleaned_page = clean_output(response.text)
130
+
131
+ raw_latex_body += f"""\\subsection*{{Page {i+1}}}
132
+ \\includegraphics[width=0.6\\textwidth]{{figures/{img_name}}}
133
+ \\par {cleaned_page} \\newpage\n"""
134
+ except Exception as e:
135
+ log(f"FAILED page {i+1} during Pass 1: {e}", pdf_filename)
136
+ raw_latex_body += f"\\subsection*{{Page {i+1}}} \\par \\textit{{Transcription failed.}} \\newpage\n"
137
+
138
+ # PASS 2: Global Document Refinement (Using Pro - No Compilation)
139
+ log("Refining full document syntax (Pass 2 - Gemini Pro).", pdf_filename)
140
+ refinement_prompt = (
141
+ "You are an expert LaTeX proofreader. Review the provided input document containing multi-page transcription math. "
142
+ "Fix common compilation bugs globally: ensure all math inline or display environments match, "
143
+ "ensure all braces are closed correctly, convert unmatched or dangling \\left/\\right markers into generic formatting "
144
+ "like standard parenthesis if necessary, and escape naked '&' markers outside of tables or matrices. "
145
+ "DO NOT delete the actual mathematical text or sentences under any circumstance. "
146
+ "Preserve the structural page breaks (\\newpage) and image macros intact. "
147
+ "Output ONLY the corrected body markup text without any markdown or code wrappers."
148
+ )
149
+
150
+ try:
151
+ refinement_response = call_gemini_with_retry(raw_latex_body, refinement_prompt, is_image=False)
152
+ final_latex_body = clean_output(refinement_response.text)
153
+ except Exception as e:
154
+ log(f"Refinement Pass 2 failed. Falling back to Pass 1 content. Error: {e}", pdf_filename)
155
+ final_latex_body = raw_latex_body
156
+
157
+ # Assemble into standard file structure
158
+ tex_path = os.path.join(workspace, "manuscript.tex")
159
+ with open(tex_path, "w", encoding="utf-8") as f:
160
+ f.write(LATEX_TEMPLATE.format(final_latex_body))
161
+
162
+ log("Saving output files to destination without compiling.", pdf_filename)
163
+ try:
164
+ final_dest_dir = os.path.join(OUTPUT_DIR, pdf_base)
165
+ if os.path.exists(final_dest_dir):
166
+ shutil.rmtree(final_dest_dir)
167
+
168
+ shutil.copytree(workspace, final_dest_dir)
169
+ log(f"SUCCESS. Content directory saved at {final_dest_dir}", pdf_filename)
170
+ except Exception as e:
171
+ log(f"SYSTEM COPY ERROR: {e}", pdf_filename)
172
+
173
+ def main():
174
+ os.makedirs(OUTPUT_DIR, exist_ok=True)
175
+ os.makedirs(WORK_DIR, exist_ok=True)
176
+
177
+ #files = ['amt-c-11-to20-5.pdf']
178
+ #detect all files
179
+ # files = [f for f in os.listdir(INPUT_DIR) if f.endswith('.pdf') and not f.startswith("processed_")]
180
+ files = ['amt-b-16-30-17.pdf','amt-b-31-57-3.pdf']
181
+ print(f"Processing {len(files)} files with Dual-Pass Reflection (Hybrid Flash-Lite / Pro)...")
182
+
183
+ pool = Pool(processes=MAX_CONCURRENT_FILES, initializer=init_worker, initargs=(API_KEY,))
184
+ try:
185
+ pool.map(process_single_pdf, files)
186
+ finally:
187
+ pool.close()
188
+ pool.join()
189
+
190
+ print("All file processing steps have successfully completed.")
191
+
192
+ if __name__ == "__main__":
193
+ main()
turing_archive/gemini_pipeline/turing_archive/personal_documents/processing_trace.log ADDED
The diff for this file is too large to render. See raw diff
 
turing_archive/gemini_pipeline/turing_archive/processed/unpublished_drafts/processed/amt-c-6-to-10-1.pdf ADDED
Binary file (24.2 kB). View file
 
turing_archive/gemini_pipeline/turing_archive/publications/compile_latex.py ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import subprocess
3
+ import logging
4
+ from multiprocessing import Pool
5
+
6
+ # ==========================================
7
+ # Logging & Configuration Setup
8
+ # ==========================================
9
+ logging.basicConfig(
10
+ level=logging.INFO,
11
+ format='%(asctime)s [%(levelname)s] %(message)s'
12
+ )
13
+
14
+ PROCESSED_DIR = "./processed_pdfs"
15
+ TOTAL_CORES = os.cpu_count() or 1
16
+ MAX_CONCURRENT_COMPILATIONS = max(1, TOTAL_CORES - 1)
17
+ ERROR_LOG_FILE = "failed_compilations.txt" # <-- Name of your persistent error list
18
+
19
+ def compile_single_tex(dir_name):
20
+ """Worker function executed by independent CPU cores."""
21
+ target_dir = os.path.join(PROCESSED_DIR, dir_name)
22
+ tex_file = "manuscript.tex"
23
+ tex_path = os.path.join(target_dir, tex_file)
24
+
25
+ if not os.path.exists(tex_path):
26
+ return None
27
+
28
+ logging.info(f"[{dir_name}] Launching XeLaTeX compilation...")
29
+
30
+ cmd = [
31
+ "xelatex",
32
+ "-interaction=nonstopmode",
33
+ "-file-line-error",
34
+ tex_file
35
+ ]
36
+
37
+ try:
38
+ result = subprocess.run(
39
+ cmd,
40
+ cwd=target_dir,
41
+ stdout=subprocess.PIPE,
42
+ stderr=subprocess.PIPE,
43
+ text=True,
44
+ check=True
45
+ )
46
+ logging.info(f"[{dir_name}] SUCCESS. PDF compiled successfully.")
47
+ return {
48
+ "dir": dir_name,
49
+ "status": "SUCCESS",
50
+ "full_output": result.stdout,
51
+ "errors": []
52
+ }
53
+
54
+ except subprocess.CalledProcessError as e:
55
+ logging.error(f"[{dir_name}] FAILED. Engine encountered compilation syntax bugs.")
56
+
57
+ error_summary = []
58
+ for line in e.stdout.splitlines():
59
+ if "error" in line.lower() or "fatal" in line.lower() or line.startswith("!"):
60
+ error_summary.append(line.strip())
61
+
62
+ if not error_summary:
63
+ error_summary = [e.stderr.strip() if e.stderr else "Non-zero exit status thrown by engine."]
64
+
65
+ return {
66
+ "dir": dir_name,
67
+ "status": "FAILED",
68
+ "full_output": e.stdout,
69
+ "errors": error_summary
70
+ }
71
+ except Exception as e:
72
+ logging.error(f"[{dir_name}] SYSTEM CALL ERROR: {e}")
73
+ return {
74
+ "dir": dir_name,
75
+ "status": "SYSTEM_ERROR",
76
+ "full_output": "",
77
+ "errors": [str(e)]
78
+ }
79
+
80
+ def main():
81
+ if not os.path.exists(PROCESSED_DIR):
82
+ print(f"Error: The target directory '{PROCESSED_DIR}' does not exist.")
83
+ return
84
+
85
+ all_contents = os.listdir(PROCESSED_DIR)
86
+ sub_dirs = [d for d in all_contents if os.path.isdir(os.path.join(PROCESSED_DIR, d))]
87
+
88
+ if not sub_dirs:
89
+ print(f"No sub-directories detected inside '{PROCESSED_DIR}'.")
90
+ return
91
+
92
+ print(f"System detected {TOTAL_CORES} cores.")
93
+ print(f"Spawning {MAX_CONCURRENT_COMPILATIONS} parallel XeLaTeX compilation engines across folders...\n")
94
+
95
+ pool = Pool(processes=MAX_CONCURRENT_COMPILATIONS)
96
+ try:
97
+ results = [r for r in pool.map(compile_single_tex, sub_dirs) if r is not None]
98
+ finally:
99
+ pool.close()
100
+ pool.join()
101
+
102
+ # ==========================================
103
+ # Final Reporting & Full Log Aggregation
104
+ # ==========================================
105
+ print("\n" + "="*60)
106
+ print(" DETAILED XELATEX OUTPUTS & ENGINE LOGS ")
107
+ print("="*60)
108
+
109
+ for res in results:
110
+ print(f"\n📂 FOLDER DATASTREAM: {res['dir']}")
111
+ print(f"Status: {'✅ SUCCESS' if res['status'] == 'SUCCESS' else '❌ FAILED'}")
112
+ print("-" * 40)
113
+
114
+ if res['status'] == 'SUCCESS':
115
+ summary_lines = [l for l in res['full_output'].splitlines() if "Output written on" in l or "pages" in l]
116
+ if summary_lines:
117
+ for sl in summary_lines:
118
+ print(f" {sl}")
119
+ else:
120
+ print(" Document compiled successfully. (Log output compressed)")
121
+ else:
122
+ print("🛑 Engine Syntax Errors Triggered:")
123
+ for err in res['errors'][:8]:
124
+ print(f" -> {err}")
125
+
126
+ print("\n📋 Last 15 Lines of Raw Engine Context Log:")
127
+ raw_lines = res['full_output'].splitlines()
128
+ for line in raw_lines[-15:]:
129
+ print(f" | {line}")
130
+ print("-" * 60)
131
+
132
+ # ==========================================
133
+ # PERSISTENT STORAGE WRITEBACK (New Addition)
134
+ # ==========================================
135
+ failures = [r for r in results if r["status"] != "SUCCESS"]
136
+
137
+ if failures:
138
+ try:
139
+ with open(ERROR_LOG_FILE, "w", encoding="utf-8") as f:
140
+ f.write("=== FAILED COMPILATIONS MANIFEST ===\n")
141
+ f.write(f"The following folders triggered XeLaTeX layout exceptions:\n\n")
142
+ for fail in failures:
143
+ f.write(f"📁 {fail['dir']}\n")
144
+ f.write(f" Primary Error: {fail['errors'][0] if fail['errors'] else 'Unknown layout bug'}\n\n")
145
+ print(f"\n💾 Saved persistent manifest of broken runs to: {ERROR_LOG_FILE}")
146
+ except Exception as file_err:
147
+ print(f"\n⚠️ System failed to write tracking manifest to disk: {file_err}")
148
+ else:
149
+ # If a subsequent run passes completely clean, purge the old error file
150
+ if os.path.exists(ERROR_LOG_FILE):
151
+ os.remove(ERROR_LOG_FILE)
152
+
153
+ # Global Stats Banner
154
+ print("\n" + "="*60)
155
+ print(" COMPILATION METRICS ")
156
+ print("="*60)
157
+ print(f"Total Folders Processed: {len(results)}")
158
+ print(f"Flawless Conversions: {len(results) - len(failures)}")
159
+ print(f"Syntax/Layout Failures: {len(failures)}")
160
+ print("="*60)
161
+
162
+ if __name__ == "__main__":
163
+ main()
turing_archive/gemini_pipeline/turing_archive/publications/failed_compilations.txt ADDED
File without changes
turing_archive/gemini_pipeline/turing_archive/publications/process.py ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # processes and tries to compile latex.
2
+ # issue is that latex is not great,
3
+ # and i need a new way to generate that latex.
4
+ import os
5
+ import shutil
6
+ import subprocess
7
+ import logging
8
+ import re
9
+ from multiprocessing import Pool
10
+ from pdf2image import convert_from_path
11
+ from google import genai
12
+ from tenacity import retry, stop_after_attempt, wait_exponential
13
+
14
+ # ==========================================
15
+ # 1. Logging Setup
16
+ # ==========================================
17
+ logging.basicConfig(
18
+ level=logging.INFO,
19
+ format='%(asctime)s [%(levelname)s] %(message)s',
20
+ handlers=[logging.FileHandler("processing_trace.log"), logging.StreamHandler()]
21
+ )
22
+
23
+ def log(msg, filename):
24
+ logging.info(f"[{filename}] {msg}")
25
+
26
+ # ==========================================
27
+ # 2. Configuration
28
+ # ==========================================
29
+ API_KEY = "AIzaSyACloyikx6S1JqZfk3daRG9XTGwTMSWn7E"
30
+ MODEL_NAME = 'gemini-2.5-flash-lite'
31
+ MAX_CONCURRENT_FILES = 6
32
+ INPUT_DIR = "."
33
+ OUTPUT_DIR = "./processed_pdfs"
34
+ WORK_DIR = "./workspace"
35
+
36
+ LATEX_TEMPLATE = r"""\documentclass[11pt,a4paper]{{article}}
37
+ \usepackage[utf8]{{inputenc}}
38
+ \usepackage{{amsmath, amssymb, amsfonts}}
39
+ \usepackage{{graphicx}}
40
+ \usepackage{{xcolor}}
41
+ \usepackage[normalem]{{ulem}}
42
+ \usepackage{{cancel}}
43
+ \usepackage{{enumitem}}
44
+ \usepackage{{geometry}}
45
+ \geometry{{margin=1in}}
46
+ \begin{{document}}
47
+ {}
48
+ \end{{document}}
49
+ """
50
+
51
+ def clean_output(text):
52
+ # 1. Remove markdown code blocks
53
+ text = re.sub(r"```latex", "", text, flags=re.IGNORECASE)
54
+ text = re.sub(r"```", "", text, flags=re.IGNORECASE)
55
+
56
+ # 2. Aggressively strip preamble commands
57
+ text = re.sub(r"\\documentclass.*", "", text)
58
+ text = re.sub(r"\\usepackage\{.*?\}", "", text)
59
+ text = re.sub(r"\\begin\{document\}", "", text)
60
+ text = re.sub(r"\\end\{document\}", "", text)
61
+
62
+ # 3. Strip structural quote commands if they cause nesting issues
63
+ text = text.replace(r"\begin{quote}", "").replace(r"\end{quote}", "")
64
+
65
+ # 4. Fix common broken LaTeX syntax generated by LLMs
66
+ text = text.replace(r"&", r"\&") # Escape alignment tabs
67
+ text = re.sub(r"\\left(?![^{])", "", text) # Remove dangling left
68
+ text = re.sub(r"\\right(?![^{])", "", text) # Remove dangling right
69
+
70
+ return text.strip()
71
+
72
+ def init_worker(api_key):
73
+ global client
74
+ client = genai.Client(api_key=api_key)
75
+
76
+ @retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=2, max=10))
77
+ def call_gemini_with_retry(img, prompt):
78
+ return client.models.generate_content(
79
+ model=MODEL_NAME,
80
+ contents=[img, prompt]
81
+ )
82
+
83
+ def process_single_pdf(pdf_filename):
84
+ if pdf_filename.startswith("processed_"):
85
+ return
86
+
87
+ pdf_base = os.path.splitext(pdf_filename)[0]
88
+ workspace = os.path.join(WORK_DIR, pdf_base)
89
+ figures_dir = os.path.join(workspace, "figures")
90
+ os.makedirs(figures_dir, exist_ok=True)
91
+
92
+ log("Initializing workspace.", pdf_filename)
93
+
94
+ try:
95
+ pages = convert_from_path(pdf_filename, dpi=200)
96
+ except Exception as e:
97
+ log(f"FAILED during extraction: {e}", pdf_filename)
98
+ return
99
+
100
+ latex_content = ""
101
+
102
+ for i, page_img in enumerate(pages):
103
+ img_name = f"page_{i+1}.png"
104
+ img_path = os.path.join(figures_dir, img_name)
105
+ page_img.save(img_path, "PNG")
106
+
107
+ log(f"Transcribing page {i+1}/{len(pages)}.", pdf_filename)
108
+
109
+ # Strict prompt to prevent boilerplate hallucination
110
+ prompt = (
111
+ "Transcribe this handwritten math page into LaTeX. "
112
+ "Output ONLY the LaTeX body content. "
113
+ "DO NOT include: \\usepackage, \\documentclass, \\begin{document}, \\end{document}. "
114
+ "Ensure all math is properly closed with '$' or environment tags. "
115
+ )
116
+
117
+ try:
118
+ response = call_gemini_with_retry(page_img, prompt)
119
+ # Use \par instead of quote to avoid nested environment errors
120
+ latex_content += f"""\\subsection*{{Page {i+1}}}
121
+ \\includegraphics[width=0.6\\textwidth]{{figures/{img_name}}}
122
+ \\par {clean_output(response.text)} \\newpage\n"""
123
+ except Exception as e:
124
+ log(f"FAILED page {i+1} after retries: {e}", pdf_filename)
125
+ latex_content += f"\\subsection*{{Page {i+1}}} \\par \\textit{{Transcription failed.}} \\newpage\n"
126
+
127
+ tex_path = os.path.join(workspace, "manuscript.tex")
128
+ with open(tex_path, "w", encoding="utf-8") as f:
129
+ f.write(LATEX_TEMPLATE.format(latex_content))
130
+
131
+ log("Compiling with XeLaTeX.", pdf_filename)
132
+ try:
133
+ # Run twice to resolve references
134
+ for _ in range(2):
135
+ subprocess.run(["xelatex", "-interaction=nonstopmode", "manuscript.tex"],
136
+ cwd=workspace, stdout=subprocess.DEVNULL)
137
+
138
+ if os.path.exists(os.path.join(workspace, "manuscript.pdf")):
139
+ shutil.move(os.path.join(workspace, "manuscript.pdf"),
140
+ os.path.join(OUTPUT_DIR, f"processed_{pdf_filename}"))
141
+ log("SUCCESS.", pdf_filename)
142
+ else:
143
+ log("COMPILATION FAILED: No PDF produced.", pdf_filename)
144
+ except Exception as e:
145
+ log(f"SYSTEM ERROR: {e}", pdf_filename)
146
+
147
+ def main():
148
+ os.makedirs(OUTPUT_DIR, exist_ok=True)
149
+ os.makedirs(WORK_DIR, exist_ok=True)
150
+
151
+ files = ['amt-c-11-to20-5.pdf']
152
+ print(f"Processing {len(files)} files...")
153
+ with Pool(processes=MAX_CONCURRENT_FILES, initializer=init_worker, initargs=(API_KEY,)) as pool:
154
+ pool.map(process_single_pdf, files)
155
+
156
+ if __name__ == "__main__":
157
+ main()
turing_archive/gemini_pipeline/turing_archive/publications/process_two_pass.py ADDED
@@ -0,0 +1,377 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import shutil
3
+ import subprocess
4
+ import logging
5
+ import re
6
+ from multiprocessing import Pool
7
+ from pdf2image import convert_from_path
8
+ from google import genai
9
+ from google.genai import types
10
+ from tenacity import retry, stop_after_attempt, wait_exponential,wait_random_exponential
11
+
12
+ # ==========================================
13
+ # 1. Logging Setup
14
+ # ==========================================
15
+ logging.basicConfig(
16
+ level=logging.INFO,
17
+ format='%(asctime)s [%(levelname)s] %(message)s',
18
+ handlers=[logging.FileHandler("processing_trace.log"), logging.StreamHandler()]
19
+ )
20
+
21
+ def log(msg, filename):
22
+ logging.info(f"[{filename}] {msg}")
23
+
24
+ # ==========================================
25
+ # 2. Configuration
26
+ # ==========================================
27
+ API_KEY = "AIzaSyACloyikx6S1JqZfk3daRG9XTGwTMSWn7E"
28
+ TRANSCRIPTION_MODEL = 'gemini-2.5-flash-lite' # Fast and cheap for page images
29
+ REFINEMENT_MODEL = 'gemini-2.5-pro' # Deep reasoning for structural math cleanup
30
+ MAX_CONCURRENT_FILES = 6
31
+ INPUT_DIR = "."
32
+ OUTPUT_DIR = "./processed_pdfs"
33
+ WORK_DIR = "./workspace"
34
+
35
+ LATEX_TEMPLATE = r"""\documentclass[11pt,a4paper]{{article}}
36
+ \usepackage[utf8]{{inputenc}}
37
+ \usepackage{{amsmath, amssymb, amsfonts}}
38
+ \usepackage{{graphicx}}
39
+ \usepackage{{xcolor}}
40
+ \usepackage[normalem]{{ulem}}
41
+ \usepackage{{cancel}}
42
+ \usepackage{{enumitem}}
43
+ \usepackage{{geometry}}
44
+ \geometry{{margin=1in}}
45
+ \begin{{document}}
46
+ {}
47
+ \end{{document}}
48
+ """
49
+
50
+ def clean_output(text):
51
+ if not text:
52
+ return ""
53
+ # 1. Remove markdown code blocks
54
+ text = re.sub(r"```latex", "", text, flags=re.IGNORECASE)
55
+ text = re.sub(r"```", "", text, flags=re.IGNORECASE)
56
+
57
+ # 2. Aggressively strip preamble commands
58
+ text = re.sub(r"\\documentclass.*", "", text)
59
+ text = re.sub(r"\\usepackage\{.*?\}", "", text)
60
+ text = re.sub(r"\\begin\{document\}", "", text)
61
+ text = re.sub(r"\\end\{document\}", "", text)
62
+
63
+ # 3. Strip structural quote commands if they cause nesting issues
64
+ text = text.replace(r"\begin{quote}", "").replace(r"\end{quote}", "")
65
+
66
+ return text.strip()
67
+
68
+ def init_worker(api_key):
69
+ global client
70
+ client = genai.Client(api_key=api_key)
71
+
72
+ @retry(
73
+ stop=stop_after_attempt(7),
74
+ wait=wait_random_exponential(multiplier=2, min=15, max=65),
75
+ before_sleep=lambda retry_state: logging.warning(
76
+ f"Rate limit hit (429). Retrying in {retry_state.next_action.sleep:.2f} seconds... (Attempt {retry_state.attempt_number}/7)"
77
+ )
78
+ )
79
+ def call_gemini_with_retry(contents, prompt, is_image=True):
80
+ if is_image:
81
+ return client.models.generate_content(
82
+ model=TRANSCRIPTION_MODEL,
83
+ contents=[contents, prompt]
84
+ )
85
+ else:
86
+ # Standardize text requests and route them to the stronger PRO model
87
+ combined_payload = f"{prompt}\n\nINPUT TEXT TO REFINE:\n{contents}"
88
+ return client.models.generate_content(
89
+ model=REFINEMENT_MODEL,
90
+ contents=combined_payload
91
+ )
92
+
93
+ def process_single_pdf(pdf_filename):
94
+ if pdf_filename.startswith("processed_"):
95
+ return
96
+
97
+ pdf_base = os.path.splitext(pdf_filename)[0]
98
+ workspace = os.path.join(WORK_DIR, pdf_base)
99
+ figures_dir = os.path.join(workspace, "figures")
100
+ os.makedirs(figures_dir, exist_ok=True)
101
+
102
+ log("Initializing workspace.", pdf_filename)
103
+
104
+ try:
105
+ pages = convert_from_path(pdf_filename, dpi=150)
106
+ except Exception as e:
107
+ log(f"FAILED during extraction: {e}", pdf_filename)
108
+ return
109
+
110
+ raw_latex_body = ""
111
+
112
+ # PASS 1: Sequential Page Transcriptions (Using Flash-Lite)
113
+ for i, page_img in enumerate(pages):
114
+ img_name = f"page_{i+1}.png"
115
+ img_path = os.path.join(figures_dir, img_name)
116
+ page_img.save(img_path, "PNG")
117
+
118
+ log(f"Transcribing page {i+1}/{len(pages)} (Pass 1 - Flash-Lite).", pdf_filename)
119
+
120
+ prompt = (
121
+ "Transcribe this handwritten math page into LaTeX. "
122
+ "Output ONLY the LaTeX body content. "
123
+ "DO NOT include: \\usepackage, \\documentclass, \\begin{document}, or \\end{document}. "
124
+ "Ensure all math is properly closed with '$' or environment tags. "
125
+ )
126
+
127
+ try:
128
+ response = call_gemini_with_retry(page_img, prompt, is_image=True)
129
+ cleaned_page = clean_output(response.text)
130
+
131
+ raw_latex_body += f"""\\subsection*{{Page {i+1}}}
132
+ \\includegraphics[width=0.6\\textwidth]{{figures/{img_name}}}
133
+ \\par {cleaned_page} \\newpage\n"""
134
+ except Exception as e:
135
+ log(f"FAILED page {i+1} during Pass 1: {e}", pdf_filename)
136
+ raw_latex_body += f"\\subsection*{{Page {i+1}}} \\par \\textit{{Transcription failed.}} \\newpage\n"
137
+
138
+ # PASS 2: Global Document Refinement (Using Pro - No Compilation)
139
+ log("Refining full document syntax (Pass 2 - Gemini Pro).", pdf_filename)
140
+ refinement_prompt = (
141
+ "You are an expert LaTeX proofreader. Review the provided input document containing multi-page transcription math. "
142
+ "Fix common compilation bugs globally: ensure all math inline or display environments match, "
143
+ "ensure all braces are closed correctly, convert unmatched or dangling \\left/\\right markers into generic formatting "
144
+ "like standard parenthesis if necessary, and escape naked '&' markers outside of tables or matrices. "
145
+ "DO NOT delete the actual mathematical text or sentences under any circumstance. "
146
+ "Preserve the structural page breaks (\\newpage) and image macros intact. "
147
+ "Output ONLY the corrected body markup text without any markdown or code wrappers."
148
+ )
149
+
150
+ try:
151
+ refinement_response = call_gemini_with_retry(raw_latex_body, refinement_prompt, is_image=False)
152
+ final_latex_body = clean_output(refinement_response.text)
153
+ except Exception as e:
154
+ log(f"Refinement Pass 2 failed. Falling back to Pass 1 content. Error: {e}", pdf_filename)
155
+ final_latex_body = raw_latex_body
156
+
157
+ # Assemble into standard file structure
158
+ tex_path = os.path.join(workspace, "manuscript.tex")
159
+ with open(tex_path, "w", encoding="utf-8") as f:
160
+ f.write(LATEX_TEMPLATE.format(final_latex_body))
161
+
162
+ log("Saving output files to destination without compiling.", pdf_filename)
163
+ try:
164
+ final_dest_dir = os.path.join(OUTPUT_DIR, pdf_base)
165
+ if os.path.exists(final_dest_dir):
166
+ shutil.rmtree(final_dest_dir)
167
+
168
+ shutil.copytree(workspace, final_dest_dir)
169
+ log(f"SUCCESS. Content directory saved at {final_dest_dir}", pdf_filename)
170
+ except Exception as e:
171
+ log(f"SYSTEM COPY ERROR: {e}", pdf_filename)
172
+
173
+ def main():
174
+ os.makedirs(OUTPUT_DIR, exist_ok=True)
175
+ os.makedirs(WORK_DIR, exist_ok=True)
176
+
177
+ #files = ['amt-c-11-to20-5.pdf']
178
+ #detect all files
179
+ files = [f for f in os.listdir(INPUT_DIR) if f.endswith('.pdf') and not f.startswith("processed_")]
180
+ print(f"Processing {len(files)} files with Dual-Pass Reflection (Hybrid Flash-Lite / Pro)...")
181
+
182
+ pool = Pool(processes=MAX_CONCURRENT_FILES, initializer=init_worker, initargs=(API_KEY,))
183
+ try:
184
+ pool.map(process_single_pdf, files)
185
+ finally:
186
+ pool.close()
187
+ pool.join()
188
+
189
+ print("All file processing steps have successfully completed.")
190
+
191
+ if __name__ == "__main__":
192
+ main()
193
+
194
+ # import os
195
+ # import shutil
196
+ # import subprocess
197
+ # import logging
198
+ # import re
199
+ # from multiprocessing import Pool
200
+ # from pdf2image import convert_from_path
201
+ # from google import genai
202
+ # from google.genai import types
203
+ # from tenacity import retry, stop_after_attempt, wait_exponential
204
+
205
+ # # ==========================================
206
+ # # 1. Logging Setup
207
+ # # ==========================================
208
+ # logging.basicConfig(
209
+ # level=logging.INFO,
210
+ # format='%(asctime)s [%(levelname)s] %(message)s',
211
+ # handlers=[logging.FileHandler("processing_trace.log"), logging.StreamHandler()]
212
+ # )
213
+
214
+ # def log(msg, filename):
215
+ # logging.info(f"[{filename}] {msg}")
216
+
217
+ # # ==========================================
218
+ # # 2. Configuration
219
+ # # ==========================================
220
+ # API_KEY = "AIzaSyACloyikx6S1JqZfk3daRG9XTGwTMSWn7E"
221
+ # MODEL_NAME = 'gemini-2.5-flash-lite'
222
+ # MAX_CONCURRENT_FILES = 6
223
+ # INPUT_DIR = "."
224
+ # OUTPUT_DIR = "./processed_pdfs"
225
+ # WORK_DIR = "./workspace"
226
+
227
+ # LATEX_TEMPLATE = r"""\documentclass[11pt,a4paper]{{article}}
228
+ # \usepackage[utf8]{{inputenc}}
229
+ # \usepackage{{amsmath, amssymb, amsfonts}}
230
+ # \usepackage{{graphicx}}
231
+ # \usepackage{{xcolor}}
232
+ # \usepackage[normalem]{{ulem}}
233
+ # \usepackage{{cancel}}
234
+ # \usepackage{{enumitem}}
235
+ # \usepackage{{geometry}}
236
+ # \geometry{{margin=1in}}
237
+ # \begin{{document}}
238
+ # {}
239
+ # \end{{document}}
240
+ # """
241
+
242
+ # def clean_output(text):
243
+ # if not text:
244
+ # return ""
245
+ # # 1. Remove markdown code blocks
246
+ # text = re.sub(r"```latex", "", text, flags=re.IGNORECASE)
247
+ # text = re.sub(r"```", "", text, flags=re.IGNORECASE)
248
+
249
+ # # 2. Aggressively strip preamble commands
250
+ # text = re.sub(r"\\documentclass.*", "", text)
251
+ # text = re.sub(r"\\usepackage\{.*?\}", "", text)
252
+ # text = re.sub(r"\\begin\{document\}", "", text)
253
+ # text = re.sub(r"\\end\{document\}", "", text)
254
+
255
+ # # 3. Strip structural quote commands if they cause nesting issues
256
+ # text = text.replace(r"\begin{quote}", "").replace(r"\end{quote}", "")
257
+
258
+ # return text.strip()
259
+
260
+ # def init_worker(api_key):
261
+ # global client
262
+ # client = genai.Client(api_key=api_key)
263
+
264
+ # @retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=2, max=10))
265
+ # def call_gemini_with_retry(contents, prompt, is_image=True):
266
+ # if is_image:
267
+ # return client.models.generate_content(
268
+ # model=MODEL_NAME,
269
+ # contents=[contents, prompt]
270
+ # )
271
+ # else:
272
+ # # Standardize non-image generation requests using a single explicit text configuration payload
273
+ # combined_payload = f"{prompt}\n\nINPUT TEXT TO REFINE:\n{contents}"
274
+ # return client.models.generate_content(
275
+ # model=MODEL_NAME,
276
+ # contents=combined_payload
277
+ # )
278
+
279
+ # def process_single_pdf(pdf_filename):
280
+ # if pdf_filename.startswith("processed_"):
281
+ # return
282
+
283
+ # pdf_base = os.path.splitext(pdf_filename)[0]
284
+ # workspace = os.path.join(WORK_DIR, pdf_base)
285
+ # figures_dir = os.path.join(workspace, "figures")
286
+ # os.makedirs(figures_dir, exist_ok=True)
287
+
288
+ # log("Initializing workspace.", pdf_filename)
289
+
290
+ # try:
291
+ # pages = convert_from_path(pdf_filename, dpi=150)
292
+ # except Exception as e:
293
+ # log(f"FAILED during extraction: {e}", pdf_filename)
294
+ # return
295
+
296
+ # raw_latex_body = ""
297
+
298
+ # # PASS 1: Sequential Page Transcriptions
299
+ # for i, page_img in enumerate(pages):
300
+ # img_name = f"page_{i+1}.png"
301
+ # img_path = os.path.join(figures_dir, img_name)
302
+ # page_img.save(img_path, "PNG")
303
+
304
+ # log(f"Transcribing page {i+1}/{len(pages)} (Pass 1).", pdf_filename)
305
+
306
+ # prompt = (
307
+ # "Transcribe this handwritten math page into LaTeX. "
308
+ # "Output ONLY the LaTeX body content. "
309
+ # "DO NOT include: \\usepackage, \\documentclass, \\begin{document}, or \\end{document}. "
310
+ # "Ensure all math is properly closed with '$' or environment tags. "
311
+ # )
312
+
313
+ # try:
314
+ # response = call_gemini_with_retry(page_img, prompt, is_image=True)
315
+ # cleaned_page = clean_output(response.text)
316
+
317
+ # raw_latex_body += f"""\\subsection*{{Page {i+1}}}
318
+ # \\includegraphics[width=0.6\\textwidth]{{figures/{img_name}}}
319
+ # \\par {cleaned_page} \\newpage\n"""
320
+ # except Exception as e:
321
+ # log(f"FAILED page {i+1} during Pass 1: {e}", pdf_filename)
322
+ # raw_latex_body += f"\\subsection*{{Page {i+1}}} \\par \\textit{{Transcription failed.}} \\newpage\n"
323
+
324
+ # # PASS 2: Global Document Refinement (No Compilation)
325
+ # log("Refining full document syntax (Pass 2).", pdf_filename)
326
+ # refinement_prompt = (
327
+ # "You are an expert LaTeX proofreader. Review the provided input document containing multi-page transcription math. "
328
+ # "Fix common compilation bugs globally: ensure all math inline or display environments match, "
329
+ # "ensure all braces are closed correctly, convert unmatched or dangling \\left/\\right markers into generic formatting "
330
+ # "like standard parenthesis if necessary, and escape naked '&' markers outside of tables or matrices. "
331
+ # "DO NOT delete the actual mathematical text or sentences under any circumstance. "
332
+ # "Preserve the structural page breaks (\\newpage) and image macros intact. "
333
+ # "Output ONLY the corrected body markup text without any markdown or code wrappers."
334
+ # )
335
+
336
+ # try:
337
+ # refinement_response = call_gemini_with_retry(raw_latex_body, refinement_prompt, is_image=False)
338
+ # final_latex_body = clean_output(refinement_response.text)
339
+ # except Exception as e:
340
+ # log(f"Refinement Pass 2 failed. Falling back to Pass 1 content. Error: {e}", pdf_filename)
341
+ # final_latex_body = raw_latex_body
342
+
343
+ # # Assemble into standard file structure
344
+ # tex_path = os.path.join(workspace, "manuscript.tex")
345
+ # with open(tex_path, "w", encoding="utf-8") as f:
346
+ # f.write(LATEX_TEMPLATE.format(final_latex_body))
347
+
348
+ # log("Saving output files to destination without compiling.", pdf_filename)
349
+ # try:
350
+ # final_dest_dir = os.path.join(OUTPUT_DIR, pdf_base)
351
+ # if os.path.exists(final_dest_dir):
352
+ # shutil.rmtree(final_dest_dir)
353
+
354
+ # shutil.copytree(workspace, final_dest_dir)
355
+ # log(f"SUCCESS. Content directory saved at {final_dest_dir}", pdf_filename)
356
+ # except Exception as e:
357
+ # log(f"SYSTEM COPY ERROR: {e}", pdf_filename)
358
+
359
+ # def main():
360
+ # os.makedirs(OUTPUT_DIR, exist_ok=True)
361
+ # os.makedirs(WORK_DIR, exist_ok=True)
362
+
363
+ # files = ['amt-c-11-to20-5.pdf']
364
+ # print(f"Processing {len(files)} files with Dual-Pass Reflection...")
365
+
366
+ # # Explicitly managing the pool lifecycle ensures complete structural teardown upon map exit
367
+ # pool = Pool(processes=MAX_CONCURRENT_FILES, initializer=init_worker, initargs=(API_KEY,))
368
+ # try:
369
+ # pool.map(process_single_pdf, files)
370
+ # finally:
371
+ # pool.close()
372
+ # pool.join()
373
+
374
+ # print("All file processing steps have successfully completed.")
375
+
376
+ # if __name__ == "__main__":
377
+ # main()
turing_archive/gemini_pipeline/turing_archive/publications/process_two_pass_gemini_flash.py ADDED
@@ -0,0 +1,193 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import shutil
3
+ import subprocess
4
+ import logging
5
+ import re
6
+ from multiprocessing import Pool
7
+ from pdf2image import convert_from_path
8
+ from google import genai
9
+ from google.genai import types
10
+ from tenacity import retry, stop_after_attempt, wait_exponential,wait_random_exponential
11
+
12
+ # ==========================================
13
+ # 1. Logging Setup
14
+ # ==========================================
15
+ logging.basicConfig(
16
+ level=logging.INFO,
17
+ format='%(asctime)s [%(levelname)s] %(message)s',
18
+ handlers=[logging.FileHandler("processing_trace.log"), logging.StreamHandler()]
19
+ )
20
+
21
+ def log(msg, filename):
22
+ logging.info(f"[{filename}] {msg}")
23
+
24
+ # ==========================================
25
+ # 2. Configuration
26
+ # ==========================================
27
+ API_KEY = "AIzaSyACloyikx6S1JqZfk3daRG9XTGwTMSWn7E"
28
+ TRANSCRIPTION_MODEL = 'gemini-2.5-flash' # Fast and cheap for page images
29
+ REFINEMENT_MODEL = 'gemini-2.5-pro' # Deep reasoning for structural math cleanup
30
+ MAX_CONCURRENT_FILES = 6
31
+ INPUT_DIR = "."
32
+ OUTPUT_DIR = "./processed_pdfs"
33
+ WORK_DIR = "./workspace"
34
+
35
+ LATEX_TEMPLATE = r"""\documentclass[11pt,a4paper]{{article}}
36
+ \usepackage[utf8]{{inputenc}}
37
+ \usepackage{{amsmath, amssymb, amsfonts}}
38
+ \usepackage{{graphicx}}
39
+ \usepackage{{xcolor}}
40
+ \usepackage[normalem]{{ulem}}
41
+ \usepackage{{cancel}}
42
+ \usepackage{{enumitem}}
43
+ \usepackage{{geometry}}
44
+ \geometry{{margin=1in}}
45
+ \begin{{document}}
46
+ {}
47
+ \end{{document}}
48
+ """
49
+
50
+ def clean_output(text):
51
+ if not text:
52
+ return ""
53
+ # 1. Remove markdown code blocks
54
+ text = re.sub(r"```latex", "", text, flags=re.IGNORECASE)
55
+ text = re.sub(r"```", "", text, flags=re.IGNORECASE)
56
+
57
+ # 2. Aggressively strip preamble commands
58
+ text = re.sub(r"\\documentclass.*", "", text)
59
+ text = re.sub(r"\\usepackage\{.*?\}", "", text)
60
+ text = re.sub(r"\\begin\{document\}", "", text)
61
+ text = re.sub(r"\\end\{document\}", "", text)
62
+
63
+ # 3. Strip structural quote commands if they cause nesting issues
64
+ text = text.replace(r"\begin{quote}", "").replace(r"\end{quote}", "")
65
+
66
+ return text.strip()
67
+
68
+ def init_worker(api_key):
69
+ global client
70
+ client = genai.Client(api_key=api_key)
71
+
72
+ @retry(
73
+ stop=stop_after_attempt(7),
74
+ wait=wait_random_exponential(multiplier=2, min=15, max=65),
75
+ before_sleep=lambda retry_state: logging.warning(
76
+ f"Rate limit hit (429). Retrying in {retry_state.next_action.sleep:.2f} seconds... (Attempt {retry_state.attempt_number}/7)"
77
+ )
78
+ )
79
+ def call_gemini_with_retry(contents, prompt, is_image=True):
80
+ if is_image:
81
+ return client.models.generate_content(
82
+ model=TRANSCRIPTION_MODEL,
83
+ contents=[contents, prompt]
84
+ )
85
+ else:
86
+ # Standardize text requests and route them to the stronger PRO model
87
+ combined_payload = f"{prompt}\n\nINPUT TEXT TO REFINE:\n{contents}"
88
+ return client.models.generate_content(
89
+ model=REFINEMENT_MODEL,
90
+ contents=combined_payload
91
+ )
92
+
93
+ def process_single_pdf(pdf_filename):
94
+ if pdf_filename.startswith("processed_"):
95
+ return
96
+
97
+ pdf_base = os.path.splitext(pdf_filename)[0]
98
+ workspace = os.path.join(WORK_DIR, pdf_base)
99
+ figures_dir = os.path.join(workspace, "figures")
100
+ os.makedirs(figures_dir, exist_ok=True)
101
+
102
+ log("Initializing workspace.", pdf_filename)
103
+
104
+ try:
105
+ pages = convert_from_path(pdf_filename, dpi=150)
106
+ except Exception as e:
107
+ log(f"FAILED during extraction: {e}", pdf_filename)
108
+ return
109
+
110
+ raw_latex_body = ""
111
+
112
+ # PASS 1: Sequential Page Transcriptions (Using Flash-Lite)
113
+ for i, page_img in enumerate(pages):
114
+ img_name = f"page_{i+1}.png"
115
+ img_path = os.path.join(figures_dir, img_name)
116
+ page_img.save(img_path, "PNG")
117
+
118
+ log(f"Transcribing page {i+1}/{len(pages)} (Pass 1 - Flash).", pdf_filename)
119
+
120
+ prompt = (
121
+ "Transcribe this handwritten math page into LaTeX. "
122
+ "Output ONLY the LaTeX body content. "
123
+ "DO NOT include: \\usepackage, \\documentclass, \\begin{document}, or \\end{document}. "
124
+ "Ensure all math is properly closed with '$' or environment tags. "
125
+ )
126
+
127
+ try:
128
+ response = call_gemini_with_retry(page_img, prompt, is_image=True)
129
+ cleaned_page = clean_output(response.text)
130
+
131
+ raw_latex_body += f"""\\subsection*{{Page {i+1}}}
132
+ \\includegraphics[width=0.6\\textwidth]{{figures/{img_name}}}
133
+ \\par {cleaned_page} \\newpage\n"""
134
+ except Exception as e:
135
+ log(f"FAILED page {i+1} during Pass 1: {e}", pdf_filename)
136
+ raw_latex_body += f"\\subsection*{{Page {i+1}}} \\par \\textit{{Transcription failed.}} \\newpage\n"
137
+
138
+ # PASS 2: Global Document Refinement (Using Pro - No Compilation)
139
+ log("Refining full document syntax (Pass 2 - Gemini Pro).", pdf_filename)
140
+ refinement_prompt = (
141
+ "You are an expert LaTeX proofreader. Review the provided input document containing multi-page transcription math. "
142
+ "Fix common compilation bugs globally: ensure all math inline or display environments match, "
143
+ "ensure all braces are closed correctly, convert unmatched or dangling \\left/\\right markers into generic formatting "
144
+ "like standard parenthesis if necessary, and escape naked '&' markers outside of tables or matrices. "
145
+ "DO NOT delete the actual mathematical text or sentences under any circumstance. "
146
+ "Preserve the structural page breaks (\\newpage) and image macros intact. "
147
+ "Output ONLY the corrected body markup text without any markdown or code wrappers."
148
+ )
149
+
150
+ try:
151
+ refinement_response = call_gemini_with_retry(raw_latex_body, refinement_prompt, is_image=False)
152
+ final_latex_body = clean_output(refinement_response.text)
153
+ except Exception as e:
154
+ log(f"Refinement Pass 2 failed. Falling back to Pass 1 content. Error: {e}", pdf_filename)
155
+ final_latex_body = raw_latex_body
156
+
157
+ # Assemble into standard file structure
158
+ tex_path = os.path.join(workspace, "manuscript.tex")
159
+ with open(tex_path, "w", encoding="utf-8") as f:
160
+ f.write(LATEX_TEMPLATE.format(final_latex_body))
161
+
162
+ log("Saving output files to destination without compiling.", pdf_filename)
163
+ try:
164
+ final_dest_dir = os.path.join(OUTPUT_DIR, pdf_base)
165
+ if os.path.exists(final_dest_dir):
166
+ shutil.rmtree(final_dest_dir)
167
+
168
+ shutil.copytree(workspace, final_dest_dir)
169
+ log(f"SUCCESS. Content directory saved at {final_dest_dir}", pdf_filename)
170
+ except Exception as e:
171
+ log(f"SYSTEM COPY ERROR: {e}", pdf_filename)
172
+
173
+ def main():
174
+ os.makedirs(OUTPUT_DIR, exist_ok=True)
175
+ os.makedirs(WORK_DIR, exist_ok=True)
176
+
177
+ #files = ['amt-c-11-to20-5.pdf']
178
+ #detect all files
179
+ # files = [f for f in os.listdir(INPUT_DIR) if f.endswith('.pdf') and not f.startswith("processed_")]
180
+ files = ['amt-b-16-30-17.pdf','amt-b-31-57-3.pdf']
181
+ print(f"Processing {len(files)} files with Dual-Pass Reflection (Hybrid Flash-Lite / Pro)...")
182
+
183
+ pool = Pool(processes=MAX_CONCURRENT_FILES, initializer=init_worker, initargs=(API_KEY,))
184
+ try:
185
+ pool.map(process_single_pdf, files)
186
+ finally:
187
+ pool.close()
188
+ pool.join()
189
+
190
+ print("All file processing steps have successfully completed.")
191
+
192
+ if __name__ == "__main__":
193
+ main()
turing_archive/gemini_pipeline/turing_archive/publications/processing_trace.log ADDED
The diff for this file is too large to render. See raw diff
 
turing_archive/gemini_pipeline/turing_archive/publications/texput.log ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ This is XeTeX, Version 3.141592653-2.6-0.999995 (TeX Live 2023/Debian) (preloaded format=xelatex 2026.5.9) 14 JUN 2026 09:53
2
+ entering extended mode
3
+ restricted \write18 enabled.
4
+ file:line:error style messages enabled.
5
+ %&-line parsing enabled.
6
+ **dmanuscript.tex
7
+
8
+ ! Emergency stop.
9
+ <*> dmanuscript.tex
10
+
11
+ *** (job aborted, file error in nonstop mode)
12
+
13
+
14
+ Here is how much of TeX's memory you used:
15
+ 2 strings out of 474878
16
+ 21 string characters out of 5762517
17
+ 1915627 words of memory out of 5000000
18
+ 22152 multiletter control sequences out of 15000+600000
19
+ 558069 words of font info for 36 fonts, out of 8000000 for 9000
20
+ 1348 hyphenation exceptions out of 8191
21
+ 0i,0n,0p,1b,6s stack positions out of 10000i,1000n,20000p,200000b,200000s
22
+ No pages of output.
turing_archive/gemini_pipeline/turing_archive/unpublished_drafts/compile_latex.py ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import subprocess
3
+ import logging
4
+ from multiprocessing import Pool
5
+
6
+ # ==========================================
7
+ # Logging & Configuration Setup
8
+ # ==========================================
9
+ logging.basicConfig(
10
+ level=logging.INFO,
11
+ format='%(asctime)s [%(levelname)s] %(message)s'
12
+ )
13
+
14
+ PROCESSED_DIR = "./processed_pdfs"
15
+ TOTAL_CORES = os.cpu_count() or 1
16
+ MAX_CONCURRENT_COMPILATIONS = max(1, TOTAL_CORES - 1)
17
+ ERROR_LOG_FILE = "failed_compilations.txt" # <-- Name of your persistent error list
18
+
19
+ def compile_single_tex(dir_name):
20
+ """Worker function executed by independent CPU cores."""
21
+ target_dir = os.path.join(PROCESSED_DIR, dir_name)
22
+ tex_file = "manuscript.tex"
23
+ tex_path = os.path.join(target_dir, tex_file)
24
+
25
+ if not os.path.exists(tex_path):
26
+ return None
27
+
28
+ logging.info(f"[{dir_name}] Launching XeLaTeX compilation...")
29
+
30
+ cmd = [
31
+ "xelatex",
32
+ "-interaction=nonstopmode",
33
+ "-file-line-error",
34
+ tex_file
35
+ ]
36
+
37
+ try:
38
+ result = subprocess.run(
39
+ cmd,
40
+ cwd=target_dir,
41
+ stdout=subprocess.PIPE,
42
+ stderr=subprocess.PIPE,
43
+ text=True,
44
+ check=True
45
+ )
46
+ logging.info(f"[{dir_name}] SUCCESS. PDF compiled successfully.")
47
+ return {
48
+ "dir": dir_name,
49
+ "status": "SUCCESS",
50
+ "full_output": result.stdout,
51
+ "errors": []
52
+ }
53
+
54
+ except subprocess.CalledProcessError as e:
55
+ logging.error(f"[{dir_name}] FAILED. Engine encountered compilation syntax bugs.")
56
+
57
+ error_summary = []
58
+ for line in e.stdout.splitlines():
59
+ if "error" in line.lower() or "fatal" in line.lower() or line.startswith("!"):
60
+ error_summary.append(line.strip())
61
+
62
+ if not error_summary:
63
+ error_summary = [e.stderr.strip() if e.stderr else "Non-zero exit status thrown by engine."]
64
+
65
+ return {
66
+ "dir": dir_name,
67
+ "status": "FAILED",
68
+ "full_output": e.stdout,
69
+ "errors": error_summary
70
+ }
71
+ except Exception as e:
72
+ logging.error(f"[{dir_name}] SYSTEM CALL ERROR: {e}")
73
+ return {
74
+ "dir": dir_name,
75
+ "status": "SYSTEM_ERROR",
76
+ "full_output": "",
77
+ "errors": [str(e)]
78
+ }
79
+
80
+ def main():
81
+ if not os.path.exists(PROCESSED_DIR):
82
+ print(f"Error: The target directory '{PROCESSED_DIR}' does not exist.")
83
+ return
84
+
85
+ all_contents = os.listdir(PROCESSED_DIR)
86
+ sub_dirs = [d for d in all_contents if os.path.isdir(os.path.join(PROCESSED_DIR, d))]
87
+
88
+ if not sub_dirs:
89
+ print(f"No sub-directories detected inside '{PROCESSED_DIR}'.")
90
+ return
91
+
92
+ print(f"System detected {TOTAL_CORES} cores.")
93
+ print(f"Spawning {MAX_CONCURRENT_COMPILATIONS} parallel XeLaTeX compilation engines across folders...\n")
94
+
95
+ pool = Pool(processes=MAX_CONCURRENT_COMPILATIONS)
96
+ try:
97
+ results = [r for r in pool.map(compile_single_tex, sub_dirs) if r is not None]
98
+ finally:
99
+ pool.close()
100
+ pool.join()
101
+
102
+ # ==========================================
103
+ # Final Reporting & Full Log Aggregation
104
+ # ==========================================
105
+ print("\n" + "="*60)
106
+ print(" DETAILED XELATEX OUTPUTS & ENGINE LOGS ")
107
+ print("="*60)
108
+
109
+ for res in results:
110
+ print(f"\n📂 FOLDER DATASTREAM: {res['dir']}")
111
+ print(f"Status: {'✅ SUCCESS' if res['status'] == 'SUCCESS' else '❌ FAILED'}")
112
+ print("-" * 40)
113
+
114
+ if res['status'] == 'SUCCESS':
115
+ summary_lines = [l for l in res['full_output'].splitlines() if "Output written on" in l or "pages" in l]
116
+ if summary_lines:
117
+ for sl in summary_lines:
118
+ print(f" {sl}")
119
+ else:
120
+ print(" Document compiled successfully. (Log output compressed)")
121
+ else:
122
+ print("🛑 Engine Syntax Errors Triggered:")
123
+ for err in res['errors'][:8]:
124
+ print(f" -> {err}")
125
+
126
+ print("\n📋 Last 15 Lines of Raw Engine Context Log:")
127
+ raw_lines = res['full_output'].splitlines()
128
+ for line in raw_lines[-15:]:
129
+ print(f" | {line}")
130
+ print("-" * 60)
131
+
132
+ # ==========================================
133
+ # PERSISTENT STORAGE WRITEBACK (New Addition)
134
+ # ==========================================
135
+ failures = [r for r in results if r["status"] != "SUCCESS"]
136
+
137
+ if failures:
138
+ try:
139
+ with open(ERROR_LOG_FILE, "w", encoding="utf-8") as f:
140
+ f.write("=== FAILED COMPILATIONS MANIFEST ===\n")
141
+ f.write(f"The following folders triggered XeLaTeX layout exceptions:\n\n")
142
+ for fail in failures:
143
+ f.write(f"📁 {fail['dir']}\n")
144
+ f.write(f" Primary Error: {fail['errors'][0] if fail['errors'] else 'Unknown layout bug'}\n\n")
145
+ print(f"\n💾 Saved persistent manifest of broken runs to: {ERROR_LOG_FILE}")
146
+ except Exception as file_err:
147
+ print(f"\n⚠️ System failed to write tracking manifest to disk: {file_err}")
148
+ else:
149
+ # If a subsequent run passes completely clean, purge the old error file
150
+ if os.path.exists(ERROR_LOG_FILE):
151
+ os.remove(ERROR_LOG_FILE)
152
+
153
+ # Global Stats Banner
154
+ print("\n" + "="*60)
155
+ print(" COMPILATION METRICS ")
156
+ print("="*60)
157
+ print(f"Total Folders Processed: {len(results)}")
158
+ print(f"Flawless Conversions: {len(results) - len(failures)}")
159
+ print(f"Syntax/Layout Failures: {len(failures)}")
160
+ print("="*60)
161
+
162
+ if __name__ == "__main__":
163
+ main()
turing_archive/gemini_pipeline/turing_archive/unpublished_drafts/failed_compilations.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ too many image errors. need to re do
2
+ 📁 amt-c-11-to20-7
3
+ Primary Error: ./manuscript.tex:12: LaTeX Error: Can be used only in preamble.
4
+
5
+ 📁 amt-c-6-to-10-1
6
+ Primary Error: Non-zero exit status thrown by engine.
7
+
turing_archive/gemini_pipeline/turing_archive/unpublished_drafts/process.py ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # processes and tries to compile latex.
2
+ # issue is that latex is not great,
3
+ # and i need a new way to generate that latex.
4
+ import os
5
+ import shutil
6
+ import subprocess
7
+ import logging
8
+ import re
9
+ from multiprocessing import Pool
10
+ from pdf2image import convert_from_path
11
+ from google import genai
12
+ from tenacity import retry, stop_after_attempt, wait_exponential
13
+
14
+ # ==========================================
15
+ # 1. Logging Setup
16
+ # ==========================================
17
+ logging.basicConfig(
18
+ level=logging.INFO,
19
+ format='%(asctime)s [%(levelname)s] %(message)s',
20
+ handlers=[logging.FileHandler("processing_trace.log"), logging.StreamHandler()]
21
+ )
22
+
23
+ def log(msg, filename):
24
+ logging.info(f"[{filename}] {msg}")
25
+
26
+ # ==========================================
27
+ # 2. Configuration
28
+ # ==========================================
29
+ API_KEY = "AIzaSyACloyikx6S1JqZfk3daRG9XTGwTMSWn7E"
30
+ MODEL_NAME = 'gemini-2.5-flash-lite'
31
+ MAX_CONCURRENT_FILES = 6
32
+ INPUT_DIR = "."
33
+ OUTPUT_DIR = "./processed_pdfs"
34
+ WORK_DIR = "./workspace"
35
+
36
+ LATEX_TEMPLATE = r"""\documentclass[11pt,a4paper]{{article}}
37
+ \usepackage[utf8]{{inputenc}}
38
+ \usepackage{{amsmath, amssymb, amsfonts}}
39
+ \usepackage{{graphicx}}
40
+ \usepackage{{xcolor}}
41
+ \usepackage[normalem]{{ulem}}
42
+ \usepackage{{cancel}}
43
+ \usepackage{{enumitem}}
44
+ \usepackage{{geometry}}
45
+ \geometry{{margin=1in}}
46
+ \begin{{document}}
47
+ {}
48
+ \end{{document}}
49
+ """
50
+
51
+ def clean_output(text):
52
+ # 1. Remove markdown code blocks
53
+ text = re.sub(r"```latex", "", text, flags=re.IGNORECASE)
54
+ text = re.sub(r"```", "", text, flags=re.IGNORECASE)
55
+
56
+ # 2. Aggressively strip preamble commands
57
+ text = re.sub(r"\\documentclass.*", "", text)
58
+ text = re.sub(r"\\usepackage\{.*?\}", "", text)
59
+ text = re.sub(r"\\begin\{document\}", "", text)
60
+ text = re.sub(r"\\end\{document\}", "", text)
61
+
62
+ # 3. Strip structural quote commands if they cause nesting issues
63
+ text = text.replace(r"\begin{quote}", "").replace(r"\end{quote}", "")
64
+
65
+ # 4. Fix common broken LaTeX syntax generated by LLMs
66
+ text = text.replace(r"&", r"\&") # Escape alignment tabs
67
+ text = re.sub(r"\\left(?![^{])", "", text) # Remove dangling left
68
+ text = re.sub(r"\\right(?![^{])", "", text) # Remove dangling right
69
+
70
+ return text.strip()
71
+
72
+ def init_worker(api_key):
73
+ global client
74
+ client = genai.Client(api_key=api_key)
75
+
76
+ @retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=2, max=10))
77
+ def call_gemini_with_retry(img, prompt):
78
+ return client.models.generate_content(
79
+ model=MODEL_NAME,
80
+ contents=[img, prompt]
81
+ )
82
+
83
+ def process_single_pdf(pdf_filename):
84
+ if pdf_filename.startswith("processed_"):
85
+ return
86
+
87
+ pdf_base = os.path.splitext(pdf_filename)[0]
88
+ workspace = os.path.join(WORK_DIR, pdf_base)
89
+ figures_dir = os.path.join(workspace, "figures")
90
+ os.makedirs(figures_dir, exist_ok=True)
91
+
92
+ log("Initializing workspace.", pdf_filename)
93
+
94
+ try:
95
+ pages = convert_from_path(pdf_filename, dpi=200)
96
+ except Exception as e:
97
+ log(f"FAILED during extraction: {e}", pdf_filename)
98
+ return
99
+
100
+ latex_content = ""
101
+
102
+ for i, page_img in enumerate(pages):
103
+ img_name = f"page_{i+1}.png"
104
+ img_path = os.path.join(figures_dir, img_name)
105
+ page_img.save(img_path, "PNG")
106
+
107
+ log(f"Transcribing page {i+1}/{len(pages)}.", pdf_filename)
108
+
109
+ # Strict prompt to prevent boilerplate hallucination
110
+ prompt = (
111
+ "Transcribe this handwritten math page into LaTeX. "
112
+ "Output ONLY the LaTeX body content. "
113
+ "DO NOT include: \\usepackage, \\documentclass, \\begin{document}, \\end{document}. "
114
+ "Ensure all math is properly closed with '$' or environment tags. "
115
+ )
116
+
117
+ try:
118
+ response = call_gemini_with_retry(page_img, prompt)
119
+ # Use \par instead of quote to avoid nested environment errors
120
+ latex_content += f"""\\subsection*{{Page {i+1}}}
121
+ \\includegraphics[width=0.6\\textwidth]{{figures/{img_name}}}
122
+ \\par {clean_output(response.text)} \\newpage\n"""
123
+ except Exception as e:
124
+ log(f"FAILED page {i+1} after retries: {e}", pdf_filename)
125
+ latex_content += f"\\subsection*{{Page {i+1}}} \\par \\textit{{Transcription failed.}} \\newpage\n"
126
+
127
+ tex_path = os.path.join(workspace, "manuscript.tex")
128
+ with open(tex_path, "w", encoding="utf-8") as f:
129
+ f.write(LATEX_TEMPLATE.format(latex_content))
130
+
131
+ log("Compiling with XeLaTeX.", pdf_filename)
132
+ try:
133
+ # Run twice to resolve references
134
+ for _ in range(2):
135
+ subprocess.run(["xelatex", "-interaction=nonstopmode", "manuscript.tex"],
136
+ cwd=workspace, stdout=subprocess.DEVNULL)
137
+
138
+ if os.path.exists(os.path.join(workspace, "manuscript.pdf")):
139
+ shutil.move(os.path.join(workspace, "manuscript.pdf"),
140
+ os.path.join(OUTPUT_DIR, f"processed_{pdf_filename}"))
141
+ log("SUCCESS.", pdf_filename)
142
+ else:
143
+ log("COMPILATION FAILED: No PDF produced.", pdf_filename)
144
+ except Exception as e:
145
+ log(f"SYSTEM ERROR: {e}", pdf_filename)
146
+
147
+ def main():
148
+ os.makedirs(OUTPUT_DIR, exist_ok=True)
149
+ os.makedirs(WORK_DIR, exist_ok=True)
150
+
151
+ files = ['amt-c-11-to20-5.pdf']
152
+ print(f"Processing {len(files)} files...")
153
+ with Pool(processes=MAX_CONCURRENT_FILES, initializer=init_worker, initargs=(API_KEY,)) as pool:
154
+ pool.map(process_single_pdf, files)
155
+
156
+ if __name__ == "__main__":
157
+ main()
turing_archive/gemini_pipeline/turing_archive/unpublished_drafts/process_two_pass.py ADDED
@@ -0,0 +1,377 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ dimport os
2
+ import shutil
3
+ import subprocess
4
+ import logging
5
+ import re
6
+ from multiprocessing import Pool
7
+ from pdf2image import convert_from_path
8
+ from google import genai
9
+ from google.genai import types
10
+ from tenacity import retry, stop_after_attempt, wait_exponential,wait_random_exponential
11
+
12
+ # ==========================================
13
+ # 1. Logging Setup
14
+ # ==========================================
15
+ logging.basicConfig(
16
+ level=logging.INFO,
17
+ format='%(asctime)s [%(levelname)s] %(message)s',
18
+ handlers=[logging.FileHandler("processing_trace.log"), logging.StreamHandler()]
19
+ )
20
+
21
+ def log(msg, filename):
22
+ logging.info(f"[{filename}] {msg}")
23
+
24
+ # ==========================================
25
+ # 2. Configuration
26
+ # ==========================================
27
+ API_KEY = "AIzaSyACloyikx6S1JqZfk3daRG9XTGwTMSWn7E"
28
+ TRANSCRIPTION_MODEL = 'gemini-2.5-flash-lite' # Fast and cheap for page images
29
+ REFINEMENT_MODEL = 'gemini-2.5-pro' # Deep reasoning for structural math cleanup
30
+ MAX_CONCURRENT_FILES = 6
31
+ INPUT_DIR = "."
32
+ OUTPUT_DIR = "./processed_pdfs"
33
+ WORK_DIR = "./workspace"
34
+
35
+ LATEX_TEMPLATE = r"""\documentclass[11pt,a4paper]{{article}}
36
+ \usepackage[utf8]{{inputenc}}
37
+ \usepackage{{amsmath, amssymb, amsfonts}}
38
+ \usepackage{{graphicx}}
39
+ \usepackage{{xcolor}}
40
+ \usepackage[normalem]{{ulem}}
41
+ \usepackage{{cancel}}
42
+ \usepackage{{enumitem}}
43
+ \usepackage{{geometry}}
44
+ \geometry{{margin=1in}}
45
+ \begin{{document}}
46
+ {}
47
+ \end{{document}}
48
+ """
49
+
50
+ def clean_output(text):
51
+ if not text:
52
+ return ""
53
+ # 1. Remove markdown code blocks
54
+ text = re.sub(r"```latex", "", text, flags=re.IGNORECASE)
55
+ text = re.sub(r"```", "", text, flags=re.IGNORECASE)
56
+
57
+ # 2. Aggressively strip preamble commands
58
+ text = re.sub(r"\\documentclass.*", "", text)
59
+ text = re.sub(r"\\usepackage\{.*?\}", "", text)
60
+ text = re.sub(r"\\begin\{document\}", "", text)
61
+ text = re.sub(r"\\end\{document\}", "", text)
62
+
63
+ # 3. Strip structural quote commands if they cause nesting issues
64
+ text = text.replace(r"\begin{quote}", "").replace(r"\end{quote}", "")
65
+
66
+ return text.strip()
67
+
68
+ def init_worker(api_key):
69
+ global client
70
+ client = genai.Client(api_key=api_key)
71
+
72
+ @retry(
73
+ stop=stop_after_attempt(7),
74
+ wait=wait_random_exponential(multiplier=2, min=15, max=65),
75
+ before_sleep=lambda retry_state: logging.warning(
76
+ f"Rate limit hit (429). Retrying in {retry_state.next_action.sleep:.2f} seconds... (Attempt {retry_state.attempt_number}/7)"
77
+ )
78
+ )
79
+ def call_gemini_with_retry(contents, prompt, is_image=True):
80
+ if is_image:
81
+ return client.models.generate_content(
82
+ model=TRANSCRIPTION_MODEL,
83
+ contents=[contents, prompt]
84
+ )
85
+ else:
86
+ # Standardize text requests and route them to the stronger PRO model
87
+ combined_payload = f"{prompt}\n\nINPUT TEXT TO REFINE:\n{contents}"
88
+ return client.models.generate_content(
89
+ model=REFINEMENT_MODEL,
90
+ contents=combined_payload
91
+ )
92
+
93
+ def process_single_pdf(pdf_filename):
94
+ if pdf_filename.startswith("processed_"):
95
+ return
96
+
97
+ pdf_base = os.path.splitext(pdf_filename)[0]
98
+ workspace = os.path.join(WORK_DIR, pdf_base)
99
+ figures_dir = os.path.join(workspace, "figures")
100
+ os.makedirs(figures_dir, exist_ok=True)
101
+
102
+ log("Initializing workspace.", pdf_filename)
103
+
104
+ try:
105
+ pages = convert_from_path(pdf_filename, dpi=150)
106
+ except Exception as e:
107
+ log(f"FAILED during extraction: {e}", pdf_filename)
108
+ return
109
+
110
+ raw_latex_body = ""
111
+
112
+ # PASS 1: Sequential Page Transcriptions (Using Flash-Lite)
113
+ for i, page_img in enumerate(pages):
114
+ img_name = f"page_{i+1}.png"
115
+ img_path = os.path.join(figures_dir, img_name)
116
+ page_img.save(img_path, "PNG")
117
+
118
+ log(f"Transcribing page {i+1}/{len(pages)} (Pass 1 - Flash-Lite).", pdf_filename)
119
+
120
+ prompt = (
121
+ "Transcribe this handwritten math page into LaTeX. "
122
+ "Output ONLY the LaTeX body content. "
123
+ "DO NOT include: \\usepackage, \\documentclass, \\begin{document}, or \\end{document}. "
124
+ "Ensure all math is properly closed with '$' or environment tags. "
125
+ )
126
+
127
+ try:
128
+ response = call_gemini_with_retry(page_img, prompt, is_image=True)
129
+ cleaned_page = clean_output(response.text)
130
+
131
+ raw_latex_body += f"""\\subsection*{{Page {i+1}}}
132
+ \\includegraphics[width=0.6\\textwidth]{{figures/{img_name}}}
133
+ \\par {cleaned_page} \\newpage\n"""
134
+ except Exception as e:
135
+ log(f"FAILED page {i+1} during Pass 1: {e}", pdf_filename)
136
+ raw_latex_body += f"\\subsection*{{Page {i+1}}} \\par \\textit{{Transcription failed.}} \\newpage\n"
137
+
138
+ # PASS 2: Global Document Refinement (Using Pro - No Compilation)
139
+ log("Refining full document syntax (Pass 2 - Gemini Pro).", pdf_filename)
140
+ refinement_prompt = (
141
+ "You are an expert LaTeX proofreader. Review the provided input document containing multi-page transcription math. "
142
+ "Fix common compilation bugs globally: ensure all math inline or display environments match, "
143
+ "ensure all braces are closed correctly, convert unmatched or dangling \\left/\\right markers into generic formatting "
144
+ "like standard parenthesis if necessary, and escape naked '&' markers outside of tables or matrices. "
145
+ "DO NOT delete the actual mathematical text or sentences under any circumstance. "
146
+ "Preserve the structural page breaks (\\newpage) and image macros intact. "
147
+ "Output ONLY the corrected body markup text without any markdown or code wrappers."
148
+ )
149
+
150
+ try:
151
+ refinement_response = call_gemini_with_retry(raw_latex_body, refinement_prompt, is_image=False)
152
+ final_latex_body = clean_output(refinement_response.text)
153
+ except Exception as e:
154
+ log(f"Refinement Pass 2 failed. Falling back to Pass 1 content. Error: {e}", pdf_filename)
155
+ final_latex_body = raw_latex_body
156
+
157
+ # Assemble into standard file structure
158
+ tex_path = os.path.join(workspace, "manuscript.tex")
159
+ with open(tex_path, "w", encoding="utf-8") as f:
160
+ f.write(LATEX_TEMPLATE.format(final_latex_body))
161
+
162
+ log("Saving output files to destination without compiling.", pdf_filename)
163
+ try:
164
+ final_dest_dir = os.path.join(OUTPUT_DIR, pdf_base)
165
+ if os.path.exists(final_dest_dir):
166
+ shutil.rmtree(final_dest_dir)
167
+
168
+ shutil.copytree(workspace, final_dest_dir)
169
+ log(f"SUCCESS. Content directory saved at {final_dest_dir}", pdf_filename)
170
+ except Exception as e:
171
+ log(f"SYSTEM COPY ERROR: {e}", pdf_filename)
172
+
173
+ def main():
174
+ os.makedirs(OUTPUT_DIR, exist_ok=True)
175
+ os.makedirs(WORK_DIR, exist_ok=True)
176
+
177
+ #files = ['amt-c-11-to20-5.pdf']
178
+ #detect all files
179
+ files = [f for f in os.listdir(INPUT_DIR) if f.endswith('.pdf') and not f.startswith("processed_")]
180
+ print(f"Processing {len(files)} files with Dual-Pass Reflection (Hybrid Flash-Lite / Pro)...")
181
+
182
+ pool = Pool(processes=MAX_CONCURRENT_FILES, initializer=init_worker, initargs=(API_KEY,))
183
+ try:
184
+ pool.map(process_single_pdf, files)
185
+ finally:
186
+ pool.close()
187
+ pool.join()
188
+
189
+ print("All file processing steps have successfully completed.")
190
+
191
+ if __name__ == "__main__":
192
+ main()
193
+
194
+ # import os
195
+ # import shutil
196
+ # import subprocess
197
+ # import logging
198
+ # import re
199
+ # from multiprocessing import Pool
200
+ # from pdf2image import convert_from_path
201
+ # from google import genai
202
+ # from google.genai import types
203
+ # from tenacity import retry, stop_after_attempt, wait_exponential
204
+
205
+ # # ==========================================
206
+ # # 1. Logging Setup
207
+ # # ==========================================
208
+ # logging.basicConfig(
209
+ # level=logging.INFO,
210
+ # format='%(asctime)s [%(levelname)s] %(message)s',
211
+ # handlers=[logging.FileHandler("processing_trace.log"), logging.StreamHandler()]
212
+ # )
213
+
214
+ # def log(msg, filename):
215
+ # logging.info(f"[{filename}] {msg}")
216
+
217
+ # # ==========================================
218
+ # # 2. Configuration
219
+ # # ==========================================
220
+ # API_KEY = "AIzaSyACloyikx6S1JqZfk3daRG9XTGwTMSWn7E"
221
+ # MODEL_NAME = 'gemini-2.5-flash-lite'
222
+ # MAX_CONCURRENT_FILES = 6
223
+ # INPUT_DIR = "."
224
+ # OUTPUT_DIR = "./processed_pdfs"
225
+ # WORK_DIR = "./workspace"
226
+
227
+ # LATEX_TEMPLATE = r"""\documentclass[11pt,a4paper]{{article}}
228
+ # \usepackage[utf8]{{inputenc}}
229
+ # \usepackage{{amsmath, amssymb, amsfonts}}
230
+ # \usepackage{{graphicx}}
231
+ # \usepackage{{xcolor}}
232
+ # \usepackage[normalem]{{ulem}}
233
+ # \usepackage{{cancel}}
234
+ # \usepackage{{enumitem}}
235
+ # \usepackage{{geometry}}
236
+ # \geometry{{margin=1in}}
237
+ # \begin{{document}}
238
+ # {}
239
+ # \end{{document}}
240
+ # """
241
+
242
+ # def clean_output(text):
243
+ # if not text:
244
+ # return ""
245
+ # # 1. Remove markdown code blocks
246
+ # text = re.sub(r"```latex", "", text, flags=re.IGNORECASE)
247
+ # text = re.sub(r"```", "", text, flags=re.IGNORECASE)
248
+
249
+ # # 2. Aggressively strip preamble commands
250
+ # text = re.sub(r"\\documentclass.*", "", text)
251
+ # text = re.sub(r"\\usepackage\{.*?\}", "", text)
252
+ # text = re.sub(r"\\begin\{document\}", "", text)
253
+ # text = re.sub(r"\\end\{document\}", "", text)
254
+
255
+ # # 3. Strip structural quote commands if they cause nesting issues
256
+ # text = text.replace(r"\begin{quote}", "").replace(r"\end{quote}", "")
257
+
258
+ # return text.strip()
259
+
260
+ # def init_worker(api_key):
261
+ # global client
262
+ # client = genai.Client(api_key=api_key)
263
+
264
+ # @retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=2, max=10))
265
+ # def call_gemini_with_retry(contents, prompt, is_image=True):
266
+ # if is_image:
267
+ # return client.models.generate_content(
268
+ # model=MODEL_NAME,
269
+ # contents=[contents, prompt]
270
+ # )
271
+ # else:
272
+ # # Standardize non-image generation requests using a single explicit text configuration payload
273
+ # combined_payload = f"{prompt}\n\nINPUT TEXT TO REFINE:\n{contents}"
274
+ # return client.models.generate_content(
275
+ # model=MODEL_NAME,
276
+ # contents=combined_payload
277
+ # )
278
+
279
+ # def process_single_pdf(pdf_filename):
280
+ # if pdf_filename.startswith("processed_"):
281
+ # return
282
+
283
+ # pdf_base = os.path.splitext(pdf_filename)[0]
284
+ # workspace = os.path.join(WORK_DIR, pdf_base)
285
+ # figures_dir = os.path.join(workspace, "figures")
286
+ # os.makedirs(figures_dir, exist_ok=True)
287
+
288
+ # log("Initializing workspace.", pdf_filename)
289
+
290
+ # try:
291
+ # pages = convert_from_path(pdf_filename, dpi=150)
292
+ # except Exception as e:
293
+ # log(f"FAILED during extraction: {e}", pdf_filename)
294
+ # return
295
+
296
+ # raw_latex_body = ""
297
+
298
+ # # PASS 1: Sequential Page Transcriptions
299
+ # for i, page_img in enumerate(pages):
300
+ # img_name = f"page_{i+1}.png"
301
+ # img_path = os.path.join(figures_dir, img_name)
302
+ # page_img.save(img_path, "PNG")
303
+
304
+ # log(f"Transcribing page {i+1}/{len(pages)} (Pass 1).", pdf_filename)
305
+
306
+ # prompt = (
307
+ # "Transcribe this handwritten math page into LaTeX. "
308
+ # "Output ONLY the LaTeX body content. "
309
+ # "DO NOT include: \\usepackage, \\documentclass, \\begin{document}, or \\end{document}. "
310
+ # "Ensure all math is properly closed with '$' or environment tags. "
311
+ # )
312
+
313
+ # try:
314
+ # response = call_gemini_with_retry(page_img, prompt, is_image=True)
315
+ # cleaned_page = clean_output(response.text)
316
+
317
+ # raw_latex_body += f"""\\subsection*{{Page {i+1}}}
318
+ # \\includegraphics[width=0.6\\textwidth]{{figures/{img_name}}}
319
+ # \\par {cleaned_page} \\newpage\n"""
320
+ # except Exception as e:
321
+ # log(f"FAILED page {i+1} during Pass 1: {e}", pdf_filename)
322
+ # raw_latex_body += f"\\subsection*{{Page {i+1}}} \\par \\textit{{Transcription failed.}} \\newpage\n"
323
+
324
+ # # PASS 2: Global Document Refinement (No Compilation)
325
+ # log("Refining full document syntax (Pass 2).", pdf_filename)
326
+ # refinement_prompt = (
327
+ # "You are an expert LaTeX proofreader. Review the provided input document containing multi-page transcription math. "
328
+ # "Fix common compilation bugs globally: ensure all math inline or display environments match, "
329
+ # "ensure all braces are closed correctly, convert unmatched or dangling \\left/\\right markers into generic formatting "
330
+ # "like standard parenthesis if necessary, and escape naked '&' markers outside of tables or matrices. "
331
+ # "DO NOT delete the actual mathematical text or sentences under any circumstance. "
332
+ # "Preserve the structural page breaks (\\newpage) and image macros intact. "
333
+ # "Output ONLY the corrected body markup text without any markdown or code wrappers."
334
+ # )
335
+
336
+ # try:
337
+ # refinement_response = call_gemini_with_retry(raw_latex_body, refinement_prompt, is_image=False)
338
+ # final_latex_body = clean_output(refinement_response.text)
339
+ # except Exception as e:
340
+ # log(f"Refinement Pass 2 failed. Falling back to Pass 1 content. Error: {e}", pdf_filename)
341
+ # final_latex_body = raw_latex_body
342
+
343
+ # # Assemble into standard file structure
344
+ # tex_path = os.path.join(workspace, "manuscript.tex")
345
+ # with open(tex_path, "w", encoding="utf-8") as f:
346
+ # f.write(LATEX_TEMPLATE.format(final_latex_body))
347
+
348
+ # log("Saving output files to destination without compiling.", pdf_filename)
349
+ # try:
350
+ # final_dest_dir = os.path.join(OUTPUT_DIR, pdf_base)
351
+ # if os.path.exists(final_dest_dir):
352
+ # shutil.rmtree(final_dest_dir)
353
+
354
+ # shutil.copytree(workspace, final_dest_dir)
355
+ # log(f"SUCCESS. Content directory saved at {final_dest_dir}", pdf_filename)
356
+ # except Exception as e:
357
+ # log(f"SYSTEM COPY ERROR: {e}", pdf_filename)
358
+
359
+ # def main():
360
+ # os.makedirs(OUTPUT_DIR, exist_ok=True)
361
+ # os.makedirs(WORK_DIR, exist_ok=True)
362
+
363
+ # files = ['amt-c-11-to20-5.pdf']
364
+ # print(f"Processing {len(files)} files with Dual-Pass Reflection...")
365
+
366
+ # # Explicitly managing the pool lifecycle ensures complete structural teardown upon map exit
367
+ # pool = Pool(processes=MAX_CONCURRENT_FILES, initializer=init_worker, initargs=(API_KEY,))
368
+ # try:
369
+ # pool.map(process_single_pdf, files)
370
+ # finally:
371
+ # pool.close()
372
+ # pool.join()
373
+
374
+ # print("All file processing steps have successfully completed.")
375
+
376
+ # if __name__ == "__main__":
377
+ # main()
turing_archive/gemini_pipeline/turing_archive/unpublished_drafts/processing_trace.log ADDED
The diff for this file is too large to render. See raw diff
 
turing_archive/gemini_pipeline/turing_net/c04/085.gif ADDED

Git LFS Details

  • SHA256: f03dad8d964223bd1d40efb44262b9b8f8b99ff1f639baa5ac298efd9701993f
  • Pointer size: 130 Bytes
  • Size of remote file: 53 kB
turing_archive/gemini_pipeline/turing_net/c04/088.gif ADDED

Git LFS Details

  • SHA256: d8eb067b229fa7da4f502a264a08e1e7066eb745773a8c2acdc780f48b613bf2
  • Pointer size: 130 Bytes
  • Size of remote file: 22 kB
turing_archive/gemini_pipeline/turing_net/c04/091.gif ADDED

Git LFS Details

  • SHA256: c51fac3f929de2555aec5d2057cf9e9d5db34840139f06a88bb4b555ad3ab888
  • Pointer size: 130 Bytes
  • Size of remote file: 26.1 kB
turing_archive/gemini_pipeline/turing_net/c04/094.gif ADDED

Git LFS Details

  • SHA256: 9ef636f73bd997713a39d38daedcb4f9a3fe226c77f5acb3181c3a6cab68f866
  • Pointer size: 130 Bytes
  • Size of remote file: 24.1 kB
turing_archive/gemini_pipeline/turing_net/c04/095.gif ADDED

Git LFS Details

  • SHA256: 134bf4d61840cd0e368f433d453e70ca138830036ec7795c9e0db2598cd480fc
  • Pointer size: 130 Bytes
  • Size of remote file: 19.8 kB
turing_archive/gemini_pipeline/turing_net/c04/096.gif ADDED

Git LFS Details

  • SHA256: 9faa8071bc774e254a06ff0aeb9fd12a197742c392fbbdb777a063ed66016a56
  • Pointer size: 130 Bytes
  • Size of remote file: 27.5 kB
turing_archive/gemini_pipeline/turing_net/c04/097.gif ADDED

Git LFS Details

  • SHA256: f64d360ad3d84d5359d6cbeb9339190ee164685c745c3a5af2565d03370b0b2a
  • Pointer size: 130 Bytes
  • Size of remote file: 23.7 kB
turing_archive/gemini_pipeline/turing_net/c04/098.gif ADDED

Git LFS Details

  • SHA256: 48f3c6ab6a25d560d2351385169484d3e276c4d07a5845889996d03845fe206e
  • Pointer size: 130 Bytes
  • Size of remote file: 25.6 kB
turing_archive/gemini_pipeline/turing_net/c04/099.gif ADDED

Git LFS Details

  • SHA256: 0df8a3f1b9b092fc3dfdcfc28dfe1938c3d0d900c8b2bf7b23006c6125660af2
  • Pointer size: 130 Bytes
  • Size of remote file: 24.9 kB
turing_archive/gemini_pipeline/turing_net/c04/100.gif ADDED

Git LFS Details

  • SHA256: 9537a0163b6ab2bf6c3143398e2749207023c2c7bd90157406cf9e69f3dd0cd2
  • Pointer size: 130 Bytes
  • Size of remote file: 21.1 kB
turing_archive/gemini_pipeline/turing_net/c04/101.gif ADDED

Git LFS Details

  • SHA256: e5579779f98dc8600e81a2dfddd601d47e71847e5faf434779d0aeeef5b4a94e
  • Pointer size: 130 Bytes
  • Size of remote file: 21.5 kB
turing_archive/gemini_pipeline/turing_net/c04/102.gif ADDED

Git LFS Details

  • SHA256: 8b431a63621e16d73d7939f7ce52da695deecd46518c31c068836725acf24217
  • Pointer size: 130 Bytes
  • Size of remote file: 21.3 kB
turing_archive/gemini_pipeline/turing_net/c04/103.gif ADDED

Git LFS Details

  • SHA256: eeebca1c29a2eadcadd3f0e793ab6028e32af4052eea8897210a9e3565acb9aa
  • Pointer size: 130 Bytes
  • Size of remote file: 64 kB
turing_archive/gemini_pipeline/turing_net/c04/104.gif ADDED

Git LFS Details

  • SHA256: 17144e7c56a65c75bbeb10817de7b286f59f97bb5c8ee5e3a4ce87d63067a2a0
  • Pointer size: 130 Bytes
  • Size of remote file: 26.8 kB