CodeCraft Tablet AI

Offline code generator for Android tablets

Describe what you want to code


                
Ready Model: Offline Templates
` } }; // Check if prompt matches any template const lowerPrompt = prompt.toLowerCase(); for (const [key, code] of Object.entries(templates[language] || {})) { if (lowerPrompt.includes(key)) { return code; } } // Default template switch(language) { case 'python': return `# ${prompt}\ndef main():\n # Your code here\n pass\n\nif __name__ == "__main__":\n main()`; case 'javascript': return `// ${prompt}\nfunction main() {\n // Your code here\n}\n\nmain();`; case 'html': return `\n\n\n ${prompt}\n\n\n \n\n`; default: return `/* ${prompt} */\n// Your ${language} code here`; } } function fixFromTemplate(code, errorDesc) { const lowerError = errorDesc?.toLowerCase() || ''; const lines = code.split('\n'); // Enhanced error detection with line numbers const lineMatch = lowerError.match(/line (\d+)/); let problemLine = lineMatch ? parseInt(lineMatch[1]) - 1 : -1; // More comprehensive error patterns if (lowerError.includes('indexerror') || lowerError.includes('out of range')) { // Add bounds checking with line targeting if (problemLine >= 0 && problemLine < lines.length) { lines[problemLine] = lines[problemLine].replace( /(\w+)\s*\[([^\]]+)\]/g, (match, arr, idx) => `if 0 <= ${idx} < len(${arr}):\n ${match}\nelse:\n # Handle out of range` ); } else { // Global replacement if line not specified code = code.replace(/(\w+)\s*\[([^\]]+)\]/g, (match, arr, idx) => `if 0 <= ${idx} < len(${arr}):\n ${match}\nelse:\n # Handle out of range`); } } if (lowerError.includes('syntaxerror') || lowerError.includes('invalid syntax')) { // More syntax fixes with context awareness if (problemLine >= 0 && problemLine < lines.length) { const line = lines[problemLine]; if (line.includes('=') && !line.includes('==')) { lines[problemLine] = line.replace(/=([^=])/g, '==$1'); } if (line.trim().endsWith(':')) { lines[problemLine] += ' pass'; } if (line.includes('print ') && !line.includes('(')) { lines[problemLine] = line.replace(/print (\w+)/, 'print($1)'); } } } // Add type conversion where needed if (lowerError.includes('typeerror') || lowerError.includes('concatenate')) { for (let i = 0; i < lines.length; i++) { if (lines[i].includes('+')) { lines[i] = lines[i].replace(/"([^"]*)"\s*\+\s*([^+\s;]+)/g, '"$1" + str($2)'); } } } // For undefined errors, wrap in try-catch if (problemLine >= 0 && !lowerError.includes('indentationerror')) { const indent = lines[problemLine].match(/^\s*/)[0]; lines[problemLine] = `${indent}try:\n${indent} ${lines[problemLine].trim()}\n${indent}except Exception as e:\n${indent} print(f"Error: {e}")`; } return lines.join('\n'); } function generateGoalFromTemplate(goalText) { // Simple goal breakdown template return { title: goalText, steps: [ { title: "Setup project structure", description: "Create basic files and folders for your project", code: "mkdir myproject\ncd myproject" }, { title: "Implement core functionality", description: "Write the main code that makes your project work" }, { title: "Add user interface", description: "Create the visual elements users will interact with" }, { title: "Test and debug", description: "Find and fix any issues in your code" }, { title: "Document your project", description: "Write instructions so others can use your project" } ] }; } // Enhanced history management with IndexedDB const dbName = 'CodeCraftDB'; const dbVersion = 1; let db; function initDB() { return new Promise((resolve, reject) => { const request = indexedDB.open(dbName, dbVersion); request.onupgradeneeded = (event) => { db = event.target.result; if (!db.objectStoreNames.contains('history')) { const store = db.createObjectStore('history', { keyPath: 'id', autoIncrement: true }); store.createIndex('type', 'type', { unique: false }); store.createIndex('timestamp', 'timestamp', { unique: false }); } }; request.onsuccess = (event) => { db = event.target.result; resolve(db); }; request.onerror = (event) => { console.error('IndexedDB error:', event.target.error); reject(event.target.error); }; }); } async function saveToHistory(type, data) { if (!db) { try { await initDB(); } catch (error) { console.error('Failed to init DB, falling back to localStorage'); return saveToLocalStorage(type, data); } } const transaction = db.transaction(['history'], 'readwrite'); const store = transaction.objectStore('history'); const historyItem = { type, data, timestamp: new Date().toISOString() }; return new Promise((resolve) => { const request = store.add(historyItem); request.onsuccess = () => { resolve(); }; request.onerror = (event) => { console.error('Error saving to IndexedDB:', event.target.error); saveToLocalStorage(type, data); resolve(); }; }); } function saveToLocalStorage(type, data) { const historyItem = { type, data, timestamp: new Date().toISOString() }; const history = JSON.parse(localStorage.getItem('codecraft-history') || '[]'); history.unshift(historyItem); localStorage.setItem('codecraft-history', JSON.stringify(history.slice(0, 100))); } async function loadHistory(filter = 'all') { if (!db) { try { await initDB(); } catch (error) { console.error('Failed to init DB, using localStorage'); return loadFromLocalStorage(filter); } } return new Promise((resolve) => { const transaction = db.transaction(['history'], 'readonly'); const store = transaction.objectStore('history'); const index = store.index('timestamp'); const request = index.openCursor(null, 'prev'); const results = []; request.onsuccess = (event) => { const cursor = event.target.result; if (cursor) { if (filter === 'all' || cursor.value.type === filter) { results.push(cursor.value); } cursor.continue(); } else { resolve(results.slice(0, 100)); } }; request.onerror = (event) => { console.error('Error loading from IndexedDB:', event.target.error); resolve(loadFromLocalStorage(filter)); }; }); } function loadFromLocalStorage(filter) { const history = JSON.parse(localStorage.getItem('codecraft-history') || '[]'); return filter === 'all' ? history : history.filter(item => item.type === filter); } async function loadHistory(filter = 'all') { if (!db) { try { await initDB(); } catch (error) { console.error('DB init failed, using localStorage'); const history = JSON.parse(localStorage.getItem('codecraft-history') || '[]'); return filter === 'all' ? history : history.filter(item => item.type === filter); } } return new Promise((resolve) => { const transaction = db.transaction(['history'], 'readonly'); const store = transaction.objectStore('history'); const index = store.index('timestamp'); const request = index.openCursor(null, 'prev'); const results = []; request.onsuccess = (event) => { const cursor = event.target.result; if (cursor) { if (filter === 'all' || cursor.value.type === filter) { results.push(cursor.value); } if (results.length < 100) { cursor.continue(); } else { resolve(results); } } else { resolve(results); } }; request.onerror = () => { const history = JSON.parse(localStorage.getItem('codecraft-history') || '[]'); resolve(filter === 'all' ? history : history.filter(item => item.type === filter)); }; }); } // Initialize the app with model loading document.addEventListener('DOMContentLoaded', async () => { // Initialize IndexedDB try { await initDB(); } catch (error) { console.error('IndexedDB initialization failed:', error); } // Check and load model if (typeof ort !== 'undefined') { document.getElementById('model-status').textContent = 'Model: Loading...'; try { await loadModel(); } catch (error) { console.error('Model loading failed:', error); document.getElementById('model-status').textContent = 'Model: Offline Templates'; } } // Load history when history tab is shown document.getElementById('tab-history').addEventListener('click', () => { const filter = document.getElementById('history-filter').value; const historyItems = loadHistory(filter); const container = document.getElementById('history-items'); container.innerHTML = ''; historyItems.forEach(item => { const itemElement = document.createElement('div'); itemElement.className = 'p-4 bg-white rounded-lg shadow'; let content = ''; if (item.type === 'code') { content = `
Code Generation (${item.data.language})
${item.data.prompt}
${item.data.code.substring(0, 100)}...
`; } else if (item.type === 'bugfix') { content = `
Bug Fix
${item.data.errorDesc || 'No error description'}
Fixed ${item.data.buggyCode.split('\n').length} lines of code
`; } else if (item.type === 'goal') { content = `
Goal Plan
${item.data.goalText}
${item.data.plan.steps.length} steps planned
`; } itemElement.innerHTML = content; container.appendChild(itemElement); }); }); // Copy and download functionality document.getElementById('copy-code').addEventListener('click', () => { const code = document.getElementById('generated-code').textContent; navigator.clipboard.writeText(code); updateStatus('Code copied to clipboard'); }); document.getElementById('download-code').addEventListener('click', () => { const code = document.getElementById('generated-code').textContent; const language = document.getElementById('language-select').value; const extension = { 'python': 'py', 'javascript': 'js', 'html': 'html', 'css': 'css', 'c': 'c', 'cpp': 'cpp', 'java': 'java' }[language] || 'txt'; const blob = new Blob([code], {type: 'text/plain'}); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = `code.${extension}`; a.click(); URL.revokeObjectURL(url); updateStatus('Code downloaded'); }); });