Goalgo-Ai-Free-Lab

GoAlgo AI Free Lab | Free AI Image Generator, Prompt Genius & Upscaler
100% FREE

Goalgo-Ai-free-lab

Free AI tools to create, convert, and explore β€” powered by GoAlgo AI.

100% Free Tools: AI image generation, smart prompt creation, and live currency conversion

What's in your mind?

🧠 Prompt Genius Analysis
πŸ“š Expert Templates

Upload an Image to Upscale

Drag & drop or click to select a file

Upload Reference Image (Optional)

Drag & drop or click to select an image for style reference
Conversion Result
3.67 AED
1 USD = 3.67 AED

Your creation will appear here

Enter a prompt and click generate to start

Generating...'; const loadingText = referenceImage ? 'AI is analyzing reference and creating your image...' : 'AI is creating your image...'; outputSection.innerHTML = `
${loadingText}

This may take 10-30 seconds

`; try { const model = document.getElementById('imageModel').value; const aspectRatio = document.getElementById('aspectRatio').value; let width = 1024, height = 1024; if (aspectRatio === '16:9') { width = 1344; height = 768; } if (aspectRatio === '9:16') { width = 768; height = 1344; } // Enhance prompt with reference image context let enhancedPrompt = prompt; if (referenceImage) { enhancedPrompt = `${prompt}, inspired by reference image style, maintaining similar composition and aesthetic elements`; } const seed = Math.floor(Math.random() * 1000000); const imageUrl = `https://image.pollinations.ai/prompt/${encodeURIComponent(enhancedPrompt)}?width=${width}&height=${height}&model=${model}&seed=${seed}&nologo=true`; // Wait for the image to load before displaying it await new Promise((resolve, reject) => { const img = new Image(); img.src = imageUrl; img.alt = "Generated image"; img.style.maxWidth = "100%"; img.style.borderRadius = "12px"; img.style.opacity = "0"; img.style.transition = "opacity 0.5s"; img.onload = () => { const referenceNote = referenceImage ? '✨ Generated with reference image guidance' : ''; outputSection.innerHTML = `
Generated with ${model.toUpperCase()} ${referenceNote}
`; resolve(); }; img.onerror = () => reject(new Error("The generated image failed to load. The model may be busy. Please try again.")); }); } catch (error) { outputSection.innerHTML = `

Generation Failed

${error.message || 'Please try again with a different prompt.'}

`; } finally { generateBtn.disabled = false; generateBtn.innerHTML = 'Generate Image'; } } async function generatePromptContent() { const generateBtn = document.getElementById('generateBtn'); const outputSection = document.getElementById('outputSection'); const task = document.getElementById('promptTask').value; generateBtn.disabled = true; generateBtn.innerHTML = '
Generating...'; const loadingText = task === 'coding' ? 'Generating code with AI...' : 'Crafting expert prompts with the Prompt Genius...'; outputSection.innerHTML = `

${loadingText}

