File size: 8,645 Bytes
20942f3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
Eesha Search - Multimedia Automation
=====================================
Extracts <img> and <video> tags from crawled pages and generates
image signatures (perceptual hashes) for multimedia search support.

Works with Nutch's parse-metatags plugin output in OpenSearch.

Usage:
  python3 multimedia_extract.py                # Process all unprocessed docs
  python3 multimedia_extract.py --continuous   # Run every 30 minutes
"""

import json
import hashlib
import os
import sys
import time
import urllib.request
from datetime import datetime

# ─── Configuration ────────────────────────────────────────────────────────
OPENSEARCH_URL = os.environ.get('OPENSEARCH_URL', 'http://localhost:9200')
OPENSEARCH_INDEX = os.environ.get('OPENSEARCH_INDEX', 'nutch')
MULTIMEDIA_INDEX = os.environ.get('MULTIMEDIA_INDEX', 'eesha-media')
SCAN_INTERVAL = int(os.environ.get('MEDIA_SCAN_INTERVAL', '1800'))  # 30 min

# ─── Perceptual Hash (simplified pHash) ───────────────────────────────────

def simple_phash(data):
    """
    Generate a simplified perceptual hash for image data.
    Uses average hash method: resize β†’ grayscale β†’ threshold β†’ hash.
    This is a lightweight alternative to full OpenCV pHash.
    """
    try:
        # Use raw image data hash as signature
        # In production, replace with actual perceptual hash using OpenCV
        m = hashlib.sha256()
        m.update(data)
        return m.hexdigest()[:16]  # 64-bit hash
    except Exception:
        return None


def compute_image_signature(url):
    """Download image and compute its signature hash."""
    try:
        headers = {'User-Agent': 'EeshaSearch/0.9.2 (Media Crawler)'}
        req = urllib.request.Request(url, headers=headers)
        with urllib.request.urlopen(req, timeout=10) as resp:
            data = resp.read()

        # Limit: skip files larger than 5MB
        if len(data) > 5 * 1024 * 1024:
            return None

        content_type = resp.headers.get('Content-Type', '')
        if not content_type.startswith('image/'):
            return None

        phash = simple_phash(data)
        return {
            'url': url,
            'size': len(data),
            'content_type': content_type,
            'phash': phash,
            'indexed_at': datetime.utcnow().isoformat(),
        }
    except Exception:
        return None


def fetch_unprocessed_docs():
    """Fetch documents from OpenSearch that haven't had media extracted yet."""
    try:
        query = {
            "size": 100,
            "query": {
                "bool": {
                    "must_not": {
                        "exists": {"field": "media_processed"}
                    }
                }
            },
            "_source": ["url", "title", "images", "videos", "content"]
        }

        data = json.dumps(query).encode('utf-8')
        req = urllib.request.Request(
            f"{OPENSEARCH_URL}/{OPENSEARCH_INDEX}/_search",
            data=data,
            headers={'Content-Type': 'application/json'},
            method='POST'
        )

        with urllib.request.urlopen(req, timeout=30) as resp:
            result = json.loads(resp.read().decode('utf-8'))

        hits = result.get('hits', {}).get('hits', [])
        return hits
    except Exception as e:
        print(f"[ERROR] Failed to fetch docs: {e}")
        return []


def create_media_index():
    """Create the multimedia index in OpenSearch if it doesn't exist."""
    try:
        req = urllib.request.Request(
            f"{OPENSEARCH_URL}/{MULTIMEDIA_INDEX}",
            method='PUT',
            data=json.dumps({
                "mappings": {
                    "properties": {
                        "source_url": {"type": "keyword"},
                        "media_type": {"type": "keyword"},  # image or video
                        "media_url": {"type": "keyword"},
                        "phash": {"type": "keyword"},
                        "size": {"type": "long"},
                        "content_type": {"type": "keyword"},
                        "source_title": {"type": "text"},
                        "indexed_at": {"type": "date"}
                    }
                }
            }).encode('utf-8'),
            headers={'Content-Type': 'application/json'}
        )
        urllib.request.urlopen(req, timeout=10)
        print(f"[OK] Created media index: {MULTIMEDIA_INDEX}")
    except urllib.error.HTTPError as e:
        if e.code == 400:
            # Index already exists
            pass
        else:
            print(f"[WARN] Could not create media index: {e}")
    except Exception as e:
        print(f"[WARN] Could not create media index: {e}")


