🔍 Code Extractor

function export_to_word

Maturity: 46

Flask route handler that exports a chat conversation to a formatted Microsoft Word (.docx) document with styled headings, timestamps, and references.

File:
/tf/active/vicechatdev/docchat/app.py
Lines:
1758 - 1834
Complexity:
moderate

Purpose

This function provides an API endpoint to export chat conversation history between a user and an AI assistant into a professionally formatted Word document. It creates a document with a centered title, export timestamp, color-coded role headings (blue for user, green for assistant), message content, and any associated references. The document is generated in-memory and returned as a downloadable file attachment.

Source Code

def export_to_word():
    """Export chat conversation to Word document"""
    try:
        from docx import Document
        from docx.shared import Inches, Pt, RGBColor
        from docx.enum.text import WD_ALIGN_PARAGRAPH
        from io import BytesIO
        
        data = request.get_json()
        conversation = data.get('conversation', [])
        
        if not conversation:
            return jsonify({'error': 'No conversation to export'}), 400
        
        # Create document
        doc = Document()
        
        # Add title
        title = doc.add_heading('DocChat Conversation History', 0)
        title.alignment = WD_ALIGN_PARAGRAPH.CENTER
        
        # Add export date
        date_para = doc.add_paragraph()
        date_para.alignment = WD_ALIGN_PARAGRAPH.CENTER
        date_run = date_para.add_run(f'Exported on {datetime.now().strftime("%B %d, %Y at %H:%M")}')
        date_run.font.size = Pt(10)
        date_run.font.color.rgb = RGBColor(128, 128, 128)
        
        doc.add_paragraph()  # Spacer
        
        # Add conversation
        for msg in conversation:
            role = msg.get('role', 'user')
            content = msg.get('content', '')
            
            # Add role heading
            if role == 'user':
                heading = doc.add_heading('You', level=2)
                heading.runs[0].font.color.rgb = RGBColor(37, 99, 235)  # Blue
            else:
                heading = doc.add_heading('Assistant', level=2)
                heading.runs[0].font.color.rgb = RGBColor(16, 185, 129)  # Green
            
            # Add content
            para = doc.add_paragraph(content)
            
            # Add references if present
            if role == 'assistant' and 'references' in msg and msg['references']:
                doc.add_paragraph()
                ref_heading = doc.add_paragraph()
                ref_heading.add_run('References:').bold = True
                ref_heading.runs[0].font.size = Pt(10)
                
                for i, ref in enumerate(msg['references'], 1):
                    ref_para = doc.add_paragraph(style='List Number')
                    ref_para.add_run(ref.get('file_name', 'Unknown document')).font.size = Pt(9)
            
            doc.add_paragraph()  # Spacer between messages
        
        # Save to BytesIO
        file_stream = BytesIO()
        doc.save(file_stream)
        file_stream.seek(0)
        
        return send_file(
            file_stream,
            mimetype='application/vnd.openxmlformats-officedocument.wordprocessingml.document',
            as_attachment=True,
            download_name=f'chat-export-{datetime.now().strftime("%Y%m%d")}.docx'
        )
        
    except ImportError:
        logger.error("python-docx not installed")
        return jsonify({'error': 'Word export requires python-docx library'}), 500
    except Exception as e:
        logger.error(f"Error exporting to Word: {e}")
        return jsonify({'error': str(e)}), 500

Return Value

Returns a Flask Response object containing either: (1) A send_file response with the Word document as an attachment (mimetype: application/vnd.openxmlformats-officedocument.wordprocessingml.document) with filename format 'chat-export-YYYYMMDD.docx', or (2) A JSON error response with appropriate HTTP status code (400 for empty conversation, 500 for import errors or other exceptions) containing an 'error' key with error message string.

Dependencies

  • flask
  • python-docx
  • logging
  • datetime
  • io

Required Imports

from flask import request, jsonify, send_file
from datetime import datetime
import logging

Conditional/Optional Imports

These imports are only needed under specific conditions:

from docx import Document

Condition: Required for Word document creation - imported lazily inside function

Required (conditional)
from docx.shared import Inches, Pt, RGBColor

Condition: Required for Word document formatting - imported lazily inside function

Required (conditional)
from docx.enum.text import WD_ALIGN_PARAGRAPH

Condition: Required for text alignment in Word document - imported lazily inside function

Required (conditional)
from io import BytesIO

Condition: Required for in-memory file handling - imported lazily inside function

Required (conditional)

Usage Example

# Client-side usage (JavaScript fetch example)
const conversation = [
  { role: 'user', content: 'What is machine learning?' },
  { 
    role: 'assistant', 
    content: 'Machine learning is a subset of AI...', 
    references: [{ file_name: 'ml_guide.pdf' }] 
  }
];

fetch('/api/export/word', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ conversation: conversation })
})
.then(response => response.blob())
.then(blob => {
  const url = window.URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = 'chat-export.docx';
  a.click();
});

Best Practices

  • Ensure python-docx is installed before deploying this endpoint, or handle ImportError gracefully
  • The conversation array should be validated on the client side before sending to avoid empty exports
  • Consider adding file size limits for very long conversations to prevent memory issues
  • The function uses lazy imports for docx libraries - this is good for optional features but may cause first-request delays
  • Error logging is implemented but consider adding more detailed logging for debugging export issues
  • The download filename includes only the date (YYYYMMDD) - consider adding time or unique identifiers for multiple exports per day
  • References are only displayed for assistant messages - ensure this matches your application's requirements
  • The function requires authentication via login_required decorator - ensure session management is properly configured

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function export_document 74.5% similar

    Flask route handler that exports a document in either DOCX or PDF format, verifying user ownership and document access before generating the export file.

    From: /tf/active/vicechatdev/vice_ai/new_app.py
  • function export_to_pdf_v1 72.6% similar

    Flask route handler that exports a chat conversation to a PDF file with formatted messages, roles, and references using the reportlab library.

    From: /tf/active/vicechatdev/docchat/app.py
  • function api_export_document 67.2% similar

    Flask API endpoint that exports a document in either DOCX or PDF format, with authentication and authorization checks.

    From: /tf/active/vicechatdev/vice_ai/complex_app.py
  • function export_report 65.5% similar

    Flask route handler that exports an analysis report for a given session in either PDF or Word format, retrieving session data and generating a downloadable file.

    From: /tf/active/vicechatdev/full_smartstat/app.py
  • function api_chat_upload_document 65.0% similar

    Flask API endpoint that handles document upload for chat context, processes the document to extract text content, and stores it for later retrieval in chat sessions.

    From: /tf/active/vicechatdev/vice_ai/complex_app.py
← Back to Browse