`; try { const industry = document.getElementById('promptIndustry').value; const task = document.getElementById('promptTask').value; const tone = document.getElementById('promptTone').value; const userInput = document.getElementById('promptInput').value.trim(); const includeExamples = document.getElementById('includeExamples').checked; const prompts = await generateAdvancedPrompts(industry, task, tone, userInput, includeExamples); displayAdvancedPromptResults(prompts); } catch (error) { displayError(error.message); } finally { generateBtn.disabled = false; generateBtn.innerHTML = 'Generate with Genius'; } } async function generateAdvancedPrompts(industry, task, tone, userInput, includeExamples) { // --- Detailed Component Definitions --- const roles = { marketing: "a world-class marketing strategist known for creating viral campaigns and doubling conversion rates", content: "an award-winning creative content director who specializes in crafting narratives that captivate and engage audiences", business: "a principal business analyst from a top-tier consulting firm, with deep expertise in market disruption and growth hacking", education: "a master instructional designer renowned for creating highly effective and engaging learning experiences for adult professionals", 'image-generation': "a visionary digital artist and concept designer, similar to masters like Syd Mead or Feng Zhu, known for creating breathtaking and highly detailed visuals", coding: "a 10x full-stack software architect with decades of experience in building scalable, secure, and elegant applications", 'video-generation': "an acclaimed film director and visual storyteller, with a portfolio of award-winning cinematic shorts and commercials" }; const objectives = { generate: `Your primary objective is to generate 3-5 exceptionally innovative and distinct ideas related to "{input}". Each idea must be practical yet push the boundaries of conventional thinking.`, analyze: `Your core mission is to conduct a comprehensive, multi-faceted analysis of "{input}". You must dissect its strengths, weaknesses, hidden opportunities, and potential threats, providing deep, actionable insights.`, write: `Your task is to write exceptionally compelling and persuasive copy for "{input}". The copy must be polished, impactful, and ready for immediate publication to a discerning audience.`, plan: `Your goal is to develop a robust, step-by-step strategic plan for "{input}". This plan must be detailed, actionable, and include a clear timeline, resource allocation, and measurable Key Performance Indicators (KPIs).`, 'image-generation': `Your objective is to craft a masterfully detailed and evocative text-to-image prompt based on the core concept: "{input}". The prompt must be a work of art in itself, designed to guide an AI image generator to produce a masterpiece.`, coding: `Your mission is to write production-quality code that is clean, highly efficient, scalable, and impeccably documented to solve the following problem: "{input}".`, 'video-generation': `Your task is to create a professional-grade, detailed video script and shot list for a video about "{input}". The plan should be clear enough for a production team to execute flawlessly.` }; const outputFormats = { generate: "a structured numbered list. For each idea, provide a catchy title, a one-paragraph summary, and a list of key features or benefits.", analyze: "a formal report format. Use clear headings for each section (e.g., 'SWOT Analysis', 'Market Positioning', 'Competitive Landscape'), and use bullet points for key findings.", write: "the final, polished copy only. Do not include any introductory phrases like 'Here is the copy'. The output should be ready to be copied and pasted directly.", plan: "a document with sections for 'Phase 1', 'Phase 2', etc., detailing actions and expected outcomes. Include a 'Resources Needed' and 'Success Metrics' section.", 'image-generation': "a single, concise paragraph of descriptive text. Do not add any explanations or conversational text outside of the prompt itself.", coding: "a clean code block with the requested code, followed by a separate section with a brief explanation of how it works and its dependencies.", 'video-generation': "a table with columns for 'Scene Number', 'Camera Shot', 'Action/Dialogue', and 'Sound/Music'. Be highly descriptive in each cell." }; const baseRole = roles[task] || roles[industry] || 'an expert AI assistant'; const baseObjective = objectives[task] || 'provide information about "{input}"'; const baseOutputFormat = outputFormats[task] || 'a well-structured text.'; // --- Prompt 1: The Expert's Take (Professional & Structured) --- const prompt1 = { role: `You are ${baseRole}.`, objective: baseObjective.replace('{input}', userInput || 'the specified topic'), constraints: [ `The tone must be strictly ${tone}.`, "The response must be well-researched, accurate, and demonstrate deep domain expertise.", "Avoid jargon where possible, but if necessary, explain it clearly.", includeExamples ? "Incorporate specific, real-world examples to illustrate key points." : "Focus on the core concepts without needing examples." ], outputFormat: `Output Format: Provide the response as ${baseOutputFormat}` }; // --- Prompt 2: The Creative's Take (Innovative & Unconventional) --- const prompt2 = { role: `You are a creative disruptor and visionary thinker, blending the expertise of ${baseRole} with an artist's imagination.`, objective: baseObjective.replace('{input}', userInput || 'the specified topic') + " However, your goal is to approach this from a completely unconventional angle, offering a perspective that is surprising, innovative, and challenges the status quo.", constraints: [ `The tone should be a mix of ${tone} and highly creative.`, "Prioritize originality and 'out-of-the-box' thinking over conventional wisdom.", "Use metaphors, analogies, and storytelling to make your points more memorable and impactful.", "The final output should feel both inspiring and actionable." ], outputFormat: `Output Format: Provide the response as ${baseOutputFormat.replace('a structured numbered list', 'a narrative or a mind-map-style list').replace('a formal report format', 'a compelling memo to a CEO')}` }; // Combine constraints into a single string for each prompt prompt1.constraints = "Constraints: " + prompt1.constraints.join(' '); prompt2.constraints = "Constraints: " + prompt2.constraints.join(' '); return [prompt1, prompt2]; } function generateSimpleCode(userInput) { const input = userInput.toLowerCase(); // Detect if user wants Python code if (input.includes('python') || input.includes('calculator') && input.includes('app')) { return `# ${userInput} # Python Calculator Application class Calculator: """A simple calculator class with basic arithmetic operations""" def __init__(self): self.history = [] def add(self, a, b): """Addition operation""" result = a + b self.history.append(f"{a} + {b} = {result}") return result def subtract(self, a, b): """Subtraction operation""" result = a - b self.history.append(f"{a} - {b} = {result}") return result def multiply(self, a, b): """Multiplication operation""" result = a * b self.history.append(f"{a} * {b} = {result}") return result def divide(self, a, b): """Division operation with zero-division handling""" if b == 0: return "Error: Cannot divide by zero" result = a / b self.history.append(f"{a} / {b} = {result}") return result def power(self, a, b): """Power operation""" result = a ** b self.history.append(f"{a} ^ {b} = {result}") return result def get_history(self): """Get calculation history""" return self.history def clear_history(self): """Clear calculation history""" self.history = [] return "History cleared" def main(): """Main function to run the calculator""" calc = Calculator() print("=" * 40) print(" PYTHON CALCULATOR APP") print("=" * 40) print("Available operations:") print("1. Addition (+)") print("2. Subtraction (-)") print("3. Multiplication (*)") print("4. Division (/)") print("5. Power (^)") print("6. History") print("7. Clear History") print("8. Exit") print("=" * 40) while True: try: choice = input("\nEnter your choice (1-8): ") if choice == '8': print("Thank you for using the calculator!") break elif choice == '6': history = calc.get_history() if history: print("\nCalculation History:") for item in history: print(f" {item}") else: print("No calculations in history.") elif choice == '7': print(calc.clear_history()) elif choice in ['1', '2', '3', '4', '5']: num1 = float(input("Enter first number: ")) num2 = float(input("Enter second number: ")) if choice == '1': result = calc.add(num1, num2) elif choice == '2': result = calc.subtract(num1, num2) elif choice == '3': result = calc.multiply(num1, num2) elif choice == '4': result = calc.divide(num1, num2) elif choice == '5': result = calc.power(num1, num2) print(f"Result: {result}") else: print("Invalid choice! Please enter 1-8.") except ValueError: print("Invalid input! Please enter valid numbers.") except KeyboardInterrupt: print("\nExiting calculator...") break except Exception as e: print(f"An error occurred: {e}") # Example usage and testing if __name__ == "__main__": # Quick examples print("Quick Examples:") calc_demo = Calculator() print(f"10 + 5 = {calc_demo.add(10, 5)}") print(f"10 - 3 = {calc_demo.subtract(10, 3)}") print(f"4 * 6 = {calc_demo.multiply(4, 6)}") print(f"15 / 3 = {calc_demo.divide(15, 3)}") print(f"2 ^ 3 = {calc_demo.power(2, 3)}") print("\nStarting interactive calculator...") main()`; } // Default to HTML for other requests return ` ${userInput}

