update web app cookbook
This commit is contained in:
parent
aaf69731ee
commit
92ccbea299
|
|
@ -87,8 +87,9 @@ From there, it's easy to implement popular design patterns like ([Multi-](https:
|
|||
| [Code Generator](https://github.com/The-Pocket/PocketFlow/tree/main/cookbook/pocketflow-code-generator) | ★☆☆ <sup>*Beginner*</sup> | Generate test cases, implement solutions, and iteratively improve code |
|
||||
| [MCP](https://github.com/The-Pocket/PocketFlow/tree/main/cookbook/pocketflow-mcp) | ★☆☆ <sup>*Beginner*</sup> | Agent using Model Context Protocol for numerical operations |
|
||||
| [A2A](https://github.com/The-Pocket/PocketFlow/tree/main/cookbook/pocketflow-a2a) | ★☆☆ <sup>*Beginner*</sup> | Agent wrapped with A2A protocol for inter-agent communication |
|
||||
| [Streamlit HITL](https://github.com/The-Pocket/PocketFlow/tree/main/cookbook/pocketflow-streamlit-hitl) | ★☆☆ <sup>*Beginner*</sup> | Streamlit app for human-in-the-loop image generation |
|
||||
| [FastAPI HITL](https://github.com/The-Pocket/PocketFlow/tree/main/cookbook/pocketflow-fastapi-hitl) | ★☆☆ <sup>*Beginner*</sup> | FastAPI app for async human review loop with SSE |
|
||||
| [Streamlit FSM](https://github.com/The-Pocket/PocketFlow/tree/main/cookbook/pocketflow-streamlit-fsm) | ★☆☆ <sup>*Beginner*</sup> | Streamlit app with finite state machine for HITL image generation |
|
||||
| [FastAPI WebSocket](https://github.com/The-Pocket/PocketFlow/tree/main/cookbook/pocketflow-fastapi-websocket) | ★☆☆ <sup>*Beginner*</sup> | Real-time chat interface with streaming LLM responses via WebSocket |
|
||||
| [FastAPI Background](https://github.com/The-Pocket/PocketFlow/tree/main/cookbook/pocketflow-fastapi-background) | ★☆☆ <sup>*Beginner*</sup> | FastAPI app with background jobs and real-time progress via SSE |
|
||||
| [Voice Chat](https://github.com/The-Pocket/PocketFlow/tree/main/cookbook/pocketflow-voice-chat) | ★☆☆ <sup>*Beginner*</sup> | An interactive voice chat application with VAD, STT, LLM, and TTS. |
|
||||
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -1,18 +1,24 @@
|
|||
# PocketFlow FastAPI Background Job
|
||||
# PocketFlow FastAPI Background Jobs with Real-time Progress
|
||||
|
||||
A minimal example of running PocketFlow workflows as background jobs with real-time progress updates via Server-Sent Events (SSE).
|
||||
A web application demonstrating PocketFlow workflows running as FastAPI background jobs with real-time progress updates via Server-Sent Events (SSE).
|
||||
|
||||
<p align="center">
|
||||
<img
|
||||
src="./assets/banner.png" width="800"
|
||||
/>
|
||||
</p>
|
||||
|
||||
## Features
|
||||
|
||||
- Start article generation jobs via REST API
|
||||
- Real-time granular progress updates via SSE (shows progress for each section)
|
||||
- Background processing with FastAPI
|
||||
- Simple three-step workflow: Outline → Content → Style
|
||||
- Web interface for easy job submission and monitoring
|
||||
- **Modern Web UI**: Clean interface with real-time progress visualization
|
||||
- **Background Processing**: Non-blocking article generation using FastAPI BackgroundTasks
|
||||
- **Server-Sent Events**: Real-time progress streaming without polling
|
||||
- **Granular Progress**: Section-by-section updates during content generation
|
||||
- **PocketFlow Integration**: Three-node workflow (Outline → Content → Style)
|
||||
|
||||
## Getting Started
|
||||
## How to Run
|
||||
|
||||
1. Install dependencies:
|
||||
1. Install Dependencies:
|
||||
```bash
|
||||
pip install -r requirements.txt
|
||||
```
|
||||
|
|
@ -22,53 +28,54 @@ pip install -r requirements.txt
|
|||
export OPENAI_API_KEY=your_api_key_here
|
||||
```
|
||||
|
||||
3. Run the server:
|
||||
3. Run the FastAPI Server:
|
||||
```bash
|
||||
python main.py
|
||||
```
|
||||
|
||||
## Usage
|
||||
4. Access the Web UI:
|
||||
Open your browser and navigate to `http://localhost:8000`.
|
||||
|
||||
### Web Interface (Recommended)
|
||||
5. Use the Application:
|
||||
- Enter an article topic or click suggested topics
|
||||
- Click "Generate Article" to start background processing
|
||||
- Watch real-time progress updates with step indicators
|
||||
- Copy the final article when complete
|
||||
|
||||
1. Open your browser and go to `http://localhost:8000`
|
||||
2. Enter an article topic (e.g., "AI Safety", "Climate Change")
|
||||
3. Click "Generate Article"
|
||||
4. You'll be redirected to a progress page showing real-time updates
|
||||
5. The final article will appear when generation is complete
|
||||
## How It Works
|
||||
|
||||
### API Usage
|
||||
The application uses PocketFlow to define a three-step article generation workflow. FastAPI handles web requests and manages real-time SSE communication for progress updates.
|
||||
|
||||
#### Start a Job
|
||||
```bash
|
||||
curl -X POST "http://localhost:8000/start-job" -d "topic=AI Safety" -H "Content-Type: application/x-www-form-urlencoded"
|
||||
**PocketFlow Workflow:**
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
A[Generate Outline] --> B[Write Content]
|
||||
B --> C[Apply Style]
|
||||
```
|
||||
|
||||
Response:
|
||||
```json
|
||||
{"job_id": "123e4567-e89b-12d3-a456-426614174000", "topic": "AI Safety", "status": "started"}
|
||||
```
|
||||
1. **`GenerateOutline`**: Creates structured outline with up to 3 sections
|
||||
2. **`WriteContent` (BatchNode)**: Writes content for each section individually, sending progress updates
|
||||
3. **`ApplyStyle`**: Polishes the article with conversational tone
|
||||
|
||||
#### Monitor Progress
|
||||
```bash
|
||||
curl "http://localhost:8000/progress/123e4567-e89b-12d3-a456-426614174000"
|
||||
```
|
||||
**FastAPI & SSE Integration:**
|
||||
|
||||
SSE Stream:
|
||||
```
|
||||
data: {"step": "outline", "progress": 33, "data": {"sections": ["Introduction", "Challenges", "Solutions"]}}
|
||||
data: {"step": "content", "progress": 44, "data": {"section": "Introduction", "completed_sections": 1, "total_sections": 3}}
|
||||
data: {"step": "content", "progress": 55, "data": {"section": "Challenges", "completed_sections": 2, "total_sections": 3}}
|
||||
data: {"step": "content", "progress": 66, "data": {"section": "Solutions", "completed_sections": 3, "total_sections": 3}}
|
||||
data: {"step": "content", "progress": 66, "data": {"draft_length": 1234, "status": "complete"}}
|
||||
data: {"step": "complete", "progress": 100, "data": {"final_article": "..."}}
|
||||
```
|
||||
- The `/start-job` endpoint creates a unique job, initializes an SSE queue, and schedules the workflow using `BackgroundTasks`
|
||||
- Nodes send progress updates to the job-specific `sse_queue` during execution
|
||||
- The `/progress/{job_id}` endpoint streams real-time updates to the client via Server-Sent Events
|
||||
- The web UI displays progress with animated bars, step indicators, and detailed status messages
|
||||
|
||||
**Progress Updates:**
|
||||
- 33%: Outline generation complete
|
||||
- 33-66%: Content writing (individual section updates)
|
||||
- 66-100%: Style application
|
||||
- 100%: Article ready
|
||||
|
||||
## Files
|
||||
|
||||
- `main.py` - FastAPI app with background jobs and SSE
|
||||
- `flow.py` - PocketFlow workflow definition
|
||||
- `nodes.py` - Workflow nodes (Outline, Content, Style)
|
||||
- `utils/call_llm.py` - LLM utility function
|
||||
- `static/index.html` - Main page for starting jobs
|
||||
- `static/progress.html` - Progress monitoring page with real-time updates
|
||||
- [`main.py`](./main.py): FastAPI application with background jobs and SSE endpoints
|
||||
- [`flow.py`](./flow.py): PocketFlow workflow definition connecting the three nodes
|
||||
- [`nodes.py`](./nodes.py): Workflow nodes (GenerateOutline, WriteContent BatchNode, ApplyStyle)
|
||||
- [`utils/call_llm.py`](./utils/call_llm.py): OpenAI LLM utility function
|
||||
- [`static/index.html`](./static/index.html): Modern job submission form with topic suggestions
|
||||
- [`static/progress.html`](./static/progress.html): Real-time progress monitoring with animations
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 451 KiB |
|
|
@ -18,8 +18,8 @@ active_jobs = {}
|
|||
def run_article_workflow(job_id: str, topic: str):
|
||||
"""Run the article workflow in background"""
|
||||
try:
|
||||
# Create shared store with SSE queue
|
||||
sse_queue = asyncio.Queue()
|
||||
# Get the pre-created queue from active_jobs
|
||||
sse_queue = active_jobs[job_id]
|
||||
shared = {
|
||||
"topic": topic,
|
||||
"sse_queue": sse_queue,
|
||||
|
|
@ -28,9 +28,6 @@ def run_article_workflow(job_id: str, topic: str):
|
|||
"final_article": ""
|
||||
}
|
||||
|
||||
# Store the queue for SSE access
|
||||
active_jobs[job_id] = sse_queue
|
||||
|
||||
# Run the workflow
|
||||
flow = create_article_flow()
|
||||
flow.run(shared)
|
||||
|
|
@ -46,6 +43,10 @@ async def start_job(background_tasks: BackgroundTasks, topic: str = Form(...)):
|
|||
"""Start a new article generation job"""
|
||||
job_id = str(uuid.uuid4())
|
||||
|
||||
# Create SSE queue and register job immediately
|
||||
sse_queue = asyncio.Queue()
|
||||
active_jobs[job_id] = sse_queue
|
||||
|
||||
# Start background task
|
||||
background_tasks.add_task(run_article_workflow, job_id, topic)
|
||||
|
||||
|
|
@ -62,6 +63,9 @@ async def get_progress(job_id: str):
|
|||
|
||||
sse_queue = active_jobs[job_id]
|
||||
|
||||
# Send initial connection confirmation
|
||||
yield f"data: {json.dumps({'step': 'connected', 'progress': 0, 'data': {'message': 'Connected to job progress'}})}\n\n"
|
||||
|
||||
try:
|
||||
while True:
|
||||
# Wait for next progress update
|
||||
|
|
|
|||
|
|
@ -3,120 +3,214 @@
|
|||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>PocketFlow Article Generator</title>
|
||||
<title>Article Generator</title>
|
||||
<style>
|
||||
body {
|
||||
font-family: Arial, sans-serif;
|
||||
max-width: 600px;
|
||||
margin: 50px auto;
|
||||
padding: 20px;
|
||||
background-color: #f5f5f5;
|
||||
}
|
||||
.container {
|
||||
background: white;
|
||||
padding: 30px;
|
||||
border-radius: 10px;
|
||||
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
|
||||
}
|
||||
h1 {
|
||||
color: #333;
|
||||
text-align: center;
|
||||
margin-bottom: 30px;
|
||||
}
|
||||
.form-group {
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
label {
|
||||
display: block;
|
||||
margin-bottom: 5px;
|
||||
font-weight: bold;
|
||||
color: #555;
|
||||
}
|
||||
input[type="text"] {
|
||||
width: 100%;
|
||||
padding: 12px;
|
||||
border: 2px solid #ddd;
|
||||
border-radius: 5px;
|
||||
font-size: 16px;
|
||||
* {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
input[type="text"]:focus {
|
||||
border-color: #4CAF50;
|
||||
outline: none;
|
||||
|
||||
body {
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
|
||||
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
||||
min-height: 100vh;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 20px;
|
||||
}
|
||||
button {
|
||||
background-color: #4CAF50;
|
||||
color: white;
|
||||
padding: 12px 30px;
|
||||
border: none;
|
||||
border-radius: 5px;
|
||||
cursor: pointer;
|
||||
font-size: 16px;
|
||||
|
||||
.container {
|
||||
background: white;
|
||||
border-radius: 20px;
|
||||
padding: 40px;
|
||||
box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
|
||||
max-width: 500px;
|
||||
width: 100%;
|
||||
}
|
||||
button:hover {
|
||||
background-color: #45a049;
|
||||
}
|
||||
button:disabled {
|
||||
background-color: #cccccc;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
.loading {
|
||||
text-align: center;
|
||||
color: #666;
|
||||
margin-top: 20px;
|
||||
}
|
||||
|
||||
.logo {
|
||||
font-size: 2.5rem;
|
||||
font-weight: 700;
|
||||
background: linear-gradient(135deg, #667eea, #764ba2);
|
||||
-webkit-background-clip: text;
|
||||
-webkit-text-fill-color: transparent;
|
||||
background-clip: text;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.subtitle {
|
||||
color: #6b7280;
|
||||
font-size: 1.1rem;
|
||||
margin-bottom: 40px;
|
||||
font-weight: 400;
|
||||
}
|
||||
|
||||
.form-group {
|
||||
margin-bottom: 30px;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
label {
|
||||
display: block;
|
||||
font-weight: 600;
|
||||
color: #374151;
|
||||
margin-bottom: 8px;
|
||||
font-size: 0.95rem;
|
||||
}
|
||||
|
||||
input[type="text"] {
|
||||
width: 100%;
|
||||
padding: 16px 20px;
|
||||
border: 2px solid #e5e7eb;
|
||||
border-radius: 12px;
|
||||
font-size: 1rem;
|
||||
transition: all 0.3s ease;
|
||||
background: #f9fafb;
|
||||
}
|
||||
|
||||
input[type="text"]:focus {
|
||||
outline: none;
|
||||
border-color: #667eea;
|
||||
background: white;
|
||||
box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
|
||||
}
|
||||
|
||||
.submit-btn {
|
||||
width: 100%;
|
||||
padding: 16px;
|
||||
background: linear-gradient(135deg, #667eea, #764ba2);
|
||||
color: white;
|
||||
border: none;
|
||||
border-radius: 12px;
|
||||
font-size: 1.1rem;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
transition: all 0.3s ease;
|
||||
margin-top: 10px;
|
||||
}
|
||||
|
||||
.submit-btn:hover {
|
||||
transform: translateY(-2px);
|
||||
box-shadow: 0 10px 25px rgba(102, 126, 234, 0.3);
|
||||
}
|
||||
|
||||
.submit-btn:active {
|
||||
transform: translateY(0);
|
||||
}
|
||||
|
||||
.example-topics {
|
||||
margin-top: 30px;
|
||||
padding-top: 30px;
|
||||
border-top: 1px solid #e5e7eb;
|
||||
}
|
||||
|
||||
.example-topics h3 {
|
||||
color: #6b7280;
|
||||
font-size: 0.9rem;
|
||||
font-weight: 600;
|
||||
margin-bottom: 15px;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.5px;
|
||||
}
|
||||
|
||||
.topic-tags {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.topic-tag {
|
||||
background: #f3f4f6;
|
||||
color: #6b7280;
|
||||
padding: 6px 12px;
|
||||
border-radius: 20px;
|
||||
font-size: 0.85rem;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s ease;
|
||||
border: 1px solid transparent;
|
||||
}
|
||||
|
||||
.topic-tag:hover {
|
||||
background: #e5e7eb;
|
||||
color: #374151;
|
||||
}
|
||||
|
||||
@media (max-width: 480px) {
|
||||
.container {
|
||||
padding: 30px 20px;
|
||||
}
|
||||
|
||||
.logo {
|
||||
font-size: 2rem;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<h1>🚀 Article Generator</h1>
|
||||
<form id="jobForm">
|
||||
<div class="logo">✨ Article AI</div>
|
||||
<p class="subtitle">Generate engaging articles with AI assistance</p>
|
||||
|
||||
<form id="articleForm" action="/start-job" method="post">
|
||||
<div class="form-group">
|
||||
<label for="topic">Article Topic:</label>
|
||||
<input type="text" id="topic" name="topic" placeholder="e.g., AI Safety, Climate Change, Space Exploration" required>
|
||||
<label for="topic">What would you like to write about?</label>
|
||||
<input type="text" id="topic" name="topic" placeholder="Enter your topic here..." required>
|
||||
</div>
|
||||
<button type="submit" id="submitBtn">Generate Article</button>
|
||||
|
||||
<button type="submit" class="submit-btn">Generate Article</button>
|
||||
</form>
|
||||
<div id="loading" class="loading" style="display: none;">
|
||||
Starting your article generation...
|
||||
|
||||
<div class="example-topics">
|
||||
<h3>Popular Topics</h3>
|
||||
<div class="topic-tags">
|
||||
<span class="topic-tag" onclick="setTopic('AI Safety')">AI Safety</span>
|
||||
<span class="topic-tag" onclick="setTopic('Climate Change')">Climate Change</span>
|
||||
<span class="topic-tag" onclick="setTopic('Space Exploration')">Space Exploration</span>
|
||||
<span class="topic-tag" onclick="setTopic('Renewable Energy')">Renewable Energy</span>
|
||||
<span class="topic-tag" onclick="setTopic('Mental Health')">Mental Health</span>
|
||||
<span class="topic-tag" onclick="setTopic('Future of Work')">Future of Work</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
document.getElementById('jobForm').addEventListener('submit', async function(e) {
|
||||
function setTopic(topic) {
|
||||
document.getElementById('topic').value = topic;
|
||||
}
|
||||
|
||||
document.getElementById('articleForm').addEventListener('submit', async function(e) {
|
||||
e.preventDefault();
|
||||
|
||||
const topic = document.getElementById('topic').value.trim();
|
||||
if (!topic) return;
|
||||
const submitBtn = document.querySelector('.submit-btn');
|
||||
const originalText = submitBtn.textContent;
|
||||
|
||||
// Show loading state
|
||||
document.getElementById('submitBtn').disabled = true;
|
||||
document.getElementById('loading').style.display = 'block';
|
||||
submitBtn.textContent = 'Starting...';
|
||||
submitBtn.disabled = true;
|
||||
|
||||
try {
|
||||
const formData = new FormData(this);
|
||||
const response = await fetch('/start-job', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/x-www-form-urlencoded',
|
||||
},
|
||||
body: `topic=${encodeURIComponent(topic)}`
|
||||
body: formData
|
||||
});
|
||||
|
||||
const result = await response.json();
|
||||
|
||||
if (result.job_id) {
|
||||
if (response.ok) {
|
||||
// Redirect to progress page
|
||||
window.location.href = `/progress.html?job_id=${result.job_id}&topic=${encodeURIComponent(topic)}`;
|
||||
window.location.href = `/progress.html?job_id=${result.job_id}&topic=${encodeURIComponent(result.topic)}`;
|
||||
} else {
|
||||
alert('Failed to start job');
|
||||
document.getElementById('submitBtn').disabled = false;
|
||||
document.getElementById('loading').style.display = 'none';
|
||||
throw new Error('Failed to start job');
|
||||
}
|
||||
} catch (error) {
|
||||
alert('Error starting job: ' + error.message);
|
||||
document.getElementById('submitBtn').disabled = false;
|
||||
document.getElementById('loading').style.display = 'none';
|
||||
submitBtn.textContent = originalText;
|
||||
submitBtn.disabled = false;
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
|
|
|||
|
|
@ -3,148 +3,374 @@
|
|||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Article Generation Progress</title>
|
||||
<title>Generating Article...</title>
|
||||
<style>
|
||||
body {
|
||||
font-family: Arial, sans-serif;
|
||||
max-width: 800px;
|
||||
margin: 20px auto;
|
||||
padding: 20px;
|
||||
background-color: #f5f5f5;
|
||||
* {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
|
||||
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
||||
min-height: 100vh;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 20px;
|
||||
}
|
||||
|
||||
.container {
|
||||
background: white;
|
||||
padding: 30px;
|
||||
border-radius: 10px;
|
||||
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
|
||||
}
|
||||
h1 {
|
||||
color: #333;
|
||||
border-radius: 20px;
|
||||
padding: 40px;
|
||||
box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
|
||||
max-width: 600px;
|
||||
width: 100%;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.logo {
|
||||
font-size: 2rem;
|
||||
font-weight: 700;
|
||||
background: linear-gradient(135deg, #667eea, #764ba2);
|
||||
-webkit-background-clip: text;
|
||||
-webkit-text-fill-color: transparent;
|
||||
background-clip: text;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.topic-title {
|
||||
color: #374151;
|
||||
font-size: 1.5rem;
|
||||
font-weight: 600;
|
||||
margin-bottom: 30px;
|
||||
}
|
||||
.topic {
|
||||
text-align: center;
|
||||
color: #666;
|
||||
margin-bottom: 30px;
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
.progress-container {
|
||||
margin-bottom: 30px;
|
||||
margin: 30px 0;
|
||||
}
|
||||
|
||||
.progress-bar {
|
||||
width: 100%;
|
||||
height: 20px;
|
||||
background-color: #f0f0f0;
|
||||
height: 8px;
|
||||
background: #f3f4f6;
|
||||
border-radius: 10px;
|
||||
overflow: hidden;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.progress-fill {
|
||||
height: 100%;
|
||||
background-color: #4CAF50;
|
||||
background: linear-gradient(90deg, #667eea, #764ba2);
|
||||
border-radius: 10px;
|
||||
width: 0%;
|
||||
transition: width 0.3s ease;
|
||||
transition: width 0.5s ease;
|
||||
position: relative;
|
||||
}
|
||||
.progress-text {
|
||||
text-align: center;
|
||||
margin-top: 10px;
|
||||
font-weight: bold;
|
||||
color: #333;
|
||||
}
|
||||
.step-info {
|
||||
background-color: #f8f9fa;
|
||||
padding: 15px;
|
||||
border-radius: 5px;
|
||||
margin-bottom: 20px;
|
||||
border-left: 4px solid #4CAF50;
|
||||
}
|
||||
.article-result {
|
||||
background-color: #f8f9fa;
|
||||
padding: 20px;
|
||||
border-radius: 5px;
|
||||
margin-top: 20px;
|
||||
white-space: pre-wrap;
|
||||
line-height: 1.6;
|
||||
}
|
||||
.error {
|
||||
background-color: #ffebee;
|
||||
color: #c62828;
|
||||
padding: 15px;
|
||||
border-radius: 5px;
|
||||
border-left: 4px solid #f44336;
|
||||
}
|
||||
.back-button {
|
||||
background-color: #2196F3;
|
||||
color: white;
|
||||
padding: 10px 20px;
|
||||
border: none;
|
||||
border-radius: 5px;
|
||||
cursor: pointer;
|
||||
text-decoration: none;
|
||||
display: inline-block;
|
||||
margin-top: 20px;
|
||||
}
|
||||
.back-button:hover {
|
||||
background-color: #1976D2;
|
||||
}
|
||||
.loading-dots {
|
||||
display: inline-block;
|
||||
}
|
||||
.loading-dots:after {
|
||||
|
||||
.progress-fill::after {
|
||||
content: '';
|
||||
animation: dots 1.5s steps(5, end) infinite;
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
background: linear-gradient(90deg, transparent, rgba(255,255,255,0.3), transparent);
|
||||
animation: shimmer 2s infinite;
|
||||
}
|
||||
|
||||
@keyframes shimmer {
|
||||
0% { transform: translateX(-100%); }
|
||||
100% { transform: translateX(100%); }
|
||||
}
|
||||
|
||||
.progress-text {
|
||||
color: #6b7280;
|
||||
font-size: 1rem;
|
||||
font-weight: 500;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.progress-percentage {
|
||||
color: #374151;
|
||||
font-size: 2rem;
|
||||
font-weight: 700;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.status-card {
|
||||
background: #f9fafb;
|
||||
border: 1px solid #e5e7eb;
|
||||
border-radius: 12px;
|
||||
padding: 20px;
|
||||
margin: 20px 0;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.status-title {
|
||||
color: #374151;
|
||||
font-weight: 600;
|
||||
margin-bottom: 10px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.status-content {
|
||||
color: #6b7280;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.spinner {
|
||||
display: inline-block;
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
border: 2px solid #e5e7eb;
|
||||
border-top: 2px solid #667eea;
|
||||
border-radius: 50%;
|
||||
animation: spin 1s linear infinite;
|
||||
}
|
||||
|
||||
@keyframes spin {
|
||||
0% { transform: rotate(0deg); }
|
||||
100% { transform: rotate(360deg); }
|
||||
}
|
||||
|
||||
.step-indicator {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
margin: 30px 0;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.step-indicator::before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
top: 15px;
|
||||
left: 15px;
|
||||
right: 15px;
|
||||
height: 2px;
|
||||
background: #e5e7eb;
|
||||
z-index: 1;
|
||||
}
|
||||
|
||||
.step {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
position: relative;
|
||||
z-index: 2;
|
||||
}
|
||||
|
||||
.step-circle {
|
||||
width: 30px;
|
||||
height: 30px;
|
||||
border-radius: 50%;
|
||||
background: #e5e7eb;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-weight: 600;
|
||||
font-size: 0.8rem;
|
||||
margin-bottom: 8px;
|
||||
transition: all 0.3s ease;
|
||||
}
|
||||
|
||||
.step-circle.active {
|
||||
background: linear-gradient(135deg, #667eea, #764ba2);
|
||||
color: white;
|
||||
}
|
||||
|
||||
.step-circle.completed {
|
||||
background: #10b981;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.step-label {
|
||||
font-size: 0.8rem;
|
||||
color: #6b7280;
|
||||
text-align: center;
|
||||
max-width: 80px;
|
||||
}
|
||||
|
||||
.result-section {
|
||||
display: none;
|
||||
text-align: left;
|
||||
margin-top: 30px;
|
||||
}
|
||||
|
||||
.result-section.show {
|
||||
display: block;
|
||||
}
|
||||
|
||||
.article-content {
|
||||
background: #f9fafb;
|
||||
border: 1px solid #e5e7eb;
|
||||
border-radius: 12px;
|
||||
padding: 25px;
|
||||
line-height: 1.6;
|
||||
color: #374151;
|
||||
white-space: pre-wrap;
|
||||
max-height: 400px;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.action-buttons {
|
||||
display: flex;
|
||||
gap: 15px;
|
||||
margin-top: 20px;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.btn {
|
||||
padding: 12px 24px;
|
||||
border-radius: 10px;
|
||||
font-weight: 600;
|
||||
text-decoration: none;
|
||||
transition: all 0.3s ease;
|
||||
cursor: pointer;
|
||||
border: none;
|
||||
font-size: 0.95rem;
|
||||
}
|
||||
|
||||
.btn-primary {
|
||||
background: linear-gradient(135deg, #667eea, #764ba2);
|
||||
color: white;
|
||||
}
|
||||
|
||||
.btn-primary:hover {
|
||||
transform: translateY(-2px);
|
||||
box-shadow: 0 8px 20px rgba(102, 126, 234, 0.3);
|
||||
}
|
||||
|
||||
.btn-secondary {
|
||||
background: #f3f4f6;
|
||||
color: #374151;
|
||||
border: 1px solid #e5e7eb;
|
||||
}
|
||||
|
||||
.btn-secondary:hover {
|
||||
background: #e5e7eb;
|
||||
}
|
||||
|
||||
.error-message {
|
||||
background: #fef2f2;
|
||||
border: 1px solid #fecaca;
|
||||
color: #dc2626;
|
||||
padding: 15px;
|
||||
border-radius: 10px;
|
||||
margin: 20px 0;
|
||||
}
|
||||
|
||||
@media (max-width: 480px) {
|
||||
.container {
|
||||
padding: 30px 20px;
|
||||
}
|
||||
|
||||
.step-indicator {
|
||||
margin: 20px 0;
|
||||
}
|
||||
|
||||
.step-label {
|
||||
font-size: 0.7rem;
|
||||
max-width: 60px;
|
||||
}
|
||||
|
||||
.action-buttons {
|
||||
flex-direction: column;
|
||||
}
|
||||
@keyframes dots {
|
||||
0%, 20% { content: ''; }
|
||||
40% { content: '.'; }
|
||||
60% { content: '..'; }
|
||||
80%, 100% { content: '...'; }
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<h1>📝 Generating Your Article</h1>
|
||||
<div class="topic" id="topicDisplay"></div>
|
||||
<div class="logo">✨ Article AI</div>
|
||||
<div class="topic-title" id="topicTitle">Generating your article...</div>
|
||||
|
||||
<div class="progress-container">
|
||||
<div class="progress-percentage" id="progressPercentage">0%</div>
|
||||
<div class="progress-bar">
|
||||
<div class="progress-fill" id="progressFill"></div>
|
||||
</div>
|
||||
<div class="progress-text" id="progressText">Starting<span class="loading-dots"></span></div>
|
||||
<div class="progress-text" id="progressText">Initializing...</div>
|
||||
</div>
|
||||
|
||||
<div id="stepInfo" class="step-info" style="display: none;"></div>
|
||||
<div id="errorInfo" class="error" style="display: none;"></div>
|
||||
<div id="articleResult" class="article-result" style="display: none;"></div>
|
||||
<div class="step-indicator">
|
||||
<div class="step">
|
||||
<div class="step-circle" id="step1">1</div>
|
||||
<div class="step-label">Outline</div>
|
||||
</div>
|
||||
<div class="step">
|
||||
<div class="step-circle" id="step2">2</div>
|
||||
<div class="step-label">Content</div>
|
||||
</div>
|
||||
<div class="step">
|
||||
<div class="step-circle" id="step3">3</div>
|
||||
<div class="step-label">Style</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<a href="/" class="back-button">← Generate Another Article</a>
|
||||
<div class="status-card" id="statusCard">
|
||||
<div class="status-title" id="statusTitle">
|
||||
<span class="spinner"></span>
|
||||
Getting started...
|
||||
</div>
|
||||
<div class="status-content" id="statusContent">
|
||||
Preparing to generate your article. This may take a few moments.
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="result-section" id="resultSection">
|
||||
<h3 style="margin-bottom: 15px; color: #374151;">Your Article is Ready! 🎉</h3>
|
||||
<div class="article-content" id="articleContent"></div>
|
||||
<div class="action-buttons">
|
||||
<button class="btn btn-primary" onclick="copyToClipboard()">Copy Article</button>
|
||||
<a href="/" class="btn btn-secondary">Generate Another</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="error-message" id="errorMessage" style="display: none;"></div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
// Get job_id and topic from URL parameters
|
||||
const urlParams = new URLSearchParams(window.location.search);
|
||||
const jobId = urlParams.get('job_id');
|
||||
const topic = urlParams.get('topic');
|
||||
|
||||
if (!jobId) {
|
||||
document.getElementById('errorInfo').style.display = 'block';
|
||||
document.getElementById('errorInfo').textContent = 'No job ID provided';
|
||||
} else {
|
||||
document.getElementById('topicDisplay').textContent = `Topic: ${topic || 'Unknown'}`;
|
||||
startProgressMonitoring(jobId);
|
||||
if (topic) {
|
||||
document.getElementById('topicTitle').textContent = `"${topic}"`;
|
||||
}
|
||||
|
||||
function startProgressMonitoring(jobId) {
|
||||
if (!jobId) {
|
||||
showError('No job ID provided');
|
||||
} else {
|
||||
connectToProgress();
|
||||
}
|
||||
|
||||
function connectToProgress() {
|
||||
const eventSource = new EventSource(`/progress/${jobId}`);
|
||||
|
||||
eventSource.onmessage = function(event) {
|
||||
try {
|
||||
const data = JSON.parse(event.data);
|
||||
handleProgressUpdate(data);
|
||||
} catch (error) {
|
||||
console.error('Error parsing SSE data:', error);
|
||||
}
|
||||
};
|
||||
|
||||
eventSource.onerror = function(error) {
|
||||
console.error('SSE connection error:', error);
|
||||
showError('Connection lost. Please refresh the page.');
|
||||
eventSource.close();
|
||||
};
|
||||
}
|
||||
|
||||
function handleProgressUpdate(data) {
|
||||
if (data.error) {
|
||||
showError(data.error);
|
||||
eventSource.close();
|
||||
return;
|
||||
}
|
||||
|
||||
|
|
@ -152,71 +378,103 @@
|
|||
return; // Ignore heartbeat messages
|
||||
}
|
||||
|
||||
updateProgress(data);
|
||||
const progress = data.progress || 0;
|
||||
updateProgress(progress);
|
||||
|
||||
if (data.step === 'complete') {
|
||||
showFinalResult(data.data.final_article);
|
||||
eventSource.close();
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error parsing SSE data:', error);
|
||||
}
|
||||
};
|
||||
|
||||
eventSource.onerror = function(event) {
|
||||
console.error('SSE connection error:', event);
|
||||
showError('Connection lost. Please refresh the page.');
|
||||
eventSource.close();
|
||||
};
|
||||
}
|
||||
|
||||
function updateProgress(data) {
|
||||
const progressFill = document.getElementById('progressFill');
|
||||
const progressText = document.getElementById('progressText');
|
||||
const stepInfo = document.getElementById('stepInfo');
|
||||
|
||||
// Update progress bar
|
||||
progressFill.style.width = data.progress + '%';
|
||||
|
||||
// Update progress text and step info
|
||||
switch (data.step) {
|
||||
case 'connected':
|
||||
updateStatus('🔗 Connected', 'Successfully connected to the article generation process.');
|
||||
break;
|
||||
|
||||
case 'outline':
|
||||
progressText.textContent = 'Creating outline... (33%)';
|
||||
stepInfo.style.display = 'block';
|
||||
stepInfo.innerHTML = `<strong>Step 1:</strong> Generated outline with sections: ${data.data.sections.join(', ')}`;
|
||||
break;
|
||||
case 'content':
|
||||
if (data.data.section) {
|
||||
// Individual section progress
|
||||
progressText.textContent = `Writing content... (${data.progress}%)`;
|
||||
stepInfo.innerHTML = `<strong>Step 2:</strong> Completed section "${data.data.section}" (${data.data.completed_sections}/${data.data.total_sections})`;
|
||||
updateStepIndicator(1);
|
||||
if (data.data && data.data.sections) {
|
||||
updateStatus('📝 Creating Outline', `Generated outline with ${data.data.sections.length} sections`);
|
||||
} else {
|
||||
// Final content completion
|
||||
progressText.textContent = 'Writing content... (66%)';
|
||||
stepInfo.innerHTML = `<strong>Step 2:</strong> Generated ${data.data.draft_length} characters of content`;
|
||||
updateStatus('📝 Creating Outline', 'Generating article structure and main points...');
|
||||
}
|
||||
break;
|
||||
|
||||
case 'content':
|
||||
updateStepIndicator(2);
|
||||
if (data.data && data.data.section) {
|
||||
updateStatus('✍️ Writing Content',
|
||||
`Writing section: "${data.data.section}" (${data.data.completed_sections}/${data.data.total_sections})`);
|
||||
} else {
|
||||
updateStatus('✍️ Writing Content', 'Creating detailed content for each section...');
|
||||
}
|
||||
break;
|
||||
|
||||
case 'style':
|
||||
updateStepIndicator(3);
|
||||
updateStatus('🎨 Applying Style', 'Polishing the article with engaging, conversational tone...');
|
||||
break;
|
||||
|
||||
case 'complete':
|
||||
progressText.textContent = 'Complete! (100%)';
|
||||
stepInfo.innerHTML = `<strong>Step 3:</strong> Applied conversational styling - Article ready!`;
|
||||
updateStepIndicator(3, true);
|
||||
updateProgress(100);
|
||||
updateStatus('✅ Complete!', 'Your article has been generated successfully.');
|
||||
if (data.data && data.data.final_article) {
|
||||
showResult(data.data.final_article);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
function showFinalResult(article) {
|
||||
const resultDiv = document.getElementById('articleResult');
|
||||
resultDiv.style.display = 'block';
|
||||
resultDiv.textContent = article;
|
||||
function updateProgress(percentage) {
|
||||
document.getElementById('progressPercentage').textContent = `${percentage}%`;
|
||||
document.getElementById('progressFill').style.width = `${percentage}%`;
|
||||
}
|
||||
|
||||
function showError(errorMessage) {
|
||||
const errorDiv = document.getElementById('errorInfo');
|
||||
errorDiv.style.display = 'block';
|
||||
errorDiv.textContent = `Error: ${errorMessage}`;
|
||||
function updateStatus(title, content) {
|
||||
document.getElementById('statusTitle').innerHTML = `<span class="spinner"></span> ${title}`;
|
||||
document.getElementById('statusContent').textContent = content;
|
||||
}
|
||||
|
||||
const progressText = document.getElementById('progressText');
|
||||
progressText.textContent = 'Failed';
|
||||
function updateStepIndicator(step, completed = false) {
|
||||
// Reset all steps
|
||||
for (let i = 1; i <= 3; i++) {
|
||||
const stepElement = document.getElementById(`step${i}`);
|
||||
stepElement.className = 'step-circle';
|
||||
if (i < step) {
|
||||
stepElement.classList.add('completed');
|
||||
stepElement.innerHTML = '✓';
|
||||
} else if (i === step) {
|
||||
stepElement.classList.add(completed ? 'completed' : 'active');
|
||||
stepElement.innerHTML = completed ? '✓' : i;
|
||||
} else {
|
||||
stepElement.innerHTML = i;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function showResult(article) {
|
||||
document.getElementById('statusCard').style.display = 'none';
|
||||
document.getElementById('articleContent').textContent = article;
|
||||
document.getElementById('resultSection').classList.add('show');
|
||||
}
|
||||
|
||||
function showError(message) {
|
||||
document.getElementById('errorMessage').textContent = message;
|
||||
document.getElementById('errorMessage').style.display = 'block';
|
||||
document.getElementById('statusCard').style.display = 'none';
|
||||
}
|
||||
|
||||
function copyToClipboard() {
|
||||
const article = document.getElementById('articleContent').textContent;
|
||||
navigator.clipboard.writeText(article).then(() => {
|
||||
const btn = event.target;
|
||||
const originalText = btn.textContent;
|
||||
btn.textContent = 'Copied!';
|
||||
btn.style.background = '#10b981';
|
||||
setTimeout(() => {
|
||||
btn.textContent = originalText;
|
||||
btn.style.background = '';
|
||||
}, 2000);
|
||||
}).catch(err => {
|
||||
console.error('Failed to copy: ', err);
|
||||
alert('Failed to copy to clipboard');
|
||||
});
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
|
|
|
|||
|
|
@ -1 +0,0 @@
|
|||
# Utils package for FastAPI Background Job Interface
|
||||
|
Before Width: | Height: | Size: 1.7 MiB After Width: | Height: | Size: 1.7 MiB |
|
Before Width: | Height: | Size: 2.4 MiB After Width: | Height: | Size: 2.4 MiB |
Loading…
Reference in New Issue