0% found this document useful (0 votes)
6 views25 pages

Current

Current with solution

Uploaded by

bittu23091988
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views25 pages

Current

Current with solution

Uploaded by

bittu23091988
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

<!

DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>vidyadarshan Electricity 10</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.
min.css" rel="stylesheet">
<style>
.canvas-container {
border: 1px solid #000;
touch-action: none;
background-color: white;
margin-bottom: 15px;
}
.concept-card {
cursor: pointer;
transition: all 0.3s;
}
.concept-card:hover {
transform: translateY(-5px);
box-shadow: 0 10px 20px rgba(0,0,0,0.1);
}
#recognizedText {
white-space: pre-wrap;
font-family: monospace;
}
.tool-btn {
margin-bottom: 5px;
width: 100%;
}
.tool-btn.active {
background-color: #0d6efd;
color: white;
}
.color-option {
width: 25px;
height: 25px;
display: inline-block;
margin-right: 5px;
cursor: pointer;
border: 1px solid #ddd;
}
.selected-color {
border: 2px solid #000;
}
.section-title {
margin-top: 20px;
margin-bottom: 10px;
padding-bottom: 5px;
border-bottom: 1px solid #eee;
}
#questionBank {
max-height: 100px;
overflow-y: auto;
}
.question-item {
cursor: pointer;
padding: 5px;
border-bottom: 1px solid #eee;
}
.question-item:hover {
background-color: #f8f9fa;
}
.selected-question {
background-color: #e9ecef;
}
.custom-question-container {
margin-top: 15px;
}
.tab-button {
padding: 8px 15px;
border: 1px solid #dee2e6;
background-color: #f8f9fa;
cursor: pointer;
}
.tab-button.active {
background-color: #0d6efd;
color: white;
border-color: #0d6efd;
}
</style>
</head>
<body>
<div class="container-fluid mt-3">
<h1 class="text-center">VIDYADARSHAN PHYSICS AI TEACHER</h1>

<div class="row">
<!-- Left Column - Problem Input -->
<div class="col-md-6">
<h3 class="section-title">Problem Input</h3>

<div class="d-flex mb-3">


<div class="tab-button active" id="bankTab">Question Bank</div>
<div class="tab-button" id="customTab">Custom Question</div>
</div>

<!-- Question Bank Section -->


<div id="bankSection">
<div class="mb-3">
<label class="form-label">Select from Question Bank:</label>
<div id="questionBank" class="border rounded p-2 mb-3">
<!-- Questions will be loaded here -->
</div>
</div>
</div>

<!-- Custom Question Section -->


<div id="customSection" style="display: none;">
<div class="mb-3">
<label for="customQuestion" class="form-label">Enter Your Own
Question:</label>
<textarea class="form-control" id="customQuestion" rows="6" pla
ceholder="Type your electricity problem here..."></textarea>
</div>
<button id="useCustomBtn" class="btn btn-primary mb-3">Use This
Question</button>
</div>

<div class="mb-3">
<label for="problemText" class="form-label">Selected Problem:</la
bel>
<textarea class="form-control" id="problemText" rows="6" readonly
></textarea>
</div>

</div>

<!-- Right Column - Solution Input -->


<div class="col-md-6">
<h3 class="section-title">Your Solution</h3>
<canvas id="solutionCanvas" class="canvas-container" width="1000" h
eight="400"></canvas>

<div class="row">
<div class="col-md-8">
<div class="mb-3">
<h5>Tools</h5>
<button id="penTool" class="btn btn-outline-primary tool-btn ac
tive">Pen</button>
<button id="eraserTool" class="btn btn-outline-danger tool-btn"
>Eraser</button>
</div>
<div class="mb-3">
<h5>Pen Size</h5>
<input type="range" id="penSize" min="1" max="20" value="2" cl
ass="form-range">

</div>
<div class="mb-3">
<h5>Eraser Size</h5>
<input type="range" id="eraserSize" min="5" max="50" value="1
0" class="form-range">