Welcome to ${userInput}

This is a basic website template generated for your project.

`; } function generateImagePrompts(userInput) { return [ `Create a detailed, high-quality image of ${userInput}. Use vibrant colors, professional lighting, and sharp focus. Style: photorealistic, 4K resolution.`, `Generate an artistic interpretation of ${userInput}. Style: digital art, concept art, trending on ArtStation, highly detailed.`, `Design a minimalist, clean representation of ${userInput}. Style: modern, simple, elegant composition with perfect lighting.` ]; } function generateVideoPrompts(userInput) { return [ `Create a dynamic video showcasing ${userInput}. Include smooth camera movements, professional transitions, and engaging visual effects.`, `Generate a cinematic video about ${userInput}. Style: film-like quality, dramatic lighting, compelling storytelling elements.`, `Produce an animated explainer video for ${userInput}. Include clear narration, smooth animations, and educational visual elements.` ]; } function displayAdvancedPromptResults(prompts) { const outputSection = document.getElementById('outputSection'); let promptsHtml = prompts.map((promptObj, index) => { const fullPromptText = `${promptObj.role} ${promptObj.objective} ${promptObj.constraints} ${promptObj.outputFormat}`; const analysis = performPromptAnalysis(fullPromptText); return `
${analysis.effectiveness}% Effective
πŸ§žβ€β™‚οΈ Genius Prompt ${index + 1}:

Role: ${promptObj.role}

Objective: ${promptObj.objective}

Constraints: ${promptObj.constraints.replace('Constraints: ', '')}

Output Format: ${promptObj.outputFormat.replace('Output Format: Provide the response as ', '')}

`; }).join(''); outputSection.innerHTML = `
πŸ§žβ€β™‚οΈ Prompt Genius Results

AI-crafted prompts with intelligence analysis

