File size: 11,604 Bytes
407bf0b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
#!/usr/bin/env python3
"""
Generate instruction-tuned dataset from Stern NEON articles.

This script converts the raw JSONL articles into various formats suitable
for fine-tuning LLMs with LoRA or other methods.

Output formats:
- Alpaca format (instruction, input, output)
- ChatML/Messages format (for chat models)
- Completion format (simple text format)
"""

import json
import random
import argparse
from pathlib import Path
from typing import Generator
from dataclasses import dataclass

# Category translations for German instructions
CATEGORY_TRANSLATIONS = {
    "fuehlen": "Gefühle",
    "kaufen": "Konsum & Lifestyle",
    "freie-zeit": "Freizeit",
    "sehen": "Beobachtungen",
    "machen": "Aktivitäten",
    "wissen": "Wissen",
    "erwachsen-werden": "Erwachsenwerden",
    "familie": "Familie",
    "liebe": "Liebe",
    "sex": "Sexualität",
    "freundschaft": "Freundschaft",
    "reise": "Reisen",
    "computer-internet": "Computer & Internet",
    "musik": "Musik",
    "film-fernsehen": "Film & Fernsehen",
    "buecher": "Bücher",
    "sport": "Sport",
    "essen-trinken": "Essen & Trinken",
    "mode": "Mode",
    "wohnen": "Wohnen",
    "arbeit": "Arbeit",
    "studium": "Studium",
    "schule": "Schule",
    "politik": "Politik",
    "gesellschaft": "Gesellschaft",
}

# Instruction templates - varied to improve model generalization
INSTRUCTION_TEMPLATES = [
    # Title-based
    "Schreibe einen Artikel mit dem Titel: \"{title}\"",
    "Verfasse einen persönlichen Text zum Thema: \"{title}\"",
    "Erstelle einen NEON-Artikel mit der Überschrift: \"{title}\"",

    # Category-based
    "Schreibe einen persönlichen Artikel über {category}.",
    "Verfasse einen emotionalen Text zum Thema {category}.",

    # Title + Category
    "Schreibe einen {category}-Artikel mit dem Titel \"{title}\".",
    "Erstelle einen persönlichen Text über {category}. Der Titel soll sein: \"{title}\"",

    # With subtitle context
    "Schreibe einen Artikel mit dem Titel \"{title}\". Thema: {subtitle}",
    "Verfasse einen Text zum Thema: {subtitle}",
]

# System prompts for chat format
SYSTEM_PROMPTS = [
    "Du bist ein kreativer Autor im Stil der Stern NEON Community. Du schreibst persönliche, emotionale und authentische Texte über das Leben junger Erwachsener in Deutschland.",
    "Du bist ein talentierter Autor für persönliche Essays und Erfahrungsberichte. Dein Schreibstil ist introspektiv, ehrlich und berührend.",
    "Du schreibst im Stil von Stern NEON: persönlich, nachdenklich, manchmal melancholisch, immer authentisch. Deine Texte handeln vom Erwachsenwerden, von Liebe, Freundschaft und den kleinen Momenten des Lebens.",
]


@dataclass
class Article:
    """Represents a single article from the dataset."""
    title: str
    subtitle: str | None
    text: str
    author: str
    main_category: str
    sub_category: str
    article_id: int

    @classmethod
    def from_json(cls, data: dict) -> "Article | None":
        """Create an Article from JSON data, returns None if invalid."""
        text = data.get("text", "").strip()
        title = data.get("title", "").strip()

        # Skip articles with empty or very short text
        if not text or len(text) < 100 or not title:
            return None

        return cls(
            title=title,
            subtitle=data.get("subtitle"),
            text=text,
            author=data.get("author", "Anonym"),
            main_category=data.get("main_category", ""),
            sub_category=data.get("sub_category", ""),
            article_id=data.get("id", 0),
        )

    def get_category_name(self) -> str:
        """Get human-readable category name."""
        sub = CATEGORY_TRANSLATIONS.get(self.sub_category, self.sub_category)
        main = CATEGORY_TRANSLATIONS.get(self.main_category, self.main_category)
        if sub and sub != main:
            return f"{main} / {sub}"
        return main or "Allgemein"


def load_articles(input_path: Path) -> Generator[Article, None, None]:
    """Load and parse articles from JSONL file."""
    with open(input_path, "r", encoding="utf-8") as f:
        for line in f:
            line = line.strip()
            if not line:
                continue
            try:
                data = json.loads(line)
                article = Article.from_json(data)
                if article:
                    yield article
            except json.JSONDecodeError as e:
                print(f"Warning: Failed to parse line: {e}")
                continue


def generate_instruction(article: Article) -> str:
    """Generate a varied instruction for an article."""
    # Choose template based on available data
    available_templates = INSTRUCTION_TEMPLATES[:3]  # Title-based always available

    if article.main_category or article.sub_category:
        available_templates.extend(INSTRUCTION_TEMPLATES[3:7])  # Category templates

    if article.subtitle:
        available_templates.extend(INSTRUCTION_TEMPLATES[7:])  # Subtitle templates

    template = random.choice(available_templates)

    return template.format(
        title=article.title,
        category=article.get_category_name(),
        subtitle=article.subtitle or "",
    )


def to_alpaca_format(article: Article) -> dict:
    """Convert article to Alpaca instruction format."""
    return {
        "instruction": generate_instruction(article),
        "input": "",
        "output": article.text,
        "metadata": {
            "title": article.title,
            "author": article.author,
            "category": article.get_category_name(),
            "id": article.article_id,
        }
    }


