File size: 6,614 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
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
from langchain.messages import SystemMessage, HumanMessage
from modules import model_open_router
import os
import re

# ✅ System Prompt optimized (بديل الدليل الضخم)
SYSTEM_PROMPT = """
You are an expert in APA 7th edition reference formatting.

STRICT RULES:

- Output ONLY the formatted reference (no explanations).
- Each reference must be on a new line.
- Do NOT invent missing data.
- Use (n.d.) if date is missing.
- Keep original language (Arabic stays Arabic, English stays English).

GENERAL FORMAT RULES:

1. Author:
   - Format: Last name, Initial(s).
   - Multiple authors:
     - 2 authors: Author1, A. A., & Author2, B. B.
     - 3+ authors: Author1, A. A., et al.

2. Year:
   - Must be in parentheses: (2023)

3. Title:
   - Sentence case (only first word capitalized in English)
   - Italicize book/journal titles conceptually

4. Books:
   Author. (Year). Title (Edition). City: Publisher.

5. Journal articles:
   Author. (Year). Title. Journal Name, Volume(Issue), pages.

6. Conference papers:
   Author. (Year). Title. Conference Name, Location, Date.

7. Theses:
   Author. (Year). Title [Thesis type], Institution.

8. Websites:
   - With author:
     Author. (Year). Title. URL
   - Without author:
     Title. (Year). URL

9. Arabic references:
   - Keep Arabic format
   - Use same structure:
     المؤلف. (السنة). العنوان. المدينة: الناشر.

10. Page numbers:
   - Use pp. for English
   - Use ص for Arabic

11. Missing data:
   - Use (n.d.)
   - Use [Missing Info] only if critical

12. Fix:
   - spelling
   - punctuation
   - ordering

OUTPUT:
- Clean APA formatted references only
- No bullets
- No numbering
"""


# ✅ تحسين: batching أصغر + fallback
def normalize_references_batch(refs_list, model,batch_size=2):
    batches = []

    for i in range(0, len(refs_list), batch_size):
        chunk = refs_list[i : i + batch_size]
        batches.append("\n".join(chunk))

    results = []

    for batch in batches:
        try:
            messages = [
                SystemMessage(content=SYSTEM_PROMPT),
                HumanMessage(content=f"Format in APA 7:\n{batch}"),
            ]

            response = model.invoke(messages)

            formatted = [
                line.strip() for line in response.content.split("\n") if line.strip()
            ]

            results.extend(formatted)

        except Exception as e:
            print(f"Error in batch: {e}")

            # fallback: رجعهم زي ما هم
            results.extend(batch.split("\n"))

    return results


# ✅ استخراج المراجع
def extract_references(book_json):
    refs = []

    for chapter in book_json.get("chapters", []):
        for section in chapter.get("sections", []):
            for plan in section.get("plans", {}).values():
                for chunk in plan.get("rag_context", {}).get("chunks", []):
                    ref = chunk.get("reference_apa")
                    if ref:
                        refs.append(ref)

    book_name = book_json.get("book_title", "<Book Title>")

    return refs, book_name


# ✅ إزالة التكرار
def remove_duplicates(refs):
    return list(dict.fromkeys(refs))


# ✅ HTML cleaner
def save_refs_to_html(refs_list, book_name):
    """
    تحويل قائمة المراجع إلى ملف HTML منسق أكاديمياً مع اسم الكتاب
    """
    html_content = f"""
    <!DOCTYPE html>
    <html lang="ar" dir="rtl">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>قائمة المراجع - APA 7th Edition</title>
        <style>
            @import url('https://fonts.googleapis.com/css2?family=Amiri&family=Lato&display=swap');

            body {{
                font-family: 'Amiri', serif;
                line-height: 1.8;
                background-color: #f4f7f6;
                color: #333;
                padding: 40px;
                max-width: 900px;
                margin: auto;
            }}

            .container {{
                background: white;
                padding: 50px;
                box-shadow: 0 4px 15px rgba(0,0,0,0.1);
                border-radius: 8px;
            }}

            .book-title {{
                text-align: center;
                font-size: 22px;
                color: #555;
                margin-bottom: 10px;
            }}

            h1 {{
                text-align: center;
                color: #2c3e50;
                border-bottom: 2px solid #2c3e50;
                padding-bottom: 10px;
                margin-bottom: 40px;
                font-size: 28px;
            }}

            .reference-list {{
                list-style-type: none;
                padding: 0;
            }}

            .reference-item {{
                margin-bottom: 20px;
                padding-right: 30px;
                text-indent: -30px;
                text-align: justify;
                word-wrap: break-word;
            }}

            .reference-item a {{
                color: #2980b9;
                text-decoration: none;
                font-family: 'Lato', sans-serif;
                font-size: 0.9em;
            }}

            .reference-item a:hover {{
                text-decoration: underline;
            }}

            @media print {{
                body {{ background: white; padding: 0; }}
                .container {{ box-shadow: none; border: none; }}
            }}
        </style>
    </head>
    <body>
        <div class="container">
            <div class="book-title">{book_name}</div>
            <h1>قائمة المراجع (APA 7th Edition)</h1>
            <ul class="reference-list">
    """

    for ref in refs_list:
        import re

        url_pattern = r"(https?://\S+)"
        formatted_ref = re.sub(
            url_pattern, r'<br><a href="\1" target="_blank">\1</a>', ref
        )

        html_content += f'<li class="reference-item">{formatted_ref}</li>\n'

    html_content += """
            </ul>
        </div>
    </body>
    </html>
    """

    return html_content


# ✅ Main pipeline
def run_references(book_json):
    refs, book_name = extract_references(book_json)
    print(f"Extracted: {len(refs)}")

    refs = remove_duplicates(refs)
    print(f"Unique: {len(refs)}")
    
    # ✅ Model (يفضل موديل أسرع)
    model = model_open_router()
    fixed = normalize_references_batch(refs, model)
    print(f"Formatted: {len(fixed)}")

    html = save_refs_to_html(fixed, book_name)

    return html