[READ-ONLY] Mirror of https://github.com/mrgnw/scripts.
1# /// script
2# dependencies = [
3# "pytesseract",
4# "Pillow",
5# "pillow-heif",
6# ]
7# ///
8
9import os
10import json
11import re
12import shutil
13from pathlib import Path
14import pytesseract
15from PIL import Image
16import pillow_heif
17
18# Register HEIF opener for PIL
19pillow_heif.register_heif_opener()
20
21def extract_instagram_handles(text):
22 """Extract Instagram handles from text using regex."""
23 # Match @ followed by letters, numbers, periods, and underscores
24 pattern = r'@[A-Za-z0-9._]+\b'
25 return re.findall(pattern, text)
26
27def process_image(image_path):
28 """Extract text from image using OCR."""
29 try:
30 img = Image.open(image_path)
31 # Convert image to RGB if necessary
32 if img.mode != 'RGB':
33 img = img.convert('RGB')
34 text = pytesseract.image_to_string(img)
35 return text
36 except Exception as e:
37 print(f"Error processing {image_path}: {e}")
38 return ""
39
40def main():
41 # Create processed directory if it doesn't exist
42 processed_dir = Path('processed')
43 processed_dir.mkdir(exist_ok=True)
44
45 # Get all image files in current directory
46 image_files = []
47 for ext in ['.heic', '.jpg', '.jpeg', '.png']:
48 image_files.extend(Path('.').glob(f'*{ext}'))
49 image_files.extend(Path('.').glob(f'*{ext.upper()}'))
50
51 # Process each image
52 with open('instagram_handles.jsonl', 'w', encoding='utf-8') as f:
53 for image_path in image_files:
54 # Skip files already in processed directory
55 if 'processed' in str(image_path):
56 continue
57
58 print(f"Processing {image_path}")
59 text = process_image(image_path)
60 handles = extract_instagram_handles(text)
61
62 if handles:
63 # Write results to JSONL file
64 for handle in handles:
65 result = {
66 'file': image_path.name,
67 'ig': handle
68 }
69 f.write(json.dumps(result) + '\n')
70
71 # Move file to processed directory
72 shutil.move(str(image_path), str(processed_dir / image_path.name))
73
74if __name__ == "__main__":
75 main()