pvanand commited on
Commit
0289fc8
1 Parent(s): 6c8ee89

Create document-generator.py

Browse files
Files changed (1) hide show
  1. document-generator.py +279 -0
document-generator.py ADDED
@@ -0,0 +1,279 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # File: prompts.py
2
+
3
+ DOCUMENT_OUTLINE_PROMPT_SYSTEM = """You are a document generator. Provide the outline of the document requested in <prompt></prompt> in JSON format.
4
+ Include sections and subsections if required. Use the "Content" field to provide a specific prompt or instruction for generating content for that particular section or subsection.
5
+
6
+ OUTPUT IN FOLLOWING JSON FORMAT enclosed in <output> tags
7
+ <output>
8
+ {
9
+ "Document": {
10
+ "Title": "Document Title",
11
+ "Author": "Author Name",
12
+ "Date": "YYYY-MM-DD",
13
+ "Version": "1.0",
14
+
15
+ "Sections": [
16
+ {
17
+ "SectionNumber": "1",
18
+ "Title": "Section Title",
19
+ "Content": "Specific prompt or instruction for generating content for this section",
20
+ "Subsections": [
21
+ {
22
+ "SectionNumber": "1.1",
23
+ "Title": "Subsection Title",
24
+ "Content": "Specific prompt or instruction for generating content for this subsection"
25
+ }
26
+ ]
27
+ }
28
+ ]
29
+ }
30
+ }
31
+ </output>"""
32
+
33
+ DOCUMENT_OUTLINE_PROMPT_USER = """<prompt>{query}</prompt>"""
34
+
35
+ DOCUMENT_SECTION_PROMPT_SYSTEM = """You are a document generator, You need to output only the content requested in the section in the prompt.
36
+ FORMAT YOUR OUTPUT AS MARKDOWN ENCLOSED IN <response></response> tags
37
+ <overall_objective>{overall_objective}</overall_objective>
38
+ <document_layout>{document_layout}</document_layout>"""
39
+
40
+ DOCUMENT_SECTION_PROMPT_USER = """<prompt>Output the content for the section "{section_or_subsection_title}" formatted as markdown. Follow this instruction: {content_instruction}</prompt>"""
41
+
42
+ # File: app.py
43
+
44
+ import os
45
+ import json
46
+ import re
47
+ from typing import List, Dict, Optional, Any, Callable
48
+ from openai import OpenAI
49
+ import logging
50
+ import functools
51
+ from fastapi import APIRouter, HTTPException
52
+ from pydantic import BaseModel
53
+ #from prompts import *
54
+
55
+ logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
56
+ logger = logging.getLogger(__name__)
57
+
58
+ def log_execution(func: Callable) -> Callable:
59
+ @functools.wraps(func)
60
+ def wrapper(*args: Any, **kwargs: Any) -> Any:
61
+ logger.info(f"Executing {func.__name__}")
62
+ try:
63
+ result = func(*args, **kwargs)
64
+ logger.info(f"{func.__name__} completed successfully")
65
+ return result
66
+ except Exception as e:
67
+ logger.error(f"Error in {func.__name__}: {e}")
68
+ raise
69
+ return wrapper
70
+
71
+ class AIClient:
72
+ def __init__(self):
73
+ self.client = OpenAI(
74
+ base_url="https://openrouter.ai/api/v1",
75
+ api_key=os.environ['OPENROUTER_API_KEY']
76
+ )
77
+
78
+ @log_execution
79
+ def generate_response(
80
+ self,
81
+ messages: List[Dict[str, str]],
82
+ model: str = "openai/gpt-4o-mini",
83
+ max_tokens: int = 32000
84
+ ) -> Optional[str]:
85
+ if not messages:
86
+ return None
87
+ response = self.client.chat.completions.create(
88
+ model=model,
89
+ messages=messages,
90
+ max_tokens=max_tokens,
91
+ stream=False
92
+ )
93
+ return response.choices[0].message.content
94
+
95
+ class DocumentGenerator:
96
+ def __init__(self, ai_client: AIClient):
97
+ self.ai_client = ai_client
98
+ self.document_outline = None
99
+ self.content_messages = []
100
+
101
+ @staticmethod
102
+ def extract_between_tags(text: str, tag: str) -> str:
103
+ pattern = f"<{tag}>(.*?)</{tag}>"
104
+ match = re.search(pattern, text, re.DOTALL)
105
+ return match.group(1).strip() if match else ""
106
+
107
+ @staticmethod
108
+ def remove_duplicate_title(content: str, title: str, section_number: str) -> str:
109
+ patterns = [
110
+ rf"^#+\s*{re.escape(section_number)}(?:\s+|\s*:\s*|\.\s*){re.escape(title)}",
111
+ rf"^#+\s*{re.escape(title)}",
112
+ rf"^{re.escape(section_number)}(?:\s+|\s*:\s*|\.\s*){re.escape(title)}",
113
+ rf"^{re.escape(title)}",
114
+ ]
115
+
116
+ for pattern in patterns:
117
+ content = re.sub(pattern, "", content, flags=re.MULTILINE | re.IGNORECASE)
118
+
119
+ return content.lstrip()
120
+
121
+ @log_execution
122
+ def generate_document_outline(self, query: str, max_retries: int = 3) -> Optional[Dict]:
123
+ messages = [
124
+ {"role": "system", "content": DOCUMENT_OUTLINE_PROMPT_SYSTEM},
125
+ {"role": "user", "content": DOCUMENT_OUTLINE_PROMPT_USER.format(query=query)}
126
+ ]
127
+
128
+ for attempt in range(max_retries):
129
+ outline_response = self.ai_client.generate_response(messages, model="openai/gpt-4o")
130
+ outline_json_text = self.extract_between_tags(outline_response, "output")
131
+
132
+ try:
133
+ self.document_outline = json.loads(outline_json_text)
134
+ return self.document_outline
135
+ except json.JSONDecodeError as e:
136
+ if attempt < max_retries - 1:
137
+ logger.warning(f"Failed to parse JSON (attempt {attempt + 1}): {e}")
138
+ logger.info("Retrying...")
139
+ else:
140
+ logger.error(f"Failed to parse JSON after {max_retries} attempts: {e}")
141
+ return None
142
+
143
+ @log_execution
144
+ def generate_content(self, title: str, content_instruction: str, section_number: str) -> str:
145
+ self.content_messages.append({
146
+ "role": "user",
147
+ "content": DOCUMENT_SECTION_PROMPT_USER.format(
148
+ section_or_subsection_title=title,
149
+ content_instruction=content_instruction
150
+ )
151
+ })
152
+ section_response = self.ai_client.generate_response(self.content_messages)
153
+ content = self.extract_between_tags(section_response, "response")
154
+ content = self.remove_duplicate_title(content, title, section_number)
155
+ self.content_messages.append({
156
+ "role": "assistant",
157
+ "content": section_response
158
+ })
159
+ return content
160
+
161
+ @log_execution
162
+ def generate_document(self, query: str) -> Dict:
163
+ self.generate_document_outline(query)
164
+
165
+ if self.document_outline is None:
166
+ raise ValueError("Failed to generate a valid document outline")
167
+
168
+ overall_objective = query
169
+ document_layout = json.dumps(self.document_outline, indent=2)
170
+
171
+ self.content_messages = [
172
+ {
173
+ "role": "system",
174
+ "content": DOCUMENT_SECTION_PROMPT_SYSTEM.format(
175
+ overall_objective=overall_objective,
176
+ document_layout=document_layout
177
+ )
178
+ }
179
+ ]
180
+
181
+ for section in self.document_outline["Document"].get("Sections", []):
182
+ section_title = section.get("Title", "")
183
+ section_number = section.get("SectionNumber", "")
184
+ content_instruction = section.get("Content", "")
185
+ logger.info(f"Generating content for section: {section_title}")
186
+ section["Content"] = self.generate_content(section_title, content_instruction, section_number)
187
+
188
+ for subsection in section.get("Subsections", []):
189
+ subsection_title = subsection.get("Title", "")
190
+ subsection_number = subsection.get("SectionNumber", "")
191
+ subsection_content_instruction = subsection.get("Content", "")
192
+ logger.info(f"Generating content for subsection: {subsection_title}")
193
+ subsection["Content"] = self.generate_content(subsection_title, subsection_content_instruction, subsection_number)
194
+
195
+ return self.document_outline
196
+
197
+
198
+ class MarkdownConverter:
199
+ @staticmethod
200
+ def slugify(text: str) -> str:
201
+ return re.sub(r'\W+', '-', text.lower())
202
+
203
+ @classmethod
204
+ def generate_toc(cls, sections: List[Dict]) -> str:
205
+ toc = "<div style='page-break-before: always;'></div>\n\n"
206
+ toc += "<h2 style='color: #2c3e50; text-align: center;'>Table of Contents</h2>\n\n"
207
+ toc += "<nav style='background-color: #f8f9fa; padding: 20px; border-radius: 5px; line-height: 1.6;'>\n\n"
208
+ for section in sections:
209
+ section_number = section['SectionNumber']
210
+ section_title = section['Title']
211
+ toc += f"<p><a href='#{cls.slugify(section_title)}' style='color: #3498db; text-decoration: none;'>{section_number}. {section_title}</a></p>\n\n"
212
+
213
+ for subsection in section.get('Subsections', []):
214
+ subsection_number = subsection['SectionNumber']
215
+ subsection_title = subsection['Title']
216
+ toc += f"<p style='margin-left: 20px;'><a href='#{cls.slugify(subsection_title)}' style='color: #2980b9; text-decoration: none;'>{subsection_number} {subsection_title}</a></p>\n\n"
217
+
218
+ toc += "</nav>\n\n"
219
+ return toc
220
+
221
+ @classmethod
222
+ def convert_to_markdown(cls, document: Dict) -> str:
223
+ # First page with centered content
224
+ markdown = "<div style='text-align: center; padding-top: 33vh;'>\n\n"
225
+ markdown += f"<h1 style='color: #2c3e50; border-bottom: 2px solid #3498db; padding-bottom: 10px; display: inline-block;'>{document['Title']}</h1>\n\n"
226
+ markdown += f"<p style='color: #7f8c8d;'><em>By {document['Author']}</em></p>\n\n"
227
+ markdown += f"<p style='color: #95a5a6;'>Version {document['Version']} | {document['Date']}</p>\n\n"
228
+ markdown += "</div>\n\n"
229
+
230
+ # Table of Contents on the second page
231
+ markdown += cls.generate_toc(document['Sections'])
232
+
233
+ # Main content
234
+ markdown += "<div style='max-width: 800px; margin: 0 auto; font-family: \"Segoe UI\", Arial, sans-serif; line-height: 1.6;'>\n\n"
235
+
236
+ for section in document['Sections']:
237
+ markdown += "<div style='page-break-before: always;'></div>\n\n"
238
+ section_number = section['SectionNumber']
239
+ section_title = section['Title']
240
+ markdown += f"<h2 id='{cls.slugify(section_title)}' style='color: #2c3e50; border-bottom: 1px solid #bdc3c7; padding-bottom: 5px;'>{section_number}. {section_title}</h2>\n\n"
241
+ markdown += f"<div style='color: #34495e; margin-bottom: 20px;'>\n\n{section['Content']}\n\n</div>\n\n"
242
+
243
+ for subsection in section.get('Subsections', []):
244
+ subsection_number = subsection['SectionNumber']
245
+ subsection_title = subsection['Title']
246
+ markdown += f"<h3 id='{cls.slugify(subsection_title)}' style='color: #34495e;'>{subsection_number} {subsection_title}</h3>\n\n"
247
+ markdown += f"<div style='color: #34495e; margin-bottom: 20px;'>\n\n{subsection['Content']}\n\n</div>\n\n"
248
+
249
+ markdown += "</div>"
250
+ return markdown
251
+
252
+
253
+ router = APIRouter()
254
+
255
+ class DocumentRequest(BaseModel):
256
+ query: str
257
+
258
+ class DocumentResponse(BaseModel):
259
+ json_document: Dict
260
+ markdown_document: str
261
+
262
+ @router.post("/generate-document", response_model=DocumentResponse)
263
+ async def generate_document_endpoint(request: DocumentRequest):
264
+ ai_client = AIClient()
265
+ document_generator = DocumentGenerator(ai_client)
266
+
267
+ try:
268
+ # Generate the document
269
+ json_document = document_generator.generate_document(request.query)
270
+
271
+ # Convert to Markdown
272
+ markdown_document = MarkdownConverter.convert_to_markdown(json_document["Document"])
273
+
274
+ return DocumentResponse(
275
+ json_document=json_document,
276
+ markdown_document=markdown_document
277
+ )
278
+ except Exception as e:
279
+ raise HTTPException(status_code=500, detail=str(e))