</div>
<div class="mb-3">
<h5>Color</h5>
<div class="color-option selected-color" style="background-col
or: #000000;" data-color="#000000"></div>
<div class="color-option" style="background-color: #ff0000;" da
ta-color="#ff0000"></div>
<div class="color-option" style="background-color: #0000ff;" da
ta-color="#0000ff"></div>
<div class="color-option" style="background-color: #008000;" d
ata-color="#008000"></div>
</div>
</div>
<div class="col-md-4">
<button id="clearCanvas" class="btn btn-warning mb-3">Clear Ca
nvas</button>
<button id="recognizeBtn" class="btn btn-success mb-3">Analyze
Solution</button>
</div>
</div>

<div id="recognizedText" class="mt-3 p-2 border rounded"></div>


</div>
</div>

<!-- Analysis Section -->


<div class="row mt-4">
<div class="col-12">
<h3 class="section-title">Analysis Results</h3>
<div id="loadingAnalysis" class="text-center" style="display:none;">
<div class="spinner-border text-primary" role="status">
<span class="visually-hidden">Loading...</span>
</div>
<p>Analyzing your solution...</p>
</div>
<div id="errorAnalysis" class="alert alert-danger" style="display:none;"
></div>
<div id="solutionAnalysisResult"></div>
<div id="conceptRemediation" class="mt-4"></div>
<div id="practiceProblems" class="mt-4"></div>
</div>
</div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.b
undle.min.js"></script>
<script>
// Configuration - Replace with your actual Gemini API key
const GEMINI_API_KEY = 'AIzaSyDgBhaI9zWmolWSI0gIYh2Zrep4vAx62rw';
// Replace with your actual key

// Question Bank - Sample kinematics questions