def to_chat_format(article: Article) -> dict:
    """Convert article to ChatML/messages format."""
    system_prompt = random.choice(SYSTEM_PROMPTS)
    user_message = generate_instruction(article)

    return {
        "messages": [
            {"role": "system", "content": system_prompt},
            {"role": "user", "content": user_message},
            {"role": "assistant", "content": article.text},
        ],
        "metadata": {
            "title": article.title,
            "author": article.author,
            "id": article.article_id,
        }
    }


def to_completion_format(article: Article) -> dict:
    """Convert article to simple completion format."""
    category = article.get_category_name()
    subtitle_line = f"\n### Untertitel: {article.subtitle}" if article.subtitle else ""

    text = f"""### Kategorie: {category}
### Titel: {article.title}{subtitle_line}

{article.text}"""

    return {
        "text": text,
        "metadata": {
            "title": article.title,
            "author": article.author,
            "id": article.article_id,
        }
    }


def to_sharegpt_format(article: Article) -> dict:
    """Convert article to ShareGPT format (used by Axolotl and others)."""
    system_prompt = random.choice(SYSTEM_PROMPTS)
    user_message = generate_instruction(article)

    return {
        "conversations": [
            {"from": "system", "value": system_prompt},
            {"from": "human", "value": user_message},
            {"from": "gpt", "value": article.text},
        ],
        "id": f"neon_{article.article_id}",
    }


FORMAT_HANDLERS = {
    "alpaca": to_alpaca_format,
    "chat": to_chat_format,
    "completion": to_completion_format,
    "sharegpt": to_sharegpt_format,
}


def process_dataset(
    input_path: Path,
    output_path: Path,
    output_format: str = "alpaca",
    min_length: int = 100,
    max_length: int | None = None,
    seed: int = 42,
) -> dict:
    """Process the entire dataset and write to output file."""
    random.seed(seed)

    handler = FORMAT_HANDLERS.get(output_format)
    if not handler:
        raise ValueError(f"Unknown format: {output_format}. Choose from: {list(FORMAT_HANDLERS.keys())}")

    stats = {
        "total_processed": 0,
        "skipped_short": 0,
        "skipped_long": 0,
        "categories": {},
    }

    with open(output_path, "w", encoding="utf-8") as out_file:
        for article in load_articles(input_path):
            # Length filtering
            text_len = len(article.text)
            if text_len < min_length:
                stats["skipped_short"] += 1
                continue
            if max_length and text_len > max_length:
                stats["skipped_long"] += 1
                continue

            # Convert to output format
            output_record = handler(article)
            out_file.write(json.dumps(output_record, ensure_ascii=False) + "\n")

            # Update stats
            stats["total_processed"] += 1
            cat = article.get_category_name()
            stats["categories"][cat] = stats["categories"].get(cat, 0) + 1

    return stats


def main():
    parser = argparse.ArgumentParser(
        description="Generate instruction-tuned dataset from Stern NEON articles",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
Examples:
  # Generate Alpaca format (default)
  python generate_instructions.py ../stern_neon_user_poetry.jsonl -o ../neon_alpaca.jsonl

  # Generate ChatML format for chat models
  python generate_instructions.py ../stern_neon_user_poetry.jsonl -o ../neon_chat.jsonl -f chat

  # Generate ShareGPT format for Axolotl
  python generate_instructions.py ../stern_neon_user_poetry.jsonl -o ../neon_sharegpt.jsonl -f sharegpt

  # Filter by text length
  python generate_instructions.py ../stern_neon_user_poetry.jsonl -o ../neon_filtered.jsonl --min-length 500 --max-length 5000
        """
    )

    parser.add_argument(
        "input",
        type=Path,
        help="Path to input JSONL file (stern_neon_user_poetry.jsonl)",
    )
    parser.add_argument(
        "-o", "--output",
        type=Path,
        required=True,
        help="Path to output JSONL file",
    )
    parser.add_argument(
        "-f", "--format",
        choices=list(FORMAT_HANDLERS.keys()),
        default="alpaca",
        help="Output format (default: alpaca)",
    )
    parser.add_argument(
        "--min-length",
        type=int,
        default=100,
        help="Minimum text length in characters (default: 100)",
    )
    parser.add_argument(
        "--max-length",
        type=int,
        default=None,
        help="Maximum text length in characters (default: no limit)",
    )
    parser.add_argument(
        "--seed",
        type=int,
        default=42,
        help="Random seed for reproducibility (default: 42)",
    )

    args = parser.parse_args()

    if not args.input.exists():
        print(f"Error: Input file not found: {args.input}")
        return 1

    print(f"Processing {args.input}...")
    print(f"Output format: {args.format}")
    print(f"Output file: {args.output}")
    print()

    stats = process_dataset(
        input_path=args.input,
        output_path=args.output,
        output_format=args.format,
        min_length=args.min_length,
        max_length=args.max_length,
        seed=args.seed,
    )

    print("=" * 50)
    print("Processing complete!")
    print(f"  Total articles processed: {stats['total_processed']}")
    print(f"  Skipped (too short): {stats['skipped_short']}")
    print(f"  Skipped (too long): {stats['skipped_long']}")
    print()
    print("Top categories:")
    sorted_cats = sorted(stats["categories"].items(), key=lambda x: x[1], reverse=True)
    for cat, count in sorted_cats[:10]:
        print(f"  {cat}: {count}")
    print()
    print(f"Output written to: {args.output}")

    return 0


if __name__ == "__main__":
    exit(main())