{
  "name": "OMR Answer Sheet Auto-Grader",
  "nodes": [
    {
      "parameters": {
        "resource": "image",
        "modelId": {
          "__rl": true,
          "value": "gemini-3-flash-preview",
          "mode": "list",
          "cachedResultName": "gemini-3-flash-preview"
        },
        "text": "=You are an OMR sheet analysis system.\n\nTask:\nAnalyze the provided OMR answer sheet image and extract ONLY the student's marked answers.\n\nStrict rules:\n- Ignore all headers, instructions, logos, barcodes, or any other text.\n- High Focus ONLY on the answer bubbles and properlly right answer provide.\n- For each question, detect the clearly filled/marked option (A, B, C, or D).\n- If multiple bubbles are filled for a question, select the darkest/most clearly marked one.\n- If no option is clearly marked for a question, skip that question entirely.\n- Do NOT guess answers.\n- Do NOT explain anything.\n- Do NOT add confidence scores or metadata.\n\nOutput format (MANDATORY):\n- Plain text only\n- Exactly in the format shown below\n- One answer per line\n- Sequential numbering starting from question 1\n- No extra spaces, symbols, or commentary\n- Extract a student details\n\nRequired output structure:\n \"student\":\n    \"name\": \"string | null\",\n    \"rollNumber\": \"string | null\",\n    \"class\": \"string | null\"\nanswer :\n1. A\n2. B\n3. C\n4. D\n5. A\n...\n(continue until the last detected question)",
        "simplify": false,
        "options": {
          "format": "json"
        }
      },
      "type": "@n8n/n8n-nodes-langchain.ollama",
      "typeVersion": 1,
      "position": [
        224,
        752
      ],
      "id": "e18a6e76-bb63-4cc8-accf-3ffccd05b5d7",
      "name": "Analyze image",
      "credentials": {
        "ollamaApi": {
          "id": "rfzMdfBkQbXa2MmP",
          "name": "Ollama account"
        }
      }
    },
    {
      "parameters": {
        "mode": "combine",
        "combineBy": "combineByPosition",
        "options": {}
      },
      "type": "n8n-nodes-base.merge",
      "typeVersion": 3.2,
      "position": [
        672,
        656
      ],
      "id": "8f45e41b-0737-49a2-bcd9-5cc4e21acf8c",
      "name": "Merge Answer"
    },
    {
      "parameters": {
        "jsCode": "// // function parseAnswers(input) {\n// //   if (!input) return {};\n\n// //   // If already object, return as is\n// //   if (typeof input === \"object\") {\n// //     return input;\n// //   }\n\n// //   // If string, normalize and parse\n// //   if (typeof input === \"string\") {\n// //     let obj = {};\n// //     let parts = input\n// //       .replace(/->/g, \":\")        // handle \"->\" also\n// //       .replace(/\\n/g, \",\")        // handle line breaks\n// //       .split(\",\");\n\n// //     for (let p of parts) {\n// //       let [q, ans] = p.split(\":\").map(s => s.trim());\n// //       if (q && ans) obj[q] = ans.toUpperCase();\n// //     }\n// //     return obj;\n// //   }\n\n// //   return {};\n// // }\n\n// // // ---- Extract Inputs (safe handling)\n// // const item = $input.item?.json || {};\n// // const originalRaw = item.chatInput || item.CorrectAnswer || {};\n// // const userRaw = item.UserAnswers || {};\n\n// // const original = parseAnswers(originalRaw);\n// // const user = parseAnswers(userRaw);\n\n// // let correct = 0;\n// // let incorrect = 0;\n// // let results = [];\n\n// // const total = Object.keys(original).length || Object.keys(user).length || 0;\n\n// // // ---- Comparison logic\n// // for (let i = 1; i <= total; i++) {\n// //   const q = String(i);\n// //   const correctAns = original[q] || \"Not Available\";\n// //   const given = user[q] || \"Not Attempted\";\n\n// //   if (given === correctAns) {\n// //     correct++;\n// //     results.push({ question: i, given, correctAns, status: \"Correct\" });\n// //   } else {\n// //     incorrect++;\n// //     results.push({ question: i, given, correctAns, status: \"Incorrect\" });\n// //   }\n// // }\n\n// // // ---- Calculate percentage safely\n// // const scorePercentage = total > 0 ? ((correct / total) * 100).toFixed(2) : \"0.00\";\n\n// // // ---- Return final structured output\n// // return [\n// //   {\n// //     json: {\n// //       totalQuestions: total,\n// //       correct,\n// //       incorrect,\n// //       scorePercentage,\n// //       results\n// //     }\n// //   }\n// // ];\n\n\n\n\n// function parseAnswers(input) {\n//   if (!input) return {};\n\n//   // If already object, return as is\n//   if (typeof input === \"object\") {\n//     return input;\n//   }\n\n//   // If string, normalize and parse\n//   if (typeof input === \"string\") {\n//     let obj = {};\n//     let parts = input\n//       .replace(/->/g, \":\")\n//       .replace(/\\n/g, \",\")\n//       .split(\",\");\n\n//     for (let p of parts) {\n//       let [q, ans] = p.split(\":\").map(s => s.trim());\n//       if (q && ans) obj[q] = ans.toUpperCase();\n//     }\n//     return obj;\n//   }\n\n//   return {};\n// }\n\n// // ---- Extract Inputs\n// const item = $input.item?.json || {};\n\n// // ✅ STUDENT DETAILS (DIRECT, NO PARSING)\n// const student = item.student || {\n//   name: null,\n//   rollNumber: null,\n//   class: null\n// };\n\n// // ---- Answers\n// const originalRaw = item.chatInput || item.CorrectAnswer || {};\n// const userRaw = item.UserAnswers || {};\n\n// const original = parseAnswers(originalRaw);\n// const user = parseAnswers(userRaw);\n\n// // ---- Evaluation\n// let correct = 0;\n// let incorrect = 0;\n// let results = [];\n\n// const total =\n//   Object.keys(original).length ||\n//   Object.keys(user).length ||\n//   0;\n\n// for (let i = 1; i <= total; i++) {\n//   const q = String(i);\n//   const correctAns = original[q] || \"Not Available\";\n//   const given = user[q] || \"Not Attempted\";\n\n//   if (given === correctAns) {\n//     correct++;\n//     results.push({\n//       question: i,\n//       given,\n//       correctAns,\n//       status: \"Correct\"\n//     });\n//   } else {\n//     incorrect++;\n//     results.push({\n//       question: i,\n//       given,\n//       correctAns,\n//       status: \"Incorrect\"\n//     });\n//   }\n// }\n\n// // ---- Score\n// const scorePercentage =\n//   total > 0 ? ((correct / total) * 100).toFixed(2) : \"0.00\";\n\n// // ---- FINAL API RESPONSE\n// return [\n//   {\n//     json: {\n//       student,\n//       totalQuestions: total,\n//       correct,\n//       incorrect,\n//       scorePercentage,\n//       results\n//     }\n//   }\n// ];\n\n\nfunction parseAnswers(input) {\n  if (!input) return {};\n\n  if (typeof input === \"object\") {\n    return input;\n  }\n\n  if (typeof input === \"string\") {\n    let obj = {};\n    let parts = input\n      .replace(/->/g, \":\")\n      .replace(/\\n/g, \",\")\n      .split(\",\");\n\n    for (let p of parts) {\n      let [q, ans] = p.split(\":\").map(s => s.trim());\n      if (q && ans) obj[q] = ans.toUpperCase();\n    }\n    return obj;\n  }\n\n  return {};\n}\n\n// ---- Extract Inputs\nconst item = $input.item?.json || {};\n\n// ---- Student Details\nconst student = item.student || {\n  name: null,\n  rollNumber: null,\n  class: null\n};\n\n// ---- Answers\nconst original = parseAnswers(item.chatInput || item.CorrectAnswer || {});\nconst user = parseAnswers(item.UserAnswers || {});\n\n// ---- Evaluation\nlet correct = 0;\nlet incorrect = 0;\nlet results = [];\nlet binaryResult = {}; // 👈 for Google Sheets (Q.1 = 1/0)\n\nconst total =\n  Object.keys(original).length ||\n  Object.keys(user).length ||\n  0;\n\nfor (let i = 1; i <= total; i++) {\n  const q = String(i);\n  const correctAns = original[q] || \"Not Available\";\n  const given = user[q] || \"Not Attempted\";\n\n  const isCorrect = given === correctAns;\n  const value = isCorrect ? 1 : 0;\n\n  if (isCorrect) {\n    correct++;\n  } else {\n    incorrect++;\n  }\n\n  results.push({\n    question: i,\n    given,\n    correctAns,\n    status: isCorrect ? \"Correct\" : \"Incorrect\",\n    value // 👈 1 or 0\n  });\n\n  binaryResult[`Q.${i}`] = value; // 👈 Q.1, Q.2, ...\n}\n\n// ---- Score\nconst scorePercentage =\n  total > 0 ? ((correct / total) * 100).toFixed(2) : \"0.00\";\n\n// ---- FINAL OUTPUT\nreturn [\n  {\n    json: {\n      student,\n      totalQuestions: total,\n      correct,\n      incorrect,\n      scorePercentage,\n      results,        // detailed\n      binaryResult    // 👈 PERFECT FOR GOOGLE SHEETS\n    }\n  }\n];\n"
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        896,
        656
      ],
      "id": "0ecfb7d4-f220-4cb5-a205-f2bd07539269",
      "name": "Calculate Result"
    },
    {
      "parameters": {
        "respondWith": "json",
        "responseBody": "={{ {\n  status: \"success\",\n  data: $json\n} }}",
        "options": {}
      },
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1.4,
      "position": [
        1280,
        656
      ],
      "id": "1e01b8a6-6e4f-4e94-89b5-d5dc26bb2336",
      "name": "Send Result Respond"
    },
    {
      "parameters": {
        "jsCode": "// // Get input JSON\n// const input = items[0].json;\n\n// // Get raw AI response text\n// const content = input.message?.content || \"\";\n\n// // Regex to capture answers like \"1:A\", \"2 : B\", etc.\n// const regex = /(\\d+)\\s*[:\\.]\\s*([A-D])/g;\n\n// let match;\n// const pairs = [];\n\n// // Extract question-answer pairs\n// while ((match = regex.exec(content)) !== null) {\n//   pairs.push(`${match[1]}:${match[2]}`);\n// }\n\n// // Join into a single string\n// const userAnswersStr = pairs.join(\", \");\n\n// // Return ONLY user answers\n// return [\n//   {\n//     json: {\n//       UserAnswers: userAnswersStr\n//     }\n//   }\n// ];\n\n\n\n// ===============================\n// 1. GET INPUT\n// ===============================\nconst input = items[0].json;\nlet content = input.message?.content || \"\";\n\n// Remove ``` fences if present\ncontent = content.replace(/```/g, \"\").trim();\n\n// ===============================\n// 2. EXTRACT STUDENT DETAILS\n// ===============================\nconst student = {\n  name: null,\n  rollNumber: null,\n  class: null\n};\n\n// Name\nconst nameMatch = content.match(/\"name\"\\s*:\\s*\"([^\"]+)\"/i);\nif (nameMatch) student.name = nameMatch[1].trim();\n\n// Roll Number\nconst rollMatch = content.match(/\"rollNumber\"\\s*:\\s*\"([^\"]+)\"/i);\nif (rollMatch) student.rollNumber = rollMatch[1].trim();\n\n// Class\nconst classMatch = content.match(/\"class\"\\s*:\\s*\"([^\"]+)\"/i);\nif (classMatch) student.class = classMatch[1].trim();\n\n// ===============================\n// 3. EXTRACT USER ANSWERS\n// ===============================\n\n// Regex to capture answers like \"1:A\", \"1. A\", \"2 : B\"\nconst regex = /(\\d+)\\s*[:\\.]\\s*([A-D])/g;\n\nlet match;\nconst pairs = [];\n\n// Extract question-answer pairs\nwhile ((match = regex.exec(content)) !== null) {\n  pairs.push(`${match[1]}:${match[2]}`);\n}\n\n// Join into a single string\nconst userAnswersStr = pairs.join(\", \");\n\n// ===============================\n// 4. FINAL OUTPUT\n// ===============================\nreturn [\n  {\n    json: {\n      student,\n      UserAnswers: userAnswersStr\n    }\n  }\n];\n"
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        448,
        752
      ],
      "id": "4751c744-abe1-44ab-90f0-89cc01cfec50",
      "name": "Convert User Ans in Format"
    },
    {
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "1209b6e5-0167-4c2a-b9bd-b894760a4027",
              "name": "CorrectAnswer",
              "value": "1:B, 2:A, 3:D, 4:C, 5:B, 6:D, 7:B, 8:C, 9:A, 10:B, 11:D, 12:C, 13:A, 14:D, 15:B, 16:C, 17:D, 18:A, 19:B, 20:C",
              "type": "string"
            }
          ]
        },
        "options": {}
      },
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        336,
        592
      ],
      "id": "966cd470-c8dd-4fd8-a55d-ec023905fe59",
      "name": "Set Your Correct Answer"
    },
    {
      "parameters": {
        "httpMethod": "POST",
        "path": "omr-sheet-checker",
        "options": {}
      },
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2.1,
      "position": [
        -16,
        656
      ],
      "id": "41d6c6a0-f57e-4719-841a-251924b7c172",
      "name": "Send Student Ans Img",
      "webhookId": "eb6fba06-d53d-4c24-a7ee-7b7b31e5cbbe"
    },
    {
      "parameters": {
        "operation": "append",
        "documentId": {
          "__rl": true,
          "value": "15nvRI8zcJ2n-QBXNk9xyd1GM8Vj7_1lJ3K7vO7Qfq3w",
          "mode": "list",
          "cachedResultName": "Students Result"
        },
        "sheetName": {
          "__rl": true,
          "value": "gid=0",
          "mode": "list",
          "cachedResultName": "Sheet1"
        },
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "Student Name": "={{ $json.student.name }}",
            "Roll No": "={{ $json.student.rollNumber }}",
            "Class": "={{ $json.student.class }}",
            "Correct": "={{ $json.correct }}",
            "Incorrect": "={{ $json.incorrect }}",
            "Score Percentage": "={{ $json.scorePercentage }}%",
            "Q.1": "={{ $json.results[0].value }}",
            "Q.2": "={{ $json.results[1].value }}",
            "Q.3": "={{ $json.results[2].value }}",
            "Q.4": "={{ $json.results[3].value }}",
            "Q.5": "={{ $json.results[4].value }}",
            "Q.7": "={{ $json.results[6].value }}",
            "Q.6": "={{ $json.results[5].value }}",
            "Q.8": "={{ $json.results[7].value }}",
            "Q.9": "={{ $json.results[8].value }}",
            "Q.12": "={{ $json.results[11].value }}",
            "Q.11": "={{ $json.results[10].value }}",
            "Q.14": "={{ $json.results[13].value }}",
            "Q.13": "={{ $json.results[12].value }}",
            "Q.16": "={{ $json.results[15].value }}",
            "Q.15": "={{ $json.results[14].value }}",
            "Q.18": "={{ $json.results[17].value }}",
            "Q.17": "={{ $json.results[16].value }}",
            "Q.20": "={{ $json.results[19].value }}",
            "Q.19": "={{ $json.results[18].value }}",
            "Q.10": "={{ $json.results[9].value }}"
          },
          "matchingColumns": [],
          "schema": [
            {
              "id": "Student Name",
              "displayName": "Student Name",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Roll No",
              "displayName": "Roll No",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Class",
              "displayName": "Class",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Q.1",
              "displayName": "Q.1",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Q.2",
              "displayName": "Q.2",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Q.3",
              "displayName": "Q.3",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Q.4",
              "displayName": "Q.4",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Q.5",
              "displayName": "Q.5",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Q.6",
              "displayName": "Q.6",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Q.7",
              "displayName": "Q.7",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Q.8",
              "displayName": "Q.8",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Q.9",
              "displayName": "Q.9",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Q.10",
              "displayName": "Q.10",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Q.11",
              "displayName": "Q.11",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Q.12",
              "displayName": "Q.12",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Q.13",
              "displayName": "Q.13",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Q.14",
              "displayName": "Q.14",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Q.15",
              "displayName": "Q.15",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Q.16",
              "displayName": "Q.16",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Q.17",
              "displayName": "Q.17",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Q.18",
              "displayName": "Q.18",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Q.19",
              "displayName": "Q.19",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Q.20",
              "displayName": "Q.20",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Correct",
              "displayName": "Correct",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Incorrect",
              "displayName": "Incorrect",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "Score Percentage",
              "displayName": "Score Percentage",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            }
          ],
          "attemptToConvertTypes": false,
          "convertFieldsToString": false
        },
        "options": {}
      },
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "position": [
        1088,
        656
      ],
      "id": "c27a4c7c-4a1f-4ab6-864f-17593233dfa7",
      "name": "Append Result in Sheet",
      "credentials": {
        "googleSheetsOAuth2Api": {
          "id": "GojUvCMDXbhY8HrB",
          "name": "Google Sheets account"
        }
      }
    },
    {
      "parameters": {
        "content": "## Google Sheet\nCreate your own spreadsheet with these tabs/columns, then select it in the Google Sheets nodes:\n- **Students Result → Sheet1**: `Student Name`, `Roll No`, `Class`, `Q.1`, `Q.2`, `Q.3`, `Q.4`, `Q.5`, `Q.6`, `Q.7`, `Q.8`, `Q.9`, `Q.10`, `Q.11`, `Q.12`, `Q.13`, `Q.14`, `Q.15`, `Q.16`, `Q.17`, `Q.18`, `Q.19`, `Q.20`, `Correct`, `Incorrect`, `Score Percentage`\n\n\n## Webhook Payload :\nForm-Data\nkey-name : file\nValue : Upload Img",
        "height": 256
      },
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -48,
        320
      ],
      "id": "c95ad311-0f51-4de0-8cb7-db99558414d8",
      "name": "Sticky Note"
    }
  ],
  "pinData": {},
  "connections": {
    "Analyze image": {
      "main": [
        [
          {
            "node": "Convert User Ans in Format",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Merge Answer": {
      "main": [
        [
          {
            "node": "Calculate Result",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Calculate Result": {
      "main": [
        [
          {
            "node": "Append Result in Sheet",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Convert User Ans in Format": {
      "main": [
        [
          {
            "node": "Merge Answer",
            "type": "main",
            "index": 1
          }
        ]
      ]
    },
    "Set Your Correct Answer": {
      "main": [
        [
          {
            "node": "Merge Answer",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Send Student Ans Img": {
      "main": [
        [
          {
            "node": "Analyze image",
            "type": "main",
            "index": 0
          },
          {
            "node": "Set Your Correct Answer",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Append Result in Sheet": {
      "main": [
        [
          {
            "node": "Send Result Respond",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "active": false,
  "settings": {
    "executionOrder": "v1"
  },
  "versionId": "76281001-6dc7-4bcf-abe3-28435da636ef",
  "meta": {
    "templateCredsSetupCompleted": true,
    "instanceId": "f1c26778ec36097a9722a22c47c5e9c01f00b8862dadd0121ec118026a370fa6"
  },
  "id": "QPM2lJ84AGzuluWD",
  "tags": []
}