{
  "id": "8DYI99J1q8APXjWY",
  "meta": {
    "templateCredsSetupCompleted": true
  },
  "name": "Radiology Image to Detailed Report Converter",
  "tags": [],
  "nodes": [
    {
      "id": "89d05f4e-32c8-4ce2-aabb-26068052a70b",
      "name": "Upload Image Trigger",
      "type": "n8n-nodes-base.webhook",
      "position": [
        180,
        -120
      ],
      "parameters": {
        "path": "radiology-upload",
        "options": {},
        "httpMethod": "POST"
      },
      "typeVersion": 2
    },
    {
      "id": "395b8ea6-f7aa-4d47-a73c-22ab891674ec",
      "name": "Extract Image Data",
      "type": "n8n-nodes-base.code",
      "position": [
        400,
        -120
      ],
      "parameters": {
        "jsCode": "// Extract image and patient data from webhook\nconst data = $input.first().json;\n\nreturn [{\n  json: {\n    patient_name: data.patient_name || 'Patient',\n    patient_id: data.patient_id || 'N/A',\n    scan_type: data.scan_type || 'X-Ray',\n    body_part: data.body_part || 'Chest',\n    image_url: data.image_url,\n    image_base64: data.image_base64,\n    doctor_name: data.doctor_name || 'Dr. Smith',\n    scan_date: data.scan_date || new Date().toISOString().split('T')[0],\n    urgency: data.urgency || 'routine'\n  }\n}];"
      },
      "typeVersion": 2
    },
    {
      "id": "090ab8d4-4e1c-4c23-9fe8-f6c74b850a8a",
      "name": "Analyze Radiology Image with AI",
      "type": "n8n-nodes-base.httpRequest",
      "position": [
        620,
        -120
      ],
      "parameters": {
        "url": "https://api.openai.com/v1/chat/completions",
        "method": "POST",
        "options": {},
        "jsonBody": "={\n  \"model\": \"gpt-4-vision-preview\",\n  \"messages\": [\n    {\n      \"role\": \"system\",\n      \"content\": \"You are a radiology expert who explains medical scans in simple, patient-friendly language. Analyze the radiology image and provide: 1) What the scan shows in simple terms 2) Any notable findings 3) What this means for the patient 4) Next steps if any. Be reassuring and avoid medical jargon. Always recommend consulting with their doctor.\"\n    },\n    {\n      \"role\": \"user\",\n      \"content\": [\n        {\n          \"type\": \"text\",\n          \"text\": \"Please analyze this {{ $json.scan_type }} scan of the {{ $json.body_part }} and explain the findings in patient-friendly terms.\"\n        },\n        {\n          \"type\": \"image_url\",\n          \"image_url\": {\n            \"url\": \"{{ $json.image_base64 ? 'data:image/jpeg;base64,' + $json.image_base64 : $json.image_url }}\"\n          }\n        }\n      ]\n    }\n  ],\n  \"max_tokens\": 1000,\n  \"temperature\": 0.3\n}",
        "sendBody": true,
        "sendHeaders": true,
        "specifyBody": "json",
        "headerParameters": {
          "parameters": [
            {
              "name": "Authorization",
              "value": "Bearer {{ $credentials.openaiApi.apiKey }}"
            },
            {
              "name": "Content-Type",
              "value": "application/json"
            }
          ]
        }
      },
      "typeVersion": 4.2
    },
    {
      "id": "47095b28-484a-47ce-b450-6dd0d719d989",
      "name": "Process AI Analysis",
      "type": "n8n-nodes-base.code",
      "position": [
        840,
        -120
      ],
      "parameters": {
        "jsCode": "// Process OpenAI response and structure the report data\nconst aiResponse = $input.first().json;\nconst patientData = $('Extract Image Data').first().json;\n\nconst aiAnalysis = aiResponse.choices[0].message.content;\n\n// Structure the analysis into sections\nconst sections = aiAnalysis.split('\\n\\n');\nlet findings = '';\nlet explanation = '';\nlet nextSteps = '';\n\n// Try to parse the AI response into structured sections\nsections.forEach(section => {\n  if (section.toLowerCase().includes('findings') || section.toLowerCase().includes('shows')) {\n    findings += section + ' ';\n  } else if (section.toLowerCase().includes('means') || section.toLowerCase().includes('indicates')) {\n    explanation += section + ' ';\n  } else if (section.toLowerCase().includes('next') || section.toLowerCase().includes('recommend')) {\n    nextSteps += section + ' ';\n  }\n});\n\n// If structured parsing didn't work well, use the full response\nif (!findings && !explanation) {\n  findings = aiAnalysis.substring(0, aiAnalysis.length / 2);\n  explanation = aiAnalysis.substring(aiAnalysis.length / 2);\n}\n\nreturn [{\n  json: {\n    ...patientData,\n    ai_analysis: aiAnalysis,\n    findings: findings.trim() || 'Analysis completed',\n    explanation: explanation.trim() || 'Please consult with your doctor for detailed explanation',\n    next_steps: nextSteps.trim() || 'Follow up with your healthcare provider as recommended',\n    report_generated: new Date().toISOString(),\n    confidence_note: 'This AI analysis is for informational purposes only. Always consult your doctor for medical advice.'\n  }\n}];"
      },
      "typeVersion": 2
    },
    {
      "id": "223aebb0-5f1e-40fb-bc00-ed70a4cba515",
      "name": "Generate PDF Report",
      "type": "n8n-nodes-base.code",
      "position": [
        1060,
        -120
      ],
      "parameters": {
        "jsCode": "// Generate HTML template for PDF conversion\nconst data = $input.first().json;\n\nconst htmlReport = `\n<!DOCTYPE html>\n<html>\n<head>\n    <style>\n        body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; margin: 40px; }\n        .header { text-align: center; border-bottom: 3px solid #4CAF50; padding-bottom: 20px; margin-bottom: 30px; }\n        .logo { font-size: 24px; font-weight: bold; color: #4CAF50; }\n        .patient-info { background-color: #f8f9fa; padding: 20px; border-radius: 8px; margin: 20px 0; }\n        .section { margin: 25px 0; }\n        .section-title { font-size: 18px; font-weight: bold; color: #2c3e50; border-left: 4px solid #4CAF50; padding-left: 15px; margin-bottom: 15px; }\n        .findings { background-color: #e8f5e8; padding: 20px; border-radius: 8px; border-left: 4px solid #4CAF50; }\n        .explanation { background-color: #fff3e0; padding: 20px; border-radius: 8px; border-left: 4px solid #ff9800; }\n        .next-steps { background-color: #e3f2fd; padding: 20px; border-radius: 8px; border-left: 4px solid #2196f3; }\n        .disclaimer { background-color: #ffebee; padding: 15px; border-radius: 8px; font-size: 14px; border: 1px solid #f44336; margin-top: 30px; }\n        .footer { text-align: center; margin-top: 40px; font-size: 12px; color: #666; }\n        .date { color: #666; font-size: 14px; }\n    </style>\n</head>\n<body>\n    <div class=\"header\">\n        <div class=\"logo\">\ud83c\udfe5 Medical Imaging Report</div>\n        <h2>Patient-Friendly Radiology Report</h2>\n        <div class=\"date\">Generated: ${new Date(data.report_generated).toLocaleDateString()}</div>\n    </div>\n    \n    <div class=\"patient-info\">\n        <h3>\ud83d\udc64 Patient Information</h3>\n        <p><strong>Patient Name:</strong> ${data.patient_name}</p>\n        <p><strong>Patient ID:</strong> ${data.patient_id}</p>\n        <p><strong>Scan Type:</strong> ${data.scan_type}</p>\n        <p><strong>Body Part:</strong> ${data.body_part}</p>\n        <p><strong>Scan Date:</strong> ${data.scan_date}</p>\n        <p><strong>Ordering Doctor:</strong> ${data.doctor_name}</p>\n    </div>\n    \n    <div class=\"section\">\n        <div class=\"section-title\">\ud83d\udd0d What We Found</div>\n        <div class=\"findings\">\n            <p>${data.findings}</p>\n        </div>\n    </div>\n    \n    <div class=\"section\">\n        <div class=\"section-title\">\ud83d\udca1 What This Means</div>\n        <div class=\"explanation\">\n            <p>${data.explanation}</p>\n        </div>\n    </div>\n    \n    <div class=\"section\">\n        <div class=\"section-title\">\ud83d\udccb Next Steps</div>\n        <div class=\"next-steps\">\n            <p>${data.next_steps}</p>\n        </div>\n    </div>\n    \n    <div class=\"disclaimer\">\n        <h4>\u26a0\ufe0f Important Disclaimer</h4>\n        <p>${data.confidence_note}</p>\n        <p>This report is generated by AI technology to help you understand your scan results. It should not replace professional medical consultation. Please discuss these findings with your healthcare provider.</p>\n    </div>\n    \n    <div class=\"footer\">\n        <p>Report generated by AI-Powered Radiology Assistant</p>\n        <p>For medical questions, contact your healthcare provider</p>\n    </div>\n</body>\n</html>\n`;\n\nreturn [{\n  json: {\n    ...data,\n    html_report: htmlReport,\n    report_filename: `Radiology_Report_${data.patient_name.replace(/\\s+/g, '_')}_${data.scan_date}.pdf`\n  }\n}];"
      },
      "typeVersion": 2
    },
    {
      "id": "4deecdc3-3b5a-4987-a62d-43f7034431c2",
      "name": "Convert to PDF",
      "type": "n8n-nodes-base.httpRequest",
      "position": [
        1280,
        -120
      ],
      "parameters": {
        "url": "https://api.html-css-to-pdf.com/v1/generate",
        "method": "POST",
        "options": {},
        "jsonBody": "={\n  \"html\": \"{{ $json.html_report }}\",\n  \"options\": {\n    \"format\": \"A4\",\n    \"margin\": {\n      \"top\": \"20mm\",\n      \"right\": \"15mm\",\n      \"bottom\": \"20mm\",\n      \"left\": \"15mm\"\n    },\n    \"displayHeaderFooter\": false\n  }\n}",
        "sendBody": true,
        "sendHeaders": true,
        "specifyBody": "json",
        "headerParameters": {
          "parameters": [
            {
              "name": "Authorization",
              "value": "Bearer {{ $credentials.pdfApi.apiKey }}"
            },
            {
              "name": "Content-Type",
              "value": "application/json"
            }
          ]
        }
      },
      "typeVersion": 4.2
    },
    {
      "id": "581fef88-4096-4193-b71e-9893fd684d1f",
      "name": "Save Report to Database",
      "type": "n8n-nodes-base.googleSheets",
      "position": [
        1720,
        -120
      ],
      "parameters": {
        "columns": {
          "value": {
            "pdf_url": "={{ $json.download_url }}",
            "body_part": "={{ $('Generate PDF Report').first().json.body_part }}",
            "scan_date": "={{ $('Generate PDF Report').first().json.scan_date }}",
            "scan_type": "={{ $('Generate PDF Report').first().json.scan_type }}",
            "timestamp": "={{ $now.toISO() }}",
            "patient_id": "={{ $('Generate PDF Report').first().json.patient_id }}",
            "patient_name": "={{ $('Generate PDF Report').first().json.patient_name }}",
            "report_status": "Generated Successfully"
          },
          "schema": [
            {
              "id": "timestamp",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "Timestamp",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "patient_name",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "Patient Name",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "patient_id",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "Patient ID",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "scan_type",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "Scan Type",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "body_part",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "Body Part",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "scan_date",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "Scan Date",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "report_status",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "Report Status",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "pdf_url",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "PDF URL",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            }
          ],
          "mappingMode": "defineBelow"
        },
        "options": {},
        "operation": "append",
        "sheetName": {
          "__rl": true,
          "mode": "list",
          "value": "Reports_Log",
          "cachedResultName": "Reports Log"
        },
        "documentId": {
          "__rl": true,
          "mode": "list",
          "value": "YOUR_REPORTS_SHEET_ID",
          "cachedResultName": "Radiology Reports"
        },
        "authentication": "serviceAccount"
      },
      "credentials": {
        "googleApi": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 4.6
    },
    {
      "id": "f2025595-5b43-48dd-a586-351054d7d6d3",
      "name": "Email Report to Patient",
      "type": "n8n-nodes-base.gmail",
      "position": [
        1940,
        -120
      ],
      "parameters": {
        "sendTo": "={{ $('Extract Image Data').first().json.patient_email || 'patient@example.com' }}",
        "message": "=<h2>Your Radiology Report is Ready! \ud83c\udfe5</h2><br><br>Dear {{ $('Generate PDF Report').first().json.patient_name }},<br><br>Your {{ $('Generate PDF Report').first().json.scan_type }} scan report is now available. This patient-friendly report explains your scan results in easy-to-understand language.<br><br><strong>Scan Details:</strong><br>\u2022 Type: {{ $('Generate PDF Report').first().json.scan_type }}<br>\u2022 Body Part: {{ $('Generate PDF Report').first().json.body_part }}<br>\u2022 Date: {{ $('Generate PDF Report').first().json.scan_date }}<br><br><strong>Key Findings:</strong><br>{{ $('Process AI Analysis').first().json.findings }}<br><br>\ud83d\udcce <strong>Your complete report is attached as a PDF.</strong><br><br>\u2757 <strong>Important:</strong> This AI-generated report is for informational purposes. Please discuss these results with {{ $('Generate PDF Report').first().json.doctor_name }} or your healthcare provider.<br><br>If you have any questions, please contact your healthcare provider.<br><br>Best regards,<br>Medical Imaging Department",
        "options": {},
        "subject": "\ud83c\udfe5 Your Radiology Report is Ready - {{ $('Generate PDF Report').first().json.patient_name }}"
      },
      "credentials": {
        "gmailOAuth2": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 2.1
    },
    {
      "id": "badb5a4d-2b43-47a9-b1c8-12db0f4e7a5b",
      "name": "Return Response",
      "type": "n8n-nodes-base.code",
      "position": [
        2160,
        -120
      ],
      "parameters": {
        "jsCode": "// Return success response with report details\nconst reportData = $('Generate PDF Report').first().json;\nconst pdfData = $('Convert to PDF').first().json;\n\nreturn [{\n  json: {\n    status: 'success',\n    message: 'Radiology report generated successfully',\n    patient_name: reportData.patient_name,\n    scan_type: reportData.scan_type,\n    body_part: reportData.body_part,\n    report_generated: reportData.report_generated,\n    pdf_url: pdfData.download_url,\n    findings_summary: reportData.findings.substring(0, 200) + '...',\n    next_steps: reportData.next_steps,\n    disclaimer: reportData.confidence_note\n  }\n}];"
      },
      "typeVersion": 2
    },
    {
      "id": "7b5c9eb3-37c2-43f8-a0f1-f95554b6c9ef",
      "name": "Workflow Overview",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        340,
        -600
      ],
      "parameters": {
        "width": 400,
        "height": 340,
        "content": "## \ud83c\udfe5 Radiology Image to Report Converter\n\n### Features:\n\u2022 AI-powered image analysis\n\u2022 Patient-friendly language\n\u2022 Professional PDF reports\n\u2022 Email delivery\n\u2022 Database logging\n\u2022 Webhook triggered\n\n### How to use:\nSend POST to webhook with image data"
      },
      "typeVersion": 1
    },
    {
      "id": "925f5199-dbac-427b-a896-228e864f524b",
      "name": "Required Setup",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        1080,
        -540
      ],
      "parameters": {
        "color": 3,
        "width": 300,
        "height": 200,
        "content": "## \u2699\ufe0f Setup Required\n\n1. OpenAI API credentials (GPT-4 Vision)\n2. PDF conversion service\n3. Gmail account for sending\n4. Google Sheets for logging\n5. Update YOUR_REPORTS_SHEET_ID"
      },
      "typeVersion": 1
    },
    {
      "id": "e5159a65-1ba2-4bc0-99dc-d89cef310932",
      "name": "Wait For PDF",
      "type": "n8n-nodes-base.wait",
      "position": [
        1500,
        -120
      ],
      "parameters": {},
      "typeVersion": 1.1
    }
  ],
  "active": false,
  "settings": {
    "executionOrder": "v1"
  },
  "versionId": "307925d2-0fa2-459f-a60c-af7b0ae0bbb3",
  "connections": {
    "Wait For PDF": {
      "main": [
        [
          {
            "node": "Save Report to Database",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Convert to PDF": {
      "main": [
        [
          {
            "node": "Wait For PDF",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Extract Image Data": {
      "main": [
        [
          {
            "node": "Analyze Radiology Image with AI",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Generate PDF Report": {
      "main": [
        [
          {
            "node": "Convert to PDF",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Process AI Analysis": {
      "main": [
        [
          {
            "node": "Generate PDF Report",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Upload Image Trigger": {
      "main": [
        [
          {
            "node": "Extract Image Data",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Email Report to Patient": {
      "main": [
        [
          {
            "node": "Return Response",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Save Report to Database": {
      "main": [
        [
          {
            "node": "Email Report to Patient",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Analyze Radiology Image with AI": {
      "main": [
        [
          {
            "node": "Process AI Analysis",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  }
}