const questionBank = [
{ id: 1, text: "Two bulbs have ratings 100 W, 220 V and 60 W, 220 V respec
tively. Which one has a greater resistance?" },
{ id: 2, text: " A torch bulb has a resistance of 1 Ω when cold. It draws a c
urrent of 0.2 A from a source of 2 V and glows. Calculate (i) the resistance of t
he bulb when glowing and (ii) explain the reason for the difference in resistan
ce." },
{ id: 3, text: "Calculate the resistance of 1 km long copper wire of radius
1 mm. (Resistivity of copper = 1.72 x 10⁻⁸ Ω·m)" },
{ id: 4, text: "When a potential difference of 2 V is applied across the end
s of a wire of 5 m length, a current of 1 A is found to flow through it. Calculate:
(i) The resistance per unit length of the wire (ii) The resistance of 2 m leng
th of this wire (iii) The resistance across the ends of the wire if it is doubled
on itself." },
{ id: 5, text: "How much work is done in moving 4 C across two point hav
ing pd. 10 V?" },
{ id: 6, text: "How much energy is given to each coulomb of charge passi
ng through a 9 V battery?" },
{ id: 7, text: "100 J of work is done in moving a charge of 5 C from one te
rminal of battery to another. What is the potential difference of battery?" },
{ id: 8, text: "If 4 × 10⁻³ J of work is done in moving a particle carrying a
charge of 16 × 10⁻⁶ C from infinity to point P, what will be the potential at the po
int?" },
{ id: 9, text: "Calculate the current and resistance of a 100 W, 200 V elect
ric bulb." },
{ id: 10, text: "Calculate the power rating of the heater coil when used on
220 V supply taking 5 Amps." },
{ id: 11, text: "A lamp can work on a 50 volt mains taking 2 amps. What v
alue of the resistance must be connected in series with it so that it can be oper
ated from 200 volt mains giving the same power?" },
{ id: 12, text: "Calculate the work done in moving a charge of 5 coulombs
from a point at a potential of 210 volts to another point at 240 volts." },
{ id: 13, text: "How many electrons pass through a lamp in one minute if
the current be 200 mA?" },
{ id: 14, text: "Calculate the current supplied by a cell if the amount of ch
arge passing through the cell in 4 seconds is 12 C?" },
{ id: 15, text: "A 2 Volt cell is connected to a 1 Ω resistor. How many elec
trons come out of the negative terminal of the cell in 2 minutes?" },
{ id: 16, text: "How much current will an electric bulb draw from a 220 V
source, if the resistance of the bulb filament is 1200 Ω?" },
{ id: 17, text: "How much current will an electric heater coil draw from a
220 V source, if the resistance of the heater coil is 100 Ω?" },
{ id: 18, text: "The potential difference between the terminals of an electr
ic heater is 60 V when it draws a current of 4 A from the source. What current w
ill the heater draw if the potential difference is increased to 120 V?" },
{ id: 19, text: "A 4 Ω resistance wire is doubled on itself. Calculate the ne
w resistance of the wire." },
{ id: 20, text: "A circuit is made of 0.4 Ω wire, a 150 Ω bulb, and a 120 Ω rh
eostat connected in series. Determine the total resistance of the circuit." },
{ id: 21, text: "A current of 0.2 Ampere flows through a conductor of resis
tance 4.5 Ω. Calculate the potential difference at the ends of the conductor." },
{ id: 22, text: "A lamp has a resistance of 96 ohms. How much current flo
ws through the lamp when it is connected to 120 volts?" },
{ id: 23, text: "The manufacturer specifies that a certain lamp will allow 0
.8 ampere of current when 120 volts is applied to it. What is the resistance of th
e lamp?" },
{ id: 24, text: "How much voltage is required to cause 1.6 amperes in a d
evice that has 30 ohms of resistance?" },
{ id: 25, text: "How much power is dissipated when 0.2 ampere of current
flows through a 100-ohm resistor?" },
{ id: 26, text: "How much energy is converted by a device that draws 1.5
amperes from a 12-volt battery for 2 hours?" },
{ id: 27, text:"When a 4V battery is connected across an unknown resisto
r there is a current of 100 mA in the circuit. The value of the resistance of the re
sister is: a) 4 Ω b) 40 Ω c) 400 Ω d) 0.4 Ω" },
{ id: 28, text:"Calculate the energy transferred when 2 A current flows thr
ough a 10 Ω resistor for 30 minutes." },
{ id: 29, text:"Calculate the amount of charge that would flow in one hour
through the element of an electric iron drawing a current of 0.4 amps." },
{ id: 30, text:"Two resistances of 4 Ω and 8 Ω are connected in parallel.
What would be the combined resistance of the system?" },
{ id: 31, text:"Two identical resistors each of resistance 2 Ohm are conn
ected in turn (1) in series (2) in parallel to a battery of 12 V. Calculate the ratio o
f power consumed in two cases." },
{ id: 32, text:"(i) A 100 W electric bulb is connected to 220 V mains powe
r supply. Calculate the strength of the electric current passing through the bulb.
(ii) If the same bulb is taken to U.S.A where the main power supply is 110 V, ho
w much electric current will pass through the bulb when connected to mains?" }
,
{ id: 33, text:"Calculate the resistance of 2 km long copper wire of radius
2 mm.(Resistivity of copper = 1.72 × 10⁻⁸ Ω·m)" },
{ id: 34, text:"A wire of length 3 m and area of cross-section 1.7 × 10⁻⁶ m
² has a resistance 3 × 10⁻² ohm. a. What is the formula for resistivity of the
wire and what is the unit of it? b. Calculate the resistivity of the wire." },
{ id: 35, text:"Two electric lamps of 100W and 25W respectively are conn
ected in parallel to a supply voltage of 200V. Calculate the total current flowing
through the circuit." },
{ id: 36, text:"A cylindrical conductor of length and uniform area of cross
section has resistance . Another conductor of the same material and resistan
ce has length . What will be its area of cross section?" },
{ id: 37, text:"A current of 5A passes through a 2Ω resistor for 30 minute
s. Calculate the electrical energy transferred." },

];

// Initialize question bank


function initializeQuestionBank() {
const questionBankElement = document.getElementById('questionBank'
);
questionBankElement.innerHTML = '';

questionBank.forEach(question => {
const questionElement = document.createElement('div');
questionElement.className = 'question-item';
questionElement.textContent = `Question ${question.id}`;
questionElement.dataset.id = question.id;
questionElement.addEventListener('click', () => selectQuestion(questi
on.id));
questionBankElement.appendChild(questionElement);
});
}

// Select question from bank


function selectQuestion(questionId) {
const question = questionBank.find(q => q.id === questionId);
if (question) {
document.getElementById('problemText').value = question.text;

// Highlight selected question


document.querySelectorAll('.question-item').forEach(item => {
item.classList.toggle('selected-question', item.dataset.id == questi
onId);
});
}
}

// Switch between question bank and custom question tabs


function setupTabSwitching() {
const bankTab = document.getElementById('bankTab');
const customTab = document.getElementById('customTab');
const bankSection = document.getElementById('bankSection');
const customSection = document.getElementById('customSection');

bankTab.addEventListener('click', () => {
bankTab.classList.add('active');
customTab.classList.remove('active');
bankSection.style.display = 'block';
customSection.style.display = 'none';
});

customTab.addEventListener('click', () => {
customTab.classList.add('active');
bankTab.classList.remove('active');
customSection.style.display = 'block';
bankSection.style.display = 'none';
});
}

// Set up custom question functionality


function setupCustomQuestion() {
document.getElementById('useCustomBtn').addEventListener('click', () =
>{
const customQuestion = document.getElementById('customQuestion'
).value.trim();
if (customQuestion) {
document.getElementById('problemText').value = customQuestion;

// Remove any selected question highlights


document.querySelectorAll('.question-item').forEach(item => {
item.classList.remove('selected-question');
});
} else {
alert('Please enter a question first');
}
});
}

// Canvas setup for handwriting


const canvas = document.getElementById('solutionCanvas');
const ctx = canvas.getContext('2d');
let isDrawing = false;
let lastX = 0;
let lastY = 0;
let currentTool = 'pen';
let currentColor = '#000000';
let currentSize = 2;
let eraserSize = 10;

// Set canvas background to white


ctx.fillStyle = 'white';
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.strokeStyle = currentColor;
ctx.lineWidth = currentSize;
ctx.lineCap = 'round';

// Initialize the app


function initializeApp() {
initializeQuestionBank();
setupTabSwitching();
setupCustomQuestion();

// Tool selection
document.getElementById('penTool').addEventListener('click', () => {
currentTool = 'pen';
document.getElementById('penTool').classList.add('active');
document.getElementById('eraserTool').classList.remove('active');
});

document.getElementById('eraserTool').addEventListener('click', () => {
currentTool = 'eraser';
document.getElementById('eraserTool').classList.add('active');
document.getElementById('penTool').classList.remove('active');
});

// Pen size control


const penSizeSlider = document.getElementById('penSize');
const penSizeValue = document.getElementById('penSizeValue');
penSizeSlider.addEventListener('input', () => {
currentSize = penSizeSlider.value;
penSizeValue.textContent = `${currentSize}px`;
if (currentTool === 'pen') {
ctx.lineWidth = currentSize;
}
});

// Eraser size control


const eraserSizeSlider = document.getElementById('eraserSize');
const eraserSizeValue = document.getElementById('eraserSizeValue');
eraserSizeSlider.addEventListener('input', () => {
eraserSize = eraserSizeSlider.value;
eraserSizeValue.textContent = `${eraserSize}px`;
});

// Color selection
const colorOptions = document.querySelectorAll('.color-option');
colorOptions.forEach(option => {
option.addEventListener('click', () => {
currentColor = option.dataset.color;
ctx.strokeStyle = currentColor;
colorOptions.forEach(opt => opt.classList.remove('selected-color')
);
option.classList.add('selected-color');
});
});

// Touch and mouse event handlers


function startDrawing(e) {
isDrawing = true;
const pos = getPosition(e);
lastX = pos.x;
lastY = pos.y;

if (currentTool === 'eraser') {


ctx.globalCompositeOperation = 'destination-out';
ctx.lineWidth = eraserSize;
ctx.beginPath();
ctx.arc(lastX, lastY, eraserSize/2, 0, Math.PI * 2);
ctx.fill();
} else {
ctx.globalCompositeOperation = 'source-over';
ctx.lineWidth = currentSize;
ctx.strokeStyle = currentColor;
ctx.beginPath();
ctx.moveTo(lastX, lastY);
}
}

function draw(e) {
if (!isDrawing) return;

const pos = getPosition(e);

if (currentTool === 'eraser') {


ctx.globalCompositeOperation = 'destination-out';
ctx.lineWidth = eraserSize;
ctx.beginPath();
ctx.moveTo(lastX, lastY);
ctx.lineTo(pos.x, pos.y);
ctx.stroke();
} else {
ctx.globalCompositeOperation = 'source-over';
ctx.lineWidth = currentSize;
ctx.strokeStyle = currentColor;
ctx.lineTo(pos.x, pos.y);
ctx.stroke();
}

lastX = pos.x;
lastY = pos.y;
}

function stopDrawing() {
isDrawing = false;
ctx.beginPath(); // Start a new path for the next stroke
}
function getPosition(e) {
let x, y;
if (e.type.includes('touch')) {
const touch = e.touches[0] || e.changedTouches[0];
const rect = canvas.getBoundingClientRect();
x = touch.clientX - rect.left;
y = touch.clientY - rect.top;
} else {
const rect = canvas.getBoundingClientRect();
x = e.clientX - rect.left;
y = e.clientY - rect.top;
}
return { x, y };
}

// Event listeners for both mouse and touch


canvas.addEventListener('mousedown', startDrawing);
canvas.addEventListener('mousemove', draw);
canvas.addEventListener('mouseup', stopDrawing);
canvas.addEventListener('mouseout', stopDrawing);

canvas.addEventListener('touchstart', (e) => {


e.preventDefault();
startDrawing(e);
});
canvas.addEventListener('touchmove', (e) => {
e.preventDefault();
draw(e);
});
canvas.addEventListener('touchend', (e) => {
e.preventDefault();
stopDrawing();
});
// Clear canvas
document.getElementById('clearCanvas').addEventListener('click', () => {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = 'white';
ctx.fillRect(0, 0, canvas.width, canvas.height);
document.getElementById('recognizedText').textContent = '';
// Reset to default drawing settings
ctx.globalCompositeOperation = 'source-over';
ctx.strokeStyle = currentColor;
ctx.lineWidth = currentSize;
});

// Recognize handwriting (using Gemini API)


document.getElementById('recognizeBtn').addEventListener('click', asyn
c () => {
const problemText = document.getElementById('problemText').value;
if (!problemText.trim()) {
alert('Please select or enter a problem first');
return;
}

// Show loading state


document.getElementById('loadingAnalysis').style.display = 'block';
document.getElementById('errorAnalysis').style.display = 'none';

try {
// Convert canvas to image data
const imageData = canvas.toDataURL('image/png');

// Call Gemini API for handwriting recognition and analysis


const analysis = await analyzeSolutionWithGemini(problemText, im
ageData);
// Display the recognized text
document.getElementById('recognizedText').textContent = analysis.
recognized_text || "No text recognized";

// Display the full analysis


displayAnalysisResults(analysis);

} catch (error) {
document.getElementById('errorAnalysis').textContent = `Error: ${er
ror.message}`;
document.getElementById('errorAnalysis').style.display = 'block';
} finally {
document.getElementById('loadingAnalysis').style.display = 'none';
}
});

// Analyze the problem (using Gemini API)


document.getElementById('analyzeBtn').addEventListener('click', async (
) => {
const problemText = document.getElementById('problemText').value;
if (!problemText.trim()) {
alert('Please select or enter a problem first');
return;
}

try {
const response = await analyzeProblemWithGemini(problemText);
document.getElementById('problemAnalysis').innerHTML = `
<div class="card">
<div class="card-header">
Problem Analysis
</div>
<div class="card-body">
<h5 class="card-title">Key Concepts</h5>
<p class="card-text">${formatAsBullets(response.concepts)
}</p>
<h5 class="card-title">Expected Approach</h5>
<p class="card-text">${formatAsParagraphs(response.appro
ach)}</p>
<h5 class="card-title">Common Mistakes</h5>
<p class="card-text">${formatAsBullets(response.common_
mistakes)}</p>
</div>
</div>
`;
} catch (error) {
document.getElementById('problemAnalysis').innerHTML = `
<div class="alert alert-danger">Error analyzing problem: ${error.m
essage}</div>
`;
}
});
}

// Analyze solution using Gemini API (both image recognition and analysis
)
async function analyzeSolutionWithGemini(problemText, imageData) {
const prompt = `you are a physics teacher.Student ask problem from yo
u with:
1. A kinematics problem statement
2. An image of a student's handwritten solution to this problem

Please:
1. Extract and transcribe the handwritten solution text
2. Analyze the solution for mistakes
3. Provide the correct solution approach
4. Identify weak concepts
5. Suggest 2 that covers all weak concept for practice practice problems

Return your response as a JSON object with these properties:


- recognized_text (string)
- mistakes (array)
- correct_solution (string)
- weak_concepts (array)
- practice_problems (array)

Problem: ${problemText}`;

const response = await callGeminiAPI(prompt, imageData);

try {
return JSON.parse(response);
} catch {
// Fallback if JSON parsing fails
return {
recognized_text: "Could not recognize text",
mistakes: ["Analysis failed"],
correct_solution: "Could not analyze solution",
weak_concepts: [],
practice_problems: []
};
}
}

// Generic function to call Gemini API


async function callGeminiAPI(prompt, imageData = null) {
const parts = [{ text: prompt }];
if (imageData) {
parts.push({
inline_data: {
mime_type: "image/png",
data: imageData.split(',')[1]
}
});
}

const response = await fetch(`https://generativelanguage.googleapis.co


m/v1beta/models/gemini-2.0-flash:generateContent?key=${GEMINI_API_KEY}`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
contents: [{
parts: parts
}],
generationConfig: {
response_mime_type: "application/json"
}
})
});

const data = await response.json();

if (!response.ok) {
throw new Error(data.error?.message || 'Failed to call Gemini API');
}
return data.candidates?.[0]?.content?.parts?.[0]?.text || '';
}

// Display analysis results


function displayAnalysisResults(analysis) {
const resultDiv = document.getElementById('solutionAnalysisResult');
const conceptDiv = document.getElementById('conceptRemediation');
const practiceDiv = document.getElementById('practiceProblems');

// Main analysis results


resultDiv.innerHTML = `
<div class="card mb-4">
<div class="card-header bg-primary text-white">
Solution Analysis
</div>
<div class="card-body">
<h5 class="card-title">Identified Mistakes</h5>
<div class="card-text">${formatAsBullets(analysis.mistakes)}</di
v>

<h5 class="card-title mt-3">Correct Solution</h5>


<div class="card-text">${formatAsParagraphs(analysis.correct_s
olution)}</div>

<h5 class="card-title mt-3">Weak Concepts</h5>


<div class="card-text">${formatAsBullets(analysis.weak_concept
s)}</div>
</div>
</div>
`;

// Concept explanations
if (analysis.weak_concepts && analysis.weak_concepts.length > 0) {
conceptDiv.innerHTML = '<h4>Concept Explanations</h4><div class=
"row" id="conceptCards"></div>';
const cardsContainer = document.getElementById('conceptCards');

analysis.weak_concepts.forEach(concept => {
const card = document.createElement('div');
card.className = 'col-md-6 mb-3';
card.innerHTML = `
<div class="card concept-card h-100">
<div class="card-header">
${concept}
</div>
<div class="card-body">
<p class="card-text">Loading explanation...</p>
</div>
</div>
`;
cardsContainer.appendChild(card);

// Load explanation asynchronously


loadConceptExplanation(concept, card);
});
} else {
conceptDiv.innerHTML = '';
}

// Practice problems
if (analysis.practice_problems && analysis.practice_problems.length > 0
){
practiceDiv.innerHTML = `
<div class="card">
<div class="card-header bg-success text-white">
Recommended Practice Problems
</div>
<div class="card-body">
${formatAsNumberedList(analysis.practice_problems)}
</div>
</div>
`;
} else {
practiceDiv.innerHTML = '';
}
}

// Load concept explanation


async function loadConceptExplanation(concept, cardElement) {
try {
const prompt = `Explain the current concept "${concept}" to a high sc
hool student in 20 word only.
Format as JSON .`;

const response = await callGeminiAPI(prompt);


const result = JSON.parse(response);

cardElement.querySelector('.card-text').innerHTML = `
<p>${result.explanation || 'No explanation available'}</p>
${result.example ? `<div class="mt-2"><strong>Example:</strong> $
{result.example}</div>` : ''}
`;
} catch (error) {
cardElement.querySelector('.card-text').textContent = `Failed to load e
xplanation: ${error.message}`;
}
}

// Helper functions
function formatAsBullets(text) {
if (Array.isArray(text)) {
return `<ul>${text.map(item => `<li>${item}</li>`).join('')}</ul>`;
}
return `<ul><li>${text}</li></ul>`;
}

function formatAsNumberedList(items) {
if (Array.isArray(items)) {
return `<ol>${items.map(item => `<li>${item}</li>`).join('')}</ol>`;
}
return items;
}

function formatAsParagraphs(text) {
if (Array.isArray(text)) {
return text.map(para => `<p>${para}</p>`).join('');
}
return `<p>${text}</p>`;
}

// Initialize the application when the page loads


window.addEventListener('DOMContentLoaded', initializeApp);
</script>
</body>
</html>

You might also like