-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathapi.py
More file actions
568 lines (476 loc) · 17.1 KB
/
api.py
File metadata and controls
568 lines (476 loc) · 17.1 KB
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
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
"""
OpenBlog Neo - FastAPI Application
RESTful API wrapper for the blog generation pipeline.
Usage:
uvicorn api:app --reload --port 8000
API Docs:
- Swagger UI: http://localhost:8000/docs
- ReDoc: http://localhost:8000/redoc
- OpenAPI JSON: http://localhost:8000/openapi.json
"""
import asyncio
import re
import threading
import uuid
from datetime import datetime
from enum import Enum
from pathlib import Path
from typing import Dict, List, Optional
from urllib.parse import unquote
from fastapi import FastAPI, HTTPException, BackgroundTasks, Query
from fastapi.responses import FileResponse, JSONResponse
from pydantic import BaseModel, Field, HttpUrl, field_validator
# Import pipeline
from run_pipeline import run_pipeline, process_single_article
# =============================================================================
# Pydantic Models for API
# =============================================================================
class JobStatus(str, Enum):
"""Job status enumeration."""
PENDING = "pending"
RUNNING = "running"
COMPLETED = "completed"
FAILED = "failed"
# Valid export formats (whitelist for security)
VALID_EXPORT_FORMATS = {"html", "markdown", "json", "csv", "xlsx", "pdf"}
class PipelineRequest(BaseModel):
"""Request model for starting a pipeline job."""
keywords: List[str] = Field(
...,
min_length=1,
max_length=20,
description="List of keywords to generate articles for (1-20)",
json_schema_extra={"example": ["AI in healthcare", "Machine learning basics"]}
)
company_url: HttpUrl = Field(
...,
description="Company website URL for context",
json_schema_extra={"example": "https://example.com"}
)
language: str = Field(
default="en",
max_length=10,
pattern=r"^[a-z]{2}(-[A-Z]{2})?$",
description="Target language code (ISO 639-1)",
json_schema_extra={"example": "en"}
)
market: str = Field(
default="US",
max_length=10,
pattern=r"^[A-Z]{2,3}$",
description="Target market code",
json_schema_extra={"example": "US"}
)
skip_images: bool = Field(
default=False,
description="Skip image generation to speed up processing"
)
max_parallel: Optional[int] = Field(
default=None,
ge=1,
le=10,
description="Max concurrent articles (1-10, None = unlimited)"
)
export_formats: List[str] = Field(
default=["html", "json"],
description="Export formats: html, markdown, json, csv, xlsx, pdf"
)
@field_validator("keywords")
@classmethod
def validate_keywords(cls, v: List[str]) -> List[str]:
"""Validate keywords are non-empty strings."""
validated = [kw.strip() for kw in v if kw and kw.strip()]
if not validated:
raise ValueError("At least one non-empty keyword is required")
if len(validated) > 20:
raise ValueError("Maximum 20 keywords allowed")
return validated
@field_validator("export_formats")
@classmethod
def validate_export_formats(cls, v: List[str]) -> List[str]:
"""Validate export formats against whitelist."""
invalid = set(v) - VALID_EXPORT_FORMATS
if invalid:
raise ValueError(f"Invalid export formats: {invalid}. Valid: {VALID_EXPORT_FORMATS}")
return v
class JobResponse(BaseModel):
"""Response model for job creation."""
job_id: str = Field(..., description="Unique job identifier")
status: JobStatus = Field(..., description="Current job status")
message: str = Field(..., description="Status message")
created_at: str = Field(..., description="Job creation timestamp")
class JobStatusResponse(BaseModel):
"""Response model for job status check."""
job_id: str
status: JobStatus
progress: Optional[Dict] = Field(None, description="Progress details")
result: Optional[Dict] = Field(None, description="Pipeline result (when completed)")
error: Optional[str] = Field(None, description="Error message (when failed)")
created_at: str
updated_at: str
class ArticlePreviewResponse(BaseModel):
"""Response model for article preview."""
job_id: str
keyword: str
headline: Optional[str] = None
meta_description: Optional[str] = None
word_count: Optional[int] = None
status: str
class HealthResponse(BaseModel):
"""Health check response."""
status: str = "healthy"
version: str = "1.0.0"
timestamp: str
# =============================================================================
# In-Memory Job Store (replace with Redis/DB in production)
# =============================================================================
class JobStore:
"""Thread-safe in-memory job store."""
def __init__(self):
self._jobs: Dict[str, dict] = {}
self._lock = threading.Lock()
def create(self, job_id: str, request: PipelineRequest) -> dict:
job = {
"job_id": job_id,
"status": JobStatus.PENDING,
"request": request.model_dump(),
"progress": {"articles_completed": 0, "articles_total": len(request.keywords)},
"result": None,
"error": None,
"created_at": datetime.utcnow().isoformat(),
"updated_at": datetime.utcnow().isoformat(),
}
with self._lock:
self._jobs[job_id] = job
return job
def get(self, job_id: str) -> Optional[dict]:
with self._lock:
return self._jobs.get(job_id)
def update(self, job_id: str, **kwargs) -> Optional[dict]:
with self._lock:
if job_id in self._jobs:
self._jobs[job_id].update(kwargs)
self._jobs[job_id]["updated_at"] = datetime.utcnow().isoformat()
return self._jobs[job_id]
return None
def list_all(self, limit: int = 50) -> List[dict]:
with self._lock:
jobs = sorted(
self._jobs.values(),
key=lambda x: x["created_at"],
reverse=True
)
return jobs[:limit]
def delete(self, job_id: str) -> bool:
with self._lock:
if job_id in self._jobs:
del self._jobs[job_id]
return True
return False
# Global job store
job_store = JobStore()
# =============================================================================
# FastAPI Application
# =============================================================================
app = FastAPI(
title="OpenBlog Neo API",
description="""
## AI-Powered Blog Generation Pipeline
OpenBlog Neo generates high-quality, SEO-optimized blog articles using Google's Gemini AI.
### Pipeline Stages
1. **Stage 1: Set Context** - Analyze company website, extract context
2. **Stage 2: Blog Generation** - Generate article content + images
3. **Stage 3: Quality Check** - Apply quality fixes
4. **Stage 4: URL Verification** - Validate and fix dead links
5. **Stage 5: Internal Links** - Add internal linking
### Features
- 🚀 Parallel article processing
- 🖼️ AI-generated images (optional)
- 📊 Multiple export formats (HTML, Markdown, JSON, CSV, XLSX, PDF)
- 🔗 Automatic internal linking
- ✅ URL verification and replacement
""",
version="1.0.0",
docs_url="/docs",
redoc_url="/redoc",
openapi_url="/openapi.json",
contact={
"name": "OpenBlog Neo",
"url": "https://github.com/federicodeponte/openblog",
},
license_info={
"name": "MIT",
},
)
# =============================================================================
# Background Task Runner
# =============================================================================
async def run_pipeline_job(job_id: str, request: PipelineRequest):
"""Background task to run the pipeline."""
try:
job_store.update(job_id, status=JobStatus.RUNNING)
# Create output directory
output_dir = Path(f"output/api_jobs/{job_id}")
output_dir.mkdir(parents=True, exist_ok=True)
# Run pipeline
result = await run_pipeline(
keywords=request.keywords,
company_url=str(request.company_url),
language=request.language,
market=request.market,
skip_images=request.skip_images,
max_parallel=request.max_parallel,
output_dir=output_dir,
export_formats=request.export_formats,
)
job_store.update(
job_id,
status=JobStatus.COMPLETED,
result=result,
progress={
"articles_completed": result["articles_successful"],
"articles_total": result["articles_total"],
"articles_failed": result["articles_failed"],
}
)
except Exception as e:
job_store.update(
job_id,
status=JobStatus.FAILED,
error=str(e)
)
# =============================================================================
# API Endpoints
# =============================================================================
@app.get(
"/",
response_model=HealthResponse,
tags=["Health"],
summary="Health check",
)
async def health_check():
"""Check API health status."""
return HealthResponse(
status="healthy",
version="1.0.0",
timestamp=datetime.utcnow().isoformat(),
)
@app.get(
"/health",
response_model=HealthResponse,
tags=["Health"],
summary="Health check (alias)",
)
async def health():
"""Health check endpoint (alias for root)."""
return await health_check()
@app.post(
"/api/v1/jobs",
response_model=JobResponse,
status_code=202,
tags=["Jobs"],
summary="Start a new pipeline job",
)
async def create_job(
request: PipelineRequest,
background_tasks: BackgroundTasks,
):
"""
Start a new blog generation pipeline job.
The job runs asynchronously in the background. Use the returned `job_id`
to check status via `GET /api/v1/jobs/{job_id}`.
**Example request:**
```json
{
"keywords": ["AI in healthcare", "Machine learning basics"],
"company_url": "https://example.com",
"language": "en",
"market": "US",
"skip_images": false,
"export_formats": ["html", "json"]
}
```
"""
job_id = str(uuid.uuid4())
job = job_store.create(job_id, request)
# Start background task
background_tasks.add_task(run_pipeline_job, job_id, request)
return JobResponse(
job_id=job_id,
status=JobStatus.PENDING,
message=f"Job created. Processing {len(request.keywords)} article(s).",
created_at=job["created_at"],
)
@app.get(
"/api/v1/jobs",
response_model=List[JobStatusResponse],
tags=["Jobs"],
summary="List all jobs",
)
async def list_jobs(
limit: int = Query(default=50, ge=1, le=100, description="Max jobs to return"),
):
"""List all pipeline jobs, sorted by creation time (newest first)."""
jobs = job_store.list_all(limit=limit)
return [
JobStatusResponse(
job_id=job["job_id"],
status=job["status"],
progress=job.get("progress"),
result=None, # Don't include full result in list view
error=job.get("error"),
created_at=job["created_at"],
updated_at=job["updated_at"],
)
for job in jobs
]
@app.get(
"/api/v1/jobs/{job_id}",
response_model=JobStatusResponse,
tags=["Jobs"],
summary="Get job status",
)
async def get_job(job_id: str):
"""
Get the status and result of a pipeline job.
Returns full result when job is completed.
"""
job = job_store.get(job_id)
if not job:
raise HTTPException(status_code=404, detail=f"Job {job_id} not found")
return JobStatusResponse(
job_id=job["job_id"],
status=job["status"],
progress=job.get("progress"),
result=job.get("result"),
error=job.get("error"),
created_at=job["created_at"],
updated_at=job["updated_at"],
)
@app.delete(
"/api/v1/jobs/{job_id}",
status_code=204,
tags=["Jobs"],
summary="Delete a job",
)
async def delete_job(job_id: str):
"""Delete a job and its results."""
if not job_store.delete(job_id):
raise HTTPException(status_code=404, detail=f"Job {job_id} not found")
return None
@app.get(
"/api/v1/jobs/{job_id}/articles",
response_model=List[ArticlePreviewResponse],
tags=["Articles"],
summary="List articles for a job",
)
async def list_job_articles(job_id: str):
"""Get a preview of all articles generated by a job."""
job = job_store.get(job_id)
if not job:
raise HTTPException(status_code=404, detail=f"Job {job_id} not found")
if job["status"] != JobStatus.COMPLETED:
return [
ArticlePreviewResponse(
job_id=job_id,
keyword=kw,
status="pending" if job["status"] == JobStatus.PENDING else "processing",
)
for kw in job["request"]["keywords"]
]
result = job.get("result", {})
articles = []
for article_result in result.get("results", []):
article = article_result.get("article", {})
articles.append(ArticlePreviewResponse(
job_id=job_id,
keyword=article_result.get("keyword", ""),
headline=article.get("Headline") if article else None,
meta_description=article.get("Meta_Description") if article else None,
word_count=article.get("Word_Count") if article else None,
status="completed" if article else "failed",
))
return articles
def _sanitize_path_component(value: str) -> str:
"""Sanitize a path component to prevent path traversal attacks."""
# URL decode first
decoded = unquote(value)
# Remove any path traversal attempts
sanitized = re.sub(r'[./\\]', '', decoded)
# Limit length
return sanitized[:200]
@app.get(
"/api/v1/jobs/{job_id}/articles/{keyword}/html",
tags=["Articles"],
summary="Get article HTML",
)
async def get_article_html(job_id: str, keyword: str):
"""Get the rendered HTML for a specific article."""
# Validate job_id is a valid UUID to prevent injection
try:
uuid.UUID(job_id)
except ValueError:
raise HTTPException(status_code=400, detail="Invalid job_id format")
job = job_store.get(job_id)
if not job:
raise HTTPException(status_code=404, detail=f"Job {job_id} not found")
if job["status"] != JobStatus.COMPLETED:
raise HTTPException(status_code=400, detail="Job not completed")
# Sanitize keyword to prevent path traversal
safe_keyword = unquote(keyword)
result = job.get("result", {})
for article_result in result.get("results", []):
if article_result.get("keyword") == safe_keyword:
exported = article_result.get("exported_files", {})
html_path = exported.get("html")
if html_path:
file_path = Path(html_path).resolve()
# Ensure file is within allowed output directory
allowed_base = Path("output").resolve()
if not str(file_path).startswith(str(allowed_base)):
raise HTTPException(status_code=403, detail="Access denied")
if file_path.exists():
return FileResponse(
str(file_path),
media_type="text/html",
filename=f"{_sanitize_path_component(article_result.get('slug', keyword))}.html"
)
raise HTTPException(status_code=404, detail="HTML file not found")
raise HTTPException(status_code=404, detail=f"Article '{safe_keyword}' not found")
@app.post(
"/api/v1/generate",
tags=["Sync"],
summary="Generate article (synchronous)",
response_class=JSONResponse,
)
async def generate_sync(request: PipelineRequest):
"""
Generate articles synchronously (blocking).
**Warning:** This endpoint blocks until all articles are generated.
For large batches, use the async job endpoint instead.
Returns the full pipeline result directly.
"""
if len(request.keywords) > 3:
raise HTTPException(
status_code=400,
detail="Synchronous generation limited to 3 keywords. Use /api/v1/jobs for larger batches."
)
output_dir = Path(f"output/api_sync/{datetime.utcnow().strftime('%Y%m%d_%H%M%S')}")
output_dir.mkdir(parents=True, exist_ok=True)
result = await run_pipeline(
keywords=request.keywords,
company_url=str(request.company_url),
language=request.language,
market=request.market,
skip_images=request.skip_images,
max_parallel=request.max_parallel,
output_dir=output_dir,
export_formats=request.export_formats,
)
return result
# =============================================================================
# Run with: uvicorn api:app --reload
# =============================================================================
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)