${promptsHtml}
`; } async function convertCurrency() { const amount = document.getElementById('currencyAmount').value || 1; const from = document.getElementById('fromCurrency').value; const to = document.getElementById('toCurrency').value; const resultAmountEl = document.getElementById('resultAmount'); const exchangeRateEl = document.getElementById('exchangeRate'); resultAmountEl.textContent = '...'; exchangeRateEl.textContent = 'Fetching live rates...'; try { const response = await fetch(`https://api.exchangerate-api.com/v4/latest/${from}`); if (!response.ok) { throw new Error('Network response was not ok'); } const data = await response.json(); const rate = data.rates[to]; if (!rate) { throw new Error(`Rate for ${to} not found.`); } const result = (amount * rate).toFixed(2); resultAmountEl.textContent = `${result} ${to}`; exchangeRateEl.textContent = `1 ${from} = ${rate.toFixed(4)} ${to}`; } catch (error) { console.error('Error fetching currency rates:', error); resultAmountEl.textContent = 'Error'; exchangeRateEl.textContent = 'Could not fetch live rates.'; } } function switchCurrencies() { const fromCurrency = document.getElementById('fromCurrency'); const toCurrency = document.getElementById('toCurrency'); const tempValue = fromCurrency.value; fromCurrency.value = toCurrency.value; toCurrency.value = tempValue; convertCurrency(); } function downloadImage(url, filename = 'ai-generated-image.jpg') { const a = document.createElement('a'); a.href = url; a.download = filename; a.click(); } function selectPrompt(prompt) { document.getElementById('promptInput').value = prompt; analyzePrompt(); } function copyPrompt(prompt) { navigator.clipboard.writeText(prompt); showNotification('πŸ“‹ Prompt copied to clipboard!', 'success'); } function refinePrompt(prompt) { const refined = generateEnhancedPrompt(prompt); document.getElementById('promptInput').value = refined; analyzePrompt(); showNotification('✨ Prompt refined and enhanced!', 'success'); } function generateMoreVariations() { const currentPrompt = document.getElementById('promptInput').value.trim(); if (!currentPrompt) { showNotification('Please enter a base prompt first', 'error'); return; } generatePromptContent(); } function displayCodeResults(codeArray) { const outputSection = document.getElementById('outputSection'); const code = String(codeArray[0] || 'No code generated'); // Detect if it's Python code const isPython = code.includes('def ') || code.includes('class ') || code.includes('import ') || code.includes('# Python'); const language = isPython ? 'Python' : 'HTML'; const fileExtension = isPython ? 'py' : 'html'; outputSection.innerHTML = `
πŸ’» Generated ${language} Code

Ready-to-use ${language} code

