-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
221 lines (172 loc) · 7.53 KB
/
Copy pathmain.py
File metadata and controls
221 lines (172 loc) · 7.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
import os
import pdfplumber
import ollama
import pywhatkit as kit
import time
from docx import Document
from docx.shared import Pt, RGBColor
from docx.enum.text import WD_ALIGN_PARAGRAPH
# UPDATE THESE — REQUIRED
PDF_PATH = "input.pdf" # 👈 Path to your PDF file
OUTPUT_PATH = "output.docx" # 👈 Where to save the Word document
# WHATSAPP SETTINGS
WHATSAPP_NUMBER = "+911234567890" # 👈 Your WhatsApp number (with country code)
SEND_TO_WHATSAPP = True # 👈 Set to False if you only want the Word doc
WHATSAPP_WAIT_TIME = 15 # 👈 Seconds to wait for WhatsApp Web to load
CLOSE_TAB_AFTER = True # 👈 Close browser tab after sending?
# UPDATE THESE — OLLAMA SETTINGS
MODEL_NAME = "llama3.2" # 👈 Run `ollama list` in terminal to confirm name
# Common names: llama3.2, llama3, mistral, phi3
PROMPT = ( # 👈 Change this to control what Ollama does
"You are a document analyst. Analyze the following PDF text and provide:"
"1. SUMMARY: A brief 2-3 sentence overview of what this document is about"
"2. KEY ACTION POINTS: A numbered list of the most important actions, tasks, or takeaways from the document"
"3. IMPORTANT DETAILS: Any critical dates, names, numbers, or deadlines mentioned"
"Keep it concise and clear. Only include what is actually present in the document."
)
# ============================================================
# ✏️ UPDATE THESE — DOCX FORMATTING (optional)
# ============================================================
# Use the PDF filename as the document title
PDF_FILENAME = os.path.basename(PDF_PATH)
DOC_TITLE = os.path.splitext(PDF_FILENAME)[0] # Extracts name without .pdf extension
FONT_NAME = "Calibri" # 👈 Font for body text (Arial, Times New Roman, etc.)
FONT_SIZE = 11 # 👈 Font size for body text (in points)
#NO CHANGES NEEDED BELOW THIS LINE
def extract_text_page_by_page(pdf_path):
"""
Reads every page of the PDF individually.
Returns a list of texts, one for each page.
"""
if not os.path.exists(pdf_path):
raise FileNotFoundError(f"PDF not found at: {pdf_path}")
pages_content = []
with pdfplumber.open(pdf_path) as pdf:
total_pages = len(pdf.pages)
print(f" Found {total_pages} page(s) in PDF")
for i, page in enumerate(pdf.pages):
page_text = page.extract_text()
if page_text and page_text.strip():
pages_content.append({
"number": i + 1,
"text": page_text.strip()
})
else:
print(f" ⚠️ Page {i + 1} has no extractable text (might be a scanned image)")
return pages_content
def process_with_ollama(text, prompt):
"""
Sends the extracted PDF text to your local Ollama model.
Uses the official `ollama` Python library.
Ollama must be running on your machine (ollama serve).
"""
print(f" Model : {MODEL_NAME}")
print(f" Prompt : {prompt[:70]}...")
response = ollama.chat(
model=MODEL_NAME,
messages=[
{
"role": "user",
"content": f"{prompt}\n\n{text}"
}
]
)
return response.message.content
def send_to_whatsapp(phone, message):
"""
Sends a message via WhatsApp Web using pywhatkit.
Requires you to be logged into WhatsApp Web on your default browser.
"""
# Basic format check (must start with + and contain digits)
if not phone.startswith("+") or not phone[1:].isdigit():
raise ValueError(f"Number {phone} is not in correct format (must start with + and include country code)")
print(f" 📤 Sending message to {phone}...")
kit.sendwhatmsg_instantly(
phone_no=phone,
message=message,
wait_time=WHATSAPP_WAIT_TIME,
tab_close=CLOSE_TAB_AFTER,
close_time=3
)
print(" ✅ Message sent!")
def write_to_docx(content, output_path):
"""
Writes the Ollama-processed text into a formatted .docx Word document.
- Lines starting with '--- Page N ---' become Word headings
- Everything else becomes body paragraphs
"""
doc = Document()
# --- Document title ---
title = doc.add_heading(DOC_TITLE, level=0)
title.alignment = WD_ALIGN_PARAGRAPH.CENTER
# --- Add a thin separator line after title ---
doc.add_paragraph("_" * 60)
# --- Write each line as a paragraph or heading ---
for line in content.split("\n"):
line = line.strip()
if not line:
continue # skip blank lines
elif line.startswith("---") and line.endswith("---"):
# Convert "--- Page 1 ---" markers into Word Heading 1
heading_text = line.strip("- ").strip()
doc.add_heading(heading_text, level=1)
elif line.startswith("#"):
# Support markdown-style headings from Ollama output
level = min(line.count("#", 0, 6), 4)
heading_text = line.lstrip("#").strip()
doc.add_heading(heading_text, level=level)
else:
# Regular body paragraph
para = doc.add_paragraph()
run = para.add_run(line)
run.font.name = FONT_NAME
run.font.size = Pt(FONT_SIZE)
doc.save(output_path)
# ============================================================
# MAIN PIPELINE
# ============================================================
def main():
print("\n" + "=" * 55)
print(" DocuMate AI Pipeline")
print("=" * 55)
# Step 1 — Extract text from PDF individually
print("\n📄 Step 1: Extracting text page-by-page...")
try:
pages = extract_text_page_by_page(PDF_PATH)
except FileNotFoundError as e:
print(f"❌ Error: {e}")
return
if not pages:
print("❌ No text was extracted from the PDF.")
return
print(f" ✅ Extracted text from {len(pages)} page(s)")
combined_summary = ""
# Step 2 & 3 — Process each page and send to WhatsApp
for page in pages:
print(f"\n🤖 Processing Page {page['number']}...")
try:
# Get summary for THIS page
summary = process_with_ollama(page['text'], PROMPT)
page_summary_header = f"📄 PAGE {page['number']} SUMMARY:\n"
full_message = f"{page_summary_header}{summary}"
combined_summary += f"--- Page {page['number']} ---\n{summary}\n\n"
# Send to WhatsApp
if SEND_TO_WHATSAPP:
try:
send_to_whatsapp(WHATSAPP_NUMBER, full_message)
# Small delay between pages to ensure the previous tab closes/completes
time.sleep(2)
except Exception as e:
print(f"\n❌ Error: Number {WHATSAPP_NUMBER} does not exist or could not be reached.")
print(" Check the number and try again. Extraction will now stop.")
return # Stop the entire script
except Exception as e:
print(f"❌ Error during Page {page['number']} processing: {e}")
return # Stop processing if any serious error occurs
# Step 4 — Write everything back to .docx
print("\n📝 Step 4: Finalizing Word document...")
write_to_docx(combined_summary, OUTPUT_PATH)
print(f" ✅ Full summary saved to: {os.path.abspath(OUTPUT_PATH)}")
print("\n✅ All pages processed!\n")
if __name__ == "__main__":
main()