File size: 5,158 Bytes
325b94c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations
from typing import Dict, Any, List

from core.books.storage import (
    fetch_raw_docs_for_user,
    mark_raw_status,
    upsert_document_metadata,
)
from schemas.books.sources_schema import SourceForAgent, DocMetadata
from agents.books.apa_agent import run_metadata_agent


# -------- limits (VERY IMPORTANT) --------
MAX_PAGES = 5
MAX_CHARS_PER_PAGE = 5000


def _build_agent_input(raw: Dict[str, Any]) -> Dict[str, Any]:
    pages = raw.get("pages_head") or []
    # pages = pages[:MAX_PAGES]
    # pages = [p[:MAX_CHARS_PER_PAGE] for p in pages]

    return SourceForAgent(
        source_url=raw["source_url"],
        source_type=raw.get("source_type", "pdf"),
        domain=raw.get("domain", ""),
        search_title=raw.get("search_title", "") or "",
        search_snippet=raw.get("search_snippet", "") or "",
        text_pages=pages,
    ).model_dump()


def process_user_metadata(user_id: str, book_id: str | None = None) -> Dict[str, Any]:
    pending = fetch_raw_docs_for_user(
        user_id=user_id,
        book_id=book_id,
        status="pending",
    )

    total = len(pending)
    processed = 0
    failed = 0
    items: List[Dict[str, Any]] = []
    tokens = []

    if total == 0:
        return {
            "user_id": user_id,
            "book_id": book_id,
            "total": 0,
            "processed": 0,
            "failed": 0,
            "items": [],
            "mode": "sequential",
        }

    for raw in pending:
        doc_id = raw["doc_id"]
        url = raw["source_url"]

        pages_head = raw.get("pages_head") or []
        if not pages_head:
            mark_raw_status(doc_id, "failed", "no_pages_head")
            failed += 1
            items.append(
                {
                    "doc_id": doc_id,
                    "url": url,
                    "status": "failed",
                    "reason": "no_pages_head",
                }
            )
            continue

        mark_raw_status(doc_id, "processing", "")
        
        try:
            agent_in = _build_agent_input(raw)
            out, token_usage = run_metadata_agent(agent_in)
        except Exception as e:
            print(f"⚠️ LLM internal exception for doc_id {doc_id}: {e}")
            out = None

        # ---- بعد الـ try/except ----
        if not isinstance(out, dict):
            mark_raw_status(doc_id, "failed", "llm_exception")
            failed += 1
            items.append(
                {
                    "doc_id": doc_id,
                    "url": url,
                    "status": "failed",
                    "reason": "llm_exception",
                }
            )
            continue
        
        if token_usage:    
            tokens.append(token_usage)

        print(f"Metadata agent output for doc_id {doc_id}: {type(out)} - {out}")    
        print(f"is_valid: {out.get('is_valid')}")
        if not out.get("is_valid"):
            reason = out.get("reason", "invalid")
            mark_raw_status(doc_id, "failed", reason)
            failed += 1
            items.append(
                {
                    "doc_id": doc_id,
                    "url": url,
                    "status": "failed",
                    "reason": reason,
                }
            )
            continue

        md = out.get("metadata") or {}
        if "title" not in md or "authors" not in md:
            mark_raw_status(doc_id, "failed", "missing_title_or_authors")
            failed += 1
            items.append(
                {
                    "doc_id": doc_id,
                    "url": url,
                    "status": "failed",
                    "reason": "missing_title_or_authors",
                }
            )
            continue

        try:
            doc_md = DocMetadata(
                doc_id=doc_id,
                title=md["title"],
                authors=md["authors"],
                year=md.get("year"),
                publisher_or_journal=md.get("publisher_or_journal") or "",
                normalized_source_type=out.get("normalized_source_type", "pdf"),
                apa7=md.get("apa7") or "",
                metadata=out,
            )

            upsert_document_metadata(doc_md)
            mark_raw_status(doc_id, "processed", "")
            processed += 1
            items.append(
                {
                    "doc_id": doc_id,
                    "url": url,
                    "status": "processed",
                    "title": doc_md.title,
                }
            )

        except Exception:
            mark_raw_status(doc_id, "failed", "db_failed")
            failed += 1
            items.append(
                {
                    "doc_id": doc_id,
                    "url": url,
                    "status": "failed",
                    "reason": "db_failed",
                }
            )

    return {
        "user_id": user_id,
        "book_id": book_id,
        "total": total,
        "processed": processed,
        "failed": failed,
        "items": items,
        "mode": "sequential",
        "tokens": tokens,
    }