${language} Code:
${!isPython ? `` : ''}
${code.replace(//g, '>')}
${isPython ? '

πŸ’‘ Save as .py file and run with: python filename.py

' : ''}
`; } function copyCode(code) { const decodedCode = code.replace(/\\n/g, '\n').replace(/\\'/g, "'"); navigator.clipboard.writeText(decodedCode); showNotification('πŸ’» Code copied to clipboard!', 'success'); } function previewCode(code) { const decodedCode = code.replace(/\\n/g, '\n').replace(/\\'/g, "'"); const newWindow = window.open('', '_blank'); newWindow.document.write(decodedCode); newWindow.document.close(); } function generateMoreCode() { generatePromptContent(); } function downloadCode(code, filename) { const decodedCode = code.replace(/\\n/g, '\n').replace(/\\'/g, "'"); const blob = new Blob([decodedCode], { type: 'text/plain' }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = filename; a.click(); URL.revokeObjectURL(url); showNotification('πŸ“ Code file downloaded!', 'success'); } // --- Prompt Genie Intelligence Functions --- function analyzePrompt() { const prompt = document.getElementById('promptInput').value.trim(); const interpretationBox = document.getElementById('interpretationBox'); const interpretationText = document.getElementById('interpretationText'); const genieMetrics = document.getElementById('genieMetrics'); if (!prompt) { interpretationBox.classList.remove('show'); return; } // Real-time analysis const analysis = performPromptAnalysis(prompt); interpretationText.innerHTML = `
Intent: ${analysis.intent}
Clarity Score: ${analysis.clarity}/10
Suggestions: ${analysis.suggestions.join(', ')}
`; genieMetrics.innerHTML = `
${analysis.wordCount}
Words
${analysis.complexity}
Complexity
${analysis.specificity}
Specificity
${analysis.effectiveness}%
Effectiveness
`; interpretationBox.classList.add('show'); } function performPromptAnalysis(prompt) { const words = prompt.split(/\s+/).length; const sentences = prompt.split(/[.!?]+/).length - 1; // Intent detection const intents = { 'create': /\b(create|generate|make|build|design|craft)\b/i, 'analyze': /\b(analyze|examine|review|evaluate|assess)\b/i, 'explain': /\b(explain|describe|tell|show|how)\b/i, 'compare': /\b(compare|contrast|versus|vs|difference)\b/i, 'list': /\b(list|enumerate|outline|steps|process)\b/i }; let detectedIntent = 'general'; for (const [intent, pattern] of Object.entries(intents)) { if (pattern.test(prompt)) { detectedIntent = intent; break; } } // Clarity scoring let clarity = 5; if (words > 10) clarity += 2; if (sentences > 1) clarity += 1; if (/\b(specific|detailed|comprehensive)\b/i.test(prompt)) clarity += 2; if (/\?/.test(prompt)) clarity += 1; clarity = Math.min(10, clarity); // Suggestions const suggestions = []; if (words < 5) suggestions.push('Add more detail'); if (!prompt.includes('?') && detectedIntent === 'general') suggestions.push('Be more specific'); if (!/\b(please|could|would)\b/i.test(prompt)) suggestions.push('Use polite language'); if (suggestions.length === 0) suggestions.push('Well structured'); return { intent: detectedIntent.charAt(0).toUpperCase() + detectedIntent.slice(1), wordCount: words, clarity: clarity, clarityColor: clarity >= 8 ? '#48bb78' : clarity >= 6 ? '#ed8936' : '#f56565', complexity: words > 20 ? 'High' : words > 10 ? 'Medium' : 'Low', specificity: /\b(specific|detailed|exactly|precisely)\b/i.test(prompt) ? 'High' : 'Medium', effectiveness: Math.min(95, 60 + (clarity * 3) + (words > 10 ? 10 : 0)), suggestions: suggestions }; } function enhancePromptAuto() { const promptInput = document.getElementById('promptInput'); const currentPrompt = promptInput.value.trim(); if (!currentPrompt) { alert('Please enter a prompt first'); return; } const enhanced = generateEnhancedPrompt(currentPrompt); promptInput.value = enhanced; analyzePrompt(); // Show enhancement notification showNotification('✨ Prompt enhanced with AI suggestions!', 'success'); } function generateEnhancedPrompt(original) { const enhancements = { structure: 'Please provide a detailed and comprehensive response about', context: 'Consider the following context and requirements:', format: 'Structure your response with clear headings and examples.', tone: 'Use a professional and informative tone throughout.' }; let enhanced = original; // Add structure if missing if (!/\b(please|could|would)\b/i.test(enhanced)) { enhanced = `Please ${enhanced.toLowerCase()}`; } // Add specificity if (enhanced.length < 50) { enhanced += '. Include specific examples and actionable insights.'; } // Add format guidance if (!/\b(format|structure|organize)\b/i.test(enhanced)) { enhanced += ' Organize the response in a clear, easy-to-follow format.'; } return enhanced; } function showPromptTemplates() { const templatesDiv = document.getElementById('promptTemplates'); const templateGrid = document.getElementById('templateGrid'); const templates = [ { title: 'Content Creation', desc: 'Generate engaging content for any platform', preview: 'Create compelling content about [topic] for [audience]...' }, { title: 'Problem Solving', desc: 'Structured approach to complex problems', preview: 'Analyze the problem of [issue] and provide 3 solutions...' }, { title: 'Learning & Education', desc: 'Educational content and explanations', preview: 'Explain [concept] in simple terms with examples...' }, { title: 'Business Strategy', desc: 'Strategic business insights and planning', preview: 'Develop a strategy for [business goal] considering...' }, { title: 'Creative Writing', desc: 'Storytelling and creative content', preview: 'Write a creative story about [theme] with [elements]...' }, { title: 'Data Analysis', desc: 'Analytical and research-focused prompts', preview: 'Analyze the data trends in [field] and identify...' } ]; templateGrid.innerHTML = templates.map(template => `
${template.title}
${template.desc}
${template.preview}
`).join(''); templatesDiv.style.display = templatesDiv.style.display === 'none' ? 'block' : 'none'; } function applyTemplate(templateName) { const templates = { 'Content Creation': 'Create compelling and engaging content about [your topic] for [target audience]. Include a catchy headline, key points, and a clear call-to-action. Make it shareable and optimized for [platform].', 'Problem Solving': 'Analyze the problem of [describe your challenge] and provide 3 practical solutions. For each solution, include implementation steps, potential obstacles, and success metrics.', 'Learning & Education': 'Explain [concept or topic] in simple, easy-to-understand terms. Include real-world examples, analogies, and a step-by-step breakdown. Make it suitable for [audience level].', 'Business Strategy': 'Develop a comprehensive strategy for [business goal or challenge]. Consider market conditions, resources, timeline, and provide actionable recommendations with measurable outcomes.', 'Creative Writing': 'Write a creative and engaging [type of content] about [theme or subject]. Include vivid descriptions, compelling characters or elements, and maintain [desired tone] throughout.', 'Data Analysis': 'Analyze the trends and patterns in [data or field]. Identify key insights, correlations, and provide data-driven recommendations for [specific outcome or decision].' }; const promptInput = document.getElementById('promptInput'); promptInput.value = templates[templateName] || ''; analyzePrompt(); // Hide templates document.getElementById('promptTemplates').style.display = 'none'; showNotification(`πŸ“ ${templateName} template applied!`, 'info'); } function confirmInterpretation() { showNotification('βœ… Prompt analysis confirmed!', 'success'); } function showNotification(message, type = 'info') { const notification = document.createElement('div'); notification.style.cssText = ` position: fixed; top: 20px; right: 20px; background: ${type === 'success' ? '#48bb78' : type === 'error' ? '#f56565' : '#667eea'}; color: white; padding: 1rem 1.5rem; border-radius: 8px; z-index: 1000; animation: slideInRight 0.3s ease; `; notification.textContent = message; document.body.appendChild(notification); setTimeout(() => { notification.style.animation = 'slideOutRight 0.3s ease'; setTimeout(() => notification.remove(), 300); }, 3000); } function handleTaskTypeChange() { const taskType = document.getElementById('promptTask').value; const industryGroup = document.getElementById('promptIndustryGroup'); const toneGroup = document.getElementById('promptToneGroup'); // Hide Industry and Tone for specific task types const hideForTasks = ['image-generation', 'video-generation']; if (hideForTasks.includes(taskType)) { if (industryGroup) industryGroup.classList.add('d-none'); if (toneGroup) toneGroup.classList.add('d-none'); } else { if (industryGroup) industryGroup.classList.remove('d-none'); if (toneGroup) toneGroup.classList.remove('d-none'); } } // --- Upscale and File Handling Functions --- function handleDragOver(e) { e.preventDefault(); e.currentTarget.classList.add('dragover'); } function handleDragLeave(e) { e.currentTarget.classList.remove('dragover'); } function handleDrop(e) { e.preventDefault(); e.currentTarget.classList.remove('dragover'); const files = Array.from(e.dataTransfer.files); processFiles(files); } function handleFileSelect(e) { const files = Array.from(e.target.files); processFiles(files); } function processFiles(files) { // For upscale, we only want one image if (currentMode === 'upscale' && files.length > 0) { uploadedFiles = [files[0]]; updateFileDisplay(); } } function addFileTag(file) { const container = document.getElementById('uploadedFiles'); container.innerHTML = ''; // Clear previous files const tag = document.createElement('div'); tag.className = 'file-tag'; tag.innerHTML = ` ${file.name.substring(0, 20)}${file.name.length > 20 ? '...' : ''} Γ— `; container.appendChild(tag); } function removeFile(fileName) { uploadedFiles = uploadedFiles.filter(f => f.name !== fileName); updateFileDisplay(); } function updateFileDisplay() { const container = document.getElementById('uploadedFiles'); container.innerHTML = ''; uploadedFiles.forEach(file => addFileTag(file)); } function resetOutputSection() { const outputSection = document.getElementById('outputSection'); outputSection.innerHTML = `

Your creation will appear here

Enter a prompt and click generate to start

`; } function clearUploadedFiles() { uploadedFiles = []; const uploadedFilesContainer = document.getElementById('uploadedFiles'); if (uploadedFilesContainer) { uploadedFilesContainer.innerHTML = ''; } const fileInput = document.getElementById('fileInput'); if (fileInput) { fileInput.value = ''; } // Clear image reference files const imageReferenceFiles = document.getElementById('imageReferenceFiles'); if (imageReferenceFiles) { imageReferenceFiles.innerHTML = ''; } const imageReferenceInput = document.getElementById('imageReferenceInput'); if (imageReferenceInput) { imageReferenceInput.value = ''; } } // Image reference upload functions function handleImageReferenceDrop(e) { e.preventDefault(); e.currentTarget.classList.remove('dragover'); const files = Array.from(e.dataTransfer.files); processImageReferenceFiles(files); } function handleImageReferenceSelect(e) { const files = Array.from(e.target.files); processImageReferenceFiles(files); } function processImageReferenceFiles(files) { const imageFiles = files.filter(file => file.type.startsWith('image/')); if (imageFiles.length > 0) { referenceImage = imageFiles[0]; const container = document.getElementById('imageReferenceFiles'); container.innerHTML = ''; const file = imageFiles[0]; // Only take the first image const tag = document.createElement('div'); tag.className = 'file-tag'; tag.innerHTML = ` ${file.name.substring(0, 20)}${file.name.length > 20 ? '...' : ''} Γ— `; container.appendChild(tag); } } function removeImageReference() { referenceImage = null; const container = document.getElementById('imageReferenceFiles'); const input = document.getElementById('imageReferenceInput'); if (container) container.innerHTML = ''; if (input) input.value = ''; } function clearPromptAndAnalysis() { document.getElementById('promptInput').value = ''; const interpretationBox = document.getElementById('interpretationBox'); if (interpretationBox) interpretationBox.classList.remove('show'); const promptTemplates = document.getElementById('promptTemplates'); if (promptTemplates) promptTemplates.style.display = 'none'; } // --- Prompt Genie Intelligence Functions --- function analyzePrompt() { const prompt = document.getElementById('promptInput').value.trim(); const interpretationBox = document.getElementById('interpretationBox'); const interpretationText = document.getElementById('interpretationText'); const genieMetrics = document.getElementById('genieMetrics'); if (!prompt) { interpretationBox.classList.remove('show'); return; } // Real-time analysis const analysis = performPromptAnalysis(prompt); interpretationText.innerHTML = `
Intent: ${analysis.intent}
Clarity Score: ${analysis.clarity}/10
Suggestions: ${analysis.suggestions.join(', ')}
`; genieMetrics.innerHTML = `
${analysis.wordCount}
Words
${analysis.complexity}
Complexity
${analysis.specificity}
Specificity
${analysis.effectiveness}%
Effectiveness
`; interpretationBox.classList.add('show'); } function performPromptAnalysis(prompt) { const words = prompt.split(/\s+/).length; const sentences = prompt.split(/[.!?]+/).length - 1; // Intent detection const intents = { 'create': /\b(create|generate|make|build|design|craft)\b/i, 'analyze': /\b(analyze|examine|review|evaluate|assess)\b/i, 'explain': /\b(explain|describe|tell|show|how)\b/i, 'compare': /\b(compare|contrast|versus|vs|difference)\b/i, 'list': /\b(list|enumerate|outline|steps|process)\b/i }; let detectedIntent = 'general'; for (const [intent, pattern] of Object.entries(intents)) { if (pattern.test(prompt)) { detectedIntent = intent; break; } } // Clarity scoring let clarity = 5; if (words > 10) clarity += 2; if (sentences > 1) clarity += 1; if (/\b(specific|detailed|comprehensive)\b/i.test(prompt)) clarity += 2; if (/\?/.test(prompt)) clarity += 1; clarity = Math.min(10, clarity); // Suggestions const suggestions = []; if (words < 5) suggestions.push('Add more detail'); if (!prompt.includes('?') && detectedIntent === 'general') suggestions.push('Be more specific'); if (!/\b(please|could|would)\b/i.test(prompt)) suggestions.push('Use polite language'); if (suggestions.length === 0) suggestions.push('Well structured'); return { intent: detectedIntent.charAt(0).toUpperCase() + detectedIntent.slice(1), wordCount: words, clarity: clarity, clarityColor: clarity >= 8 ? '#48bb78' : clarity >= 6 ? '#ed8936' : '#f56565', complexity: words > 20 ? 'High' : words > 10 ? 'Medium' : 'Low', specificity: /\b(specific|detailed|exactly|precisely)\b/i.test(prompt) ? 'High' : 'Medium', effectiveness: Math.min(95, 60 + (clarity * 3) + (words > 10 ? 10 : 0)), suggestions: suggestions }; } function enhancePromptAuto() { const promptInput = document.getElementById('promptInput'); const currentPrompt = promptInput.value.trim(); if (!currentPrompt) { alert('Please enter a prompt first'); return; } const enhanced = generateEnhancedPrompt(currentPrompt); promptInput.value = enhanced; analyzePrompt(); // Show enhancement notification showNotification('✨ Prompt enhanced with AI suggestions!', 'success'); } function generateEnhancedPrompt(original) { const enhancements = { structure: 'Please provide a detailed and comprehensive response about', context: 'Consider the following context and requirements:', format: 'Structure your response with clear headings and examples.', tone: 'Use a professional and informative tone throughout.' }; let enhanced = original; // Add structure if missing if (!/\b(please|could|would)\b/i.test(enhanced)) { enhanced = `Please ${enhanced.toLowerCase()}`; } // Add specificity if (enhanced.length < 50) { enhanced += '. Include specific examples and actionable insights.'; } // Add format guidance if (!/\b(format|structure|organize)\b/i.test(enhanced)) { enhanced += ' Organize the response in a clear, easy-to-follow format.'; } return enhanced; } function showPromptTemplates() { const templatesDiv = document.getElementById('promptTemplates'); const templateGrid = document.getElementById('templateGrid'); const templates = [ { title: 'Content Creation', desc: 'Generate engaging content for any platform', preview: 'Create compelling content about [topic] for [audience]...' }, { title: 'Problem Solving', desc: 'Structured approach to complex problems', preview: 'Analyze the problem of [issue] and provide 3 solutions...' }, { title: 'Learning & Education', desc: 'Educational content and explanations', preview: 'Explain [concept] in simple terms with examples...' }, { title: 'Business Strategy', desc: 'Strategic business insights and planning', preview: 'Develop a strategy for [business goal] considering...' }, { title: 'Creative Writing', desc: 'Storytelling and creative content', preview: 'Write a creative story about [theme] with [elements]...' }, { title: 'Data Analysis', desc: 'Analytical and research-focused prompts', preview: 'Analyze the data trends in [field] and identify...' } ]; templateGrid.innerHTML = templates.map(template => `
${template.title}
${template.desc}
${template.preview}
`).join(''); templatesDiv.style.display = templatesDiv.style.display === 'none' ? 'block' : 'none'; } function applyTemplate(templateName) { const templates = { 'Content Creation': 'Create compelling and engaging content about [your topic] for [target audience]. Include a catchy headline, key points, and a clear call-to-action. Make it shareable and optimized for [platform].', 'Problem Solving': 'Analyze the problem of [describe your challenge] and provide 3 practical solutions. For each solution, include implementation steps, potential obstacles, and success metrics.', 'Learning & Education': 'Explain [concept or topic] in simple, easy-to-understand terms. Include real-world examples, analogies, and a step-by-step breakdown. Make it suitable for [audience level].', 'Business Strategy': 'Develop a comprehensive strategy for [business goal or challenge]. Consider market conditions, resources, timeline, and provide actionable recommendations with measurable outcomes.', 'Creative Writing': 'Write a creative and engaging [type of content] about [theme or subject]. Include vivid descriptions, compelling characters or elements, and maintain [desired tone] throughout.', 'Data Analysis': 'Analyze the trends and patterns in [data or field]. Identify key insights, correlations, and provide data-driven recommendations for [specific outcome or decision].' }; const promptInput = document.getElementById('promptInput'); promptInput.value = templates[templateName] || ''; analyzePrompt(); // Hide templates document.getElementById('promptTemplates').style.display = 'none'; showNotification(`πŸ“ ${templateName} template applied!`, 'info'); } function confirmInterpretation() { showNotification('βœ… Prompt analysis confirmed!', 'success'); } function handleTaskTypeChange() { const taskType = document.getElementById('promptTask').value; const industryGroup = document.getElementById('promptIndustryGroup'); const toneGroup = document.getElementById('promptToneGroup'); // Hide Industry and Tone for specific task types const hideForTasks = ['image-generation', 'video-generation']; if (hideForTasks.includes(taskType)) { if (industryGroup) industryGroup.classList.add('d-none'); if (toneGroup) toneGroup.classList.add('d-none'); } else { if (industryGroup) industryGroup.classList.remove('d-none'); if (toneGroup) toneGroup.classList.remove('d-none'); } // Clear the prompt input when task type changes document.getElementById('promptInput').value = ''; analyzePrompt(); // This will hide the analysis box as the prompt is now empty } async function upscaleImage() { if (uploadedFiles.length === 0) { alert('Please upload an image to upscale'); return; } const imageFile = uploadedFiles.find(file => file.type.startsWith('image/')); if (!imageFile) { alert('Please upload a valid image file'); return; } const generateBtn = document.getElementById('generateBtn'); const outputSection = document.getElementById('outputSection'); const upscaleFactor = parseInt(document.getElementById('upscaleFactor').value); const outputFormat = document.getElementById('outputFormat').value; const enhanceQuality = document.getElementById('enhanceQuality').checked; generateBtn.disabled = true; generateBtn.innerHTML = '
Upscaling...'; outputSection.innerHTML = `

Upscaling your image...

`; try { const upscaledImageUrl = await processImageUpscale(imageFile, upscaleFactor, outputFormat, enhanceQuality); displayUpscaleResult(upscaledImageUrl, upscaleFactor, outputFormat); } catch (error) { displayError('Upscale failed: ' + error.message); } finally { generateBtn.disabled = false; generateBtn.innerHTML = 'Upscale Image'; } } function processImageUpscale(imageFile, factor, format, enhance) { return new Promise((resolve, reject) => { const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); const img = new Image(); img.onload = function() { canvas.width = img.width * factor; canvas.height = img.height * factor; ctx.imageSmoothingEnabled = enhance; ctx.imageSmoothingQuality = enhance ? 'high' : 'low'; ctx.drawImage(img, 0, 0, canvas.width, canvas.height); resolve(canvas.toDataURL(`image/${format}`, 0.95)); }; img.onerror = () => reject(new Error('Failed to load image')); img.src = URL.createObjectURL(imageFile); }); } function displayUpscaleResult(imageUrl, factor, format) { const outputSection = document.getElementById('outputSection'); outputSection.innerHTML = `
Upscaled ${factor}x in ${format.toUpperCase()} format
`; } function shareResult(url) { if (navigator.share) { navigator.share({ title: 'AI Generated Content', url: url }); } else { navigator.clipboard.writeText(url); alert('URL copied to clipboard!'); } } function displayError(message) { const outputSection = document.getElementById('outputSection'); outputSection.innerHTML = `

Operation Failed

${message}

`; } // Initialize the app document.addEventListener('DOMContentLoaded', function() { // Tab switching document.querySelectorAll('.mode-btn').forEach(btn => { btn.addEventListener('click', () => switchMode(btn.dataset.mode)); }); // Generate button document.getElementById('generateBtn').addEventListener('click', generateContent); // Currency converter inputs ['fromCurrency', 'toCurrency', 'currencyAmount'].forEach(id => { const el = document.getElementById(id); if (el) el.addEventListener('input', convertCurrency); }); // Set initial mode switchMode('image'); });