-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApp.jsx
More file actions
218 lines (193 loc) · 6.01 KB
/
Copy pathApp.jsx
File metadata and controls
218 lines (193 loc) · 6.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
import { useState, useRef } from 'react';
// API Configuration
// Create a .env file with: VITE_API_KEY=your-api-key-here
// Get a free key at: https://dashboard.apiverve.com
const API_KEY = import.meta.env.VITE_API_KEY;
const API_URL = 'https://api.apiverve.com/v1/imagecaption';
function App() {
const [image, setImage] = useState(null);
const [preview, setPreview] = useState(null);
const [caption, setCaption] = useState('');
const [loading, setLoading] = useState(false);
const [error, setError] = useState('');
const [history, setHistory] = useState([]);
const fileInputRef = useRef(null);
// Handle file selection
const handleFileChange = (e) => {
const file = e.target.files[0];
if (!file) return;
// Validate file type
if (!file.type.startsWith('image/')) {
setError('Please select an image file');
return;
}
// Validate file size (5MB max)
if (file.size > 5 * 1024 * 1024) {
setError('Image must be less than 5MB');
return;
}
setImage(file);
setPreview(URL.createObjectURL(file));
setCaption('');
setError('');
};
// Handle drag and drop
const handleDrop = (e) => {
e.preventDefault();
const file = e.dataTransfer.files[0];
if (file) {
const input = fileInputRef.current;
const dt = new DataTransfer();
dt.items.add(file);
input.files = dt.files;
handleFileChange({ target: { files: [file] } });
}
};
// Generate caption
const generateCaption = async () => {
if (!image) return;
if (!API_KEY) {
setError('Add your API key to .env file (VITE_API_KEY=your-key)');
return;
}
setLoading(true);
setError('');
setCaption('');
try {
const formData = new FormData();
formData.append('image', image);
const response = await fetch(API_URL, {
method: 'POST',
headers: {
'x-api-key': API_KEY
},
body: formData
});
const data = await response.json();
if (data.status === 'ok' && data.data) {
const newCaption = data.data.caption || data.data.text || 'No caption generated';
setCaption(newCaption);
// Add to history
setHistory(prev => [{
id: Date.now(),
imageUrl: preview,
caption: newCaption
}, ...prev.slice(0, 9)]);
} else {
setError(data.error || 'Failed to generate caption');
}
} catch (err) {
setError('API request failed. Check your API key.');
console.error('API Error:', err);
} finally {
setLoading(false);
}
};
// Clear current image
const clearImage = () => {
setImage(null);
setPreview(null);
setCaption('');
setError('');
if (fileInputRef.current) {
fileInputRef.current.value = '';
}
};
// Copy caption to clipboard
const copyCaption = () => {
navigator.clipboard.writeText(caption);
};
return (
<div className="app">
<header>
<h1>AI Image Caption</h1>
<p className="subtitle">Generate intelligent captions for any image</p>
</header>
<main>
{/* Upload Section */}
<section className="upload-section">
{!preview ? (
<div
className="upload-area"
onClick={() => fileInputRef.current?.click()}
onDrop={handleDrop}
onDragOver={(e) => e.preventDefault()}
>
<div className="upload-icon">🖼️</div>
<p>Drop an image here or <span className="link">browse</span></p>
<span className="hint">Supports JPG, PNG, GIF (max 5MB)</span>
<input
ref={fileInputRef}
type="file"
accept="image/*"
onChange={handleFileChange}
hidden
/>
</div>
) : (
<div className="preview-container">
<img src={preview} alt="Preview" className="preview-image" />
<button className="clear-btn" onClick={clearImage}>×</button>
</div>
)}
</section>
{/* Generate Button */}
<button
className="generate-btn"
onClick={generateCaption}
disabled={!image || loading}
>
{loading ? (
<>
<span className="spinner"></span>
Analyzing Image...
</>
) : (
<>✨ Generate Caption</>
)}
</button>
{/* Error Display */}
{error && <div className="error">{error}</div>}
{/* Caption Result */}
{caption && (
<div className="result">
<div className="result-header">
<h3>Generated Caption</h3>
<button className="copy-btn" onClick={copyCaption}>
Copy
</button>
</div>
<p className="caption-text">{caption}</p>
</div>
)}
{/* History Section */}
{history.length > 0 && (
<section className="history-section">
<h2>Recent Captions</h2>
<div className="history-grid">
{history.map(item => (
<div key={item.id} className="history-item">
<img src={item.imageUrl} alt="History" />
<p>{item.caption}</p>
</div>
))}
</div>
</section>
)}
</main>
<footer>
<p>
Powered by{' '}
<a
href="https://apiverve.com/marketplace/imagecaption?utm_source=github&utm_medium=tutorial&utm_campaign=image-caption-react-tutorial"
target="_blank"
rel="noopener noreferrer"
>
APIVerve Image Caption API
</a>
</p>
</footer>
</div>
);
}
export default App;