File size: 9,515 Bytes
342973b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Content Generator - Generate academic content using AI models
"""

import re
from typing import Dict, List, Optional, Any
from textwrap import dedent
import logging

logger = logging.getLogger(__name__)


class ContentGenerator:
    """
    Generate academic content using Hugging Face models.
    """

    def __init__(self, model_name: str = "HuggingFaceH4/zephyr-7b-beta"):
        """
        Initialize content generator.

        Args:
            model_name: Hugging Face model identifier
        """
        self.model_name = model_name
        self.pipeline = None
        self._init_model()

    def _init_model(self):
        """Initialize the language model."""
        try:
            from transformers import pipeline

            self.pipeline = pipeline(
                "text-generation",
                model=self.model_name,
                device=-1,  # Use CPU
                torch_dtype="auto",
            )
            logger.info(f"Model {self.model_name} loaded successfully")
        except Exception as e:
            logger.warning(f"Model loading failed: {e}. Using fallback generation.")
            self.pipeline = None

    def generate_section(
        self,
        title: str,
        context: str = "",
        topic: str = "",
        word_count: int = 300,
        style: str = "academic",
    ) -> str:
        """
        Generate a single document section.

        Args:
            title: Section title
            context: Additional context for generation
            topic: Main topic of the section
            word_count: Target word count
            style: Writing style (academic, formal, informal, etc.)

        Returns:
            Generated section content
        """
        prompt = self._create_prompt(title, context, topic, style, word_count)

        if self.pipeline:
            return self._generate_with_model(prompt, word_count)
        else:
            return self._generate_fallback(title, topic, word_count)

    def _create_prompt(
        self, title: str, context: str, topic: str, style: str, word_count: int
    ) -> str:
        """Create generation prompt."""
        prompt = dedent(
            f"""
        Write a {style} section titled "{title}" about {topic}.
        Context: {context}
        
        Requirements:
        - Approximately {word_count} words
        - Professional {style} tone
        - Well-structured with clear paragraphs
        - Informative and engaging
        
        Section Content:
        """
        )
        return prompt

    def _generate_with_model(self, prompt: str, word_count: int) -> str:
        """Generate using the loaded model."""
        try:
            max_tokens = min(word_count // 4 + 100, 512)  # Rough estimation: 4 chars per word

            result = self.pipeline(
                prompt,
                max_length=max_tokens,
                num_return_sequences=1,
                temperature=0.7,
                top_p=0.95,
                do_sample=True,
            )

            if result and len(result) > 0:
                generated_text = result[0]["generated_text"]
                # Extract only the new content after the prompt
                content = generated_text[len(prompt) :].strip()
                return content if content else self._generate_fallback("Content", "", word_count)

            return self._generate_fallback("Content", "", word_count)

        except Exception as e:
            logger.warning(f"Generation failed: {e}. Using fallback.")
            return self._generate_fallback("Content", "", word_count)

    def _generate_fallback(self, title: str, topic: str, word_count: int) -> str:
        """Generate content using fallback method when model is unavailable."""
        templates = {
            "introduction": "This section introduces the key concepts and provides context. ",
            "methodology": "This section describes the methods and approaches used. ",
            "results": "This section presents the key findings and outcomes. ",
            "discussion": "This section analyzes the implications and significance. ",
            "conclusion": "This section summarizes the main points and conclusions. ",
            "literature review": "This section reviews relevant existing research and scholarship. ",
        }

        title_lower = title.lower()
        base_text = templates.get(title_lower, f"This section discusses {topic}. ")

        # Generate paragraphs to reach target word count
        paragraphs = []
        target_words = word_count

        while len(" ".join(paragraphs)) < target_words:
            paragraph = (
                f"{base_text} "
                f"The significance of {topic} cannot be overstated in the context of modern {title.lower()}. "
                f"Through careful analysis and consideration, we find that multiple factors contribute to this outcome. "
                f"Furthermore, the evidence suggests that continued research and investigation in this area will yield valuable insights. "
                f"In conclusion, this aspect merits further attention from researchers and practitioners alike."
            )
            paragraphs.append(paragraph)

        return " ".join(paragraphs)[: word_count * 4]  # Rough character limit

    def generate_document_sections(
        self,
        sections: List[str],
        context: str = "",
        topics: List[str] = None,
        style: str = "academic",
        total_words: int = 2000,
    ) -> Dict[str, str]:
        """
        Generate multiple sections for a complete document.

        Args:
            sections: List of section titles
            context: Document context
            topics: Topic for each section
            style: Writing style
            total_words: Target total word count

        Returns:
            Dictionary of section_title: content
        """
        if topics is None:
            topics = [f"aspect {i}" for i in range(len(sections))]

        # Distribute words across sections
        words_per_section = total_words // len(sections)

        content = {}
        for section, topic in zip(sections, topics):
            section_content = self.generate_section(
                title=section,
                context=context,
                topic=topic,
                word_count=words_per_section,
                style=style,
            )
            content[section] = section_content

        return content

    def improve_content(self, content: str) -> str:
        """
        Improve existing content for better readability and flow.

        Args:
            content: Original content

        Returns:
            Improved content
        """
        # Simple improvements without model
        improved = self._improve_sentences(content)
        improved = self._fix_grammar_basic(improved)
        improved = self._improve_flow(improved)

        return improved

    def _improve_sentences(self, text: str) -> str:
        """Improve sentence structure."""
        # Break up overly long sentences
        sentences = re.split(r"(?<=[.!?])\s+", text)
        improved_sentences = []

        for sent in sentences:
            if len(sent) > 200:  # Split very long sentences
                parts = sent.split(",")
                if len(parts) > 2:
                    improved_sentences.extend(parts)
                else:
                    improved_sentences.append(sent)
            else:
                improved_sentences.append(sent)

        return " ".join(improved_sentences)

    def _fix_grammar_basic(self, text: str) -> str:
        """Apply basic grammar improvements."""
        # Fix common issues
        text = re.sub(r"\b(a)\s+([aeiou])", r"an \2", text)  # a -> an
        text = re.sub(r"\s+", " ", text)  # Remove extra spaces
        text = re.sub(r"\s([.,;:])", r"\1", text)  # Fix spacing before punctuation

        return text

    def _improve_flow(self, text: str) -> str:
        """Improve text flow and transitions."""
        transitions = {
            r"^Therefore": "As a result",
            r"^However": "Nevertheless",
            r"^Also": "Additionally",
            r"^Finally": "In conclusion",
        }

        for pattern, replacement in transitions.items():
            text = re.sub(pattern, replacement, text, flags=re.MULTILINE)

        return text

    def generate_outline(self, topic: str, sections: List[str]) -> Dict[str, List[str]]:
        """
        Generate detailed outline for document.

        Args:
            topic: Main topic
            sections: Section titles

        Returns:
            Outline with key points per section
        """
        outline = {}

        for section in sections:
            # Generate key points for each section
            key_points = [
                f"Overview of {section.lower()}",
                f"Key aspects of {section.lower()}",
                f"Implications for {topic}",
                f"Current trends in {section.lower()}",
                f"Future directions for {section.lower()}",
            ]

            outline[section] = key_points[:3]  # Select 3 key points per section

        return outline

    def estimate_tokens(self, text: str) -> int:
        """
        Estimate token count for text.

        Args:
            text: Input text

        Returns:
            Estimated token count
        """
        # Rough estimation: 1 token ≈ 4 characters
        return len(text) // 4