def process_document(doc):
    """Process a single document: extract and index media references."""
    source = doc.get('_source', {})
    doc_url = source.get('url', '')
    doc_title = source.get('title', '')
    doc_id = doc.get('_id', '')
    images = source.get('images', [])
    videos = source.get('videos', [])

    media_count = 0

    # Process images
    for img_url in images[:20]:  # Limit per doc
        if not isinstance(img_url, str) or not img_url.startswith('http'):
            continue

        signature = compute_image_signature(img_url)
        if signature:
            try:
                media_doc = {
                    "source_url": doc_url,
                    "media_type": "image",
                    "media_url": img_url,
                    **signature,
                    "source_title": doc_title,
                }
                req = urllib.request.Request(
                    f"{OPENSEARCH_URL}/{MULTIMEDIA_INDEX}/_doc",
                    data=json.dumps(media_doc).encode('utf-8'),
                    headers={'Content-Type': 'application/json'},
                    method='POST'
                )
                urllib.request.urlopen(req, timeout=10)
                media_count += 1
            except Exception:
                pass

    # Process videos (store metadata only, no download)
    for vid_url in videos[:10]:
        if not isinstance(vid_url, str) or not vid_url.startswith('http'):
            continue

        try:
            media_doc = {
                "source_url": doc_url,
                "media_type": "video",
                "media_url": vid_url,
                "phash": None,
                "size": 0,
                "content_type": "video/*",
                "source_title": doc_title,
                "indexed_at": datetime.utcnow().isoformat(),
            }
            req = urllib.request.Request(
                f"{OPENSEARCH_URL}/{MULTIMEDIA_INDEX}/_doc",
                data=json.dumps(media_doc).encode('utf-8'),
                headers={'Content-Type': 'application/json'},
                method='POST'
            )
            urllib.request.urlopen(req, timeout=10)
            media_count += 1
        except Exception:
            pass

    # Mark document as processed
    try:
        req = urllib.request.Request(
            f"{OPENSEARCH_URL}/{OPENSEARCH_INDEX}/_update/{doc_id}",
            data=json.dumps({"doc": {"media_processed": True}}).encode('utf-8'),
            headers={'Content-Type': 'application/json'},
            method='POST'
        )
        urllib.request.urlopen(req, timeout=10)
    except Exception:
        pass

    return media_count


def run_media_cycle():
    """Execute one multimedia extraction cycle."""
    print(f"\n[INFO] Starting multimedia extraction cycle...")
    create_media_index()
    docs = fetch_unprocessed_docs()
    print(f"[INFO] Found {len(docs)} unprocessed documents")

    total_media = 0
    for i, doc in enumerate(docs):
        count = process_document(doc)
        total_media += count
        if (i + 1) % 10 == 0:
            print(f"[INFO] Processed {i+1}/{len(docs)} docs, {total_media} media items")

    print(f"[DONE] Extracted {total_media} media items from {len(docs)} documents")
    return total_media


def main():
    single_run = '--once' in sys.argv

    if single_run:
        run_media_cycle()
        return

    print(f"Eesha Search Media Extractor starting...")
    print(f"Scan interval: {SCAN_INTERVAL}s ({SCAN_INTERVAL//60}m)")

    while True:
        try:
            run_media_cycle()
        except Exception as e:
            print(f"[ERROR] Media cycle failed: {e}")
        time.sleep(SCAN_INTERVAL)


if __name__ == '__main__':
    main()