-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsnip2text.py
333 lines (273 loc) · 11.8 KB
/
snip2text.py
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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
import tkinter as tk
from tkinter import ttk, messagebox
from PIL import ImageGrab, Image
import pytesseract
import requests
import base64
import json
import io
import threading
# Configure pytesseract path if needed
# pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'
# Configuration for Claude API
CLAUDE_API_ENDPOINT = "https://api.anthropic.com/v1/messages"
CLAUDE_API_KEY = "YOUR_API_KEY_HERE" # Replace with your actual API key
ANTHROPIC_VERSION = "2023-06-01"
class SnippetTool:
def __init__(self, root):
self.root = root
self.root.title("Screen Snippet Tool")
self.root.geometry("800x600")
self.root.minsize(600, 400)
# Style configuration
self.style = ttk.Style()
self.style.theme_use('clam')
self.style.configure("TButton", padding=6, relief="flat", background="#ccc")
self.style.configure("TLabel", padding=6)
self.style.configure("TNotebook.Tab", padding=[12, 4])
# Main container
self.main_frame = ttk.Frame(root)
self.main_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
# Create notebook for tabs
self.notebook = ttk.Notebook(self.main_frame)
self.notebook.pack(fill=tk.BOTH, expand=True)
# Create tabs
self.capture_tab = ttk.Frame(self.notebook)
self.text_tab = ttk.Frame(self.notebook)
self.analysis_tab = ttk.Frame(self.notebook)
self.notebook.add(self.capture_tab, text="Capture")
self.notebook.add(self.text_tab, text="OCR Text")
self.notebook.add(self.analysis_tab, text="Claude Analysis")
# Initialize tabs
self.setup_capture_tab()
self.setup_text_tab()
self.setup_analysis_tab()
# Status bar
self.status = tk.StringVar()
self.status.set("Ready")
self.status_bar = ttk.Label(root, textvariable=self.status, relief="sunken", anchor='w')
self.status_bar.pack(side=tk.BOTTOM, fill=tk.X)
# Store the latest capture
self.current_image = None
self.current_text = None
def setup_capture_tab(self):
# Instructions
instruction_label = ttk.Label(
self.capture_tab,
text="Capture a region of your screen to extract text.\n"
"Press the button below and select the area to capture.",
justify=tk.CENTER
)
instruction_label.pack(pady=20)
# Capture button
self.capture_button = ttk.Button(
self.capture_tab,
text="Capture Screen Region",
command=self.start_capture
)
self.capture_button.pack(pady=10)
def setup_text_tab(self):
self.text_tab.columnconfigure(0, weight=1)
self.text_tab.rowconfigure(1, weight=1)
# Label
ttk.Label(self.text_tab, text="Extracted Text:").grid(row=0, column=0, sticky='w', padx=10, pady=(10, 0))
# Text area with scrollbar
text_frame = ttk.Frame(self.text_tab)
text_frame.grid(row=1, column=0, sticky='nsew', padx=10, pady=5)
self.text_scrollbar = ttk.Scrollbar(text_frame)
self.text_area = tk.Text(
text_frame,
wrap='word',
yscrollcommand=self.text_scrollbar.set,
font=("Segoe UI", 10)
)
self.text_scrollbar.config(command=self.text_area.yview)
self.text_area.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
self.text_scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
# Buttons
button_frame = ttk.Frame(self.text_tab)
button_frame.grid(row=2, column=0, pady=10)
ttk.Button(
button_frame,
text="Copy to Clipboard",
command=lambda: self.copy_to_clipboard(self.text_area.get("1.0", tk.END))
).pack(side=tk.LEFT, padx=5)
ttk.Button(
button_frame,
text="Analyze with Claude",
command=self.start_claude_analysis
).pack(side=tk.LEFT, padx=5)
# Context menu
self.setup_context_menu(self.text_area)
def setup_analysis_tab(self):
self.analysis_tab.columnconfigure(0, weight=1)
self.analysis_tab.rowconfigure(1, weight=1)
# Label
ttk.Label(self.analysis_tab, text="Claude Analysis:").grid(row=0, column=0, sticky='w', padx=10, pady=(10, 0))
# Analysis text area
analysis_frame = ttk.Frame(self.analysis_tab)
analysis_frame.grid(row=1, column=0, sticky='nsew', padx=10, pady=5)
self.analysis_scrollbar = ttk.Scrollbar(analysis_frame)
self.analysis_area = tk.Text(
analysis_frame,
wrap='word',
yscrollcommand=self.analysis_scrollbar.set,
font=("Segoe UI", 10)
)
self.analysis_scrollbar.config(command=self.analysis_area.yview)
self.analysis_area.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
self.analysis_scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
# Buttons
button_frame = ttk.Frame(self.analysis_tab)
button_frame.grid(row=2, column=0, pady=10)
ttk.Button(
button_frame,
text="Copy to Clipboard",
command=lambda: self.copy_to_clipboard(self.analysis_area.get("1.0", tk.END))
).pack(side=tk.LEFT, padx=5)
# Context menu
self.setup_context_menu(self.analysis_area)
def setup_context_menu(self, widget):
context_menu = tk.Menu(widget, tearoff=0)
context_menu.add_command(
label="Copy",
command=lambda: self.copy_selection(widget)
)
widget.bind("<Button-3>", lambda e: context_menu.tk_popup(e.x_root, e.y_root))
def copy_selection(self, widget):
try:
selection = widget.selection_get()
self.root.clipboard_clear()
self.root.clipboard_append(selection)
except tk.TclError:
pass
def start_capture(self):
self.root.withdraw()
self.status.set("Preparing to capture...")
self.root.after(500, self.select_region)
def select_region(self):
self.selection_window = tk.Toplevel(self.root)
self.selection_window.attributes('-fullscreen', True, '-alpha', 0.3)
self.selection_window.configure(background='black')
self.canvas = tk.Canvas(self.selection_window, cursor="cross", bg="black")
self.canvas.pack(fill=tk.BOTH, expand=True)
self.start_x = self.start_y = self.rect = None
self.canvas.bind("<ButtonPress-1>", self.on_mouse_down)
self.canvas.bind("<B1-Motion>", self.on_mouse_drag)
self.canvas.bind("<ButtonRelease-1>", self.on_mouse_up)
def on_mouse_down(self, event):
self.start_x = self.canvas.canvasx(event.x)
self.start_y = self.canvas.canvasy(event.y)
self.rect = self.canvas.create_rectangle(
self.start_x, self.start_y, self.start_x, self.start_y,
outline='red', width=2
)
def on_mouse_drag(self, event):
cur_x, cur_y = (self.canvas.canvasx(event.x), self.canvas.canvasy(event.y))
self.canvas.coords(self.rect, self.start_x, self.start_y, cur_x, cur_y)
def on_mouse_up(self, event):
self.end_x = self.canvas.canvasx(event.x)
self.end_y = self.canvas.canvasy(event.y)
self.selection_window.destroy()
self.capture_region()
def capture_region(self):
self.status.set("Capturing screen region...")
x1, y1 = min(self.start_x, self.end_x), min(self.start_y, self.end_y)
x2, y2 = max(self.start_x, self.end_x), max(self.start_y, self.end_y)
try:
self.current_image = ImageGrab.grab(bbox=(x1, y1, x2, y2))
self.status.set("Performing OCR...")
self.current_text = pytesseract.image_to_string(self.current_image)
# Update text tab
self.text_area.config(state=tk.NORMAL)
self.text_area.delete(1.0, tk.END)
self.text_area.insert(tk.END, self.current_text)
self.text_area.config(state=tk.DISABLED)
# Switch to text tab
self.notebook.select(1)
# Copy to clipboard
self.root.clipboard_clear()
self.root.clipboard_append(self.current_text)
except Exception as e:
messagebox.showerror("Error", f"An error occurred: {e}")
self.status.set("Error occurred.")
finally:
self.root.deiconify()
self.status.set("Ready")
def copy_to_clipboard(self, text):
self.root.clipboard_clear()
self.root.clipboard_append(text)
messagebox.showinfo("Copied", "Text has been copied to the clipboard.")
def start_claude_analysis(self):
if not self.current_image:
messagebox.showwarning("No Image", "Please capture an image first.")
return
proceed = messagebox.askyesno(
"Claude Analysis",
"Do you want to analyze the captured image with Claude for further insights?"
)
if proceed:
self.status.set("Analyzing with Claude...")
thread = threading.Thread(target=self.analyze_with_claude, daemon=True)
thread.start()
def analyze_with_claude(self):
try:
# Convert image to base64
buffered = io.BytesIO()
self.current_image.save(buffered, format="PNG")
img_base64 = base64.b64encode(buffered.getvalue()).decode("utf-8")
# Prepare the data payload
data = {
"messages": [
{
"role": "user",
"content": [
{
"type": "text",
"text": "Extract all visible text from this image exactly as it appears, including punctuation and line breaks. Do not add any analysis, interpretation, or comments—only provide the raw text."
},
{
"type": "image",
"source": {
"type": "base64",
"media_type": "image/png",
"data": img_base64
}
}
]
}
],
"model": "claude-3-5-sonnet-20240620",
"max_tokens": 4096
}
headers = {
"Content-Type": "application/json",
"x-api-key": CLAUDE_API_KEY,
"anthropic-version": ANTHROPIC_VERSION
}
response = requests.post(CLAUDE_API_ENDPOINT, headers=headers, json=data, timeout=60)
response.raise_for_status()
response_json = response.json()
# Extract analysis text
if 'content' in response_json and isinstance(response_json['content'], list):
analysis_text = ""
for message in response_json['content']:
if 'text' in message:
analysis_text += message['text'] + "\n"
else:
analysis_text = "No analysis provided."
# Update analysis tab
self.analysis_area.config(state=tk.NORMAL)
self.analysis_area.delete(1.0, tk.END)
self.analysis_area.insert(tk.END, analysis_text)
self.analysis_area.config(state=tk.DISABLED)
# Switch to analysis tab
self.notebook.select(2)
except Exception as e:
messagebox.showerror("Error", f"An error occurred while communicating with Claude API:\n{e}")
finally:
self.status.set("Ready")
if __name__ == "__main__":
root = tk.Tk()
app = SnippetTool(root)
root.mainloop()