Spaces:
Running
Running
server-side pagination
Browse files- frontend/src/pages/ExplorePage/ExplorePage.tsx +81 -73
- py_backend/app/routers/upload.py +228 -31
- py_backend/app/services/huggingface_service.py +3 -12
- py_backend/generate_production_thumbnails.py +0 -121
- py_backend/static/assets/{AdminPage-kwx131wq.js β AdminPage-BeakVMzz.js} +1 -1
- py_backend/static/assets/{ExportModal-k_VKbTpi.js β ExportModal-DJU5iFtN.js} +1 -1
- py_backend/static/assets/index-5HpHyjh5.js +2 -0
- py_backend/static/assets/{index-LmdVBMha.js β index-BzYyR-qc.js} +2 -2
- py_backend/static/assets/{index-D_a-CF3t.js β index-CU7P_Hff.js} +1 -1
- py_backend/static/assets/{index-DvX--7c_.js β index-DrfgCGTV.js} +2 -2
- py_backend/static/assets/index-GUsf-iOM.js +0 -2
- py_backend/static/assets/{jszip.min-DgY44d1h.js β jszip.min-JNyb8pkO.js} +1 -1
- py_backend/static/assets/{useAdmin-BGW0gk2h.js β useAdmin-B4TrJLwR.js} +1 -1
- py_backend/static/index.html +1 -1
frontend/src/pages/ExplorePage/ExplorePage.tsx
CHANGED
@@ -76,6 +76,8 @@ export default function ExplorePage() {
|
|
76 |
// Pagination state
|
77 |
const [currentPage, setCurrentPage] = useState(1);
|
78 |
const [itemsPerPage] = useState(10);
|
|
|
|
|
79 |
|
80 |
const viewOptions = [
|
81 |
{ key: 'explore' as const, label: 'List' },
|
@@ -84,7 +86,23 @@ export default function ExplorePage() {
|
|
84 |
|
85 |
const fetchCaptions = () => {
|
86 |
setIsLoadingContent(true);
|
87 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
88 |
.then(r => {
|
89 |
if (!r.ok) {
|
90 |
console.error('ExplorePage: Grouped endpoint failed, trying legacy endpoint');
|
@@ -105,28 +123,11 @@ export default function ExplorePage() {
|
|
105 |
return r.json();
|
106 |
})
|
107 |
.then(data => {
|
108 |
-
console.log('ExplorePage:
|
109 |
-
|
110 |
-
if (Array.isArray(data)) {
|
111 |
-
const imagesWithCaptions = data.filter((item: { title?: string; generated?: string; model?: string; image_id?: string }) => {
|
112 |
-
const hasCaption = item.generated && item.model;
|
113 |
-
const hasImageId = item.image_id && item.image_id !== 'undefined' && item.image_id !== 'null';
|
114 |
-
|
115 |
-
if (!hasImageId) {
|
116 |
-
console.error('ExplorePage: Item missing valid image_id:', item);
|
117 |
-
}
|
118 |
-
|
119 |
-
return hasCaption && hasImageId;
|
120 |
-
});
|
121 |
-
|
122 |
-
console.log('ExplorePage: Filtered images with captions:', imagesWithCaptions.length);
|
123 |
-
setCaptions(imagesWithCaptions);
|
124 |
-
} else {
|
125 |
-
console.error('ExplorePage: API response is not an array:', data);
|
126 |
-
setCaptions([]);
|
127 |
-
}
|
128 |
})
|
129 |
-
.catch(
|
|
|
130 |
setCaptions([]);
|
131 |
})
|
132 |
.finally(() => {
|
@@ -134,9 +135,51 @@ export default function ExplorePage() {
|
|
134 |
});
|
135 |
};
|
136 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
137 |
useEffect(() => {
|
138 |
fetchCaptions();
|
139 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
140 |
|
141 |
useEffect(() => {
|
142 |
const handleVisibilityChange = () => {
|
@@ -204,43 +247,8 @@ export default function ExplorePage() {
|
|
204 |
});
|
205 |
}, []);
|
206 |
|
207 |
-
|
208 |
-
|
209 |
-
const matchesSearch = !search ||
|
210 |
-
c.title?.toLowerCase().includes(search.toLowerCase()) ||
|
211 |
-
c.generated?.toLowerCase().includes(search.toLowerCase()) ||
|
212 |
-
c.source?.toLowerCase().includes(search.toLowerCase()) ||
|
213 |
-
c.event_type?.toLowerCase().includes(search.toLowerCase());
|
214 |
-
|
215 |
-
// Handle combined metadata from multi-upload items
|
216 |
-
const sourceMatches = !srcFilter ||
|
217 |
-
(c.source && c.source.split(', ').some(s => s.trim() === srcFilter));
|
218 |
-
const categoryMatches = !catFilter ||
|
219 |
-
(c.event_type && c.event_type.split(', ').some(e => e.trim() === catFilter));
|
220 |
-
const matchesRegion = !regionFilter ||
|
221 |
-
c.countries.some(country => country.r_code === regionFilter);
|
222 |
-
const matchesCountry = !countryFilter ||
|
223 |
-
c.countries.some(country => country.c_code === countryFilter);
|
224 |
-
const matchesImageType = !imageTypeFilter || c.image_type === imageTypeFilter;
|
225 |
-
const matchesUploadType = !uploadTypeFilter ||
|
226 |
-
(uploadTypeFilter === 'single' && (!c.image_count || c.image_count <= 1)) ||
|
227 |
-
(uploadTypeFilter === 'multiple' && c.image_count && c.image_count > 1);
|
228 |
-
const matchesReferenceExamples = !showReferenceExamples || c.starred === true;
|
229 |
-
|
230 |
-
return matchesSearch && sourceMatches && categoryMatches && matchesRegion && matchesCountry && matchesImageType && matchesUploadType && matchesReferenceExamples;
|
231 |
-
});
|
232 |
-
}, [captions, search, srcFilter, catFilter, regionFilter, countryFilter, imageTypeFilter, uploadTypeFilter, showReferenceExamples]);
|
233 |
-
|
234 |
-
// Pagination logic
|
235 |
-
const totalPages = Math.ceil(filtered.length / itemsPerPage);
|
236 |
-
const startIndex = (currentPage - 1) * itemsPerPage;
|
237 |
-
const endIndex = startIndex + itemsPerPage;
|
238 |
-
const paginatedResults = filtered.slice(startIndex, endIndex);
|
239 |
-
|
240 |
-
// Reset to first page when filters change
|
241 |
-
useEffect(() => {
|
242 |
-
setCurrentPage(1);
|
243 |
-
}, [search, srcFilter, catFilter, regionFilter, countryFilter, imageTypeFilter, uploadTypeFilter, showReferenceExamples]);
|
244 |
|
245 |
const exportDataset = async (images: ImageWithCaptionOut[], mode: 'standard' | 'fine-tuning' = 'fine-tuning') => {
|
246 |
if (images.length === 0) {
|
@@ -648,11 +656,11 @@ export default function ExplorePage() {
|
|
648 |
|
649 |
{/* Results Section */}
|
650 |
<div className="space-y-4">
|
651 |
-
|
652 |
-
|
653 |
-
|
654 |
-
|
655 |
-
|
656 |
|
657 |
{/* Loading State */}
|
658 |
{isLoadingContent && (
|
@@ -801,18 +809,18 @@ export default function ExplorePage() {
|
|
801 |
</div>
|
802 |
))}
|
803 |
|
804 |
-
{!
|
805 |
<div className="text-center py-12">
|
806 |
<p className="text-gray-500">No examples found.</p>
|
807 |
</div>
|
808 |
)}
|
809 |
|
810 |
{/* Enhanced Paginator Component */}
|
811 |
-
{!isLoadingContent &&
|
812 |
<Paginator
|
813 |
currentPage={currentPage}
|
814 |
totalPages={totalPages}
|
815 |
-
totalItems={
|
816 |
itemsPerPage={itemsPerPage}
|
817 |
onPageChange={setCurrentPage}
|
818 |
/>
|
@@ -873,14 +881,14 @@ export default function ExplorePage() {
|
|
873 |
setIsExporting(false);
|
874 |
}}
|
875 |
onExport={(mode, selectedTypes) => {
|
876 |
-
const filteredByType =
|
877 |
exportDataset(filteredByType, mode);
|
878 |
}}
|
879 |
-
filteredCount={
|
880 |
-
totalCount={
|
881 |
hasFilters={!!(search || srcFilter || catFilter || regionFilter || countryFilter || imageTypeFilter || uploadTypeFilter || showReferenceExamples)}
|
882 |
-
crisisMapsCount={
|
883 |
-
droneImagesCount={
|
884 |
isLoading={isExporting}
|
885 |
exportSuccess={exportSuccess}
|
886 |
/>
|
|
|
76 |
// Pagination state
|
77 |
const [currentPage, setCurrentPage] = useState(1);
|
78 |
const [itemsPerPage] = useState(10);
|
79 |
+
const [totalItems, setTotalItems] = useState(0);
|
80 |
+
const [totalPages, setTotalPages] = useState(0);
|
81 |
|
82 |
const viewOptions = [
|
83 |
{ key: 'explore' as const, label: 'List' },
|
|
|
86 |
|
87 |
const fetchCaptions = () => {
|
88 |
setIsLoadingContent(true);
|
89 |
+
|
90 |
+
// Build query parameters for server-side filtering and pagination
|
91 |
+
const params = new URLSearchParams({
|
92 |
+
page: currentPage.toString(),
|
93 |
+
limit: itemsPerPage.toString()
|
94 |
+
});
|
95 |
+
|
96 |
+
if (search) params.append('search', search);
|
97 |
+
if (srcFilter) params.append('source', srcFilter);
|
98 |
+
if (catFilter) params.append('event_type', catFilter);
|
99 |
+
if (regionFilter) params.append('region', regionFilter);
|
100 |
+
if (countryFilter) params.append('country', countryFilter);
|
101 |
+
if (imageTypeFilter) params.append('image_type', imageTypeFilter);
|
102 |
+
if (uploadTypeFilter) params.append('upload_type', uploadTypeFilter);
|
103 |
+
if (showReferenceExamples) params.append('starred_only', 'true');
|
104 |
+
|
105 |
+
fetch(`/api/images/grouped?${params.toString()}`)
|
106 |
.then(r => {
|
107 |
if (!r.ok) {
|
108 |
console.error('ExplorePage: Grouped endpoint failed, trying legacy endpoint');
|
|
|
123 |
return r.json();
|
124 |
})
|
125 |
.then(data => {
|
126 |
+
console.log('ExplorePage: Fetched captions:', data);
|
127 |
+
setCaptions(data);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
128 |
})
|
129 |
+
.catch(error => {
|
130 |
+
console.error('ExplorePage: Error fetching captions:', error);
|
131 |
setCaptions([]);
|
132 |
})
|
133 |
.finally(() => {
|
|
|
135 |
});
|
136 |
};
|
137 |
|
138 |
+
const fetchTotalCount = () => {
|
139 |
+
// Build query parameters for count endpoint
|
140 |
+
const params = new URLSearchParams();
|
141 |
+
|
142 |
+
if (search) params.append('search', search);
|
143 |
+
if (srcFilter) params.append('source', srcFilter);
|
144 |
+
if (catFilter) params.append('event_type', catFilter);
|
145 |
+
if (regionFilter) params.append('region', regionFilter);
|
146 |
+
if (countryFilter) params.append('country', countryFilter);
|
147 |
+
if (imageTypeFilter) params.append('image_type', imageTypeFilter);
|
148 |
+
if (uploadTypeFilter) params.append('upload_type', uploadTypeFilter);
|
149 |
+
if (showReferenceExamples) params.append('starred_only', 'true');
|
150 |
+
|
151 |
+
fetch(`/api/images/grouped/count?${params.toString()}`)
|
152 |
+
.then(r => {
|
153 |
+
if (!r.ok) {
|
154 |
+
console.error('ExplorePage: Count endpoint failed');
|
155 |
+
return { total_count: 0 };
|
156 |
+
}
|
157 |
+
return r.json();
|
158 |
+
})
|
159 |
+
.then(data => {
|
160 |
+
console.log('ExplorePage: Total count:', data.total_count);
|
161 |
+
setTotalItems(data.total_count);
|
162 |
+
setTotalPages(Math.ceil(data.total_count / itemsPerPage));
|
163 |
+
})
|
164 |
+
.catch(error => {
|
165 |
+
console.error('ExplorePage: Error fetching total count:', error);
|
166 |
+
setTotalItems(0);
|
167 |
+
setTotalPages(0);
|
168 |
+
});
|
169 |
+
};
|
170 |
+
|
171 |
+
// Fetch data when component mounts or filters change
|
172 |
useEffect(() => {
|
173 |
fetchCaptions();
|
174 |
+
fetchTotalCount();
|
175 |
+
}, [currentPage, search, srcFilter, catFilter, regionFilter, countryFilter, imageTypeFilter, uploadTypeFilter, showReferenceExamples]);
|
176 |
+
|
177 |
+
// Reset to first page when filters change (but not when currentPage changes)
|
178 |
+
useEffect(() => {
|
179 |
+
if (currentPage !== 1) {
|
180 |
+
setCurrentPage(1);
|
181 |
+
}
|
182 |
+
}, [search, srcFilter, catFilter, regionFilter, countryFilter, imageTypeFilter, uploadTypeFilter, showReferenceExamples]);
|
183 |
|
184 |
useEffect(() => {
|
185 |
const handleVisibilityChange = () => {
|
|
|
247 |
});
|
248 |
}, []);
|
249 |
|
250 |
+
// Server-side pagination - no client-side filtering needed
|
251 |
+
const paginatedResults = captions;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
252 |
|
253 |
const exportDataset = async (images: ImageWithCaptionOut[], mode: 'standard' | 'fine-tuning' = 'fine-tuning') => {
|
254 |
if (images.length === 0) {
|
|
|
656 |
|
657 |
{/* Results Section */}
|
658 |
<div className="space-y-4">
|
659 |
+
<div className="flex justify-between items-center">
|
660 |
+
<p className="text-sm text-gray-600">
|
661 |
+
{paginatedResults.length} of {totalItems} examples
|
662 |
+
</p>
|
663 |
+
</div>
|
664 |
|
665 |
{/* Loading State */}
|
666 |
{isLoadingContent && (
|
|
|
809 |
</div>
|
810 |
))}
|
811 |
|
812 |
+
{!paginatedResults.length && (
|
813 |
<div className="text-center py-12">
|
814 |
<p className="text-gray-500">No examples found.</p>
|
815 |
</div>
|
816 |
)}
|
817 |
|
818 |
{/* Enhanced Paginator Component */}
|
819 |
+
{!isLoadingContent && paginatedResults.length > 0 && (
|
820 |
<Paginator
|
821 |
currentPage={currentPage}
|
822 |
totalPages={totalPages}
|
823 |
+
totalItems={totalItems}
|
824 |
itemsPerPage={itemsPerPage}
|
825 |
onPageChange={setCurrentPage}
|
826 |
/>
|
|
|
881 |
setIsExporting(false);
|
882 |
}}
|
883 |
onExport={(mode, selectedTypes) => {
|
884 |
+
const filteredByType = paginatedResults.filter((img: ImageWithCaptionOut) => selectedTypes.includes(img.image_type));
|
885 |
exportDataset(filteredByType, mode);
|
886 |
}}
|
887 |
+
filteredCount={paginatedResults.length}
|
888 |
+
totalCount={totalItems}
|
889 |
hasFilters={!!(search || srcFilter || catFilter || regionFilter || countryFilter || imageTypeFilter || uploadTypeFilter || showReferenceExamples)}
|
890 |
+
crisisMapsCount={paginatedResults.filter((img: ImageWithCaptionOut) => img.image_type === 'crisis_map').length}
|
891 |
+
droneImagesCount={paginatedResults.filter((img: ImageWithCaptionOut) => img.image_type === 'drone_image').length}
|
892 |
isLoading={isExporting}
|
893 |
exportSuccess={exportSuccess}
|
894 |
/>
|
py_backend/app/routers/upload.py
CHANGED
@@ -187,8 +187,27 @@ def list_images(db: Session = Depends(get_db)):
|
|
187 |
return result
|
188 |
|
189 |
@router.get("/grouped", response_model=List[schemas.ImageOut])
|
190 |
-
def list_images_grouped(
|
191 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
192 |
# Get all captions with their associated images
|
193 |
captions = crud.get_all_captions_with_images(db)
|
194 |
result = []
|
@@ -198,13 +217,60 @@ def list_images_grouped(db: Session = Depends(get_db)):
|
|
198 |
continue
|
199 |
|
200 |
# Determine the effective image count for this caption
|
201 |
-
# Use caption.image_count if available and valid, otherwise infer from linked images
|
202 |
effective_image_count = caption.image_count if caption.image_count is not None and caption.image_count > 0 else len(caption.images)
|
203 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
204 |
if effective_image_count > 1:
|
205 |
# This is a multi-upload item, group them together
|
206 |
first_img = caption.images[0]
|
207 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
208 |
# Combine metadata from all images
|
209 |
combined_source = set()
|
210 |
combined_event_type = set()
|
@@ -229,16 +295,16 @@ def list_images_grouped(db: Session = Depends(get_db)):
|
|
229 |
# Update countries to include all unique countries
|
230 |
all_countries = []
|
231 |
for img in caption.images:
|
232 |
-
for
|
233 |
-
if not any(c["c_code"] ==
|
234 |
-
all_countries.append({"c_code":
|
235 |
img_dict["countries"] = all_countries
|
236 |
|
237 |
# Add all image IDs for reference
|
238 |
img_dict["all_image_ids"] = [str(img.image_id) for img in caption.images]
|
239 |
-
img_dict["image_count"] = effective_image_count
|
240 |
|
241 |
-
#
|
242 |
img_dict["title"] = caption.title
|
243 |
img_dict["prompt"] = caption.prompt
|
244 |
img_dict["model"] = caption.model
|
@@ -255,31 +321,162 @@ def list_images_grouped(db: Session = Depends(get_db)):
|
|
255 |
|
256 |
result.append(schemas.ImageOut(**img_dict))
|
257 |
else:
|
258 |
-
# For single images,
|
259 |
-
|
260 |
-
|
261 |
-
|
262 |
-
|
263 |
-
|
264 |
-
|
265 |
-
|
266 |
-
|
267 |
-
|
268 |
-
|
269 |
-
|
270 |
-
|
271 |
-
|
272 |
-
|
273 |
-
|
274 |
-
|
275 |
-
|
276 |
-
|
277 |
-
|
278 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
279 |
|
280 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
281 |
|
282 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
283 |
|
284 |
@router.get("/{image_id}", response_model=schemas.ImageOut)
|
285 |
def get_image(image_id: str, db: Session = Depends(get_db)):
|
|
|
187 |
return result
|
188 |
|
189 |
@router.get("/grouped", response_model=List[schemas.ImageOut])
|
190 |
+
def list_images_grouped(
|
191 |
+
page: int = 1,
|
192 |
+
limit: int = 10,
|
193 |
+
search: str = None,
|
194 |
+
source: str = None,
|
195 |
+
event_type: str = None,
|
196 |
+
region: str = None,
|
197 |
+
country: str = None,
|
198 |
+
image_type: str = None,
|
199 |
+
upload_type: str = None,
|
200 |
+
starred_only: bool = False,
|
201 |
+
db: Session = Depends(get_db)
|
202 |
+
):
|
203 |
+
"""Get images grouped by shared captions for multi-upload items with pagination and filtering"""
|
204 |
+
|
205 |
+
# Validate pagination parameters
|
206 |
+
if page < 1:
|
207 |
+
page = 1
|
208 |
+
if limit < 1 or limit > 100:
|
209 |
+
limit = 10
|
210 |
+
|
211 |
# Get all captions with their associated images
|
212 |
captions = crud.get_all_captions_with_images(db)
|
213 |
result = []
|
|
|
217 |
continue
|
218 |
|
219 |
# Determine the effective image count for this caption
|
|
|
220 |
effective_image_count = caption.image_count if caption.image_count is not None and caption.image_count > 0 else len(caption.images)
|
221 |
|
222 |
+
# Apply filters
|
223 |
+
if search:
|
224 |
+
search_lower = search.lower()
|
225 |
+
if not (caption.title and search_lower in caption.title.lower()) and \
|
226 |
+
not (caption.generated and search_lower in caption.generated.lower()):
|
227 |
+
continue
|
228 |
+
|
229 |
+
if starred_only and not caption.starred:
|
230 |
+
continue
|
231 |
+
|
232 |
if effective_image_count > 1:
|
233 |
# This is a multi-upload item, group them together
|
234 |
first_img = caption.images[0]
|
235 |
|
236 |
+
# Apply source filter
|
237 |
+
if source:
|
238 |
+
if not any(source in img.source for img in caption.images if img.source):
|
239 |
+
continue
|
240 |
+
|
241 |
+
# Apply event_type filter
|
242 |
+
if event_type:
|
243 |
+
if not any(event_type in img.event_type for img in caption.images if img.event_type):
|
244 |
+
continue
|
245 |
+
|
246 |
+
# Apply image_type filter
|
247 |
+
if image_type:
|
248 |
+
if not any(img.image_type == image_type for img in caption.images):
|
249 |
+
continue
|
250 |
+
|
251 |
+
# Apply upload_type filter
|
252 |
+
if upload_type:
|
253 |
+
if upload_type == 'single' and effective_image_count > 1:
|
254 |
+
continue
|
255 |
+
if upload_type == 'multiple' and effective_image_count <= 1:
|
256 |
+
continue
|
257 |
+
|
258 |
+
# Apply region/country filter
|
259 |
+
if region or country:
|
260 |
+
has_matching_country = False
|
261 |
+
for img in caption.images:
|
262 |
+
for img_country in img.countries:
|
263 |
+
if region and img_country.r_code == region:
|
264 |
+
has_matching_country = True
|
265 |
+
break
|
266 |
+
if country and img_country.c_code == country:
|
267 |
+
has_matching_country = True
|
268 |
+
break
|
269 |
+
if has_matching_country:
|
270 |
+
break
|
271 |
+
if not has_matching_country:
|
272 |
+
continue
|
273 |
+
|
274 |
# Combine metadata from all images
|
275 |
combined_source = set()
|
276 |
combined_event_type = set()
|
|
|
295 |
# Update countries to include all unique countries
|
296 |
all_countries = []
|
297 |
for img in caption.images:
|
298 |
+
for country_obj in img.countries:
|
299 |
+
if not any(c["c_code"] == country_obj.c_code for c in all_countries):
|
300 |
+
all_countries.append({"c_code": country_obj.c_code, "label": country_obj.label, "r_code": country_obj.r_code})
|
301 |
img_dict["countries"] = all_countries
|
302 |
|
303 |
# Add all image IDs for reference
|
304 |
img_dict["all_image_ids"] = [str(img.image_id) for img in caption.images]
|
305 |
+
img_dict["image_count"] = effective_image_count
|
306 |
|
307 |
+
# Set caption-level fields
|
308 |
img_dict["title"] = caption.title
|
309 |
img_dict["prompt"] = caption.prompt
|
310 |
img_dict["model"] = caption.model
|
|
|
321 |
|
322 |
result.append(schemas.ImageOut(**img_dict))
|
323 |
else:
|
324 |
+
# For single images, apply filters
|
325 |
+
img = caption.images[0]
|
326 |
+
|
327 |
+
if source and img.source != source:
|
328 |
+
continue
|
329 |
+
if event_type and img.event_type != event_type:
|
330 |
+
continue
|
331 |
+
if image_type and img.image_type != image_type:
|
332 |
+
continue
|
333 |
+
if upload_type == 'multiple':
|
334 |
+
continue
|
335 |
+
|
336 |
+
# Apply region/country filter
|
337 |
+
if region or country:
|
338 |
+
has_matching_country = False
|
339 |
+
for img_country in img.countries:
|
340 |
+
if region and img_country.r_code == region:
|
341 |
+
has_matching_country = True
|
342 |
+
break
|
343 |
+
if country and img_country.c_code == country:
|
344 |
+
has_matching_country = True
|
345 |
+
break
|
346 |
+
if not has_matching_country:
|
347 |
+
continue
|
348 |
+
|
349 |
+
img_dict = convert_image_to_dict(img, f"/api/images/{img.image_id}/file")
|
350 |
+
img_dict["all_image_ids"] = [str(img.image_id)]
|
351 |
+
img_dict["image_count"] = 1
|
352 |
+
|
353 |
+
# Set caption-level fields
|
354 |
+
img_dict["title"] = caption.title
|
355 |
+
img_dict["prompt"] = caption.prompt
|
356 |
+
img_dict["model"] = caption.model
|
357 |
+
img_dict["schema_id"] = caption.schema_id
|
358 |
+
img_dict["raw_json"] = caption.raw_json
|
359 |
+
img_dict["generated"] = caption.generated
|
360 |
+
img_dict["edited"] = caption.edited
|
361 |
+
img_dict["accuracy"] = caption.accuracy
|
362 |
+
img_dict["context"] = caption.context
|
363 |
+
img_dict["usability"] = caption.usability
|
364 |
+
img_dict["starred"] = caption.starred
|
365 |
+
img_dict["created_at"] = caption.created_at
|
366 |
+
img_dict["updated_at"] = caption.updated_at
|
367 |
+
|
368 |
+
result.append(schemas.ImageOut(**img_dict))
|
369 |
+
|
370 |
+
# Apply pagination
|
371 |
+
total_count = len(result)
|
372 |
+
start_index = (page - 1) * limit
|
373 |
+
end_index = start_index + limit
|
374 |
+
paginated_result = result[start_index:end_index]
|
375 |
+
|
376 |
+
return paginated_result
|
377 |
|
378 |
+
@router.get("/grouped/count")
|
379 |
+
def get_images_grouped_count(
|
380 |
+
search: str = None,
|
381 |
+
source: str = None,
|
382 |
+
event_type: str = None,
|
383 |
+
region: str = None,
|
384 |
+
country: str = None,
|
385 |
+
image_type: str = None,
|
386 |
+
upload_type: str = None,
|
387 |
+
starred_only: bool = False,
|
388 |
+
db: Session = Depends(get_db)
|
389 |
+
):
|
390 |
+
"""Get total count of images for pagination"""
|
391 |
|
392 |
+
# Get all captions with their associated images
|
393 |
+
captions = crud.get_all_captions_with_images(db)
|
394 |
+
count = 0
|
395 |
+
|
396 |
+
for caption in captions:
|
397 |
+
if not caption.images:
|
398 |
+
continue
|
399 |
+
|
400 |
+
# Determine the effective image count for this caption
|
401 |
+
effective_image_count = caption.image_count if caption.image_count is not None and caption.image_count > 0 else len(caption.images)
|
402 |
+
|
403 |
+
# Apply filters (same logic as above)
|
404 |
+
if search:
|
405 |
+
search_lower = search.lower()
|
406 |
+
if not (caption.title and search_lower in caption.title.lower()) and \
|
407 |
+
not (caption.generated and search_lower in caption.generated.lower()):
|
408 |
+
continue
|
409 |
+
|
410 |
+
if starred_only and not caption.starred:
|
411 |
+
continue
|
412 |
+
|
413 |
+
if effective_image_count > 1:
|
414 |
+
# Multi-upload item
|
415 |
+
first_img = caption.images[0]
|
416 |
+
|
417 |
+
# Apply filters
|
418 |
+
if source:
|
419 |
+
if not any(source in img.source for img in caption.images if img.source):
|
420 |
+
continue
|
421 |
+
|
422 |
+
if event_type:
|
423 |
+
if not any(event_type in img.event_type for img in caption.images if img.event_type):
|
424 |
+
continue
|
425 |
+
|
426 |
+
if image_type:
|
427 |
+
if not any(img.image_type == image_type for img in caption.images):
|
428 |
+
continue
|
429 |
+
|
430 |
+
if upload_type:
|
431 |
+
if upload_type == 'single' and effective_image_count > 1:
|
432 |
+
continue
|
433 |
+
if upload_type == 'multiple' and effective_image_count <= 1:
|
434 |
+
continue
|
435 |
+
|
436 |
+
if region or country:
|
437 |
+
has_matching_country = False
|
438 |
+
for img in caption.images:
|
439 |
+
for img_country in img.countries:
|
440 |
+
if region and img_country.r_code == region:
|
441 |
+
has_matching_country = True
|
442 |
+
break
|
443 |
+
if country and img_country.c_code == country:
|
444 |
+
has_matching_country = True
|
445 |
+
break
|
446 |
+
if has_matching_country:
|
447 |
+
break
|
448 |
+
if not has_matching_country:
|
449 |
+
continue
|
450 |
+
|
451 |
+
count += 1
|
452 |
+
else:
|
453 |
+
# Single image
|
454 |
+
img = caption.images[0]
|
455 |
+
|
456 |
+
if source and img.source != source:
|
457 |
+
continue
|
458 |
+
if event_type and img.event_type != event_type:
|
459 |
+
continue
|
460 |
+
if image_type and img.image_type != image_type:
|
461 |
+
continue
|
462 |
+
if upload_type == 'multiple':
|
463 |
+
continue
|
464 |
+
|
465 |
+
if region or country:
|
466 |
+
has_matching_country = False
|
467 |
+
for img_country in img.countries:
|
468 |
+
if region and img_country.r_code == region:
|
469 |
+
has_matching_country = True
|
470 |
+
break
|
471 |
+
if country and img_country.c_code == country:
|
472 |
+
has_matching_country = True
|
473 |
+
break
|
474 |
+
if not has_matching_country:
|
475 |
+
continue
|
476 |
+
|
477 |
+
count += 1
|
478 |
+
|
479 |
+
return {"total_count": count}
|
480 |
|
481 |
@router.get("/{image_id}", response_model=schemas.ImageOut)
|
482 |
def get_image(image_id: str, db: Session = Depends(get_db)):
|
py_backend/app/services/huggingface_service.py
CHANGED
@@ -286,18 +286,9 @@ class ProvidersGenericVLMService(HuggingFaceService):
|
|
286 |
ProvidersGenericVLMService(HF_TOKEN, "Qwen/Qwen2.5-VL-32B-Instruct", "QWEN2_5_VL_32B")
|
287 |
"""
|
288 |
def __init__(self, api_key: str, model_id: str, public_name: str | None = None):
|
289 |
-
|
290 |
-
|
291 |
-
|
292 |
-
self.model_type = ModelType.CUSTOM
|
293 |
-
class ProvidersGenericVLMService(HuggingFaceService):
|
294 |
-
"""
|
295 |
-
Generic wrapper so you can register ANY Providers VLM by model_id from config.
|
296 |
-
Example:
|
297 |
-
ProvidersGenericVLMService(HF_TOKEN, "Qwen/Qwen2.5-VL-32B-Instruct", "QWEN2_5_VL_32B")
|
298 |
-
"""
|
299 |
-
def __init__(self, api_key: str, model_id: str, public_name: str | None = None):
|
300 |
-
super().__init__(api_key, model_id)
|
301 |
# Use a human-friendly stable name that your UI/DB will reference
|
302 |
self.model_name = public_name or model_id.replace("/", "_").upper()
|
303 |
self.model_type = ModelType.CUSTOM
|
|
|
286 |
ProvidersGenericVLMService(HF_TOKEN, "Qwen/Qwen2.5-VL-32B-Instruct", "QWEN2_5_VL_32B")
|
287 |
"""
|
288 |
def __init__(self, api_key: str, model_id: str, public_name: str | None = None):
|
289 |
+
# Use the default HuggingFace providers URL
|
290 |
+
providers_url = "https://api-inference.huggingface.co/providers/openai"
|
291 |
+
super().__init__(api_key, model_id, providers_url)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
292 |
# Use a human-friendly stable name that your UI/DB will reference
|
293 |
self.model_name = public_name or model_id.replace("/", "_").upper()
|
294 |
self.model_type = ModelType.CUSTOM
|
py_backend/generate_production_thumbnails.py
DELETED
@@ -1,121 +0,0 @@
|
|
1 |
-
#!/usr/bin/env python3
|
2 |
-
|
3 |
-
import io
|
4 |
-
import os
|
5 |
-
import sys
|
6 |
-
from sqlalchemy.orm import Session
|
7 |
-
from app.database import SessionLocal
|
8 |
-
from app.models import Images
|
9 |
-
from app.services.thumbnail_service import ImageProcessingService
|
10 |
-
from app.storage import s3
|
11 |
-
from app.config import settings
|
12 |
-
|
13 |
-
def get_object_content(key: str) -> bytes:
|
14 |
-
"""Download object content from storage"""
|
15 |
-
try:
|
16 |
-
if settings.STORAGE_PROVIDER == "local":
|
17 |
-
# Local storage
|
18 |
-
file_path = os.path.join(settings.STORAGE_DIR, key)
|
19 |
-
if not os.path.exists(file_path):
|
20 |
-
return None
|
21 |
-
with open(file_path, 'rb') as f:
|
22 |
-
return f.read()
|
23 |
-
else:
|
24 |
-
# S3 storage
|
25 |
-
response = s3.get_object(Bucket=settings.S3_BUCKET, Key=key)
|
26 |
-
return response["Body"].read()
|
27 |
-
except Exception as e:
|
28 |
-
print(f"Error downloading object {key}: {str(e)}")
|
29 |
-
return None
|
30 |
-
|
31 |
-
def generate_thumbnails_for_production():
|
32 |
-
"""Generate thumbnails and detail versions for all existing images in production"""
|
33 |
-
|
34 |
-
print("Starting thumbnail generation for production images...")
|
35 |
-
print(f"Storage provider: {settings.STORAGE_PROVIDER}")
|
36 |
-
print(f"S3 bucket: {settings.S3_BUCKET}")
|
37 |
-
|
38 |
-
# Get database session
|
39 |
-
db = SessionLocal()
|
40 |
-
|
41 |
-
try:
|
42 |
-
# Find all images that don't have thumbnails yet
|
43 |
-
images_without_thumbnails = db.query(Images).filter(
|
44 |
-
(Images.thumbnail_key.is_(None)) |
|
45 |
-
(Images.detail_key.is_(None))
|
46 |
-
).all()
|
47 |
-
|
48 |
-
print(f"Found {len(images_without_thumbnails)} images without thumbnails/detail versions")
|
49 |
-
|
50 |
-
if not images_without_thumbnails:
|
51 |
-
print("All images already have thumbnails and detail versions!")
|
52 |
-
return
|
53 |
-
|
54 |
-
success_count = 0
|
55 |
-
error_count = 0
|
56 |
-
|
57 |
-
for i, image in enumerate(images_without_thumbnails, 1):
|
58 |
-
print(f"\nProcessing image {i}/{len(images_without_thumbnails)}: {image.image_id}")
|
59 |
-
|
60 |
-
try:
|
61 |
-
# Download the original image from storage
|
62 |
-
print(f" Downloading original image: {image.file_key}")
|
63 |
-
original_content = get_object_content(image.file_key)
|
64 |
-
|
65 |
-
if not original_content:
|
66 |
-
print(f" β οΈ Could not download original image: {image.file_key}")
|
67 |
-
error_count += 1
|
68 |
-
continue
|
69 |
-
|
70 |
-
# Generate filename from file_key
|
71 |
-
filename = image.file_key.split('/')[-1] if '/' in image.file_key else image.file_key
|
72 |
-
|
73 |
-
# Process all resolutions
|
74 |
-
print(f" Generating thumbnails and detail versions...")
|
75 |
-
thumbnail_result, detail_result = ImageProcessingService.process_all_resolutions(
|
76 |
-
original_content,
|
77 |
-
filename
|
78 |
-
)
|
79 |
-
|
80 |
-
# Update database with results
|
81 |
-
if thumbnail_result:
|
82 |
-
thumbnail_key, thumbnail_sha256 = thumbnail_result
|
83 |
-
image.thumbnail_key = thumbnail_key
|
84 |
-
image.thumbnail_sha256 = thumbnail_sha256
|
85 |
-
print(f" β
Thumbnail generated: {thumbnail_key}")
|
86 |
-
else:
|
87 |
-
print(f" β Failed to generate thumbnail")
|
88 |
-
|
89 |
-
if detail_result:
|
90 |
-
detail_key, detail_sha256 = detail_result
|
91 |
-
image.detail_key = detail_key
|
92 |
-
image.detail_sha256 = detail_sha256
|
93 |
-
print(f" β
Detail version generated: {detail_key}")
|
94 |
-
else:
|
95 |
-
print(f" β Failed to generate detail version")
|
96 |
-
|
97 |
-
# Commit changes to database
|
98 |
-
db.commit()
|
99 |
-
success_count += 1
|
100 |
-
print(f" β
Image {image.image_id} processed successfully")
|
101 |
-
|
102 |
-
except Exception as e:
|
103 |
-
print(f" β Error processing image {image.image_id}: {str(e)}")
|
104 |
-
db.rollback()
|
105 |
-
error_count += 1
|
106 |
-
continue
|
107 |
-
|
108 |
-
print(f"\n=== Summary ===")
|
109 |
-
print(f"Total images processed: {len(images_without_thumbnails)}")
|
110 |
-
print(f"Successful: {success_count}")
|
111 |
-
print(f"Errors: {error_count}")
|
112 |
-
print(f"Success rate: {(success_count/len(images_without_thumbnails)*100):.1f}%")
|
113 |
-
|
114 |
-
except Exception as e:
|
115 |
-
print(f"Error: {str(e)}")
|
116 |
-
db.rollback()
|
117 |
-
finally:
|
118 |
-
db.close()
|
119 |
-
|
120 |
-
if __name__ == "__main__":
|
121 |
-
generate_thumbnails_for_production()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
py_backend/static/assets/{AdminPage-kwx131wq.js β AdminPage-BeakVMzz.js}
RENAMED
@@ -1,4 +1,4 @@
|
|
1 |
-
import{r as d,j as a,N as B,H as we,O as h,z as f,n as t,I as S}from"./index-
|
2 |
Model "${o.label}" added successfully!
|
3 |
|
4 |
β οΈ IMPORTANT: Model will NOT work until you complete these steps:
|
|
|
1 |
+
import{r as d,j as a,N as B,H as we,O as h,z as f,n as t,I as S}from"./index-BzYyR-qc.js";import{u as Fe}from"./useAdmin-B4TrJLwR.js";const ke="_adminContainer_j11pf_5",Te="_adminHeader_j11pf_13",Ae="_adminSection_j11pf_20",Ie="_modelSelectionArea_j11pf_29",Pe="_modelSelectionRow_j11pf_36",$e="_modelsTable_j11pf_89",Le="_promptSubsection_j11pf_97",Ee="_promptSubsectionTitle_j11pf_109",Be="_modelCode_j11pf_152",Oe="_modelId_j11pf_157",Re="_modelActions_j11pf_163",De="_addModelButtonContainer_j11pf_169",Ue="_addModelForm_j11pf_177",ze="_addModelFormTitle_j11pf_185",He="_addModelFormGrid_j11pf_193",Ge="_addModelFormField_j11pf_206",Ve="_addModelFormCheckbox_j11pf_250",Je="_addModelFormActions_j11pf_268",Ke="_modalOverlay_j11pf_277",We="_modalContent_j11pf_291",qe="_modalBody_j11pf_302",Ye="_modalTitle_j11pf_312",Qe="_modalText_j11pf_320",Xe="_modalTextLeft_j11pf_332",Ze="_modalButtons_j11pf_355",ea="_modalForm_j11pf_363",aa="_formField_j11pf_372",la="_formLabel_j11pf_376",sa="_formInput_j11pf_385",oa="_textarea_j11pf_407",l={adminContainer:ke,adminHeader:Te,adminSection:Ae,modelSelectionArea:Ie,modelSelectionRow:Pe,modelsTable:$e,promptSubsection:Le,promptSubsectionTitle:Ee,modelCode:Be,modelId:Oe,modelActions:Re,addModelButtonContainer:De,addModelForm:Ue,addModelFormTitle:ze,addModelFormGrid:He,addModelFormField:Ge,addModelFormCheckbox:Ve,addModelFormActions:Je,modalOverlay:Ke,modalContent:We,modalBody:qe,modalTitle:Ye,modalText:Qe,modalTextLeft:Xe,modalButtons:Ze,modalForm:ea,formField:aa,formLabel:la,formInput:sa,textarea:oa},w="selectedVlmModel";function ia(){const{isAuthenticated:F,isLoading:X,login:Z,logout:ee}=Fe(),[k,O]=d.useState(""),[R,u]=d.useState(""),[D,U]=d.useState(!1),[z,H]=d.useState([]),[ae,b]=d.useState(""),[G,le]=d.useState([]),[se,oe]=d.useState([]),[te,y]=d.useState(!1),[de,N]=d.useState(!1),[ie,T]=d.useState(null),[C,A]=d.useState(null),[n,r]=d.useState({p_code:"",label:"",metadata_instructions:"",image_type:"crisis_map",is_active:!1}),[V,I]=d.useState(!1),[ne,P]=d.useState(!1),[$,L]=d.useState(null),[o,c]=d.useState({m_code:"",label:"",model_type:"custom",provider:"huggingface",model_id:"",is_available:!1}),[re,M]=d.useState(!1),[ce,E]=d.useState(!1),[me,p]=d.useState(!1),[J,K]=d.useState(""),[he,pe]=d.useState(""),[_e,_]=d.useState(""),[ue,j]=d.useState(""),x=d.useCallback(()=>{fetch("/api/models").then(e=>e.json()).then(e=>{console.log("Models data received:",e),H(e.models||[]);const s=localStorage.getItem(w);if(e.models&&e.models.length>0)if(s==="random")b("random");else if(s&&e.models.find(i=>i.m_code===s&&i.is_available))b(s);else{const i=e.models.find(m=>m.is_available)||e.models[0];b(i.m_code),localStorage.setItem(w,i.m_code)}}).catch(()=>{})},[]),v=d.useCallback(()=>{console.log("=== fetchPrompts called ==="),fetch("/api/prompts").then(e=>e.json()).then(e=>{console.log("Prompts data received:",e),le(e||[]),console.log("State update triggered with:",e||[])}).catch(e=>{console.error("Error fetching prompts:",e)})},[]),W=d.useCallback(()=>{fetch("/api/image-types").then(e=>e.json()).then(e=>{console.log("Image types data received:",e),oe(e||[])}).catch(()=>{})},[]);d.useEffect(()=>{F&&(x(),v(),W())},[F,x,v,W]);const q=e=>{A(e),r({p_code:e.p_code,label:e.label||"",metadata_instructions:e.metadata_instructions||"",image_type:e.image_type||"crisis_map",is_active:e.is_active||!1}),y(!0)},je=async()=>{try{if(!C){alert("No prompt selected for editing");return}const e=await fetch(`/api/prompts/${C.p_code}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({label:n.label,metadata_instructions:n.metadata_instructions,image_type:n.image_type,is_active:n.is_active})});if(e.ok)v(),y(!1),A(null),r({p_code:"",label:"",metadata_instructions:"",image_type:"crisis_map",is_active:!1});else{const s=await e.json();alert(`Failed to update prompt: ${s.error||"Unknown error"}`)}}catch{alert("Error updating prompt")}},Y=async(e,s)=>{try{const i=await fetch(`/api/prompts/${e}/toggle-active?image_type=${s}`,{method:"POST",headers:{"Content-Type":"application/json"}});if(i.ok)v();else{const m=await i.json();alert(`Failed to toggle prompt active status: ${m.detail||"Unknown error"}`)}}catch{alert("Error toggling prompt active status")}},Q=e=>{T(e),r({p_code:"",label:"",metadata_instructions:"",image_type:e,is_active:!1}),N(!0)},xe=async()=>{try{const e=await fetch("/api/prompts",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(e.ok)v(),N(!1),T(null),r({p_code:"",label:"",metadata_instructions:"",image_type:"crisis_map",is_active:!1});else{const s=await e.json();alert(`Failed to create prompt: ${s.detail||"Unknown error"}`)}}catch{alert("Error creating prompt")}},ve=async(e,s)=>{try{const i=await fetch(`/api/models/${e}/toggle`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({is_available:!s})});if(i.ok)H(m=>m.map(g=>g.m_code===e?{...g,is_available:!s}:g));else{const m=await i.json();alert(`Failed to toggle model availability: ${m.error||"Unknown error"}`)}}catch{alert("Error toggling model availability")}},ge=e=>{b(e),e==="random"?localStorage.setItem(w,"random"):localStorage.setItem(w,e)},fe=async()=>{try{const e=await fetch("/api/admin/models",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${localStorage.getItem("adminToken")}`},body:JSON.stringify(o)});if(e.ok){const s=`
|
2 |
Model "${o.label}" added successfully!
|
3 |
|
4 |
β οΈ IMPORTANT: Model will NOT work until you complete these steps:
|
py_backend/static/assets/{ExportModal-k_VKbTpi.js β ExportModal-DJU5iFtN.js}
RENAMED
@@ -1 +1 @@
|
|
1 |
-
import{r as n,j as e,M as P,P as W,o as F,S as A,D as H,z as b,n as v,O as V,I as z,T as q,_ as O,L as G}from"./index-LmdVBMha.js";const R=({title:c,titleId:i,...r})=>n.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg","aria-hidden":"true",viewBox:"0 0 24 24",fill:"currentColor",width:"1em",height:"1em","aria-labelledby":i},r),c?n.createElement("title",{id:i},c):null,n.createElement("g",{clipPath:"url(#checkbox-indeterminate-line_svg__a)"},n.createElement("path",{d:"M4 3h16a1 1 0 0 1 1 1v16a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1Zm1 2v14h14V5H5Zm2 6h10v2H7v-2Z"})),n.createElement("defs",null,n.createElement("clipPath",{id:"checkbox-indeterminate-line_svg__a"},n.createElement("path",{d:"M0 0h24v24H0z"})))),$=({title:c,titleId:i,...r})=>n.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg","aria-hidden":"true",viewBox:"0 0 24 24",fill:"currentColor",width:"1em",height:"1em","aria-labelledby":i},r),c?n.createElement("title",{id:i},c):null,n.createElement("g",{clipPath:"url(#filter-line_svg__a)"},n.createElement("path",{d:"M9 13.5 4 6H3V4h18v2h-1l-5 7.5V22H9v-8.5ZM6.404 6 11 12.894V20h2v-7.106L17.596 6H6.404Z"})),n.createElement("defs",null,n.createElement("clipPath",{id:"filter-line_svg__a"},n.createElement("path",{d:"M0 0h24v24H0z"}))));function D(c){const{className:i,indeterminate:r,value:j}=c;return e.jsxs(e.Fragment,{children:[r&&e.jsx(R,{className:i}),j&&!r&&e.jsx(P,{className:i}),!j&&!r&&e.jsx(W,{className:i})]})}const U="_checkbox_12g7n_1",Z="_with-background_12g7n_7",Y="_checkmark-container_12g7n_12",J="_input_12g7n_18",K="_content_12g7n_33",Q="_description_12g7n_40",X="_checked_12g7n_45",L="_checkmark_12g7n_12",ee="_disabled-checkbox_12g7n_58",m={checkbox:U,withBackground:Z,checkmarkContainer:Y,input:J,content:K,description:Q,checked:X,checkmark:L,disabledCheckbox:ee};function B(c){const{className:i,checkmark:r=D,checkmarkClassName:j,checkmarkContainerClassName:I,disabled:t,error:p,indeterminate:N,inputClassName:E,invertedLogic:d=!1,label:y,labelContainerClassName:_,name:w,onChange:f,readOnly:h,tooltip:k,value:x,description:u,withBackground:T,...S}=c,M=n.useCallback(s=>{const o=s.currentTarget.checked;f(d?!o:o,w)},[w,f,d]),C=d?!x:x,g=F(m.checkbox,i,!N&&C&&m.checked,T&&m.withBackground,t&&m.disabledCheckbox,h&&m.readOnly);return e.jsxs("label",{className:g,title:k,children:[e.jsxs("div",{className:F(m.checkmarkContainer,I),children:[e.jsx("input",{onChange:M,className:F(m.input,E),type:"checkbox",checked:C??!1,disabled:t||h,readOnly:h,...S}),e.jsx(r,{className:F(m.checkmark,j),value:C??!1,indeterminate:N,"aria-hidden":"true"})]}),(y||u)&&e.jsxs("div",{className:m.content,children:[y&&e.jsx("div",{className:_,children:y}),u&&e.jsx("div",{className:m.description,children:u})]}),p&&e.jsx(A,{children:p})]})}function _e({sources:c,types:i,regions:r,countries:j,imageTypes:I,isLoadingFilters:t=!1}){const[p,N]=n.useState(!1),{search:E,setSearch:d,srcFilter:y,setSrcFilter:_,catFilter:w,setCatFilter:f,regionFilter:h,setRegionFilter:k,countryFilter:x,setCountryFilter:u,imageTypeFilter:T,setImageTypeFilter:S,uploadTypeFilter:M,setUploadTypeFilter:C,showReferenceExamples:g,setShowReferenceExamples:s,clearAllFilters:o}=H();return e.jsxs("div",{className:"mb-6 space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-4",children:[e.jsx(b,{withInternalPadding:!0,className:"bg-white/20 backdrop-blur-sm rounded-md p-2",children:e.jsx(v,{name:"toggle-filters",variant:"secondary",onClick:()=>N(!p),className:"whitespace-nowrap",title:p?"Hide Filters":"Show Filters",children:e.jsx($,{className:"w-4 h-4"})})}),e.jsx(b,{withInternalPadding:!0,className:"bg-white/20 backdrop-blur-sm rounded-md p-2 flex-1 min-w-[300px]",children:e.jsx(V,{name:"search",placeholder:"Search examples...",value:E,onChange:a=>d(a||"")})}),e.jsx(b,{withInternalPadding:!0,className:"bg-white/20 backdrop-blur-sm rounded-md p-2",children:e.jsx(v,{name:"clear-filters",variant:"secondary",onClick:o,children:"Clear Filters"})})]}),p&&e.jsx("div",{className:"bg-white/20 backdrop-blur-sm rounded-md p-4",children:e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-4",children:[e.jsx(b,{withInternalPadding:!0,className:"p-2",children:e.jsx(z,{name:"source",placeholder:t?"Loading...":"All Sources",options:c,value:y||null,onChange:a=>_(a||""),keySelector:a=>a.s_code,labelSelector:a=>a.label,required:!1,disabled:t})}),e.jsx(b,{withInternalPadding:!0,className:"p-2",children:e.jsx(z,{name:"category",placeholder:t?"Loading...":"All Categories",options:i,value:w||null,onChange:a=>f(a||""),keySelector:a=>a.t_code,labelSelector:a=>a.label,required:!1,disabled:t})}),e.jsx(b,{withInternalPadding:!0,className:"p-2",children:e.jsx(z,{name:"region",placeholder:t?"Loading...":"All Regions",options:r,value:h||null,onChange:a=>k(a||""),keySelector:a=>a.r_code,labelSelector:a=>a.label,required:!1,disabled:t})}),e.jsx(b,{withInternalPadding:!0,className:"p-2",children:e.jsx(q,{name:"country",placeholder:t?"Loading...":"All Countries",options:j,value:x?[x]:[],onChange:a=>u(a[0]||""),keySelector:a=>a.c_code,labelSelector:a=>a.label,disabled:t})}),e.jsx(b,{withInternalPadding:!0,className:"p-2",children:e.jsx(z,{name:"imageType",placeholder:t?"Loading...":"All Image Types",options:I,value:T||null,onChange:a=>S(a||""),keySelector:a=>a.image_type,labelSelector:a=>a.label,required:!1,disabled:t})}),e.jsx(b,{withInternalPadding:!0,className:"p-2",children:e.jsx(z,{name:"uploadType",placeholder:"All Upload Types",options:[{key:"single",label:"Single Upload"},{key:"multiple",label:"Multiple Upload"}],value:M||null,onChange:a=>C(a||""),keySelector:a=>a.key,labelSelector:a=>a.label,required:!1,disabled:!1})})]})})]})}const ae="_fullSizeModalOverlay_cyz3b_1",le="_fullSizeModalContent_cyz3b_29",te="_ratingWarningContent_cyz3b_53",se="_ratingWarningTitle_cyz3b_65",ne="_exportModeSection_cyz3b_133",ie="_splitConfigSection_cyz3b_143",re="_splitConfigTitle_cyz3b_153",ce="_splitInputsContainer_cyz3b_167",oe="_splitInputGroup_cyz3b_183",de="_splitInputLabel_cyz3b_197",me="_splitInput_cyz3b_167",pe="_splitTotal_cyz3b_247",he="_splitTotalError_cyz3b_261",xe="_checkboxesContainer_cyz3b_271",ue="_ratingWarningButtons_cyz3b_289",ge="_singleExportMessage_cyz3b_309",be="_navigateButtonContainer_cyz3b_333",ve="_loadingOverlay_cyz3b_349",l={fullSizeModalOverlay:ae,fullSizeModalContent:le,ratingWarningContent:te,ratingWarningTitle:se,exportModeSection:ne,splitConfigSection:ie,splitConfigTitle:re,splitInputsContainer:ce,splitInputGroup:oe,splitInputLabel:de,splitInput:me,splitTotal:pe,splitTotalError:he,checkboxesContainer:xe,ratingWarningButtons:ue,singleExportMessage:ge,navigateButtonContainer:be,loadingOverlay:ve};function fe({isOpen:c,onClose:i,onExport:r,crisisMapsCount:j,droneImagesCount:I,isLoading:t=!1,exportSuccess:p=!1,variant:N="bulk",onNavigateAndExport:E}){const[d,y]=n.useState("standard"),[_,w]=n.useState(80),[f,h]=n.useState(10),[k,x]=n.useState(10),[u,T]=n.useState(!0),[S,M]=n.useState(!0),C=()=>{if(N==="single"){r(d,["crisis_map","drone_image"]);return}if(!u&&!S){alert("Please select at least one image type to export.");return}const s=[];u&&s.push("crisis_map"),S&&s.push("drone_image"),r(d,s)},g=()=>{i()};return c?N==="single"?e.jsx("div",{className:l.fullSizeModalOverlay,onClick:g,children:e.jsxs("div",{className:l.fullSizeModalContent,onClick:s=>s.stopPropagation(),children:[t&&e.jsx("div",{className:l.loadingOverlay,children:e.jsxs("div",{className:"flex flex-col items-center gap-4",children:[e.jsx(O,{className:"text-ifrcRed"}),e.jsx("div",{className:"text-lg font-medium",children:"Exporting..."}),e.jsx("div",{className:"text-sm text-gray-600",children:"This might take a few seconds"})]})}),p&&e.jsx("div",{className:l.loadingOverlay,children:e.jsxs("div",{className:"flex flex-col items-center gap-4",children:[e.jsx("div",{className:"text-lg font-medium",children:"Export Successful!"}),e.jsx("div",{className:"text-sm text-gray-600",children:"Your dataset has been downloaded"}),e.jsx(v,{name:"close-export-success",onClick:g,className:"mt-4",children:"Close"})]})}),e.jsxs("div",{className:l.ratingWarningContent,children:[e.jsx("h3",{className:l.ratingWarningTitle,children:"Export Single Item"}),e.jsxs("div",{className:l.singleExportMessage,children:[e.jsx("p",{children:"This only exports the 1 item currently on display."}),e.jsx("p",{children:'You may export the entire dataset from the "list view" here:'})]}),e.jsx("div",{className:l.navigateButtonContainer,children:e.jsx(v,{name:"navigate-to-list",variant:"secondary",onClick:E,children:"Navigate to List View"})}),e.jsxs("div",{className:l.ratingWarningButtons,children:[e.jsx(v,{name:"continue-export",onClick:C,disabled:t,children:t?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(O,{className:"text-white"}),"Exporting..."]}):"Continue"}),e.jsx(v,{name:"cancel-export",variant:"tertiary",onClick:g,disabled:t,children:"Cancel"})]})]})]})}):e.jsx("div",{className:l.fullSizeModalOverlay,onClick:g,children:e.jsxs("div",{className:l.fullSizeModalContent,onClick:s=>s.stopPropagation(),children:[t&&e.jsx("div",{className:l.loadingOverlay,children:e.jsxs("div",{className:"flex flex-col items-center gap-4",children:[e.jsx(O,{className:"text-ifrcRed"}),e.jsx("div",{className:"text-lg font-medium",children:"Exporting..."}),e.jsx("div",{className:"text-sm text-gray-600",children:"This might take a few seconds"})]})}),p&&e.jsx("div",{className:l.loadingOverlay,children:e.jsxs("div",{className:"flex flex-col items-center gap-4",children:[e.jsx("div",{className:"text-lg font-medium",children:"Export Successful!"}),e.jsx("div",{className:"text-sm text-gray-600",children:"Your dataset has been downloaded"}),e.jsx(v,{name:"close-export-success",onClick:g,className:"mt-4",children:"Close"})]})}),e.jsxs("div",{className:l.ratingWarningContent,children:[e.jsx("h3",{className:l.ratingWarningTitle,children:"Export Dataset"}),e.jsx("div",{className:l.exportModeSection,children:e.jsx(G,{name:"export-mode",value:d,onChange:s=>{(s==="standard"||s==="fine-tuning")&&y(s)},options:[{key:"standard",label:"Standard"},{key:"fine-tuning",label:"Fine-tuning"}],keySelector:s=>s.key,labelSelector:s=>s.label,disabled:t})}),d==="fine-tuning"&&e.jsxs("div",{className:l.splitConfigSection,children:[e.jsx("div",{className:l.splitConfigTitle,children:"Dataset Split Configuration"}),e.jsxs("div",{className:l.splitInputsContainer,children:[e.jsxs("div",{className:l.splitInputGroup,children:[e.jsx("label",{htmlFor:"train-split",className:l.splitInputLabel,children:"Train (%)"}),e.jsx("input",{id:"train-split",type:"number",min:"0",max:"100",value:_,onChange:s=>{const o=parseInt(s.target.value)||0,a=100-o;a>=0&&(w(o),f+k>a&&(h(Math.floor(a/2)),x(a-Math.floor(a/2))))},className:l.splitInput,disabled:t})]}),e.jsxs("div",{className:l.splitInputGroup,children:[e.jsx("label",{htmlFor:"test-split",className:l.splitInputLabel,children:"Test (%)"}),e.jsx("input",{id:"test-split",type:"number",min:"0",max:"100",value:f,onChange:s=>{const o=parseInt(s.target.value)||0,a=100-_-o;a>=0&&(h(o),x(a))},className:l.splitInput,disabled:t})]}),e.jsxs("div",{className:l.splitInputGroup,children:[e.jsx("label",{htmlFor:"val-split",className:l.splitInputLabel,children:"Val (%)"}),e.jsx("input",{id:"val-split",type:"number",min:"0",max:"100",value:k,onChange:s=>{const o=parseInt(s.target.value)||0,a=100-_-o;a>=0&&(x(o),h(a))},className:l.splitInput,disabled:t})]})]}),_+f+k!==100&&e.jsx("div",{className:l.splitTotal,children:e.jsx("span",{className:l.splitTotalError,children:"Must equal 100%"})})]}),e.jsxs("div",{className:l.checkboxesContainer,children:[e.jsx("div",{className:"flex items-center gap-3",children:e.jsx(B,{name:"crisis-maps",label:`Crisis Maps (${j} images)`,value:u,onChange:s=>T(s),disabled:t})}),e.jsx("div",{className:"flex items-center gap-3",children:e.jsx(B,{name:"drone-images",label:`Drone Images (${I} images)`,value:S,onChange:s=>M(s),disabled:t})})]}),e.jsxs("div",{className:l.ratingWarningButtons,children:[e.jsx(v,{name:"confirm-export",onClick:C,disabled:t,children:t?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(O,{className:"text-white"}),"Exporting..."]}):"Export Selected"}),e.jsx(v,{name:"cancel-export",variant:"tertiary",onClick:g,disabled:t,children:"Cancel"})]})]})]})}):null}export{fe as E,_e as F};
|
|
|
1 |
+
import{r as n,j as e,M as P,P as W,o as F,S as A,D as H,z as b,n as v,O as V,I as z,T as q,_ as O,L as G}from"./index-BzYyR-qc.js";const R=({title:c,titleId:i,...r})=>n.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg","aria-hidden":"true",viewBox:"0 0 24 24",fill:"currentColor",width:"1em",height:"1em","aria-labelledby":i},r),c?n.createElement("title",{id:i},c):null,n.createElement("g",{clipPath:"url(#checkbox-indeterminate-line_svg__a)"},n.createElement("path",{d:"M4 3h16a1 1 0 0 1 1 1v16a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1Zm1 2v14h14V5H5Zm2 6h10v2H7v-2Z"})),n.createElement("defs",null,n.createElement("clipPath",{id:"checkbox-indeterminate-line_svg__a"},n.createElement("path",{d:"M0 0h24v24H0z"})))),$=({title:c,titleId:i,...r})=>n.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg","aria-hidden":"true",viewBox:"0 0 24 24",fill:"currentColor",width:"1em",height:"1em","aria-labelledby":i},r),c?n.createElement("title",{id:i},c):null,n.createElement("g",{clipPath:"url(#filter-line_svg__a)"},n.createElement("path",{d:"M9 13.5 4 6H3V4h18v2h-1l-5 7.5V22H9v-8.5ZM6.404 6 11 12.894V20h2v-7.106L17.596 6H6.404Z"})),n.createElement("defs",null,n.createElement("clipPath",{id:"filter-line_svg__a"},n.createElement("path",{d:"M0 0h24v24H0z"}))));function D(c){const{className:i,indeterminate:r,value:j}=c;return e.jsxs(e.Fragment,{children:[r&&e.jsx(R,{className:i}),j&&!r&&e.jsx(P,{className:i}),!j&&!r&&e.jsx(W,{className:i})]})}const U="_checkbox_12g7n_1",Z="_with-background_12g7n_7",Y="_checkmark-container_12g7n_12",J="_input_12g7n_18",K="_content_12g7n_33",Q="_description_12g7n_40",X="_checked_12g7n_45",L="_checkmark_12g7n_12",ee="_disabled-checkbox_12g7n_58",m={checkbox:U,withBackground:Z,checkmarkContainer:Y,input:J,content:K,description:Q,checked:X,checkmark:L,disabledCheckbox:ee};function B(c){const{className:i,checkmark:r=D,checkmarkClassName:j,checkmarkContainerClassName:I,disabled:t,error:p,indeterminate:N,inputClassName:E,invertedLogic:d=!1,label:y,labelContainerClassName:_,name:w,onChange:f,readOnly:h,tooltip:k,value:x,description:u,withBackground:T,...S}=c,M=n.useCallback(s=>{const o=s.currentTarget.checked;f(d?!o:o,w)},[w,f,d]),C=d?!x:x,g=F(m.checkbox,i,!N&&C&&m.checked,T&&m.withBackground,t&&m.disabledCheckbox,h&&m.readOnly);return e.jsxs("label",{className:g,title:k,children:[e.jsxs("div",{className:F(m.checkmarkContainer,I),children:[e.jsx("input",{onChange:M,className:F(m.input,E),type:"checkbox",checked:C??!1,disabled:t||h,readOnly:h,...S}),e.jsx(r,{className:F(m.checkmark,j),value:C??!1,indeterminate:N,"aria-hidden":"true"})]}),(y||u)&&e.jsxs("div",{className:m.content,children:[y&&e.jsx("div",{className:_,children:y}),u&&e.jsx("div",{className:m.description,children:u})]}),p&&e.jsx(A,{children:p})]})}function _e({sources:c,types:i,regions:r,countries:j,imageTypes:I,isLoadingFilters:t=!1}){const[p,N]=n.useState(!1),{search:E,setSearch:d,srcFilter:y,setSrcFilter:_,catFilter:w,setCatFilter:f,regionFilter:h,setRegionFilter:k,countryFilter:x,setCountryFilter:u,imageTypeFilter:T,setImageTypeFilter:S,uploadTypeFilter:M,setUploadTypeFilter:C,showReferenceExamples:g,setShowReferenceExamples:s,clearAllFilters:o}=H();return e.jsxs("div",{className:"mb-6 space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-4",children:[e.jsx(b,{withInternalPadding:!0,className:"bg-white/20 backdrop-blur-sm rounded-md p-2",children:e.jsx(v,{name:"toggle-filters",variant:"secondary",onClick:()=>N(!p),className:"whitespace-nowrap",title:p?"Hide Filters":"Show Filters",children:e.jsx($,{className:"w-4 h-4"})})}),e.jsx(b,{withInternalPadding:!0,className:"bg-white/20 backdrop-blur-sm rounded-md p-2 flex-1 min-w-[300px]",children:e.jsx(V,{name:"search",placeholder:"Search examples...",value:E,onChange:a=>d(a||"")})}),e.jsx(b,{withInternalPadding:!0,className:"bg-white/20 backdrop-blur-sm rounded-md p-2",children:e.jsx(v,{name:"clear-filters",variant:"secondary",onClick:o,children:"Clear Filters"})})]}),p&&e.jsx("div",{className:"bg-white/20 backdrop-blur-sm rounded-md p-4",children:e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-4",children:[e.jsx(b,{withInternalPadding:!0,className:"p-2",children:e.jsx(z,{name:"source",placeholder:t?"Loading...":"All Sources",options:c,value:y||null,onChange:a=>_(a||""),keySelector:a=>a.s_code,labelSelector:a=>a.label,required:!1,disabled:t})}),e.jsx(b,{withInternalPadding:!0,className:"p-2",children:e.jsx(z,{name:"category",placeholder:t?"Loading...":"All Categories",options:i,value:w||null,onChange:a=>f(a||""),keySelector:a=>a.t_code,labelSelector:a=>a.label,required:!1,disabled:t})}),e.jsx(b,{withInternalPadding:!0,className:"p-2",children:e.jsx(z,{name:"region",placeholder:t?"Loading...":"All Regions",options:r,value:h||null,onChange:a=>k(a||""),keySelector:a=>a.r_code,labelSelector:a=>a.label,required:!1,disabled:t})}),e.jsx(b,{withInternalPadding:!0,className:"p-2",children:e.jsx(q,{name:"country",placeholder:t?"Loading...":"All Countries",options:j,value:x?[x]:[],onChange:a=>u(a[0]||""),keySelector:a=>a.c_code,labelSelector:a=>a.label,disabled:t})}),e.jsx(b,{withInternalPadding:!0,className:"p-2",children:e.jsx(z,{name:"imageType",placeholder:t?"Loading...":"All Image Types",options:I,value:T||null,onChange:a=>S(a||""),keySelector:a=>a.image_type,labelSelector:a=>a.label,required:!1,disabled:t})}),e.jsx(b,{withInternalPadding:!0,className:"p-2",children:e.jsx(z,{name:"uploadType",placeholder:"All Upload Types",options:[{key:"single",label:"Single Upload"},{key:"multiple",label:"Multiple Upload"}],value:M||null,onChange:a=>C(a||""),keySelector:a=>a.key,labelSelector:a=>a.label,required:!1,disabled:!1})})]})})]})}const ae="_fullSizeModalOverlay_cyz3b_1",le="_fullSizeModalContent_cyz3b_29",te="_ratingWarningContent_cyz3b_53",se="_ratingWarningTitle_cyz3b_65",ne="_exportModeSection_cyz3b_133",ie="_splitConfigSection_cyz3b_143",re="_splitConfigTitle_cyz3b_153",ce="_splitInputsContainer_cyz3b_167",oe="_splitInputGroup_cyz3b_183",de="_splitInputLabel_cyz3b_197",me="_splitInput_cyz3b_167",pe="_splitTotal_cyz3b_247",he="_splitTotalError_cyz3b_261",xe="_checkboxesContainer_cyz3b_271",ue="_ratingWarningButtons_cyz3b_289",ge="_singleExportMessage_cyz3b_309",be="_navigateButtonContainer_cyz3b_333",ve="_loadingOverlay_cyz3b_349",l={fullSizeModalOverlay:ae,fullSizeModalContent:le,ratingWarningContent:te,ratingWarningTitle:se,exportModeSection:ne,splitConfigSection:ie,splitConfigTitle:re,splitInputsContainer:ce,splitInputGroup:oe,splitInputLabel:de,splitInput:me,splitTotal:pe,splitTotalError:he,checkboxesContainer:xe,ratingWarningButtons:ue,singleExportMessage:ge,navigateButtonContainer:be,loadingOverlay:ve};function fe({isOpen:c,onClose:i,onExport:r,crisisMapsCount:j,droneImagesCount:I,isLoading:t=!1,exportSuccess:p=!1,variant:N="bulk",onNavigateAndExport:E}){const[d,y]=n.useState("standard"),[_,w]=n.useState(80),[f,h]=n.useState(10),[k,x]=n.useState(10),[u,T]=n.useState(!0),[S,M]=n.useState(!0),C=()=>{if(N==="single"){r(d,["crisis_map","drone_image"]);return}if(!u&&!S){alert("Please select at least one image type to export.");return}const s=[];u&&s.push("crisis_map"),S&&s.push("drone_image"),r(d,s)},g=()=>{i()};return c?N==="single"?e.jsx("div",{className:l.fullSizeModalOverlay,onClick:g,children:e.jsxs("div",{className:l.fullSizeModalContent,onClick:s=>s.stopPropagation(),children:[t&&e.jsx("div",{className:l.loadingOverlay,children:e.jsxs("div",{className:"flex flex-col items-center gap-4",children:[e.jsx(O,{className:"text-ifrcRed"}),e.jsx("div",{className:"text-lg font-medium",children:"Exporting..."}),e.jsx("div",{className:"text-sm text-gray-600",children:"This might take a few seconds"})]})}),p&&e.jsx("div",{className:l.loadingOverlay,children:e.jsxs("div",{className:"flex flex-col items-center gap-4",children:[e.jsx("div",{className:"text-lg font-medium",children:"Export Successful!"}),e.jsx("div",{className:"text-sm text-gray-600",children:"Your dataset has been downloaded"}),e.jsx(v,{name:"close-export-success",onClick:g,className:"mt-4",children:"Close"})]})}),e.jsxs("div",{className:l.ratingWarningContent,children:[e.jsx("h3",{className:l.ratingWarningTitle,children:"Export Single Item"}),e.jsxs("div",{className:l.singleExportMessage,children:[e.jsx("p",{children:"This only exports the 1 item currently on display."}),e.jsx("p",{children:'You may export the entire dataset from the "list view" here:'})]}),e.jsx("div",{className:l.navigateButtonContainer,children:e.jsx(v,{name:"navigate-to-list",variant:"secondary",onClick:E,children:"Navigate to List View"})}),e.jsxs("div",{className:l.ratingWarningButtons,children:[e.jsx(v,{name:"continue-export",onClick:C,disabled:t,children:t?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(O,{className:"text-white"}),"Exporting..."]}):"Continue"}),e.jsx(v,{name:"cancel-export",variant:"tertiary",onClick:g,disabled:t,children:"Cancel"})]})]})]})}):e.jsx("div",{className:l.fullSizeModalOverlay,onClick:g,children:e.jsxs("div",{className:l.fullSizeModalContent,onClick:s=>s.stopPropagation(),children:[t&&e.jsx("div",{className:l.loadingOverlay,children:e.jsxs("div",{className:"flex flex-col items-center gap-4",children:[e.jsx(O,{className:"text-ifrcRed"}),e.jsx("div",{className:"text-lg font-medium",children:"Exporting..."}),e.jsx("div",{className:"text-sm text-gray-600",children:"This might take a few seconds"})]})}),p&&e.jsx("div",{className:l.loadingOverlay,children:e.jsxs("div",{className:"flex flex-col items-center gap-4",children:[e.jsx("div",{className:"text-lg font-medium",children:"Export Successful!"}),e.jsx("div",{className:"text-sm text-gray-600",children:"Your dataset has been downloaded"}),e.jsx(v,{name:"close-export-success",onClick:g,className:"mt-4",children:"Close"})]})}),e.jsxs("div",{className:l.ratingWarningContent,children:[e.jsx("h3",{className:l.ratingWarningTitle,children:"Export Dataset"}),e.jsx("div",{className:l.exportModeSection,children:e.jsx(G,{name:"export-mode",value:d,onChange:s=>{(s==="standard"||s==="fine-tuning")&&y(s)},options:[{key:"standard",label:"Standard"},{key:"fine-tuning",label:"Fine-tuning"}],keySelector:s=>s.key,labelSelector:s=>s.label,disabled:t})}),d==="fine-tuning"&&e.jsxs("div",{className:l.splitConfigSection,children:[e.jsx("div",{className:l.splitConfigTitle,children:"Dataset Split Configuration"}),e.jsxs("div",{className:l.splitInputsContainer,children:[e.jsxs("div",{className:l.splitInputGroup,children:[e.jsx("label",{htmlFor:"train-split",className:l.splitInputLabel,children:"Train (%)"}),e.jsx("input",{id:"train-split",type:"number",min:"0",max:"100",value:_,onChange:s=>{const o=parseInt(s.target.value)||0,a=100-o;a>=0&&(w(o),f+k>a&&(h(Math.floor(a/2)),x(a-Math.floor(a/2))))},className:l.splitInput,disabled:t})]}),e.jsxs("div",{className:l.splitInputGroup,children:[e.jsx("label",{htmlFor:"test-split",className:l.splitInputLabel,children:"Test (%)"}),e.jsx("input",{id:"test-split",type:"number",min:"0",max:"100",value:f,onChange:s=>{const o=parseInt(s.target.value)||0,a=100-_-o;a>=0&&(h(o),x(a))},className:l.splitInput,disabled:t})]}),e.jsxs("div",{className:l.splitInputGroup,children:[e.jsx("label",{htmlFor:"val-split",className:l.splitInputLabel,children:"Val (%)"}),e.jsx("input",{id:"val-split",type:"number",min:"0",max:"100",value:k,onChange:s=>{const o=parseInt(s.target.value)||0,a=100-_-o;a>=0&&(x(o),h(a))},className:l.splitInput,disabled:t})]})]}),_+f+k!==100&&e.jsx("div",{className:l.splitTotal,children:e.jsx("span",{className:l.splitTotalError,children:"Must equal 100%"})})]}),e.jsxs("div",{className:l.checkboxesContainer,children:[e.jsx("div",{className:"flex items-center gap-3",children:e.jsx(B,{name:"crisis-maps",label:`Crisis Maps (${j} images)`,value:u,onChange:s=>T(s),disabled:t})}),e.jsx("div",{className:"flex items-center gap-3",children:e.jsx(B,{name:"drone-images",label:`Drone Images (${I} images)`,value:S,onChange:s=>M(s),disabled:t})})]}),e.jsxs("div",{className:l.ratingWarningButtons,children:[e.jsx(v,{name:"confirm-export",onClick:C,disabled:t,children:t?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(O,{className:"text-white"}),"Exporting..."]}):"Export Selected"}),e.jsx(v,{name:"cancel-export",variant:"tertiary",onClick:g,disabled:t,children:"Cancel"})]})]})]})}):null}export{fe as E,_e as F};
|
py_backend/static/assets/index-5HpHyjh5.js
ADDED
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
1 |
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/jszip.min-JNyb8pkO.js","assets/index-BzYyR-qc.js","assets/index-FBu17hMI.css"])))=>i.map(i=>d[i]);
|
2 |
+
import{j as t,z as b,n as w,v as Fe,w as De,x as Oe,B as Le,r as o,D as Me,N as Re,_ as de,L as Je,F as ze,G as We}from"./index-BzYyR-qc.js";import{u as Ue}from"./useAdmin-B4TrJLwR.js";import{F as Be,E as He}from"./ExportModal-DJU5iFtN.js";const Ve="_paginatorContainer_1l5ti_1",Ae="_paginationControls_1l5ti_19",me={paginatorContainer:Ve,paginationControls:Ae};function Ge({currentPage:N,totalPages:h,totalItems:X,itemsPerPage:U,onPageChange:C,className:S=""}){if(h<=1)return null;const u=(()=>{const g=[];if(h<=5)for(let f=1;f<=h;f++)g.push(f);else{let f=Math.max(1,N-2),_=Math.min(h,f+5-1);_===h&&(f=Math.max(1,_-5+1));for(let y=f;y<=_;y++)g.push(y)}return g})();return t.jsx("div",{className:`${me.paginatorContainer} ${S}`,children:t.jsxs("div",{className:me.paginationControls,children:[t.jsx(b,{withInternalPadding:!0,className:"bg-white/20 backdrop-blur-sm rounded-md p-2",children:t.jsxs(w,{name:"prev-page",variant:"tertiary",size:1,onClick:()=>C(Math.max(1,N-1)),disabled:N===1,title:"Previous page",children:[t.jsx(Fe,{className:"w-4 h-4"}),t.jsx("span",{className:"hidden sm:inline",children:"Previous"})]})}),t.jsxs("div",{className:"flex items-center gap-1",children:[u[0]>1&&t.jsxs(t.Fragment,{children:[t.jsx(b,{withInternalPadding:!0,className:"bg-white/20 backdrop-blur-sm rounded-md p-2",children:t.jsx(w,{name:"page-1",variant:"tertiary",size:1,onClick:()=>C(1),children:"1"})}),u[0]>2&&t.jsx(b,{withInternalPadding:!0,className:"bg-white/20 backdrop-blur-sm rounded-md p-2",children:t.jsx("span",{className:"px-2 text-gray-500",children:"..."})})]}),u.map(g=>t.jsx(b,{withInternalPadding:!0,className:"bg-white/20 backdrop-blur-sm rounded-md p-2",children:t.jsx(w,{name:`page-${g}`,variant:N===g?"primary":"tertiary",size:1,onClick:()=>C(g),children:g})},g)),u[u.length-1]<h&&t.jsxs(t.Fragment,{children:[u[u.length-1]<h-1&&t.jsx(b,{withInternalPadding:!0,className:"bg-white/20 backdrop-blur-sm rounded-md p-2",children:t.jsx("span",{className:"px-2 text-gray-500",children:"..."})}),t.jsx(b,{withInternalPadding:!0,className:"bg-white/20 backdrop-blur-sm rounded-md p-2",children:t.jsx(w,{name:`page-${h}`,variant:"tertiary",size:1,onClick:()=>C(h),children:h})})]})]}),t.jsx(b,{withInternalPadding:!0,className:"bg-white/20 backdrop-blur-sm rounded-md p-2",children:t.jsxs(w,{name:"next-page",variant:"tertiary",size:1,onClick:()=>C(Math.min(h,N+1)),disabled:N===h,title:"Next page",children:[t.jsx("span",{className:"hidden sm:inline",children:"Next"}),t.jsx(De,{className:"w-4 h-4"})]})})]})})}const Ze="_tabSelector_o9y1f_1",qe="_metadataTags_o9y1f_8",Ke="_metadataTag_o9y1f_8",Qe="_metadataTagSource_o9y1f_32",Xe="_metadataTagType_o9y1f_43",Ye="_mapItem_o9y1f_54",et="_mapItemImage_o9y1f_72",tt="_mapItemContent_o9y1f_92",at="_mapItemTitle_o9y1f_97",st="_mapItemMetadata_o9y1f_105",it="_fullSizeModalOverlay_o9y1f_134",nt="_fullSizeModalContent_o9y1f_148",lt="_ratingWarningContent_o9y1f_159",rt="_ratingWarningTitle_o9y1f_165",ot="_ratingWarningText_o9y1f_172",ct="_ratingWarningButtons_o9y1f_179",m={tabSelector:Ze,metadataTags:qe,metadataTag:Ke,metadataTagSource:Qe,metadataTagType:Xe,mapItem:Ye,mapItemImage:et,mapItemContent:tt,mapItemTitle:at,mapItemMetadata:st,fullSizeModalOverlay:it,fullSizeModalContent:nt,ratingWarningContent:lt,ratingWarningTitle:rt,ratingWarningText:ot,ratingWarningButtons:ct};function pt(){const N=Oe(),h=Le(),{isAuthenticated:X}=Ue(),[U,C]=o.useState("explore"),[S,M]=o.useState([]),{search:u,srcFilter:g,catFilter:T,regionFilter:f,countryFilter:_,imageTypeFilter:y,uploadTypeFilter:$,showReferenceExamples:E,setShowReferenceExamples:ge}=Me(),[B,pe]=o.useState([]),[H,ue]=o.useState([]),[Y,fe]=o.useState([]),[he,xe]=o.useState([]),[ee,_e]=o.useState([]),[ye,te]=o.useState(!0),[R,ae]=o.useState(!0),[je,V]=o.useState(!1),[Ne,A]=o.useState(!1),[ve,G]=o.useState(!1),[be,J]=o.useState(!1),[z,se]=o.useState(""),[Z,ie]=o.useState(!1),[W,ne]=o.useState(1),[q]=o.useState(10),[K,le]=o.useState(0),[we,re]=o.useState(0),Se=[{key:"explore",label:"List"},{key:"mapDetails",label:"Carousel"}],oe=()=>{ae(!0);const e=new URLSearchParams({page:W.toString(),limit:q.toString()});u&&e.append("search",u),g&&e.append("source",g),T&&e.append("event_type",T),f&&e.append("region",f),_&&e.append("country",_),y&&e.append("image_type",y),$&&e.append("upload_type",$),E&&e.append("starred_only","true"),fetch(`/api/images/grouped?${e.toString()}`).then(s=>s.ok?s.json():(console.error("ExplorePage: Grouped endpoint failed, trying legacy endpoint"),fetch("/api/captions/legacy").then(c=>c.ok?c.json():(console.error("ExplorePage: Legacy endpoint failed, trying regular images endpoint"),fetch("/api/images").then(j=>{if(!j.ok)throw new Error(`HTTP ${j.status}: ${j.statusText}`);return j.json()}))))).then(s=>{console.log("ExplorePage: Fetched captions:",s),M(s)}).catch(s=>{console.error("ExplorePage: Error fetching captions:",s),M([])}).finally(()=>{ae(!1)})},Te=()=>{const e=new URLSearchParams;u&&e.append("search",u),g&&e.append("source",g),T&&e.append("event_type",T),f&&e.append("region",f),_&&e.append("country",_),y&&e.append("image_type",y),$&&e.append("upload_type",$),E&&e.append("starred_only","true"),fetch(`/api/images/grouped/count?${e.toString()}`).then(s=>s.ok?s.json():(console.error("ExplorePage: Count endpoint failed"),{total_count:0})).then(s=>{console.log("ExplorePage: Total count:",s.total_count),le(s.total_count),re(Math.ceil(s.total_count/q))}).catch(s=>{console.error("ExplorePage: Error fetching total count:",s),le(0),re(0)})};o.useEffect(()=>{oe(),Te()},[W,u,g,T,f,_,y,$,E]),o.useEffect(()=>{W!==1&&ne(1)},[u,g,T,f,_,y,$,E]),o.useEffect(()=>{const e=()=>{document.hidden||oe()};return document.addEventListener("visibilitychange",e),()=>{document.removeEventListener("visibilitychange",e)}},[]),o.useEffect(()=>{new URLSearchParams(h.search).get("export")==="true"&&(V(!0),N("/explore",{replace:!0}))},[h.search,N,u,g,T,f,_,y,E]),o.useEffect(()=>{te(!0),Promise.all([fetch("/api/sources").then(e=>{if(!e.ok)throw new Error(`HTTP ${e.status}: ${e.statusText}`);return e.json()}),fetch("/api/types").then(e=>{if(!e.ok)throw new Error(`HTTP ${e.status}: ${e.statusText}`);return e.json()}),fetch("/api/regions").then(e=>{if(!e.ok)throw new Error(`HTTP ${e.status}: ${e.statusText}`);return e.json()}),fetch("/api/countries").then(e=>{if(!e.ok)throw new Error(`HTTP ${e.status}: ${e.statusText}`);return e.json()}),fetch("/api/image-types").then(e=>{if(!e.ok)throw new Error(`HTTP ${e.status}: ${e.statusText}`);return e.json()})]).then(([e,s,c,j,P])=>{pe(e),ue(s),fe(c),xe(j),_e(P)}).catch(()=>{}).finally(()=>{te(!1)})},[]);const I=S,Ee=async(e,s="fine-tuning")=>{if(e.length===0){alert("No images to export");return}A(!0),G(!1);try{const c=(await We(async()=>{const{default:i}=await import("./jszip.min-JNyb8pkO.js").then(k=>k.j);return{default:i}},__vite__mapDeps([0,1,2]))).default,j=new c,P=e.filter(i=>i.image_type==="crisis_map"),O=e.filter(i=>i.image_type==="drone_image");if(P.length>0){const i=j.folder("crisis_maps_dataset"),k=i?.folder("images");if(k){let F=1;for(const a of P)try{const v=a.image_count&&a.image_count>1?a.all_image_ids||[a.image_id]:[a.image_id],Q=v.map(async(n,x)=>{try{const l=await fetch(`/api/images/${n}/file`);if(!l.ok)throw new Error(`Failed to fetch image ${n}`);const r=await l.blob(),d=a.file_key.split(".").pop()||"jpg",p=`${String(F).padStart(4,"0")}_${String(x+1).padStart(2,"0")}.${d}`;return k.file(p,r),{success:!0,fileName:p,imageId:n}}catch(l){return console.error(`Failed to process image ${n}:`,l),{success:!1,fileName:"",imageId:n}}}),D=(await Promise.all(Q)).filter(n=>n.success);if(D.length>0){if(s==="fine-tuning"){const n=D.map(r=>`images/${r.fileName}`),x=Math.random(),l={image:n.length===1?n[0]:n,caption:a.edited||a.generated||"",metadata:{image_id:v,title:a.title,source:a.source,event_type:a.event_type,image_type:a.image_type,countries:a.countries,starred:a.starred,image_count:a.image_count||1}};if(!i)continue;if(x<.8){const r=i.file("train.jsonl");if(r){const d=await r.async("string").then(p=>JSON.parse(p||"[]")).catch(()=>[]);d.push(l),i.file("train.jsonl",JSON.stringify(d,null,2))}else i.file("train.jsonl",JSON.stringify([l],null,2))}else if(x<.9){const r=i.file("test.jsonl");if(r){const d=await r.async("string").then(p=>JSON.parse(p||"[]")).catch(()=>[]);d.push(l),i.file("test.jsonl",JSON.stringify(d,null,2))}else i.file("test.jsonl",JSON.stringify([l],null,2))}else{const r=i.file("val.jsonl");if(r){const d=await r.async("string").then(p=>JSON.parse(p||"[]")).catch(()=>[]);d.push(l),i.file("val.jsonl",JSON.stringify(d,null,2))}else i.file("val.jsonl",JSON.stringify([l],null,2))}}else{const n=D.map(l=>`images/${l.fileName}`),x={image:n.length===1?n[0]:n,caption:a.edited||a.generated||"",metadata:{image_id:v,title:a.title,source:a.source,event_type:a.event_type,image_type:a.image_type,countries:a.countries,starred:a.starred,image_count:a.image_count||1}};i&&i.file(`${String(F).padStart(4,"0")}.json`,JSON.stringify(x,null,2))}F++}}catch(v){console.error(`Failed to process caption ${a.image_id}:`,v)}}}if(O.length>0){const i=j.folder("drone_images_dataset"),k=i?.folder("images");if(k){let F=1;for(const a of O)try{const v=a.image_count&&a.image_count>1?a.all_image_ids||[a.image_id]:[a.image_id],Q=v.map(async(n,x)=>{try{const l=await fetch(`/api/images/${n}/file`);if(!l.ok)throw new Error(`Failed to fetch image ${n}`);const r=await l.blob(),d=a.file_key.split(".").pop()||"jpg",p=`${String(F).padStart(4,"0")}_${String(x+1).padStart(2,"0")}.${d}`;return k.file(p,r),{success:!0,fileName:p,imageId:n}}catch(l){return console.error(`Failed to process image ${n}:`,l),{success:!1,fileName:"",imageId:n}}}),D=(await Promise.all(Q)).filter(n=>n.success);if(D.length>0){if(s==="fine-tuning"){const n=D.map(r=>`images/${r.fileName}`),x=Math.random(),l={image:n.length===1?n[0]:n,caption:a.edited||a.generated||"",metadata:{image_id:v,title:a.title,source:a.source,event_type:a.event_type,image_type:a.image_type,countries:a.countries,starred:a.starred,image_count:a.image_count||1}};if(!i)continue;if(x<.8){const r=i.file("train.jsonl");if(r){const d=await r.async("string").then(p=>JSON.parse(p||"[]")).catch(()=>[]);d.push(l),i.file("train.jsonl",JSON.stringify(d,null,2))}else i.file("train.jsonl",JSON.stringify([l],null,2))}else if(x<.9){const r=i.file("test.jsonl");if(r){const d=await r.async("string").then(p=>JSON.parse(p||"[]")).catch(()=>[]);d.push(l),i.file("test.jsonl",JSON.stringify(d,null,2))}else i.file("test.jsonl",JSON.stringify([l],null,2))}else{const r=i.file("val.jsonl");if(r){const d=await r.async("string").then(p=>JSON.parse(p||"[]")).catch(()=>[]);d.push(l),i.file("val.jsonl",JSON.stringify(d,null,2))}else i.file("val.jsonl",JSON.stringify([l],null,2))}}else{const n=D.map(l=>`images/${l.fileName}`),x={image:n.length===1?n[0]:n,caption:a.edited||a.generated||"",metadata:{image_id:v,title:a.title,source:a.source,event_type:a.event_type,image_type:a.image_type,countries:a.countries,starred:a.starred,image_count:a.image_count||1}};i&&i.file(`${String(F).padStart(4,"0")}.json`,JSON.stringify(x,null,2))}F++}}catch(v){console.error(`Failed to process caption ${a.image_id}:`,v)}}}const $e=await j.generateAsync({type:"blob"}),ce=URL.createObjectURL($e),L=document.createElement("a");L.href=ce,L.download=`datasets_${s}_${new Date().toISOString().split("T")[0]}.zip`,document.body.appendChild(L),L.click(),document.body.removeChild(L),URL.revokeObjectURL(ce);const Pe=(P.length||0)+(O.length||0);console.log(`Exported ${s} datasets with ${Pe} total images:`),P.length>0&&console.log(`- Crisis maps: ${P.length} images`),O.length>0&&console.log(`- Drone images: ${O.length} images`),G(!0)}catch(c){console.error("Export failed:",c),alert("Failed to export dataset. Please try again.")}finally{A(!1)}},Ie=e=>{se(e),J(!0)},Ce=async()=>{if(z){ie(!0);try{console.log("Deleting image with ID:",z),(await fetch(`/api/images/${z}`,{method:"DELETE"})).ok?(M(s=>s.filter(c=>c.image_id!==z)),J(!1),se("")):(console.error("Delete failed"),alert("Failed to delete image. Please try again."))}catch(e){console.error("Delete failed:",e),alert("Failed to delete image. Please try again.")}finally{ie(!1)}}};return t.jsxs(Re,{children:[R?t.jsx("div",{className:"flex flex-col items-center justify-center min-h-[60vh]",children:t.jsxs("div",{className:"flex flex-col items-center gap-4",children:[t.jsx(de,{className:"text-ifrcRed"}),t.jsx("div",{children:"Loading examples..."})]})}):t.jsxs("div",{className:"max-w-7xl mx-auto",children:[t.jsxs("div",{className:m.tabSelector,children:[t.jsx(Je,{name:"explore-view",value:U,onChange:e=>{(e==="explore"||e==="mapDetails")&&(C(e),e==="mapDetails"&&S.length>0&&(S[0]?.image_id&&S[0].image_id!=="undefined"&&S[0].image_id!=="null"?N(`/map/${S[0].image_id}`):console.error("Invalid image_id for navigation:",S[0]?.image_id)))},options:Se,keySelector:e=>e.key,labelSelector:e=>e.label}),t.jsxs("div",{className:"flex items-center gap-2 ml-auto",children:[t.jsx(b,{withInternalPadding:!0,className:"bg-white/20 backdrop-blur-sm rounded-md p-2",children:t.jsxs(w,{name:"reference-examples",variant:E?"primary":"secondary",onClick:()=>ge(!E),className:"whitespace-nowrap",children:[t.jsx("span",{className:"mr-2",children:E?t.jsx("span",{className:"text-yellow-400",children:"β
"}):t.jsx("span",{className:"text-yellow-400",children:"β"})}),"Reference Examples"]})}),t.jsx(w,{name:"export-dataset",variant:"secondary",onClick:()=>V(!0),children:"Export"})]})]}),U==="explore"?t.jsxs("div",{className:"space-y-6",children:[t.jsx("div",{className:"mb-6 space-y-4",children:t.jsx("div",{className:"flex flex-wrap items-center gap-4",children:t.jsx(b,{withInternalPadding:!0,className:"bg-white/20 backdrop-blur-sm rounded-md p-2 flex-1 min-w-[300px]",children:t.jsx(Be,{sources:B,types:H,regions:Y,countries:he,imageTypes:ee,isLoadingFilters:ye})})})}),t.jsxs("div",{className:"space-y-4",children:[t.jsx("div",{className:"flex justify-between items-center",children:t.jsxs("p",{className:"text-sm text-gray-600",children:[I.length," of ",K," examples"]})}),R&&t.jsx("div",{className:"text-center py-12",children:t.jsxs("div",{className:"flex flex-col items-center gap-4",children:[t.jsx(de,{className:"text-ifrcRed"}),t.jsx("div",{children:"Loading examples..."})]})}),!R&&t.jsxs("div",{className:"space-y-4",children:[I.map(e=>t.jsxs("div",{className:"flex items-center gap-4",children:[t.jsxs("div",{className:`${m.mapItem} flex-1`,onClick:()=>{console.log("ExplorePage: Clicking on image with ID:",e.image_id),console.log("ExplorePage: Image data:",e),e.image_id&&e.image_id!=="undefined"&&e.image_id!=="null"?(console.log("ExplorePage: Navigating to:",`/map/${e.image_id}`),console.log("ExplorePage: Full navigation URL:",`/#/map/${e.image_id}`),N(`/map/${e.image_id}`)):(console.error("Invalid image_id for navigation:",e.image_id),console.error("Full item data:",JSON.stringify(e,null,2)),alert(`Cannot navigate: Invalid image ID (${e.image_id})`))},children:[t.jsx("div",{className:m.mapItemImage,style:{width:"120px",height:"80px"},children:e.thumbnail_url?t.jsxs(t.Fragment,{children:[console.log("ExplorePage: Using thumbnail for fast loading:",e.thumbnail_url),t.jsx("img",{src:e.thumbnail_url,alt:e.file_key,onError:s=>{console.error("ExplorePage: Thumbnail failed to load, falling back to original:",e.thumbnail_url);const c=s.target;e.image_url?c.src=e.image_url:(c.style.display="none",c.parentElement.innerHTML="Img")},onLoad:()=>console.log("ExplorePage: Thumbnail loaded successfully:",e.thumbnail_url)})]}):e.image_url?t.jsxs(t.Fragment,{children:[console.log("ExplorePage: No thumbnail available, using original image:",e.image_url),t.jsx("img",{src:e.image_url,alt:e.file_key,onError:s=>{console.error("ExplorePage: Original image failed to load:",e.image_url);const c=s.target;c.style.display="none",c.parentElement.innerHTML="Img"},onLoad:()=>console.log("ExplorePage: Original image loaded successfully:",e.image_url)})]}):t.jsxs(t.Fragment,{children:[console.log("ExplorePage: No image_url or thumbnail provided for item:",e),"'Img'"]})}),t.jsxs("div",{className:m.mapItemContent,children:[t.jsx("h3",{className:m.mapItemTitle,children:t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("span",{children:e.title||"Untitled"}),e.starred&&t.jsx("span",{className:"text-red-500 text-lg",title:"Starred image",children:"β
"})]})}),t.jsx("div",{className:m.mapItemMetadata,children:t.jsxs("div",{className:m.metadataTags,children:[e.image_type!=="drone_image"&&t.jsx("span",{className:m.metadataTagSource,children:e.source&&e.source.includes(", ")?e.source.split(", ").map(s=>B.find(c=>c.s_code===s.trim())?.label||s.trim()).join(", "):B.find(s=>s.s_code===e.source)?.label||e.source}),t.jsx("span",{className:m.metadataTagType,children:e.event_type&&e.event_type.includes(", ")?e.event_type.split(", ").map(s=>H.find(c=>c.t_code===s.trim())?.label||s.trim()).join(", "):H.find(s=>s.t_code===e.event_type)?.label||e.event_type}),t.jsx("span",{className:m.metadataTag,children:ee.find(s=>s.image_type===e.image_type)?.label||e.image_type}),e.image_count&&e.image_count>1&&t.jsxs("span",{className:m.metadataTag,title:`Multi-upload with ${e.image_count} images`,children:["π· ",e.image_count]}),(!e.image_count||e.image_count<=1)&&t.jsx("span",{className:m.metadataTag,title:"Single Upload",children:"Single"}),e.countries&&e.countries.length>0&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:m.metadataTag,children:Y.find(s=>s.r_code===e.countries[0].r_code)?.label||"Unknown Region"}),t.jsx("span",{className:m.metadataTag,children:e.countries.map(s=>s.label).join(", ")})]})]})})]})]}),X&&t.jsx(b,{withInternalPadding:!0,className:"bg-white/20 backdrop-blur-sm rounded-md p-2",children:t.jsx(w,{name:`delete-${e.image_id}`,variant:"tertiary",size:1,className:"bg-red-50 hover:bg-red-100 text-red-700 border border-red-200 hover:border-red-300",onClick:()=>Ie(e.image_id),title:"Delete","aria-label":"Delete saved image",children:t.jsx(ze,{className:"w-4 h-4"})})})]},e.image_id)),!I.length&&t.jsx("div",{className:"text-center py-12",children:t.jsx("p",{className:"text-gray-500",children:"No examples found."})}),!R&&I.length>0&&t.jsx(Ge,{currentPage:W,totalPages:we,totalItems:K,itemsPerPage:q,onPageChange:ne})]})]})]}):t.jsx("div",{className:"space-y-6",children:t.jsxs("div",{className:"text-center py-12",children:[t.jsx("p",{className:"text-gray-500",children:"Map Details view coming soon..."}),t.jsx("p",{className:"text-sm text-gray-400 mt-2",children:"This will show detailed information about individual maps"})]})})]}),be&&t.jsx("div",{className:m.fullSizeModalOverlay,onClick:()=>J(!1),children:t.jsx("div",{className:m.fullSizeModalContent,onClick:e=>e.stopPropagation(),children:t.jsxs("div",{className:m.ratingWarningContent,children:[t.jsx("h3",{className:m.ratingWarningTitle,children:"Delete Image?"}),t.jsx("p",{className:m.ratingWarningText,children:"This action cannot be undone. Are you sure you want to delete this saved image and all related data?"}),t.jsxs("div",{className:m.ratingWarningButtons,children:[t.jsx(w,{name:"confirm-delete",variant:"secondary",onClick:Ce,disabled:Z,children:Z?"Deleting...":"Delete"}),t.jsx(w,{name:"cancel-delete",variant:"tertiary",onClick:()=>J(!1),disabled:Z,children:"Cancel"})]})]})})}),t.jsx(He,{isOpen:je,onClose:()=>{V(!1),G(!1),A(!1)},onExport:(e,s)=>{const c=I.filter(j=>s.includes(j.image_type));Ee(c,e)},filteredCount:I.length,totalCount:K,hasFilters:!!(u||g||T||f||_||y||$||E),crisisMapsCount:I.filter(e=>e.image_type==="crisis_map").length,droneImagesCount:I.filter(e=>e.image_type==="drone_image").length,isLoading:Ne,exportSuccess:ve})]})}export{pt as default};
|
py_backend/static/assets/{index-LmdVBMha.js β index-BzYyR-qc.js}
RENAMED
@@ -1,4 +1,4 @@
|
|
1 |
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-
|
2 |
function $g(e,n){for(var i=0;i<n.length;i++){const o=n[i];if(typeof o!="string"&&!Array.isArray(o)){for(const s in o)if(s!=="default"&&!(s in e)){const u=Object.getOwnPropertyDescriptor(o,s);u&&Object.defineProperty(e,s,u.get?u:{enumerable:!0,get:()=>o[s]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}(function(){const n=document.createElement("link").relList;if(n&&n.supports&&n.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))o(s);new MutationObserver(s=>{for(const u of s)if(u.type==="childList")for(const d of u.addedNodes)d.tagName==="LINK"&&d.rel==="modulepreload"&&o(d)}).observe(document,{childList:!0,subtree:!0});function i(s){const u={};return s.integrity&&(u.integrity=s.integrity),s.referrerPolicy&&(u.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?u.credentials="include":s.crossOrigin==="anonymous"?u.credentials="omit":u.credentials="same-origin",u}function o(s){if(s.ep)return;s.ep=!0;const u=i(s);fetch(s.href,u)}})();var _P=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function zg(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Zc={exports:{}},Oa={},Qc={exports:{}},Ze={};/**
|
3 |
* @license React
|
4 |
* react.production.min.js
|
@@ -158,4 +158,4 @@ ${i||"AI-generated recommended actions will appear here..."}`,onChange:C,rows:12
|
|
158 |
|
159 |
Analysis: ${Er}
|
160 |
|
161 |
-
Recommended Actions: ${kr}`,Te={title:fe,edited:Me,accuracy:Kn.accuracy,context:Kn.context,usability:Kn.usability};console.log("Updating caption:",Te);const je=await fetch(`/api/images/${Ft}/caption`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(Te)}),ge=await tr(je);if(!je.ok)throw new Error(ge.error||"Caption update failed");cn(null),bt([]),ji(3)}catch(k){Pr(k,"Submit")}}async function aa(){if(console.log("handleDelete called with uploadedImageId:",Ft),!Ft){alert("No image to delete. Please try refreshing the page.");return}j(!0)}async function so(){try{console.log("Deleting image with ID:",Ft);const k=await fetch(`/api/images/${Ft}`,{method:"DELETE"});if(!k.ok){const Me=await tr(k);throw new Error(Me.error||`Delete failed with status ${k.status}`)}j(!1),sa()}catch(k){Pr(k,"Delete")}}const sa=()=>{zn(!1),o(1),x(null),_([]),C(null),cn(null),bt([]),Et(null),I(""),M(""),$(""),Z(""),de([]),W(""),he(""),be(""),le(""),U(""),Se(""),re(""),Q(""),tt(!1),Wt(""),wt(""),kn({accuracy:50,context:50,usability:50}),dn(""),Qr(""),Nr(""),Fn(""),ht([]),Pe(!1),Ce(null),me(!1),Ve(null),Ke(!1),Je(null),Tn(!1),ze(""),fn(!1),Pn(null),Be(!1),jt(null),n("/upload",{replace:!0})},lo=y.useCallback(k=>{k==="/upload"||k==="/"||(v.current?(ue(k),z(!0)):n(k))},[n]);async function Mi(){if(K&&v.current)try{await fetch(`/api/images/${v.current}`,{method:"DELETE"}),z(!1),ue(null),n(K)}catch(k){console.error("Failed to delete image before navigation:",k),z(!1),ue(null),n(K)}}const Li=async()=>{if(qe){Tn(!0),ze("Starting file conversion...");try{const k=new FormData;k.append("file",qe),k.append("preprocess_only","true"),ze("Converting file format...");const Me=await fetch("/api/images/preprocess",{method:"POST",body:k});if(!Me.ok)throw new Error("Preprocessing failed");const Te=await Me.json();ze("Finalizing conversion...");const je=atob(Te.processed_content),ge=new Uint8Array(je.length);for(let We=0;We<je.length;We++)ge[We]=je.charCodeAt(We);const Re=new File([ge],Te.processed_filename,{type:Te.processed_mime_type}),rt=URL.createObjectURL(Re);b.length===0?(x(Re),_([Re])):_(We=>[...We,Re]),C(rt),ze("Conversion complete!"),setTimeout(()=>{Ke(!1),Je(null),Tn(!1),ze("")},1e3)}catch(k){console.error("Preprocessing error:",k),ze("Conversion failed. Please try again."),setTimeout(()=>{Ke(!1),Je(null),Tn(!1),ze("")},2e3)}}},ti=()=>{Ke(!1),Je(null),Tn(!1),ze("")},uo=async k=>{f(!0);try{const Me=k.map(async Re=>{const rt=await fetch(`/api/images/${Re}`);if(!rt.ok)throw new Error(`Failed to fetch image ${Re}`);const We=await rt.json(),$t=await fetch(`/api/images/${Re}/file`);if(!$t.ok)throw new Error(`Failed to fetch image file ${Re}`);const it=await $t.blob(),Zt=We.file_key.split("/").pop()||`contributed_${Re}.png`;return{file:new File([it],Zt,{type:it.type}),imageData:We}}),Te=await Promise.all(Me),je=Te.map(Re=>Re.file),ge=Te[0]?.imageData;_(je),bt(k),k.length===1&&cn(k[0]),je.length>=1&&x(je[0]),ge?.image_type&&O(ge.image_type)}catch(Me){console.error("Failed to fetch contributed images:",Me),alert(`Failed to load contributed images: ${Me instanceof Error?Me.message:"Unknown error"}`)}finally{f(!1)}};return y.useEffect(()=>{Promise.all([fetch("/api/sources").then(k=>k.json()),fetch("/api/types").then(k=>k.json()),fetch("/api/spatial-references").then(k=>k.json()),fetch("/api/image-types").then(k=>k.json()),fetch("/api/countries").then(k=>k.json()),fetch("/api/models").then(k=>k.json())]).then(([k,Me,Te,je,ge,Re])=>{!localStorage.getItem(Il)&&Re?.length&&localStorage.setItem(Il,Re[0].m_code),xt(k),nn(Me),sn(Te),Gr(je),un(ge),k.length>0&&M(k[0].s_code),$("OTHER"),Z("OTHER"),je.length>0&&!e.get("imageType")&&!ce&&O(je[0].image_type)})},[e,ce]),y.useEffect(()=>(window.confirmNavigationIfNeeded=k=>{lo(k)},()=>{delete window.confirmNavigationIfNeeded}),[lo]),y.useEffect(()=>{const k=je=>{if(v.current){const ge="You have an uploaded image that will be deleted if you leave this page. Are you sure you want to leave?";return je.preventDefault(),je.returnValue=ge,ge}},Me=()=>{v.current&&fetch(`/api/images/${v.current}`,{method:"DELETE"}).catch(console.error)},Te=je=>{const ge=je.target,Re=ge.closest("a[href]")||ge.closest("[data-navigate]");if(Re&&v.current){const rt=Re.getAttribute("href")||Re.getAttribute("data-navigate");rt&&rt!=="#"&&!rt.startsWith("javascript:")&&!rt.startsWith("mailto:")&&(je.preventDefault(),je.stopPropagation(),lo(rt))}};return window.addEventListener("beforeunload",k),document.addEventListener("click",Te,!0),()=>{window.removeEventListener("beforeunload",k),document.removeEventListener("click",Te,!0),Me()}},[lo]),y.useEffect(()=>{if(!m){C(null);return}const k=URL.createObjectURL(m);return C(k),()=>URL.revokeObjectURL(k)},[m]),y.useEffect(()=>{const k=e.get("contribute"),Me=e.get("imageIds");if(k==="true"&&Me){const Te=Me.split(",").filter(je=>je.trim());Te.length>0&&uo(Te)}},[e]),y.useEffect(()=>{i==="2b"&&Ge(0)},[i]),g.jsxs(Gf,{children:[i!==3&&g.jsx("div",{className:"max-w-7xl mx-auto",children:g.jsxs("div",{className:q.uploadContainer,"data-step":i,children:[i===1&&!e.get("step")&&!d&&g.jsx(Ig,{files:b,file:m,preview:w,imageType:ce,onFileChange:Un,onRemoveImage:ia,onAddImage:ra,onImageTypeChange:Jr,onChangeFile:er}),i===1&&e.get("contribute")==="true"&&!d&&b.length>0&&g.jsx(Ig,{files:b,file:m,preview:w,imageType:ce,onFileChange:Un,onRemoveImage:ia,onAddImage:ra,onImageTypeChange:Jr,onChangeFile:er}),s&&g.jsxs("div",{className:q.loadingContainer,children:[g.jsx(Gl,{className:"text-ifrcRed"}),g.jsx("p",{className:q.loadingText,children:"Generating..."})]}),d&&g.jsxs("div",{className:q.loadingContainer,children:[g.jsx(Gl,{className:"text-ifrcRed"}),g.jsx("p",{className:q.loadingText,children:"Loading contribution..."})]}),(i===1&&!s&&!d||i===1&&e.get("contribute")==="true"&&!s&&!d&&b.length>0)&&g.jsx("div",{className:q.generateButtonContainer,children:Gt?g.jsx(He,{name:"generate-from-url",onClick:nr,children:"Generate Caption"}):g.jsx(He,{name:"generate",disabled:b.length===0,onClick:nr,children:"Generate"})}),i==="2a"&&g.jsxs("div",{className:q.step2Layout,children:[g.jsx("div",{className:q.mapColumn,children:g.jsx(Ag,{files:b,imageUrl:Gt,preview:w,onViewFullSize:k=>{Yr(k||null),Kr(!0)}})}),g.jsx("div",{className:q.contentColumn,children:g.jsxs("div",{className:q.metadataSectionCard,children:[g.jsx(Wj,{files:b,imageType:ce,title:fe,source:T,eventType:D,epsg:V,countries:te,centerLon:H,centerLat:ne,amslM:xe,aglM:G,headingDeg:N,yawDeg:oe,pitchDeg:se,rollDeg:J,rtkFix:Y,stdHM:tn,stdVM:lt,metadataArray:ct,sources:gt,types:_t,spatialReferences:bn,imageTypes:En,countriesOptions:ln,onTitleChange:k=>I(k||""),onSourceChange:pr,onEventTypeChange:io,onEpsgChange:Xo,onCountriesChange:oo,onCenterLonChange:ki,onCenterLatChange:ao,onAmslMChange:yu,onAglMChange:wu,onHeadingDegChange:Jo,onYawDegChange:xs,onPitchDegChange:ea,onRollDegChange:Ti,onRtkFixChange:xu,onStdHMChange:ta,onStdVMChange:nt,onImageTypeChange:Jr,updateMetadataForImage:oa}),g.jsxs("div",{className:q.confirmSection,children:[g.jsx(df,{name:"delete",variant:"tertiary",onClick:aa,title:"Delete",ariaLabel:"Delete uploaded image",children:g.jsx(uf,{})}),g.jsx(He,{name:"confirm-metadata",onClick:()=>ji("2b"),children:"Next"})]})]})})]}),i==="2b"&&g.jsxs("div",{className:q.step2bLayout,children:[g.jsxs("div",{className:`${q.topRow} ${Yn?q.ratingHidden:""}`,children:[g.jsx("div",{className:q.imageSection,children:g.jsx(Ag,{files:b,imageUrl:Gt,preview:w,onViewFullSize:k=>{Yr(k||null),Kr(!0)},currentImageIndex:jr,onGoToPrevious:Cs,onGoToNext:na,onGoToImage:Ss,showCarousel:!0})}),!Yn&&g.jsx("div",{className:q.metadataSectionCard,children:g.jsx(Gj,{isPerformanceConfirmed:Yn,scores:Kn,onScoreChange:(k,Me)=>kn(Te=>({...Te,[k]:Me})),onConfirmRatings:()=>zn(!0),onEditRatings:()=>zn(!1)})})]}),g.jsx("div",{className:q.metadataSectionCard,children:g.jsx(Zj,{description:Zr,analysis:Er,recommendedActions:kr,onDescriptionChange:k=>Qr(k||""),onAnalysisChange:k=>Nr(k||""),onRecommendedActionsChange:k=>Fn(k||""),onBack:()=>ji("2a"),onDelete:aa,onSubmit:Su,onEditRatings:()=>zn(!1),isPerformanceConfirmed:Yn})})]})]})}),i===3&&g.jsxs("div",{className:q.successContainer,children:[g.jsx(Zi,{level:2,className:q.successHeading,children:"Saved!"}),g.jsx("p",{className:q.successText,children:e.get("contribute")==="true"?"Your contribution has been successfully saved.":"Your caption has been successfully saved."}),g.jsx("div",{className:q.successButton,children:g.jsx(He,{name:"upload-another",onClick:()=>{sa()},children:"Upload Another"})})]}),g.jsx(Qj,{isOpen:$n,imageUrl:Gt,preview:w,selectedImageData:bi,onClose:()=>{Kr(!1),Yr(null)}}),g.jsx(Kj,{isOpen:hr,onClose:()=>Ei(!1)}),g.jsx(Yj,{isOpen:Tr,onConfirm:so,onCancel:()=>j(!1)}),g.jsx(Xj,{isOpen:R,onConfirm:Mi,onCancel:()=>z(!1)}),g.jsx(Jj,{isOpen:Ne,fallbackInfo:ye,onClose:()=>Pe(!1)}),g.jsx(eP,{isOpen:ve,preprocessingInfo:Fe,onClose:()=>me(!1)}),g.jsx(tP,{isOpen:Tt,preprocessingFile:qe,isPreprocessing:Xn,preprocessingProgress:jn,onConfirm:Li,onCancel:ti}),g.jsx(nP,{isOpen:Ni,unsupportedFile:Bn,onClose:()=>fn(!1)}),g.jsx(rP,{isOpen:Xr,oversizedFile:ot,onClose:()=>Be(!1),onCancel:()=>Be(!1)})]})}const iP="_helpContainer_1wavj_1",oP="_helpSection_1wavj_13",aP="_sectionHeader_1wavj_49",sP="_sectionTitle_1wavj_91",lP="_sectionContent_1wavj_105",uP="_guidelinesList_1wavj_119",cP="_buttonContainer_1wavj_181",dt={helpContainer:iP,helpSection:oP,sectionHeader:aP,sectionTitle:sP,sectionContent:lP,guidelinesList:uP,buttonContainer:cP};function dP(){const e=fs(),{setShowReferenceExamples:n}=qj(),i=()=>{e("/upload")},o=()=>{n(!0),e("/explore")},s=()=>{e("/analytics?view=crisis_maps")};return g.jsx(Gf,{className:"py-10",children:g.jsx("div",{className:dt.helpContainer,children:g.jsxs("div",{className:"space-y-8",children:[g.jsxs("div",{className:dt.helpSection,children:[g.jsx("div",{className:dt.sectionHeader,children:g.jsx(Zi,{level:3,className:dt.sectionTitle,children:"Introduction"})}),g.jsx("div",{className:dt.sectionContent,children:"In collaboration with the IFRC, PromptAid Vision is a tool that generates textual descriptions of crisis maps/crisis drone images utiliing Visual language models. This prototype is for collecting data for the fine-tuning of our own models. We aim to utilize AI tools to support national societies with rapid decision making during emergencies."}),g.jsx("div",{className:dt.buttonContainer,children:g.jsx(He,{name:"upload-now",variant:"secondary",onClick:i,children:"Upload now β"})})]}),g.jsxs("div",{className:dt.helpSection,children:[g.jsx("div",{className:dt.sectionHeader,children:g.jsx(Zi,{level:3,className:dt.sectionTitle,children:"Guidelines"})}),g.jsxs("div",{className:dt.sectionContent,children:["To make the process smoother, please follow the guidelines below:",g.jsxs("ul",{className:dt.guidelinesList,children:[g.jsx("li",{children:"Avoid uploading images that are not crisis maps/crisis drone images."}),g.jsx("li",{children:"Confirm the image details prior to modifying the description."}),g.jsx("li",{children:"Before the modification, please read the description generated and provide a rating via the rating sliders."}),g.jsx("li",{children:'Click the "Submit" button to save the description.'})]})]}),g.jsx("div",{className:dt.buttonContainer,children:g.jsx(He,{name:"see-examples",variant:"secondary",onClick:o,children:"See examples β"})})]}),g.jsxs("div",{className:dt.helpSection,children:[g.jsx("div",{className:dt.sectionHeader,children:g.jsx(Zi,{level:3,className:dt.sectionTitle,children:"VLMs"})}),g.jsx("div",{className:dt.sectionContent,children:"PromptAid Vision uses a variety of Visual Language Models (VLMs). A random VLM is selected for each upload. Therefore feel free to delete and reupload. You can view performance details here:"}),g.jsx("div",{className:dt.buttonContainer,children:g.jsx(He,{name:"view-vlm-details",variant:"secondary",onClick:s,children:"View VLM details β"})})]}),g.jsxs("div",{className:dt.helpSection,children:[g.jsx("div",{className:dt.sectionHeader,children:g.jsx(Zi,{level:3,className:dt.sectionTitle,children:"Dataset"})}),g.jsx("div",{className:dt.sectionContent,children:"All users are able to export the dataset. You could apply filters when exporting, and it have the option to organize based on model fine-tuning formats."}),g.jsx("div",{className:dt.buttonContainer,children:g.jsx(He,{name:"export-dataset",variant:"secondary",onClick:()=>{n(!1),e("/explore"),setTimeout(()=>{const u=document.querySelector('[name="export-dataset"]');u&&u.click()},100)},children:"Export dataset β"})})]}),g.jsxs("div",{className:dt.helpSection,children:[g.jsx("div",{className:dt.sectionHeader,children:g.jsx(Zi,{level:3,className:dt.sectionTitle,children:"Contact us"})}),g.jsx("div",{className:dt.sectionContent,children:"Need help or have questions about PromptAid Vision? Our team is here to support you."}),g.jsx("div",{className:dt.buttonContainer,children:g.jsx(He,{name:"contact-support",variant:"secondary",disabled:!0,children:"Get in touch β"})})]})]})})})}const fP=y.createContext(void 0),hP=({children:e})=>{const[n,i]=y.useState(!1),[o,s]=y.useState(!0),u=async()=>{const v=localStorage.getItem("adminToken");if(!v){i(!1),s(!1);return}try{(await fetch("/api/admin/verify",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${v}`}})).ok?i(!0):(localStorage.removeItem("adminToken"),i(!1))}catch(w){console.error("Error verifying admin token:",w),localStorage.removeItem("adminToken"),i(!1)}finally{s(!1)}},d=async v=>{try{const w=await fetch("/api/admin/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:v})});if(w.ok){const C=await w.json();return localStorage.setItem("adminToken",C.access_token),i(!0),!0}else return!1}catch(w){return console.error("Login error:",w),!1}},f=()=>{localStorage.removeItem("adminToken"),i(!1)};y.useEffect(()=>{u()},[]);const p={isAuthenticated:n,isLoading:o,login:d,logout:f,verifyToken:u};return g.jsx(fP.Provider,{value:p,children:e})},pP=y.lazy(()=>Qn(()=>import("./index-D_a-CF3t.js"),__vite__mapDeps([0,1]))),mP=y.lazy(()=>Qn(()=>import("./index-GUsf-iOM.js"),__vite__mapDeps([2,3,4,5,6]))),gP=y.lazy(()=>Qn(()=>import("./AdminPage-kwx131wq.js"),__vite__mapDeps([7,3,8]))),vP=y.lazy(()=>Qn(()=>import("./index-DvX--7c_.js"),__vite__mapDeps([9,3,4,5,10])));class yP extends y.Component{constructor(n){super(n),this.state={hasError:!1}}static getDerivedStateFromError(){return{hasError:!0}}componentDidCatch(n,i){console.error("Error caught by boundary:",n,i)}render(){return this.state.hasError?g.jsxs("div",{style:{padding:"20px",textAlign:"center"},children:[g.jsx("h2",{children:"Something went wrong"}),g.jsx("p",{children:"Please refresh the page to try again."}),g.jsx("button",{onClick:()=>window.location.reload(),children:"Refresh Page"})]}):this.props.children}}const yi=e=>{const n=e();return n.catch(()=>{}),n},wP=()=>{"requestIdleCallback"in window?requestIdleCallback(()=>{yi(()=>Qn(()=>import("./index-D_a-CF3t.js"),__vite__mapDeps([0,1]))),yi(()=>Qn(()=>import("./index-GUsf-iOM.js"),__vite__mapDeps([2,3,4,5,6]))),yi(()=>Qn(()=>import("./AdminPage-kwx131wq.js"),__vite__mapDeps([7,3,8]))),yi(()=>Qn(()=>import("./index-DvX--7c_.js"),__vite__mapDeps([9,3,4,5,10])))}):setTimeout(()=>{yi(()=>Qn(()=>import("./index-D_a-CF3t.js"),__vite__mapDeps([0,1]))),yi(()=>Qn(()=>import("./index-GUsf-iOM.js"),__vite__mapDeps([2,3,4,5,6]))),yi(()=>Qn(()=>import("./AdminPage-kwx131wq.js"),__vite__mapDeps([7,3,8]))),yi(()=>Qn(()=>import("./index-DvX--7c_.js"),__vite__mapDeps([9,3,4,5,10])))},1e3)},xP=vx([{element:g.jsx(LT,{}),children:[{path:"/",element:g.jsx(Fg,{})},{path:"/upload",element:g.jsx(Fg,{})},{path:"/analytics",element:g.jsx(y.Suspense,{fallback:g.jsx("div",{children:"Loading Analytics..."}),children:g.jsx(pP,{})})},{path:"/explore",element:g.jsx(y.Suspense,{fallback:g.jsx("div",{children:"Loading Explore..."}),children:g.jsx(mP,{})})},{path:"/help",element:g.jsx(dP,{})},{path:"/admin",element:g.jsx(y.Suspense,{fallback:g.jsx("div",{children:"Loading Admin..."}),children:g.jsx(gP,{})})},{path:"/map/:mapId",element:g.jsx(y.Suspense,{fallback:g.jsx("div",{children:"Loading Map Details..."}),children:g.jsx(vP,{})})}]}],{basename:"/"});function CP(){const[e,n]=y.useState([]);y.useEffect(()=>{wP()},[]);const i=y.useCallback(f=>{n(p=>Bx([...p,f],v=>v.name)??p)},[n]),o=y.useCallback(f=>{n(p=>{const v=p.findIndex(C=>C.name===f);if(v===-1)return p;const w=[...p];return w.splice(v,1),w})},[n]),s=y.useCallback((f,p)=>{n(v=>{const w=v.findIndex(m=>m.name===f);if(w===-1)return v;const C=[...v];return C[w]={...C[w],...p},C})},[n]),u=y.useMemo(()=>({alerts:e,addAlert:i,removeAlert:o,updateAlert:s}),[e,i,o,s]),d=y.useMemo(()=>({languageNamespaceStatus:{},setLanguageNamespaceStatus:()=>{},currentLanguage:"en",setCurrentLanguage:()=>{},strings:{},setStrings:()=>{},registerNamespace:()=>{}}),[]);return g.jsx(yP,{children:g.jsx(Fx.Provider,{value:u,children:g.jsx(i0.Provider,{value:d,children:g.jsx(hP,{children:g.jsx(Vj,{children:g.jsx(Nx,{router:xP})})})})})})}function SP(){return g.jsx(CP,{})}console.log("React version at runtime:",y.version,"createContext exists?",!!y.createContext);V1.createRoot(document.getElementById("root")).render(g.jsx(y.StrictMode,{children:g.jsx(SP,{})}));export{bC as A,Ko as B,EP as C,qj as D,TP as E,uf as F,Qn as G,Zi as H,qi as I,bP as J,Qj as K,bT as L,jC as M,Gf as N,kt as O,TC as P,PP as Q,u0 as R,c0 as S,Mg as T,jP as U,fP as V,_P as W,zg as X,Gl as _,$e as a,Mt as b,DP as c,OP as d,NP as e,SC as f,s0 as g,LP as h,MP as i,g as j,dr as k,qx as l,FE as m,He as n,Oe as o,Zx as p,Qa as q,y as r,l0 as s,i0 as t,Dx as u,PC as v,MC as w,fs as x,kP as y,cr as z};
|
|
|
1 |
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-CU7P_Hff.js","assets/index-B1uKTNcW.css","assets/index-5HpHyjh5.js","assets/useAdmin-B4TrJLwR.js","assets/ExportModal-DJU5iFtN.js","assets/ExportModal-BoB3JpqO.css","assets/index-C85X4vtS.css","assets/AdminPage-BeakVMzz.js","assets/AdminPage-VgSjQ50W.css","assets/index-DrfgCGTV.js","assets/index-tDgjKyWF.css"])))=>i.map(i=>d[i]);
|
2 |
function $g(e,n){for(var i=0;i<n.length;i++){const o=n[i];if(typeof o!="string"&&!Array.isArray(o)){for(const s in o)if(s!=="default"&&!(s in e)){const u=Object.getOwnPropertyDescriptor(o,s);u&&Object.defineProperty(e,s,u.get?u:{enumerable:!0,get:()=>o[s]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}(function(){const n=document.createElement("link").relList;if(n&&n.supports&&n.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))o(s);new MutationObserver(s=>{for(const u of s)if(u.type==="childList")for(const d of u.addedNodes)d.tagName==="LINK"&&d.rel==="modulepreload"&&o(d)}).observe(document,{childList:!0,subtree:!0});function i(s){const u={};return s.integrity&&(u.integrity=s.integrity),s.referrerPolicy&&(u.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?u.credentials="include":s.crossOrigin==="anonymous"?u.credentials="omit":u.credentials="same-origin",u}function o(s){if(s.ep)return;s.ep=!0;const u=i(s);fetch(s.href,u)}})();var _P=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function zg(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Zc={exports:{}},Oa={},Qc={exports:{}},Ze={};/**
|
3 |
* @license React
|
4 |
* react.production.min.js
|
|
|
158 |
|
159 |
Analysis: ${Er}
|
160 |
|
161 |
+
Recommended Actions: ${kr}`,Te={title:fe,edited:Me,accuracy:Kn.accuracy,context:Kn.context,usability:Kn.usability};console.log("Updating caption:",Te);const je=await fetch(`/api/images/${Ft}/caption`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(Te)}),ge=await tr(je);if(!je.ok)throw new Error(ge.error||"Caption update failed");cn(null),bt([]),ji(3)}catch(k){Pr(k,"Submit")}}async function aa(){if(console.log("handleDelete called with uploadedImageId:",Ft),!Ft){alert("No image to delete. Please try refreshing the page.");return}j(!0)}async function so(){try{console.log("Deleting image with ID:",Ft);const k=await fetch(`/api/images/${Ft}`,{method:"DELETE"});if(!k.ok){const Me=await tr(k);throw new Error(Me.error||`Delete failed with status ${k.status}`)}j(!1),sa()}catch(k){Pr(k,"Delete")}}const sa=()=>{zn(!1),o(1),x(null),_([]),C(null),cn(null),bt([]),Et(null),I(""),M(""),$(""),Z(""),de([]),W(""),he(""),be(""),le(""),U(""),Se(""),re(""),Q(""),tt(!1),Wt(""),wt(""),kn({accuracy:50,context:50,usability:50}),dn(""),Qr(""),Nr(""),Fn(""),ht([]),Pe(!1),Ce(null),me(!1),Ve(null),Ke(!1),Je(null),Tn(!1),ze(""),fn(!1),Pn(null),Be(!1),jt(null),n("/upload",{replace:!0})},lo=y.useCallback(k=>{k==="/upload"||k==="/"||(v.current?(ue(k),z(!0)):n(k))},[n]);async function Mi(){if(K&&v.current)try{await fetch(`/api/images/${v.current}`,{method:"DELETE"}),z(!1),ue(null),n(K)}catch(k){console.error("Failed to delete image before navigation:",k),z(!1),ue(null),n(K)}}const Li=async()=>{if(qe){Tn(!0),ze("Starting file conversion...");try{const k=new FormData;k.append("file",qe),k.append("preprocess_only","true"),ze("Converting file format...");const Me=await fetch("/api/images/preprocess",{method:"POST",body:k});if(!Me.ok)throw new Error("Preprocessing failed");const Te=await Me.json();ze("Finalizing conversion...");const je=atob(Te.processed_content),ge=new Uint8Array(je.length);for(let We=0;We<je.length;We++)ge[We]=je.charCodeAt(We);const Re=new File([ge],Te.processed_filename,{type:Te.processed_mime_type}),rt=URL.createObjectURL(Re);b.length===0?(x(Re),_([Re])):_(We=>[...We,Re]),C(rt),ze("Conversion complete!"),setTimeout(()=>{Ke(!1),Je(null),Tn(!1),ze("")},1e3)}catch(k){console.error("Preprocessing error:",k),ze("Conversion failed. Please try again."),setTimeout(()=>{Ke(!1),Je(null),Tn(!1),ze("")},2e3)}}},ti=()=>{Ke(!1),Je(null),Tn(!1),ze("")},uo=async k=>{f(!0);try{const Me=k.map(async Re=>{const rt=await fetch(`/api/images/${Re}`);if(!rt.ok)throw new Error(`Failed to fetch image ${Re}`);const We=await rt.json(),$t=await fetch(`/api/images/${Re}/file`);if(!$t.ok)throw new Error(`Failed to fetch image file ${Re}`);const it=await $t.blob(),Zt=We.file_key.split("/").pop()||`contributed_${Re}.png`;return{file:new File([it],Zt,{type:it.type}),imageData:We}}),Te=await Promise.all(Me),je=Te.map(Re=>Re.file),ge=Te[0]?.imageData;_(je),bt(k),k.length===1&&cn(k[0]),je.length>=1&&x(je[0]),ge?.image_type&&O(ge.image_type)}catch(Me){console.error("Failed to fetch contributed images:",Me),alert(`Failed to load contributed images: ${Me instanceof Error?Me.message:"Unknown error"}`)}finally{f(!1)}};return y.useEffect(()=>{Promise.all([fetch("/api/sources").then(k=>k.json()),fetch("/api/types").then(k=>k.json()),fetch("/api/spatial-references").then(k=>k.json()),fetch("/api/image-types").then(k=>k.json()),fetch("/api/countries").then(k=>k.json()),fetch("/api/models").then(k=>k.json())]).then(([k,Me,Te,je,ge,Re])=>{!localStorage.getItem(Il)&&Re?.length&&localStorage.setItem(Il,Re[0].m_code),xt(k),nn(Me),sn(Te),Gr(je),un(ge),k.length>0&&M(k[0].s_code),$("OTHER"),Z("OTHER"),je.length>0&&!e.get("imageType")&&!ce&&O(je[0].image_type)})},[e,ce]),y.useEffect(()=>(window.confirmNavigationIfNeeded=k=>{lo(k)},()=>{delete window.confirmNavigationIfNeeded}),[lo]),y.useEffect(()=>{const k=je=>{if(v.current){const ge="You have an uploaded image that will be deleted if you leave this page. Are you sure you want to leave?";return je.preventDefault(),je.returnValue=ge,ge}},Me=()=>{v.current&&fetch(`/api/images/${v.current}`,{method:"DELETE"}).catch(console.error)},Te=je=>{const ge=je.target,Re=ge.closest("a[href]")||ge.closest("[data-navigate]");if(Re&&v.current){const rt=Re.getAttribute("href")||Re.getAttribute("data-navigate");rt&&rt!=="#"&&!rt.startsWith("javascript:")&&!rt.startsWith("mailto:")&&(je.preventDefault(),je.stopPropagation(),lo(rt))}};return window.addEventListener("beforeunload",k),document.addEventListener("click",Te,!0),()=>{window.removeEventListener("beforeunload",k),document.removeEventListener("click",Te,!0),Me()}},[lo]),y.useEffect(()=>{if(!m){C(null);return}const k=URL.createObjectURL(m);return C(k),()=>URL.revokeObjectURL(k)},[m]),y.useEffect(()=>{const k=e.get("contribute"),Me=e.get("imageIds");if(k==="true"&&Me){const Te=Me.split(",").filter(je=>je.trim());Te.length>0&&uo(Te)}},[e]),y.useEffect(()=>{i==="2b"&&Ge(0)},[i]),g.jsxs(Gf,{children:[i!==3&&g.jsx("div",{className:"max-w-7xl mx-auto",children:g.jsxs("div",{className:q.uploadContainer,"data-step":i,children:[i===1&&!e.get("step")&&!d&&g.jsx(Ig,{files:b,file:m,preview:w,imageType:ce,onFileChange:Un,onRemoveImage:ia,onAddImage:ra,onImageTypeChange:Jr,onChangeFile:er}),i===1&&e.get("contribute")==="true"&&!d&&b.length>0&&g.jsx(Ig,{files:b,file:m,preview:w,imageType:ce,onFileChange:Un,onRemoveImage:ia,onAddImage:ra,onImageTypeChange:Jr,onChangeFile:er}),s&&g.jsxs("div",{className:q.loadingContainer,children:[g.jsx(Gl,{className:"text-ifrcRed"}),g.jsx("p",{className:q.loadingText,children:"Generating..."})]}),d&&g.jsxs("div",{className:q.loadingContainer,children:[g.jsx(Gl,{className:"text-ifrcRed"}),g.jsx("p",{className:q.loadingText,children:"Loading contribution..."})]}),(i===1&&!s&&!d||i===1&&e.get("contribute")==="true"&&!s&&!d&&b.length>0)&&g.jsx("div",{className:q.generateButtonContainer,children:Gt?g.jsx(He,{name:"generate-from-url",onClick:nr,children:"Generate Caption"}):g.jsx(He,{name:"generate",disabled:b.length===0,onClick:nr,children:"Generate"})}),i==="2a"&&g.jsxs("div",{className:q.step2Layout,children:[g.jsx("div",{className:q.mapColumn,children:g.jsx(Ag,{files:b,imageUrl:Gt,preview:w,onViewFullSize:k=>{Yr(k||null),Kr(!0)}})}),g.jsx("div",{className:q.contentColumn,children:g.jsxs("div",{className:q.metadataSectionCard,children:[g.jsx(Wj,{files:b,imageType:ce,title:fe,source:T,eventType:D,epsg:V,countries:te,centerLon:H,centerLat:ne,amslM:xe,aglM:G,headingDeg:N,yawDeg:oe,pitchDeg:se,rollDeg:J,rtkFix:Y,stdHM:tn,stdVM:lt,metadataArray:ct,sources:gt,types:_t,spatialReferences:bn,imageTypes:En,countriesOptions:ln,onTitleChange:k=>I(k||""),onSourceChange:pr,onEventTypeChange:io,onEpsgChange:Xo,onCountriesChange:oo,onCenterLonChange:ki,onCenterLatChange:ao,onAmslMChange:yu,onAglMChange:wu,onHeadingDegChange:Jo,onYawDegChange:xs,onPitchDegChange:ea,onRollDegChange:Ti,onRtkFixChange:xu,onStdHMChange:ta,onStdVMChange:nt,onImageTypeChange:Jr,updateMetadataForImage:oa}),g.jsxs("div",{className:q.confirmSection,children:[g.jsx(df,{name:"delete",variant:"tertiary",onClick:aa,title:"Delete",ariaLabel:"Delete uploaded image",children:g.jsx(uf,{})}),g.jsx(He,{name:"confirm-metadata",onClick:()=>ji("2b"),children:"Next"})]})]})})]}),i==="2b"&&g.jsxs("div",{className:q.step2bLayout,children:[g.jsxs("div",{className:`${q.topRow} ${Yn?q.ratingHidden:""}`,children:[g.jsx("div",{className:q.imageSection,children:g.jsx(Ag,{files:b,imageUrl:Gt,preview:w,onViewFullSize:k=>{Yr(k||null),Kr(!0)},currentImageIndex:jr,onGoToPrevious:Cs,onGoToNext:na,onGoToImage:Ss,showCarousel:!0})}),!Yn&&g.jsx("div",{className:q.metadataSectionCard,children:g.jsx(Gj,{isPerformanceConfirmed:Yn,scores:Kn,onScoreChange:(k,Me)=>kn(Te=>({...Te,[k]:Me})),onConfirmRatings:()=>zn(!0),onEditRatings:()=>zn(!1)})})]}),g.jsx("div",{className:q.metadataSectionCard,children:g.jsx(Zj,{description:Zr,analysis:Er,recommendedActions:kr,onDescriptionChange:k=>Qr(k||""),onAnalysisChange:k=>Nr(k||""),onRecommendedActionsChange:k=>Fn(k||""),onBack:()=>ji("2a"),onDelete:aa,onSubmit:Su,onEditRatings:()=>zn(!1),isPerformanceConfirmed:Yn})})]})]})}),i===3&&g.jsxs("div",{className:q.successContainer,children:[g.jsx(Zi,{level:2,className:q.successHeading,children:"Saved!"}),g.jsx("p",{className:q.successText,children:e.get("contribute")==="true"?"Your contribution has been successfully saved.":"Your caption has been successfully saved."}),g.jsx("div",{className:q.successButton,children:g.jsx(He,{name:"upload-another",onClick:()=>{sa()},children:"Upload Another"})})]}),g.jsx(Qj,{isOpen:$n,imageUrl:Gt,preview:w,selectedImageData:bi,onClose:()=>{Kr(!1),Yr(null)}}),g.jsx(Kj,{isOpen:hr,onClose:()=>Ei(!1)}),g.jsx(Yj,{isOpen:Tr,onConfirm:so,onCancel:()=>j(!1)}),g.jsx(Xj,{isOpen:R,onConfirm:Mi,onCancel:()=>z(!1)}),g.jsx(Jj,{isOpen:Ne,fallbackInfo:ye,onClose:()=>Pe(!1)}),g.jsx(eP,{isOpen:ve,preprocessingInfo:Fe,onClose:()=>me(!1)}),g.jsx(tP,{isOpen:Tt,preprocessingFile:qe,isPreprocessing:Xn,preprocessingProgress:jn,onConfirm:Li,onCancel:ti}),g.jsx(nP,{isOpen:Ni,unsupportedFile:Bn,onClose:()=>fn(!1)}),g.jsx(rP,{isOpen:Xr,oversizedFile:ot,onClose:()=>Be(!1),onCancel:()=>Be(!1)})]})}const iP="_helpContainer_1wavj_1",oP="_helpSection_1wavj_13",aP="_sectionHeader_1wavj_49",sP="_sectionTitle_1wavj_91",lP="_sectionContent_1wavj_105",uP="_guidelinesList_1wavj_119",cP="_buttonContainer_1wavj_181",dt={helpContainer:iP,helpSection:oP,sectionHeader:aP,sectionTitle:sP,sectionContent:lP,guidelinesList:uP,buttonContainer:cP};function dP(){const e=fs(),{setShowReferenceExamples:n}=qj(),i=()=>{e("/upload")},o=()=>{n(!0),e("/explore")},s=()=>{e("/analytics?view=crisis_maps")};return g.jsx(Gf,{className:"py-10",children:g.jsx("div",{className:dt.helpContainer,children:g.jsxs("div",{className:"space-y-8",children:[g.jsxs("div",{className:dt.helpSection,children:[g.jsx("div",{className:dt.sectionHeader,children:g.jsx(Zi,{level:3,className:dt.sectionTitle,children:"Introduction"})}),g.jsx("div",{className:dt.sectionContent,children:"In collaboration with the IFRC, PromptAid Vision is a tool that generates textual descriptions of crisis maps/crisis drone images utiliing Visual language models. This prototype is for collecting data for the fine-tuning of our own models. We aim to utilize AI tools to support national societies with rapid decision making during emergencies."}),g.jsx("div",{className:dt.buttonContainer,children:g.jsx(He,{name:"upload-now",variant:"secondary",onClick:i,children:"Upload now β"})})]}),g.jsxs("div",{className:dt.helpSection,children:[g.jsx("div",{className:dt.sectionHeader,children:g.jsx(Zi,{level:3,className:dt.sectionTitle,children:"Guidelines"})}),g.jsxs("div",{className:dt.sectionContent,children:["To make the process smoother, please follow the guidelines below:",g.jsxs("ul",{className:dt.guidelinesList,children:[g.jsx("li",{children:"Avoid uploading images that are not crisis maps/crisis drone images."}),g.jsx("li",{children:"Confirm the image details prior to modifying the description."}),g.jsx("li",{children:"Before the modification, please read the description generated and provide a rating via the rating sliders."}),g.jsx("li",{children:'Click the "Submit" button to save the description.'})]})]}),g.jsx("div",{className:dt.buttonContainer,children:g.jsx(He,{name:"see-examples",variant:"secondary",onClick:o,children:"See examples β"})})]}),g.jsxs("div",{className:dt.helpSection,children:[g.jsx("div",{className:dt.sectionHeader,children:g.jsx(Zi,{level:3,className:dt.sectionTitle,children:"VLMs"})}),g.jsx("div",{className:dt.sectionContent,children:"PromptAid Vision uses a variety of Visual Language Models (VLMs). A random VLM is selected for each upload. Therefore feel free to delete and reupload. You can view performance details here:"}),g.jsx("div",{className:dt.buttonContainer,children:g.jsx(He,{name:"view-vlm-details",variant:"secondary",onClick:s,children:"View VLM details β"})})]}),g.jsxs("div",{className:dt.helpSection,children:[g.jsx("div",{className:dt.sectionHeader,children:g.jsx(Zi,{level:3,className:dt.sectionTitle,children:"Dataset"})}),g.jsx("div",{className:dt.sectionContent,children:"All users are able to export the dataset. You could apply filters when exporting, and it have the option to organize based on model fine-tuning formats."}),g.jsx("div",{className:dt.buttonContainer,children:g.jsx(He,{name:"export-dataset",variant:"secondary",onClick:()=>{n(!1),e("/explore"),setTimeout(()=>{const u=document.querySelector('[name="export-dataset"]');u&&u.click()},100)},children:"Export dataset β"})})]}),g.jsxs("div",{className:dt.helpSection,children:[g.jsx("div",{className:dt.sectionHeader,children:g.jsx(Zi,{level:3,className:dt.sectionTitle,children:"Contact us"})}),g.jsx("div",{className:dt.sectionContent,children:"Need help or have questions about PromptAid Vision? Our team is here to support you."}),g.jsx("div",{className:dt.buttonContainer,children:g.jsx(He,{name:"contact-support",variant:"secondary",disabled:!0,children:"Get in touch β"})})]})]})})})}const fP=y.createContext(void 0),hP=({children:e})=>{const[n,i]=y.useState(!1),[o,s]=y.useState(!0),u=async()=>{const v=localStorage.getItem("adminToken");if(!v){i(!1),s(!1);return}try{(await fetch("/api/admin/verify",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${v}`}})).ok?i(!0):(localStorage.removeItem("adminToken"),i(!1))}catch(w){console.error("Error verifying admin token:",w),localStorage.removeItem("adminToken"),i(!1)}finally{s(!1)}},d=async v=>{try{const w=await fetch("/api/admin/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:v})});if(w.ok){const C=await w.json();return localStorage.setItem("adminToken",C.access_token),i(!0),!0}else return!1}catch(w){return console.error("Login error:",w),!1}},f=()=>{localStorage.removeItem("adminToken"),i(!1)};y.useEffect(()=>{u()},[]);const p={isAuthenticated:n,isLoading:o,login:d,logout:f,verifyToken:u};return g.jsx(fP.Provider,{value:p,children:e})},pP=y.lazy(()=>Qn(()=>import("./index-CU7P_Hff.js"),__vite__mapDeps([0,1]))),mP=y.lazy(()=>Qn(()=>import("./index-5HpHyjh5.js"),__vite__mapDeps([2,3,4,5,6]))),gP=y.lazy(()=>Qn(()=>import("./AdminPage-BeakVMzz.js"),__vite__mapDeps([7,3,8]))),vP=y.lazy(()=>Qn(()=>import("./index-DrfgCGTV.js"),__vite__mapDeps([9,3,4,5,10])));class yP extends y.Component{constructor(n){super(n),this.state={hasError:!1}}static getDerivedStateFromError(){return{hasError:!0}}componentDidCatch(n,i){console.error("Error caught by boundary:",n,i)}render(){return this.state.hasError?g.jsxs("div",{style:{padding:"20px",textAlign:"center"},children:[g.jsx("h2",{children:"Something went wrong"}),g.jsx("p",{children:"Please refresh the page to try again."}),g.jsx("button",{onClick:()=>window.location.reload(),children:"Refresh Page"})]}):this.props.children}}const yi=e=>{const n=e();return n.catch(()=>{}),n},wP=()=>{"requestIdleCallback"in window?requestIdleCallback(()=>{yi(()=>Qn(()=>import("./index-CU7P_Hff.js"),__vite__mapDeps([0,1]))),yi(()=>Qn(()=>import("./index-5HpHyjh5.js"),__vite__mapDeps([2,3,4,5,6]))),yi(()=>Qn(()=>import("./AdminPage-BeakVMzz.js"),__vite__mapDeps([7,3,8]))),yi(()=>Qn(()=>import("./index-DrfgCGTV.js"),__vite__mapDeps([9,3,4,5,10])))}):setTimeout(()=>{yi(()=>Qn(()=>import("./index-CU7P_Hff.js"),__vite__mapDeps([0,1]))),yi(()=>Qn(()=>import("./index-5HpHyjh5.js"),__vite__mapDeps([2,3,4,5,6]))),yi(()=>Qn(()=>import("./AdminPage-BeakVMzz.js"),__vite__mapDeps([7,3,8]))),yi(()=>Qn(()=>import("./index-DrfgCGTV.js"),__vite__mapDeps([9,3,4,5,10])))},1e3)},xP=vx([{element:g.jsx(LT,{}),children:[{path:"/",element:g.jsx(Fg,{})},{path:"/upload",element:g.jsx(Fg,{})},{path:"/analytics",element:g.jsx(y.Suspense,{fallback:g.jsx("div",{children:"Loading Analytics..."}),children:g.jsx(pP,{})})},{path:"/explore",element:g.jsx(y.Suspense,{fallback:g.jsx("div",{children:"Loading Explore..."}),children:g.jsx(mP,{})})},{path:"/help",element:g.jsx(dP,{})},{path:"/admin",element:g.jsx(y.Suspense,{fallback:g.jsx("div",{children:"Loading Admin..."}),children:g.jsx(gP,{})})},{path:"/map/:mapId",element:g.jsx(y.Suspense,{fallback:g.jsx("div",{children:"Loading Map Details..."}),children:g.jsx(vP,{})})}]}],{basename:"/"});function CP(){const[e,n]=y.useState([]);y.useEffect(()=>{wP()},[]);const i=y.useCallback(f=>{n(p=>Bx([...p,f],v=>v.name)??p)},[n]),o=y.useCallback(f=>{n(p=>{const v=p.findIndex(C=>C.name===f);if(v===-1)return p;const w=[...p];return w.splice(v,1),w})},[n]),s=y.useCallback((f,p)=>{n(v=>{const w=v.findIndex(m=>m.name===f);if(w===-1)return v;const C=[...v];return C[w]={...C[w],...p},C})},[n]),u=y.useMemo(()=>({alerts:e,addAlert:i,removeAlert:o,updateAlert:s}),[e,i,o,s]),d=y.useMemo(()=>({languageNamespaceStatus:{},setLanguageNamespaceStatus:()=>{},currentLanguage:"en",setCurrentLanguage:()=>{},strings:{},setStrings:()=>{},registerNamespace:()=>{}}),[]);return g.jsx(yP,{children:g.jsx(Fx.Provider,{value:u,children:g.jsx(i0.Provider,{value:d,children:g.jsx(hP,{children:g.jsx(Vj,{children:g.jsx(Nx,{router:xP})})})})})})}function SP(){return g.jsx(CP,{})}console.log("React version at runtime:",y.version,"createContext exists?",!!y.createContext);V1.createRoot(document.getElementById("root")).render(g.jsx(y.StrictMode,{children:g.jsx(SP,{})}));export{bC as A,Ko as B,EP as C,qj as D,TP as E,uf as F,Qn as G,Zi as H,qi as I,bP as J,Qj as K,bT as L,jC as M,Gf as N,kt as O,TC as P,PP as Q,u0 as R,c0 as S,Mg as T,jP as U,fP as V,_P as W,zg as X,Gl as _,$e as a,Mt as b,DP as c,OP as d,NP as e,SC as f,s0 as g,LP as h,MP as i,g as j,dr as k,qx as l,FE as m,He as n,Oe as o,Zx as p,Qa as q,y as r,l0 as s,i0 as t,Dx as u,PC as v,MC as w,fs as x,kP as y,cr as z};
|
py_backend/static/assets/{index-D_a-CF3t.js β index-CU7P_Hff.js}
RENAMED
@@ -1 +1 @@
|
|
1 |
-
import{r as s,y as nt,t as ht,a as q,c as gt,j as e,o as N,b as se,R as st,z,g as rt,d as ft,m as vt,e as pt,n as Z,A as xt,f as _t,h as Ct,i as yt,k as he,l as bt,p as ye,q as jt,s as Nt,E as wt,C as St,U as Mt,Q as It,u as Dt,N as je,_ as Et,L as Tt}from"./index-LmdVBMha.js";const kt=({title:m,titleId:a,...h})=>s.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg","aria-hidden":"true",viewBox:"0 0 24 24",fill:"currentColor",width:"1em",height:"1em","aria-labelledby":a},h),m?s.createElement("title",{id:a},m):null,s.createElement("g",{clipPath:"url(#arrow-drop-down-line_svg__a)"},s.createElement("path",{d:"m12 15-4.243-4.243 1.415-1.414L12 12.172l2.828-2.83 1.415 1.415L12 15Z"})),s.createElement("defs",null,s.createElement("clipPath",{id:"arrow-drop-down-line_svg__a"},s.createElement("path",{d:"M0 0h24v24H0z"})))),Lt=({title:m,titleId:a,...h})=>s.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg","aria-hidden":"true",viewBox:"0 0 24 24",fill:"currentColor",width:"1em",height:"1em","aria-labelledby":a},h),m?s.createElement("title",{id:a},m):null,s.createElement("g",{clipPath:"url(#arrow-drop-up-line_svg__a)"},s.createElement("path",{d:"m12 11.828-2.828 2.829-1.415-1.414L12 9l4.243 4.243-1.415 1.414L12 11.828Z"})),s.createElement("defs",null,s.createElement("clipPath",{id:"arrow-drop-up-line_svg__a"},s.createElement("path",{d:"M0 0h24v24H0z"})))),Pt=({title:m,titleId:a,...h})=>s.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg","aria-hidden":"true",viewBox:"0 0 24 24",fill:"currentColor",width:"1em",height:"1em","aria-labelledby":a},h),m?s.createElement("title",{id:a},m):null,s.createElement("g",{clipPath:"url(#information-line_svg__a)"},s.createElement("path",{d:"M12 22C6.477 22 2 17.523 2 12S6.477 2 12 2s10 4.477 10 10-4.477 10-10 10Zm0-2a8 8 0 1 0 0-16.001A8 8 0 0 0 12 20ZM11 7h2v2h-2V7Zm0 4h2v6h-2v-6Z"})),s.createElement("defs",null,s.createElement("clipPath",{id:"information-line_svg__a"},s.createElement("path",{d:"M0 0h24v24H0z"})))),Rt=({title:m,titleId:a,...h})=>s.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg","aria-hidden":"true",viewBox:"0 0 24 24",fill:"currentColor",width:"1em",height:"1em","aria-labelledby":a},h),m?s.createElement("title",{id:a},m):null,s.createElement("path",{fillRule:"evenodd",d:"m15.063 12 .937.938-4 4-4-4L8.938 12 12 15.063 15.063 12Z",clipRule:"evenodd"}),s.createElement("mask",{id:"table-sorting-line_svg__a",width:8,height:5,x:8,y:12,maskUnits:"userSpaceOnUse",style:{maskType:"luminance"}},s.createElement("path",{fillRule:"evenodd",d:"m15.063 12 .937.938-4 4-4-4L8.938 12 12 15.063 15.063 12Z",clipRule:"evenodd"})),s.createElement("g",{mask:"url(#table-sorting-line_svg__a)"},s.createElement("path",{d:"M-24-22h72v72h-72z"})),s.createElement("path",{fillRule:"evenodd",d:"M8.938 11 8 10.062l4-4 4 4-.938.938L12 7.937 8.937 11Z",clipRule:"evenodd"}),s.createElement("mask",{id:"table-sorting-line_svg__b",width:8,height:5,x:8,y:6,maskUnits:"userSpaceOnUse",style:{maskType:"luminance"}},s.createElement("path",{fillRule:"evenodd",d:"M8.938 11 8 10.062l4-4 4 4-.938.938L12 7.937 8.937 11Z",clipRule:"evenodd"})),s.createElement("g",{mask:"url(#table-sorting-line_svg__b)"},s.createElement("path",{d:"M48 45h-72v-72h72z"}))),$t="_number-output_1blvi_1",Bt={numberOutput:$t};function we(m){const{className:a,invalidText:h=nt,separatorHidden:r,compact:f,currency:g,value:b,tooltip:_,unit:y,prefix:x,suffix:w,maximumFractionDigits:C=1}=m,{currentLanguage:j}=s.useContext(ht),v=s.useMemo(()=>{if(q(b))return h;const S=gt(b,{currency:g,compact:f,separatorHidden:r,maximumFractionDigits:C,unit:y,language:j});return e.jsxs(e.Fragment,{children:[x,S,w]})},[h,b,f,r,g,y,C,x,j,w]);return e.jsx("div",{className:N(Bt.numberOutput,a),title:se(_)?String(_):void 0,children:v})}const At="_tooltip-dummy_rbf3f_1",Ft="_tooltip-content_rbf3f_7",Ot="_pointer_rbf3f_14",Ne={tooltipDummy:At,tooltipContent:Ft,pointer:Ot};function Ht(m){const{className:a,title:h,description:r,preferredWidth:f}=m,[g,b]=s.useState(!1),[_,y]=s.useState(!1),x=s.useRef(),w=s.useRef(null);return s.useEffect(()=>{const C=()=>{y(!0)},j=()=>{y(!1)};if(q(w.current))return;const{current:{parentNode:v}}=w;if(!q(v))return x.current=v,v.addEventListener("mouseover",C),v.addEventListener("mouseout",j),b(!0),()=>{v.removeEventListener("mouseover",C),v.removeEventListener("mouseout",j)}},[]),e.jsxs(e.Fragment,{children:[!g&&e.jsx("div",{className:Ne.tooltipDummy,ref:w}),_&&e.jsx(st,{className:N(Ne.tooltipContent,a),parentRef:x,pointerClassName:Ne.pointer,preferredWidth:f,children:e.jsx(z,{heading:h,withInternalPadding:!0,contentViewType:"vertical",children:r})})]})}function $(m){return m.id}const Vt="common",zt={booleanYesLabel:"Yes",booleanNoLabel:"No"},Ut={namespace:Vt,strings:zt},Wt="_boolean-output_kg1uq_1",Qt={booleanOutput:Wt};function Zt(m){const{className:a,invalidText:h,value:r}=m,f=rt(Ut);let g;return r===!0?g=f.booleanYesLabel:r===!1?g=f.booleanNoLabel:g=h,e.jsx("div",{className:N(Qt.booleanOutput,a),children:g})}const qt="_date-output_4jzjo_1",Gt={dateOutput:qt};function Yt(m){const{value:a,format:h,className:r,invalidText:f}=m,g=s.useMemo(()=>ft(a,h),[a,h]);return e.jsx("div",{className:N(Gt.dateOutput,r),children:g??f})}const Kt="_dropdown-menu_16hml_1",Xt="_icons_16hml_4",Jt="_content_16hml_5",ea="_actions_16hml_6",ta="_dropdown-icon_16hml_10",aa="_dropdown-content_16hml_16",le={dropdownMenu:Kt,icons:Xt,content:Jt,actions:ea,dropdownIcon:ta,dropdownContent:aa};function na(m){const a=s.useRef(null),{className:h,popupClassName:r,children:f,label:g,activeClassName:b,icons:_,variant:y="secondary",actions:x,withoutDropdownIcon:w,componentRef:C,elementRef:j=a,persistent:v,preferredPopupWidth:S}=m,p=s.useRef(null),[k,I]=s.useState(!1);s.useEffect(()=>{C&&(C.current={setShowDropdown:I})},[C,I]);const R=s.useCallback(()=>{I(re=>!re)},[I]),T=s.useCallback((re,ae)=>{ae||re&&v||I(!1)},[I,v]);vt(k,T,p,j);const G=s.useMemo(()=>({setShowDropdown:I}),[I]),U=!!x||!w;return e.jsxs(pt.Provider,{value:G,children:[e.jsx(Z,{name:void 0,className:N(le.dropdownMenu,k&&b,h),elementRef:j,onClick:R,variant:y,actionsContainerClassName:le.actions,iconsContainerClassName:le.icons,childrenContainerClassName:le.content,actions:U?e.jsxs(e.Fragment,{children:[x,!w&&(k?e.jsx(xt,{className:le.dropdownIcon}):e.jsx(_t,{className:le.dropdownIcon}))]}):void 0,icons:_,children:g}),k&&e.jsx(st,{elementRef:p,className:N(le.dropdownContent,r),parentRef:j,preferredWidth:S,children:f})]})}const sa="_info-popup_i3rna_1",ra="_label_i3rna_2",ia="_icon_i3rna_7",oa="_dropdown-container_i3rna_15",la="_content_i3rna_20",ge={infoPopup:sa,label:ra,icon:ia,dropdownContainer:oa,content:la};function ca(m){const{className:a,icon:h=e.jsx(Pt,{}),infoLabel:r,title:f,description:g,withoutIcon:b,popupClassName:_,descriptionClassName:y}=m;return e.jsx(na,{label:e.jsxs("div",{className:ge.label,children:[r,!b&&h&&e.jsx("div",{className:ge.icon,children:h})]}),popupClassName:N(ge.dropdownContainer,_),className:N(ge.infoPopup,a),variant:"tertiary",withoutDropdownIcon:!0,children:e.jsx(z,{heading:f,childrenContainerClassName:N(y,ge.content),withInternalPadding:!0,children:g})})}const da="_progress-wrapper_x340w_1",ua="_title_x340w_7",ma="_total_x340w_11",ha="_progress_x340w_1",fe={progressWrapper:da,title:ua,total:ma,progress:ha};function Ye(m){const{className:a,title:h,description:r,totalValue:f,value:g,showPercentageInTitle:b,children:_,color:y="var(--go-ui-color-primary-red)"}=m,x=se(g)?g:0,w=se(f)?f:0;let C;return w===0?C=0:C=x/w*100,e.jsxs("div",{className:N(fe.progressWrapper,a),children:[(h||b)&&e.jsxs("div",{className:fe.title,children:[h,b&&e.jsx(we,{value:C,suffix:"%"})]}),e.jsx("div",{className:fe.total,children:e.jsx("div",{className:fe.progress,style:{width:`${C}%`,backgroundColor:y}})}),r&&e.jsx("div",{className:fe.description,children:r}),_]})}const ga="_legend-element_1a9ic_1",fa="_color_1a9ic_7",va="_icon-container_1a9ic_14",pa="_icon_1a9ic_14",xa="_label_1a9ic_31",ve={legendElement:ga,color:fa,iconContainer:va,icon:pa,label:xa};function _a(m){const{className:a,colorClassName:h,iconClassName:r,color:f,label:g,iconSrc:b}=m;return e.jsxs("div",{className:N(ve.legendElement,a),children:[b?e.jsx("div",{style:{backgroundColor:f},className:ve.iconContainer,children:e.jsx("img",{className:N(ve.icon,r),src:b,alt:""})}):e.jsx("div",{style:{backgroundColor:f},className:N(ve.color,h)}),e.jsx("div",{className:ve.label,children:g})]})}const Ca="_text-output_10oza_1",ya="_with-background_10oza_6",ba="_label_10oza_11",ja="_with-colon_10oza_12",Na="_value_10oza_17",wa="_text-type_10oza_18",Sa="_strong_10oza_24",ee={textOutput:Ca,withBackground:ya,label:ba,withColon:ja,value:Na,textType:wa,strong:Sa};function Ke(m){const{className:a,label:h,icon:r,description:f,labelClassName:g,descriptionClassName:b,valueClassName:_,strongLabel:y,strongValue:x,strongDescription:w,withoutLabelColon:C,withBackground:j,invalidText:v=nt,...S}=m,{value:p}=m;let k=v;return S.valueType==="number"?k=e.jsx(we,{...S,invalidText:v}):S.valueType==="date"?k=e.jsx(Yt,{...S,invalidText:v}):S.valueType==="boolean"?k=e.jsx(Zt,{...S,invalidText:v}):p instanceof Date||(k=p||v),e.jsxs("div",{className:N(ee.textOutput,j&&ee.withBackground,a),children:[r,h&&e.jsx("div",{className:N(ee.label,y&&ee.strong,g,!C&&ee.withColon),children:h}),e.jsx("div",{className:N(ee.value,x&&ee.strong,S.valueType==="text"&&ee.textType,_),children:k}),f&&e.jsx("div",{className:N(ee.description,w&&ee.strong,b),children:f})]})}const Ma="_pie-chart_pyr7m_1",Ia="_legend_pyr7m_7",Da="_legend-item_pyr7m_13",pe={pieChart:Ma,legend:Ia,legendItem:Da},Ea=70,Ta=40;function Xe(m,a=1){return Math.round(m*10**a)/10**a}function Je(m,a){const h=(a-90)*Math.PI/180;return{x:Xe(m+m*Math.cos(h)),y:Xe(m+m*Math.sin(h))}}function ka(m,a,h){let r=h;const f=r-a===360;f&&(r-=1);const g=Je(m,a),b=Je(m,r),_=r-a<=180?0:1,y=["M",g.x,g.y,"A",m,m,0,_,1,b.x,b.y];return f?y.push("Z"):y.push("L",m,m,"L",g.x,g.y,"Z"),y.join(" ")}function xe(m){const{className:a,data:h,valueSelector:r,labelSelector:f,keySelector:g,colorSelector:b,colors:_,pieRadius:y=Ea,chartPadding:x=Ta,legendClassName:w,showPercentageInLegend:C}=m,j=Ct(h?.map(p=>r(p))),v=q(j)||j===0?1:j,S=s.useMemo(()=>{let p=0;const k=h?.map(I=>{const R=r(I);if(q(R))return;const T=360*(R/v);return p+=T,{key:g(I),value:R,label:f(I),startAngle:p-T,percentage:yt(R,v),endAngle:p,datum:I}}).filter(se)??[];return b?k.map(({datum:I,...R})=>({...R,color:b(I)})):k.map(({datum:I,...R},T)=>({...R,color:_[T%_.length]}))},[h,g,r,f,v,b,_]);return e.jsxs("div",{className:N(pe.pieChart,a),children:[e.jsx("svg",{className:pe.svg,style:{width:`${x+y*2}px`,height:`${x+y*2}px`},children:e.jsx("g",{style:{transform:`translate(${x/2}px, ${x/2}px)`},children:S.map(p=>e.jsx("path",{className:pe.path,d:ka(y,p.startAngle,p.endAngle),fill:p.color,children:e.jsx(Ht,{description:e.jsx(Ke,{label:p.label,value:p.value})})},p.key))})}),e.jsx("div",{className:N(pe.legend,w),children:S.map(p=>e.jsx(_a,{className:pe.legendItem,label:C?e.jsx(Ke,{label:p.label,value:p.percentage,valueType:"number",prefix:"(",suffix:"%)",withoutLabelColon:!0}):p.label,color:p.color},p.key))})]})}const La="_td_1k4cn_1",Pa={td:La};function Ra(m){const{className:a,children:h,...r}=m;return e.jsx("td",{className:N(a,Pa.td),...r,children:h})}function it(m){const{className:a,children:h,...r}=m;return e.jsx("tr",{className:a,...r,children:h})}const $a="_row_1829z_1",Ba="_cell_1829z_2",et={row:$a,cell:Ba};function Aa(m){const{data:a,keySelector:h,columns:r,rowClassName:f,cellClassName:g,rowModifier:b}=m;return e.jsx(e.Fragment,{children:a?.map((_,y)=>{const x=h(_,y),w=r.map(v=>{const{id:S,cellRenderer:p,cellRendererClassName:k,cellRendererParams:I,cellContainerClassName:R}=v,T=I(x,_,y,a),G=e.jsx(p,{className:k,...T,name:S});return e.jsx(Ra,{className:N(et.cell,R,typeof g=="function"?g(x,_,S):g),children:G},S)}),C=e.jsx(it,{className:N(et.row,typeof f=="function"?f(x,_):f),children:w});let j=C;return b&&(j=b({rowKey:x,row:C,cells:w,columns:r,datum:_})),e.jsx(s.Fragment,{children:j},x)})})}const Fa="_th_cdv41_1",Oa="_resize-handle_cdv41_8",tt={th:Fa,resizeHandle:Oa};function Ha(m){const{className:a,children:h,onResize:r,onResizeComplete:f,name:g,...b}=m,_=s.useRef(null),y=s.useRef(),x=s.useRef(),w=s.useRef(),C=s.useCallback(v=>{var S;if(se(y.current)&&_.current&&r){v.preventDefault(),v.stopPropagation();const p=v.clientX-y.current;if(se(x.current)){const k=x.current+p;w.current=k,r(k,g)}else x.current=(S=_.current)==null?void 0:S.offsetWidth}},[r,g]),j=s.useCallback(v=>{var S;v.preventDefault(),y.current=v.clientX,x.current=(S=_.current)==null?void 0:S.offsetWidth,window.addEventListener("mousemove",C,!0)},[C]);return s.useEffect(()=>{const v=()=>{y.current=void 0,x.current=void 0,f&&se(w.current)&&f(w.current,g),window.removeEventListener("mousemove",C,!0)};return window.addEventListener("mouseup",v,!0),()=>{window.removeEventListener("mouseup",v,!0),window.removeEventListener("mousemove",C,!0)}},[C,g,f]),e.jsxs("th",{ref:_,className:N(a,tt.th),...b,children:[r&&e.jsx("div",{role:"presentation",className:tt.resizeHandle,onMouseDown:j}),h]})}const Va="_table_nilhy_1",za="_table-overflow-wrapper_nilhy_8",Ua="_table-element_nilhy_13",Wa="_header-row_nilhy_23",Qa="_header-element_nilhy_24",Za="_header-component_nilhy_29",ce={table:Va,tableOverflowWrapper:za,tableElement:Ua,headerRow:Wa,headerElement:Qa,headerComponent:Za};function qa(m,a){return a??m.columnWidth??wt}function B(m){const{data:a,keySelector:h,columns:r,caption:f,className:g,captionClassName:b,headerRowClassName:_,headerCellClassName:y,rowClassName:x,cellClassName:w,rowModifier:C,fixedColumnWidth:j,resizableColumn:v,headersHidden:S,pending:p,filtered:k,errored:I=!1}=m,R=s.useRef(null),[T]=he.useState(()=>bt()),[G,U]=he.useState({});s.useEffect(()=>{U(W=>{if(q(R.current))return W;const E=R.current.getBoundingClientRect(),{width:O}=E;let A=r.map(M=>({id:M.id,stretch:!!M.columnStretch,width:qa(M,W[M.id])}));const X=ye(A.filter(M=>M.stretch).map(M=>M.width)),ne=ye(A.filter(M=>!M.stretch).map(M=>M.width)),Y=(O-ne)/X;return Y>1&&(A=A.map(M=>({...M,width:M.stretch?M.width*Y:M.width}))),jt(A,M=>M.id,M=>M.width)})},[r]);const re=he.useCallback((W,E)=>{const O=document.getElementById(`${T}-${E}`),A=Math.max(W,80);if(q(O)||(O.style.width=`${A}px`,!j))return;const X=document.getElementById(T);if(q(X))return;const ne=ye(r.map(Y=>Y.id===E?A:G[Y.id]));X.style.width=`${ne}px`},[T,G,r,j]),ae=he.useCallback((W,E)=>{se(E)&&U(O=>({...O,[E]:Math.max(W,80)}))},[U]),be=he.useMemo(()=>ye(r.map(W=>G[W.id])),[G,r]),K=q(a)||a.length===0||Object.keys(G).length===0;return e.jsxs("div",{ref:R,className:N(ce.table,g),children:[!K&&e.jsx("div",{className:ce.tableOverflowWrapper,children:e.jsxs("table",{className:ce.tableElement,style:j?{width:`${be}px`}:void 0,id:T,children:[f&&e.jsx("caption",{className:b,children:f}),e.jsx("colgroup",{children:r.map(W=>{const{id:E,columnClassName:O}=W,A=G[E],X=j?{width:`${A}px`}:void 0;return e.jsx("col",{id:`${T}-${E}`,style:X,className:N(ce.column,O)},E)})}),!S&&e.jsx("thead",{children:e.jsx(it,{className:N(ce.headerRow,_),children:r.map((W,E)=>{const{id:O,title:A,headerCellRenderer:X,headerCellRendererClassName:ne,headerCellRendererParams:Y,headerContainerClassName:M}=W,ie=e.jsx(X,{...Y,name:O,title:A,index:E,className:N(ne,ce.headerComponent)});return e.jsx(Ha,{scope:"col",name:O,onResize:v?re:void 0,onResizeComplete:v?ae:void 0,className:N(ce.headerElement,typeof y=="function"?y(O):y,M),children:ie},O)})})}),e.jsx("tbody",{children:e.jsx(Aa,{data:a,keySelector:h,columns:r,rowClassName:x,cellClassName:w,rowModifier:C})})]})}),e.jsx(Nt,{filtered:k,empty:K,errored:I,pending:p,overlayPending:!0})]})}function Ga(m){const{className:a,value:h}=m;return q(h)?null:e.jsx("div",{className:a,children:h})}const Ya="common",Ka={sortTableButtonTitle:"Sort Table"},Xa={namespace:Ya,strings:Ka},Ja="_header-cell_vn24d_1",en="_sort-button_vn24d_8",tn="_icon_vn24d_12",an="_info-popup-icon_vn24d_17",de={headerCell:Ja,sortButton:en,icon:tn,infoPopupIcon:an};function ot(m){const{className:a,titleClassName:h,title:r,name:f,sortable:g,defaultSortDirection:b="asc",infoTitle:_,infoDescription:y}=m,{sorting:x,setSorting:w}=s.useContext(St),C=rt(Xa),j=x?.name===f?x.direction:void 0,v=s.useRef(null),S=s.useCallback(()=>{if(q(w))return;let p;q(j)?p=b:j==="asc"?p="dsc":j==="dsc"&&(p="asc"),w(p?{name:f,direction:p}:void 0)},[f,w,j,b]);return e.jsxs("div",{ref:v,className:N(a,de.headerCell),children:[g&&e.jsxs(Z,{name:void 0,variant:"tertiary",onClick:S,title:C.sortTableButtonTitle,className:de.sortButton,children:[q(j)&&e.jsx(Rt,{className:de.icon}),j==="asc"&&e.jsx(Lt,{className:de.icon}),j==="dsc"&&e.jsx(kt,{className:de.icon})]}),e.jsx("div",{className:N(h,de.title),children:r}),_&&y&&e.jsx(ca,{className:de.infoPopupIcon,title:_,description:y})]})}const at={};function Q(m,a,h,r){return{id:m,title:a,columnClassName:r?.columnClassName,headerCellRenderer:ot,headerCellRendererClassName:r?.headerCellRendererClassName,headerContainerClassName:r?.headerContainerClassName,headerCellRendererParams:{sortable:r?.sortable,infoTitle:r?.headerInfoTitle,infoDescription:r?.headerInfoDescription},cellRendererClassName:r?.cellRendererClassName,cellContainerClassName:r?.cellContainerClassName,cellRenderer:Ga,cellRendererParams:(f,g)=>({value:h(g)||"--"}),valueSelector:h,valueComparator:(f,g)=>Mt(h(f),h(g)),columnWidth:r?.columnWidth,columnStretch:r?.columnStretch,columnStyle:r?.columnStyle}}function D(m,a,h,r){return{id:m,title:a,columnClassName:r?.columnClassName,headerCellRenderer:ot,headerCellRendererClassName:N(at.numberCellHeader,r?.headerCellRendererClassName),headerContainerClassName:r?.headerContainerClassName,headerCellRendererParams:{sortable:r?.sortable,infoTitle:r?.headerInfoTitle,infoDescription:r?.headerInfoDescription},cellRendererClassName:N(at.numberCell,r?.cellRendererClassName),cellContainerClassName:r?.cellContainerClassName,cellRenderer:we,cellRendererParams:(f,g)=>({value:h(g),suffix:r?.suffix,maximumFractionDigits:r?.maximumFractionDigits,invalidText:"--"}),valueSelector:h,valueComparator:(f,g)=>It(h(f),h(g)),columnWidth:r?.columnWidth,columnStretch:r?.columnStretch,columnStyle:r?.columnStyle}}const nn="_tabSelector_vlxoe_1",sn="_progressSection_vlxoe_14",rn="_progressLabel_vlxoe_20",on="_chartGrid_vlxoe_28",ln="_chartContainer_vlxoe_40",cn="_tableContainer_vlxoe_51",dn="_modelPerformance_vlxoe_59",un="_loadingContainer_vlxoe_67",mn="_errorContainer_vlxoe_77",hn="_userInteractionCards_vlxoe_96",gn="_userInteractionCard_vlxoe_96",fn="_userInteractionCardValue_vlxoe_116",vn="_userInteractionCardLabel_vlxoe_123",pn="_userInteractionCardButton_vlxoe_130",xn="_summaryStatsCards_vlxoe_148",_n="_summaryStatsCard_vlxoe_148",Cn="_summaryStatsCardValue_vlxoe_169",yn="_summaryStatsCardLabel_vlxoe_176",c={tabSelector:nn,progressSection:sn,progressLabel:rn,chartGrid:on,chartContainer:ln,tableContainer:cn,modelPerformance:dn,loadingContainer:un,errorContainer:mn,userInteractionCards:hn,userInteractionCard:gn,userInteractionCardValue:fn,userInteractionCardLabel:vn,userInteractionCardButton:pn,summaryStatsCards:xn,summaryStatsCard:_n,summaryStatsCardValue:Cn,summaryStatsCardLabel:yn};function jn(){const[m]=Dt(),[a,h]=s.useState(null),[r,f]=s.useState(!0),[g,b]=s.useState("crisis_maps"),[_,y]=s.useState([]),[x,w]=s.useState([]),[C,j]=s.useState([]),[v,S]=s.useState([]),[p,k]=s.useState(!1),[I,R]=s.useState(!1),[T,G]=s.useState(!1),[U,re]=s.useState(!1),[ae,be]=s.useState(!1),[K,W]=s.useState(!1),E=t=>{k(t==="editTime"),R(t==="percentage"),G(t==="delete"),re(t==="regions"),be(t==="sources"),W(t==="types")},O=[{key:"crisis_maps",label:"Crisis Maps"},{key:"drone_images",label:"Drone Images"}],A=s.useCallback((t,l)=>{if(!t||!l)return 0;const i=t.toLowerCase().replace(/[^\w\s]/g,"").split(/\s+/).filter(u=>u.length>0),n=l.toLowerCase().replace(/[^\w\s]/g,"").split(/\s+/).filter(u=>u.length>0);if(i.length===0&&n.length===0)return 1;if(i.length===0||n.length===0)return 0;const o=new Set(i),d=new Set(n),P=new Set([...o].filter(u=>d.has(u))),F=new Set([...o,...d]);return P.size/F.size},[]),X=s.useCallback(async()=>{f(!0);try{const l=await(await fetch("/api/images")).json(),i={},n=l.filter(u=>u.image_type==="crisis_map"),o=l.filter(u=>u.image_type==="drone_image"),d={totalCaptions:l.length,sources:{},types:{},regions:{},models:{},modelEditTimes:i,percentageModified:0,modelPercentageData:{},totalDeleteCount:0,deleteRate:0,crisisMaps:n,droneImages:o};l.forEach(u=>{if(u.source&&(d.sources[u.source]=(d.sources[u.source]||0)+1),u.event_type&&(d.types[u.event_type]=(d.types[u.event_type]||0)+1),u.countries&&u.countries.forEach(L=>{L.r_code&&(d.regions[L.r_code]=(d.regions[L.r_code]||0)+1)}),u.model){const L=u.model,V=d.models[L]||={count:0,avgAccuracy:0,avgContext:0,avgUsability:0,totalScore:0,deleteCount:0};if(V.count++,u.accuracy!=null&&(V.avgAccuracy+=u.accuracy),u.context!=null&&(V.avgContext+=u.context),u.usability!=null&&(V.avgUsability+=u.usability),u.created_at&&u.updated_at){const te=new Date(u.created_at).getTime(),Ce=new Date(u.updated_at).getTime()-te;Ce>0&&(i[L]||(i[L]=[]),i[L].push(Ce))}}}),_.forEach(u=>{u.s_code&&!d.sources[u.s_code]&&(d.sources[u.s_code]=0)}),x.forEach(u=>{u.t_code&&!d.types[u.t_code]&&(d.types[u.t_code]=0)}),C.forEach(u=>{u.r_code&&!d.regions[u.r_code]&&(d.regions[u.r_code]=0)}),["GPT-4","Claude","Gemini","Llama","Other"].forEach(u=>{d.models[u]||(d.models[u]={count:0,avgAccuracy:0,avgContext:0,avgUsability:0,totalScore:0,deleteCount:0})}),Object.values(d.models).forEach(u=>{u.count>0&&(u.avgAccuracy=Math.round(u.avgAccuracy/u.count),u.avgContext=Math.round(u.avgContext/u.count),u.avgUsability=Math.round(u.avgUsability/u.count),u.totalScore=Math.round((u.avgAccuracy+u.avgContext+u.avgUsability)/3))});const F=l.filter(u=>u.generated&&u.edited);if(F.length>0){const L=[...F.map(oe=>A(oe.generated,oe.edited))].sort((oe,Ce)=>oe-Ce),V=Math.floor(L.length/2),te=L.length%2===0?(L[V-1]+L[V])/2:L[V];d.percentageModified=Math.round((1-te)*100)}const H={};l.forEach(u=>{if(u.model&&u.generated&&u.edited){const L=A(u.generated,u.edited),V=Math.round((1-L)*100);H[u.model]||(H[u.model]=[]),H[u.model].push(V)}}),d.modelPercentageData=H;try{const u=await fetch("/api/models");if(u.ok){const L=await u.json();if(L.models){L.models.forEach(te=>{d.models[te.m_code]&&(d.models[te.m_code].deleteCount=te.delete_count||0)});const V=L.models.reduce((te,oe)=>te+(oe.delete_count||0),0);d.totalDeleteCount=V,d.deleteRate=V>0?Math.round(V/(V+l.length)*100):0}}}catch(u){console.log("Could not fetch model delete counts:",u)}h(d)}catch{h(null)}finally{f(!1)}},[_,x,C,A]),ne=s.useCallback(async()=>{try{const[t,l,i,n]=await Promise.all([fetch("/api/sources"),fetch("/api/types"),fetch("/api/regions"),fetch("/api/models")]),o=await t.json(),d=await l.json(),P=await i.json(),F=await n.json();y(o),w(d),j(P),S(F.models||[])}catch(t){console.log("Could not fetch lookup data:",t)}},[]);s.useEffect(()=>{const t=m.get("view");(t==="crisis_maps"||t==="drone_images")&&b(t)},[m]),s.useEffect(()=>{ne()},[ne]),s.useEffect(()=>{_.length>0&&x.length>0&&C.length>0&&v.length>0&&X()},[_,x,C,v,X]);const Y=s.useCallback(t=>{const l=_.find(i=>i.s_code===t);return l?l.label:t},[_]),M=s.useCallback(t=>{if(t.length===0)return 0;const l=[...t].sort((n,o)=>n-o),i=Math.floor(l.length/2);return l.length%2===0?Math.round((l[i-1]+l[i])/2):l[i]},[]),ie=s.useCallback(t=>{const l=Math.floor(t/1e3),i=Math.floor(l/60),n=Math.floor(i/60);return n>0?`${n}h ${i%60}m`:i>0?`${i}m ${l%60}s`:`${l}s`},[]),_e=s.useCallback(t=>{const l=x.find(i=>i.t_code===t);return l?l.label:t},[x]),J=s.useCallback(t=>{const l=v.find(i=>i.m_code===t);return l?l.label:t},[v]),Se=s.useMemo(()=>a?Object.entries(a.modelEditTimes||{}).filter(([,t])=>t.length>0).sort(([,t],[,l])=>M(l)-M(t)).map(([t,l],i)=>({id:i+1,name:J(t),count:l.length,avgEditTime:M(l),minEditTime:Math.min(...l),maxEditTime:Math.max(...l)})):[],[a,M,J]),Me=s.useMemo(()=>a?Object.entries(a.modelPercentageData||{}).filter(([,t])=>t.length>0).sort(([,t],[,l])=>{const i=[...t].sort((H,u)=>H-u),n=[...l].sort((H,u)=>H-u),o=Math.floor(i.length/2),d=Math.floor(n.length/2),P=i.length%2===0?(i[o-1]+i[o])/2:i[o];return(n.length%2===0?(n[d-1]+n[d])/2:n[d])-P}).map(([t,l],i)=>{const n=[...l].sort((P,F)=>P-F),o=Math.floor(n.length/2),d=n.length%2===0?Math.round((n[o-1]+n[o])/2):n[o];return{id:i+1,name:J(t),count:l.length,avgPercentageModified:d,minPercentageModified:Math.min(...l),maxPercentageModified:Math.max(...l)}}):[],[a,J]),Ie=s.useMemo(()=>a?Object.entries(a.models).filter(([,t])=>t.count>0).map(([t,l],i)=>{const n=[l.avgAccuracy,l.avgContext,l.avgUsability],o=n.reduce((F,H)=>F+H,0)/n.length,d=n.reduce((F,H)=>F+Math.pow(H-o,2),0)/n.length,P=Math.round(100-Math.sqrt(d));return{id:i+1,name:J(t),consistency:Math.max(0,P),avgScore:Math.round(o),count:l.count}}).sort((t,l)=>l.consistency-t.consistency):[],[a,J]),De=s.useMemo(()=>[Q("name","Region",t=>t.name),D("count","Count",t=>t.count),D("percentage","% of Total",t=>t.percentage,{suffix:"%",maximumFractionDigits:0})],[]),Ee=s.useMemo(()=>[Q("name","Type",t=>t.name),D("count","Count",t=>t.count),D("percentage","% of Total",t=>t.percentage,{suffix:"%",maximumFractionDigits:0})],[]),lt=s.useMemo(()=>[Q("name","Source",t=>t.name),D("count","Count",t=>t.count),D("percentage","% of Total",t=>t.percentage,{suffix:"%",maximumFractionDigits:0})],[]),Te=s.useMemo(()=>[Q("name","Model",t=>t.name),D("count","Count",t=>t.count),D("accuracy","Accuracy",t=>t.accuracy,{suffix:"%",maximumFractionDigits:0}),D("context","Context",t=>t.context,{suffix:"%",maximumFractionDigits:0}),D("usability","Usability",t=>t.usability,{suffix:"%",maximumFractionDigits:0}),D("totalScore","Total Score",t=>t.totalScore,{suffix:"%",maximumFractionDigits:0})],[]),ke=s.useMemo(()=>[Q("name","Model",t=>t.name),D("count","Count",t=>t.count),Q("avgEditTime","Median Edit Time",t=>ie(t.avgEditTime)),Q("minEditTime","Min Edit Time",t=>ie(t.minEditTime)),Q("maxEditTime","Max Edit Time",t=>ie(t.maxEditTime))],[]),Le=s.useMemo(()=>[Q("name","Model",t=>t.name),D("count","Count",t=>t.count),D("avgPercentageModified","Median % Modified",t=>t.avgPercentageModified,{suffix:"%",maximumFractionDigits:0}),D("minPercentageModified","Min % Modified",t=>t.minPercentageModified,{suffix:"%",maximumFractionDigits:0}),D("maxPercentageModified","Max % Modified",t=>t.maxPercentageModified,{suffix:"%",maximumFractionDigits:0})],[]),Pe=s.useMemo(()=>[Q("name","Model",t=>t.name),D("count","Total Count",t=>t.count),D("deleteCount","Delete Count",t=>t.deleteCount),D("deleteRate","Delete Rate",t=>t.deleteRate,{suffix:"%",maximumFractionDigits:1})],[]),ct=s.useMemo(()=>[Q("source","Source",t=>t.source),D("avgQuality","Average Quality",t=>t.avgQuality,{suffix:"%",maximumFractionDigits:0}),D("count","Count",t=>t.count)],[]),Re=s.useMemo(()=>[Q("eventType","Event Type",t=>t.eventType),D("avgQuality","Average Quality",t=>t.avgQuality,{suffix:"%",maximumFractionDigits:0}),D("count","Count",t=>t.count)],[]),$e=s.useMemo(()=>[Q("name","Model",t=>t.name),D("consistency","Consistency",t=>t.consistency,{suffix:"%",maximumFractionDigits:0}),D("avgScore","Average Score",t=>t.avgScore,{suffix:"%",maximumFractionDigits:0}),D("count","Count",t=>t.count)],[]),ue=s.useCallback(t=>a?t==="crisis_map"?a.crisisMaps.length:t==="drone_image"?a.droneImages.length:0:0,[a]),Be=s.useCallback(t=>{if(!a)return[];const l=t==="crisis_map"?a.crisisMaps:a.droneImages,i={};return l.forEach(n=>{n.countries&&n.countries.forEach(o=>{o.r_code&&(i[o.r_code]=(i[o.r_code]||0)+1)})}),Object.entries(i).filter(([,n])=>n>0).map(([n,o])=>({name:C.find(d=>d.r_code===n)?.label||n,value:o}))},[a,C]),Ae=s.useCallback(t=>{if(!a)return[];const l=t==="crisis_map"?a.crisisMaps:a.droneImages,i={};l.forEach(o=>{o.countries&&o.countries.forEach(d=>{d.r_code&&(i[d.r_code]=(i[d.r_code]||0)+1)})});const n=C.reduce((o,d)=>(d.r_code&&(o[d.r_code]={name:d.label,count:i[d.r_code]||0}),o),{});return Object.entries(n).sort(([,o],[,d])=>d.count-o.count).map(([,{name:o,count:d}],P)=>({id:P+1,name:o,count:d,percentage:l.length>0?Math.round(d/l.length*100):0}))},[a,C]),dt=s.useCallback(t=>{if(!a)return[];const l=t==="crisis_map"?a.crisisMaps:a.droneImages,i={};return l.forEach(n=>{n.source&&(i[n.source]=(i[n.source]||0)+1)}),Object.entries(i).filter(([,n])=>n>0).map(([n,o])=>({name:_.find(d=>d.s_code===n)?.label||n,value:o}))},[a,_]),ut=s.useCallback(t=>{if(!a)return[];const l=t==="crisis_map"?a.crisisMaps:a.droneImages,i={};return l.forEach(n=>{n.source&&(i[n.source]=(i[n.source]||0)+1)}),Object.entries(i).sort(([,n],[,o])=>o-n).map(([n,o],d)=>({id:d+1,name:Y(n),count:o,percentage:l.length>0?Math.round(o/l.length*100):0}))},[a,Y]),Fe=s.useCallback(t=>{if(!a)return[];const l=t==="crisis_map"?a.crisisMaps:a.droneImages,i={};return l.forEach(n=>{n.event_type&&(i[n.event_type]=(i[n.event_type]||0)+1)}),Object.entries(i).filter(([,n])=>n>0).map(([n,o])=>({name:x.find(d=>d.t_code===n)?.label||n,value:o}))},[a,x]),Oe=s.useCallback(t=>{if(!a)return[];const l=t==="crisis_map"?a.crisisMaps:a.droneImages,i={};return l.forEach(n=>{n.event_type&&(i[n.event_type]=(i[n.event_type]||0)+1)}),Object.entries(i).sort(([,n],[,o])=>o-n).map(([n,o],d)=>({id:d+1,name:_e(n),count:o,percentage:l.length>0?Math.round(o/l.length*100):0}))},[a,_e]),He=s.useCallback(t=>{if(!a)return"No data available";const l=t==="crisis_map"?a.crisisMaps:a.droneImages,i=new Set;l.forEach(d=>{d.model&&i.add(d.model)}),console.log(`Debug ${t}:`,{totalImages:l.length,usedModels:Array.from(i),availableEditTimes:Object.keys(a.modelEditTimes),modelEditTimesData:a.modelEditTimes});const o=Object.entries(a.modelEditTimes).filter(([d])=>i.has(d)).flatMap(([,d])=>d);return o.length===0?"No data available":ie(M(o))},[a,ie,M]),Ve=s.useCallback(()=>{if(!a)return"No data available";const t=a.totalCaptions||0,l=a.percentageModified||0;return t>0?Math.round(l/t*100):0},[a]),ze=s.useCallback(()=>a&&a.deleteRate>=0?`${a.deleteRate}%`:"No data available",[a]),Ue=s.useCallback(t=>{if(!a)return[];const l=t==="crisis_map"?a.crisisMaps:a.droneImages,i=new Set;return l.forEach(o=>{o.model&&i.add(o.model)}),Se.filter(o=>{const d=v.find(P=>P.label===o.name)?.m_code;return d&&i.has(d)})},[a,Se,v]),We=s.useCallback(t=>{if(!a)return[];const l=t==="crisis_map"?a.crisisMaps:a.droneImages,i=new Set;return l.forEach(o=>{o.model&&i.add(o.model)}),Me.filter(o=>{const d=v.find(P=>P.label===o.name)?.m_code;return d&&i.has(d)})},[a,Me,v]),Qe=s.useCallback(t=>{if(!a)return[];const l=t==="crisis_map"?a.crisisMaps:a.droneImages,i={};return l.forEach(n=>{n.model&&(i[n.model]||(i[n.model]={count:0,deleteCount:0}),i[n.model].count++)}),Object.entries(i).map(([n,o],d)=>{const F=a.models?.[n]?.deleteCount||0,H=o.count>0?Math.round(F/o.count*100*10)/10:0;return{id:d+1,name:J(n),count:o.count,deleteCount:F,deleteRate:H}}).sort((n,o)=>o.count-n.count)},[a,J]),Ze=s.useCallback(t=>{if(!a)return[];const l=t==="crisis_map"?a.crisisMaps:a.droneImages,i={};return l.forEach(n=>{n.model&&(i[n.model]||(i[n.model]={count:0,totalAccuracy:0,totalContext:0,totalUsability:0}),i[n.model].count++,n.accuracy!=null&&(i[n.model].totalAccuracy+=n.accuracy),n.context!=null&&(i[n.model].totalContext+=n.context),n.usability!=null&&(i[n.model].totalUsability+=n.usability))}),Object.entries(i).map(([n,o],d)=>({id:d+1,name:J(n),count:o.count,accuracy:o.count>0?Math.round(o.totalAccuracy/o.count):0,context:o.count>0?Math.round(o.totalContext/o.count):0,usability:o.count>0?Math.round(o.totalUsability/o.count):0,totalScore:o.count>0?Math.round((o.totalAccuracy+o.totalContext+o.totalUsability)/(3*o.count)):0})).sort((n,o)=>o.totalScore-n.totalScore)},[a,J]),mt=s.useCallback(t=>{if(!a)return[];const l=t==="crisis_map"?a.crisisMaps:a.droneImages,i={};return l.forEach(n=>{n.source&&(i[n.source]||(i[n.source]={total:0,count:0,totalImages:0}),i[n.source].totalImages+=1,n.accuracy!=null&&(i[n.source].total+=n.accuracy,i[n.source].count+=1))}),Object.entries(i).map(([n,o],d)=>({id:d+1,source:Y(n),avgQuality:o.count>0?Math.round(o.total/o.count):0,count:o.totalImages}))},[a,Y]),qe=s.useCallback(t=>{if(!a)return[];const l=t==="crisis_map"?a.crisisMaps:a.droneImages,i={};return l.forEach(n=>{n.event_type&&(i[n.event_type]||(i[n.event_type]={total:0,count:0,totalImages:0}),i[n.event_type].totalImages+=1,n.accuracy!=null&&(i[n.event_type].total+=n.accuracy,i[n.event_type].count+=1))}),Object.entries(i).map(([n,o],d)=>({id:d+1,eventType:_e(n),avgQuality:o.count>0?Math.round(o.total/o.count):0,count:o.totalImages}))},[a,_e]),Ge=s.useCallback(t=>{if(!a)return[];const l=t==="crisis_map"?a.crisisMaps:a.droneImages,i=new Set;return l.forEach(o=>{o.model&&i.add(o.model)}),Ie.filter(o=>{const d=v.find(P=>P.label===o.name)?.m_code;return d&&i.has(d)})},[a,Ie,v]);if(r)return e.jsx(je,{children:e.jsx("div",{className:c.loadingContainer,children:e.jsx(Et,{})})});if(!a)return e.jsx(je,{children:e.jsx("div",{className:c.errorContainer,children:e.jsx("div",{className:"text-red-500",children:"Failed to load analytics data. Please try again."})})});const me=["#F5333F","#F64752","#F75C65","#F87079","#F9858C","#FA999F","#FBADB2","#FCC2C5"];return e.jsx(je,{children:e.jsxs("div",{className:"max-w-7xl mx-auto",children:[e.jsx("div",{className:c.tabSelector,children:e.jsx(Tt,{name:"analytics-view",value:g,onChange:t=>{(t==="crisis_maps"||t==="drone_images")&&b(t)},options:O,keySelector:t=>t.key,labelSelector:t=>t.label})}),g==="crisis_maps"?e.jsxs("div",{className:c.chartGrid,children:[e.jsxs(z,{heading:"Summary Statistics",headingLevel:3,withHeaderBorder:!0,withInternalPadding:!0,children:[e.jsxs("div",{className:c.summaryStatsCards,children:[e.jsxs("div",{className:c.summaryStatsCard,children:[e.jsx("div",{className:c.summaryStatsCardValue,children:ue("crisis_map")}),e.jsx("div",{className:c.summaryStatsCardLabel,children:"Total Crisis Maps"})]}),e.jsxs("div",{className:c.summaryStatsCard,children:[e.jsx("div",{className:c.summaryStatsCardValue,children:"2000"}),e.jsx("div",{className:c.summaryStatsCardLabel,children:"Target Amount"})]})]}),e.jsxs("div",{className:c.progressSection,children:[e.jsxs("div",{className:c.progressLabel,children:[e.jsx("span",{children:"Progress towards target"}),e.jsxs("span",{children:[Math.round(ue("crisis_map")/2e3*100),"%"]})]}),e.jsx(Ye,{value:ue("crisis_map"),totalValue:2e3})]})]}),e.jsxs(z,{heading:"Distribution Analysis",headingLevel:3,withHeaderBorder:!0,withInternalPadding:!0,children:[e.jsxs("div",{className:c.userInteractionCards,children:[e.jsxs("div",{className:c.userInteractionCard,children:[e.jsx("div",{className:c.userInteractionCardLabel,children:"Regions Distribution"}),e.jsx("div",{className:c.chartContainer,children:e.jsx(xe,{data:Be("crisis_map"),valueSelector:t=>t.value,labelSelector:t=>t.name,keySelector:t=>t.name,colors:me,showPercentageInLegend:!0})}),e.jsx(Z,{name:"view-regions-details",variant:U?"primary":"secondary",onClick:()=>E(U?"none":"regions"),className:c.userInteractionCardButton,children:U?"Hide Details":"View Details"})]}),e.jsxs("div",{className:c.userInteractionCard,children:[e.jsx("div",{className:c.userInteractionCardLabel,children:"Sources Distribution"}),e.jsx("div",{className:c.chartContainer,children:e.jsx(xe,{data:dt("crisis_map"),valueSelector:t=>t.value,labelSelector:t=>t.name,keySelector:t=>t.name,colors:me,showPercentageInLegend:!0})}),e.jsx(Z,{name:"view-sources-details",variant:ae?"primary":"secondary",onClick:()=>E(ae?"none":"sources"),className:c.userInteractionCardButton,children:ae?"Hide Details":"View Details"})]}),e.jsxs("div",{className:c.userInteractionCard,children:[e.jsx("div",{className:c.userInteractionCardLabel,children:"Types Distribution"}),e.jsx("div",{className:c.chartContainer,children:e.jsx(xe,{data:Fe("crisis_map"),valueSelector:t=>t.value,labelSelector:t=>t.name,keySelector:t=>t.name,colors:me,showPercentageInLegend:!0})}),e.jsx(Z,{name:"view-types-details",variant:K?"primary":"secondary",onClick:()=>E(K?"none":"types"),className:c.userInteractionCardButton,children:K?"Hide Details":"View Details"})]})]}),U&&e.jsx("div",{className:c.modelPerformance,children:e.jsx(B,{data:Ae("crisis_map"),columns:De,keySelector:$,filtered:!1,pending:!1})}),ae&&e.jsx("div",{className:c.modelPerformance,children:e.jsx(B,{data:ut("crisis_map"),columns:lt,keySelector:$,filtered:!1,pending:!1})}),K&&e.jsx("div",{className:c.modelPerformance,children:e.jsx(B,{data:Oe("crisis_map"),columns:Ee,keySelector:$,filtered:!1,pending:!1})})]}),e.jsxs(z,{heading:"User Interaction Statistics",headingLevel:3,withHeaderBorder:!0,withInternalPadding:!0,children:[e.jsxs("div",{className:c.userInteractionCards,children:[e.jsxs("div",{className:c.userInteractionCard,children:[e.jsx("div",{className:c.userInteractionCardValue,children:He("crisis_map")}),e.jsx("div",{className:c.userInteractionCardLabel,children:"Median Edit Time"}),e.jsx(Z,{name:"view-edit-time-details",variant:p?"primary":"secondary",onClick:()=>E(p?"none":"editTime"),className:c.userInteractionCardButton,children:p?"Hide Details":"View Details"})]}),e.jsxs("div",{className:c.userInteractionCard,children:[e.jsx("div",{className:c.userInteractionCardValue,children:Ve()}),e.jsx("div",{className:c.userInteractionCardLabel,children:"Median % Modified"}),e.jsx(Z,{name:"view-percentage-details",variant:I?"primary":"secondary",onClick:()=>E(I?"none":"percentage"),className:c.userInteractionCardButton,children:I?"Hide Details":"View Details"})]}),e.jsxs("div",{className:c.userInteractionCard,children:[e.jsx("div",{className:c.userInteractionCardValue,children:ze()}),e.jsx("div",{className:c.userInteractionCardLabel,children:"Delete Rate"}),e.jsx(Z,{name:"view-delete-details",variant:T?"primary":"secondary",onClick:()=>E(T?"none":"delete"),className:c.userInteractionCardButton,children:T?"Hide Details":"View Details"})]})]}),p&&e.jsx("div",{className:c.modelPerformance,children:e.jsx(B,{data:Ue("crisis_map"),columns:ke,keySelector:$,filtered:!1,pending:!1})}),I&&e.jsx("div",{className:c.modelPerformance,children:e.jsx(B,{data:We("crisis_map"),columns:Le,keySelector:$,filtered:!1,pending:!1})}),T&&e.jsx("div",{className:c.modelPerformance,children:e.jsx(B,{data:Qe("crisis_map"),columns:Pe,keySelector:$,filtered:!1,pending:!1})})]}),e.jsx(z,{heading:"Model Performance",headingLevel:3,withHeaderBorder:!0,withInternalPadding:!0,children:e.jsx("div",{className:c.modelPerformance,children:e.jsx(B,{data:Ze("crisis_map"),columns:Te,keySelector:$,filtered:!1,pending:!1})})}),e.jsx(z,{heading:"Quality-Source Correlation",headingLevel:3,withHeaderBorder:!0,withInternalPadding:!0,children:e.jsx("div",{className:c.tableContainer,children:e.jsx(B,{data:mt("crisis_map"),columns:ct,keySelector:$,filtered:!1,pending:!1})})}),e.jsx(z,{heading:"Quality-Event Type Correlation",headingLevel:3,withHeaderBorder:!0,withInternalPadding:!0,children:e.jsx("div",{className:c.tableContainer,children:e.jsx(B,{data:qe("crisis_map"),columns:Re,keySelector:$,filtered:!1,pending:!1})})}),e.jsx(z,{heading:"Model Consistency Analysis",headingLevel:3,withHeaderBorder:!0,withInternalPadding:!0,children:e.jsx("div",{className:c.tableContainer,children:e.jsx(B,{data:Ge("crisis_map"),columns:$e,keySelector:$,filtered:!1,pending:!1})})})]}):e.jsxs("div",{className:c.chartGrid,children:[e.jsxs(z,{heading:"Summary Statistics",headingLevel:3,withHeaderBorder:!0,withInternalPadding:!0,children:[e.jsxs("div",{className:c.summaryStatsCards,children:[e.jsxs("div",{className:c.summaryStatsCard,children:[e.jsx("div",{className:c.summaryStatsCardValue,children:ue("drone_image")}),e.jsx("div",{className:c.summaryStatsCardLabel,children:"Total Drone Images"})]}),e.jsxs("div",{className:c.summaryStatsCard,children:[e.jsx("div",{className:c.summaryStatsCardValue,children:"2000"}),e.jsx("div",{className:c.summaryStatsCardLabel,children:"Target Amount"})]})]}),e.jsxs("div",{className:c.progressSection,children:[e.jsxs("div",{className:c.progressLabel,children:[e.jsx("span",{children:"Progress towards target"}),e.jsxs("span",{children:[Math.round(ue("drone_image")/2e3*100),"%"]})]}),e.jsx(Ye,{value:ue("drone_image"),totalValue:2e3})]})]}),e.jsxs(z,{heading:"Distribution Analysis",headingLevel:3,withHeaderBorder:!0,withInternalPadding:!0,children:[e.jsxs("div",{className:c.userInteractionCards,children:[e.jsxs("div",{className:c.userInteractionCard,children:[e.jsx("div",{className:c.userInteractionCardLabel,children:"Regions Distribution"}),e.jsx("div",{className:c.chartContainer,children:e.jsx(xe,{data:Be("drone_image"),valueSelector:t=>t.value,labelSelector:t=>t.name,keySelector:t=>t.name,colors:me,showPercentageInLegend:!0})}),e.jsx(Z,{name:"view-regions-details",variant:U?"primary":"secondary",onClick:()=>E(U?"none":"regions"),className:c.userInteractionCardButton,children:U?"Hide Details":"View Details"})]}),e.jsxs("div",{className:c.userInteractionCard,children:[e.jsx("div",{className:c.userInteractionCardLabel,children:"Types Distribution"}),e.jsx("div",{className:c.chartContainer,children:e.jsx(xe,{data:Fe("drone_image"),valueSelector:t=>t.value,labelSelector:t=>t.name,keySelector:t=>t.name,colors:me,showPercentageInLegend:!0})}),e.jsx(Z,{name:"view-types-details",variant:K?"primary":"secondary",onClick:()=>E(K?"none":"types"),className:c.userInteractionCardButton,children:K?"Hide Details":"View Details"})]})]}),U&&e.jsx("div",{className:c.modelPerformance,children:e.jsx(B,{data:Ae("drone_image"),columns:De,keySelector:$,filtered:!1,pending:!1})}),K&&e.jsx("div",{className:c.modelPerformance,children:e.jsx(B,{data:Oe("drone_image"),columns:Ee,keySelector:$,filtered:!1,pending:!1})})]}),e.jsxs(z,{heading:"User Interaction Statistics",headingLevel:3,withHeaderBorder:!0,withInternalPadding:!0,children:[e.jsxs("div",{className:c.userInteractionCards,children:[e.jsxs("div",{className:c.userInteractionCard,children:[e.jsx("div",{className:c.userInteractionCardValue,children:He("drone_image")}),e.jsx("div",{className:c.userInteractionCardLabel,children:"Median Edit Time"}),e.jsx(Z,{name:"view-edit-time-details",variant:p?"primary":"secondary",onClick:()=>E(p?"none":"editTime"),className:c.userInteractionCardButton,children:p?"Hide Details":"View Details"})]}),e.jsxs("div",{className:c.userInteractionCard,children:[e.jsx("div",{className:c.userInteractionCardValue,children:Ve()}),e.jsx("div",{className:c.userInteractionCardLabel,children:"Median % Modified"}),e.jsx(Z,{name:"view-percentage-details",variant:I?"primary":"secondary",onClick:()=>E(I?"none":"percentage"),className:c.userInteractionCardButton,children:I?"Hide Details":"View Details"})]}),e.jsxs("div",{className:c.userInteractionCard,children:[e.jsx("div",{className:c.userInteractionCardValue,children:ze()}),e.jsx("div",{className:c.userInteractionCardLabel,children:"Delete Rate"}),e.jsx(Z,{name:"view-delete-details",variant:T?"primary":"secondary",onClick:()=>E(T?"none":"delete"),className:c.userInteractionCardButton,children:T?"Hide Details":"View Details"})]})]}),p&&e.jsx("div",{className:c.modelPerformance,children:e.jsx(B,{data:Ue("drone_image"),columns:ke,keySelector:$,filtered:!1,pending:!1})}),I&&e.jsx("div",{className:c.modelPerformance,children:e.jsx(B,{data:We("drone_image"),columns:Le,keySelector:$,filtered:!1,pending:!1})}),T&&e.jsx("div",{className:c.modelPerformance,children:e.jsx(B,{data:Qe("drone_image"),columns:Pe,keySelector:$,filtered:!1,pending:!1})})]}),e.jsx(z,{heading:"Model Performance",headingLevel:3,withHeaderBorder:!0,withInternalPadding:!0,children:e.jsx("div",{className:c.modelPerformance,children:e.jsx(B,{data:Ze("drone_image"),columns:Te,keySelector:$,filtered:!1,pending:!1})})}),e.jsx(z,{heading:"Quality-Event Type Correlation",headingLevel:3,withHeaderBorder:!0,withInternalPadding:!0,children:e.jsx("div",{className:c.tableContainer,children:e.jsx(B,{data:qe("drone_image"),columns:Re,keySelector:$,filtered:!1,pending:!1})})}),e.jsx(z,{heading:"Model Consistency Analysis",headingLevel:3,withHeaderBorder:!0,withInternalPadding:!0,children:e.jsx("div",{className:c.tableContainer,children:e.jsx(B,{data:Ge("drone_image"),columns:$e,keySelector:$,filtered:!1,pending:!1})})})]})]})})}export{jn as default};
|
|
|
1 |
+
import{r as s,y as nt,t as ht,a as q,c as gt,j as e,o as N,b as se,R as st,z,g as rt,d as ft,m as vt,e as pt,n as Z,A as xt,f as _t,h as Ct,i as yt,k as he,l as bt,p as ye,q as jt,s as Nt,E as wt,C as St,U as Mt,Q as It,u as Dt,N as je,_ as Et,L as Tt}from"./index-BzYyR-qc.js";const kt=({title:m,titleId:a,...h})=>s.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg","aria-hidden":"true",viewBox:"0 0 24 24",fill:"currentColor",width:"1em",height:"1em","aria-labelledby":a},h),m?s.createElement("title",{id:a},m):null,s.createElement("g",{clipPath:"url(#arrow-drop-down-line_svg__a)"},s.createElement("path",{d:"m12 15-4.243-4.243 1.415-1.414L12 12.172l2.828-2.83 1.415 1.415L12 15Z"})),s.createElement("defs",null,s.createElement("clipPath",{id:"arrow-drop-down-line_svg__a"},s.createElement("path",{d:"M0 0h24v24H0z"})))),Lt=({title:m,titleId:a,...h})=>s.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg","aria-hidden":"true",viewBox:"0 0 24 24",fill:"currentColor",width:"1em",height:"1em","aria-labelledby":a},h),m?s.createElement("title",{id:a},m):null,s.createElement("g",{clipPath:"url(#arrow-drop-up-line_svg__a)"},s.createElement("path",{d:"m12 11.828-2.828 2.829-1.415-1.414L12 9l4.243 4.243-1.415 1.414L12 11.828Z"})),s.createElement("defs",null,s.createElement("clipPath",{id:"arrow-drop-up-line_svg__a"},s.createElement("path",{d:"M0 0h24v24H0z"})))),Pt=({title:m,titleId:a,...h})=>s.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg","aria-hidden":"true",viewBox:"0 0 24 24",fill:"currentColor",width:"1em",height:"1em","aria-labelledby":a},h),m?s.createElement("title",{id:a},m):null,s.createElement("g",{clipPath:"url(#information-line_svg__a)"},s.createElement("path",{d:"M12 22C6.477 22 2 17.523 2 12S6.477 2 12 2s10 4.477 10 10-4.477 10-10 10Zm0-2a8 8 0 1 0 0-16.001A8 8 0 0 0 12 20ZM11 7h2v2h-2V7Zm0 4h2v6h-2v-6Z"})),s.createElement("defs",null,s.createElement("clipPath",{id:"information-line_svg__a"},s.createElement("path",{d:"M0 0h24v24H0z"})))),Rt=({title:m,titleId:a,...h})=>s.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg","aria-hidden":"true",viewBox:"0 0 24 24",fill:"currentColor",width:"1em",height:"1em","aria-labelledby":a},h),m?s.createElement("title",{id:a},m):null,s.createElement("path",{fillRule:"evenodd",d:"m15.063 12 .937.938-4 4-4-4L8.938 12 12 15.063 15.063 12Z",clipRule:"evenodd"}),s.createElement("mask",{id:"table-sorting-line_svg__a",width:8,height:5,x:8,y:12,maskUnits:"userSpaceOnUse",style:{maskType:"luminance"}},s.createElement("path",{fillRule:"evenodd",d:"m15.063 12 .937.938-4 4-4-4L8.938 12 12 15.063 15.063 12Z",clipRule:"evenodd"})),s.createElement("g",{mask:"url(#table-sorting-line_svg__a)"},s.createElement("path",{d:"M-24-22h72v72h-72z"})),s.createElement("path",{fillRule:"evenodd",d:"M8.938 11 8 10.062l4-4 4 4-.938.938L12 7.937 8.937 11Z",clipRule:"evenodd"}),s.createElement("mask",{id:"table-sorting-line_svg__b",width:8,height:5,x:8,y:6,maskUnits:"userSpaceOnUse",style:{maskType:"luminance"}},s.createElement("path",{fillRule:"evenodd",d:"M8.938 11 8 10.062l4-4 4 4-.938.938L12 7.937 8.937 11Z",clipRule:"evenodd"})),s.createElement("g",{mask:"url(#table-sorting-line_svg__b)"},s.createElement("path",{d:"M48 45h-72v-72h72z"}))),$t="_number-output_1blvi_1",Bt={numberOutput:$t};function we(m){const{className:a,invalidText:h=nt,separatorHidden:r,compact:f,currency:g,value:b,tooltip:_,unit:y,prefix:x,suffix:w,maximumFractionDigits:C=1}=m,{currentLanguage:j}=s.useContext(ht),v=s.useMemo(()=>{if(q(b))return h;const S=gt(b,{currency:g,compact:f,separatorHidden:r,maximumFractionDigits:C,unit:y,language:j});return e.jsxs(e.Fragment,{children:[x,S,w]})},[h,b,f,r,g,y,C,x,j,w]);return e.jsx("div",{className:N(Bt.numberOutput,a),title:se(_)?String(_):void 0,children:v})}const At="_tooltip-dummy_rbf3f_1",Ft="_tooltip-content_rbf3f_7",Ot="_pointer_rbf3f_14",Ne={tooltipDummy:At,tooltipContent:Ft,pointer:Ot};function Ht(m){const{className:a,title:h,description:r,preferredWidth:f}=m,[g,b]=s.useState(!1),[_,y]=s.useState(!1),x=s.useRef(),w=s.useRef(null);return s.useEffect(()=>{const C=()=>{y(!0)},j=()=>{y(!1)};if(q(w.current))return;const{current:{parentNode:v}}=w;if(!q(v))return x.current=v,v.addEventListener("mouseover",C),v.addEventListener("mouseout",j),b(!0),()=>{v.removeEventListener("mouseover",C),v.removeEventListener("mouseout",j)}},[]),e.jsxs(e.Fragment,{children:[!g&&e.jsx("div",{className:Ne.tooltipDummy,ref:w}),_&&e.jsx(st,{className:N(Ne.tooltipContent,a),parentRef:x,pointerClassName:Ne.pointer,preferredWidth:f,children:e.jsx(z,{heading:h,withInternalPadding:!0,contentViewType:"vertical",children:r})})]})}function $(m){return m.id}const Vt="common",zt={booleanYesLabel:"Yes",booleanNoLabel:"No"},Ut={namespace:Vt,strings:zt},Wt="_boolean-output_kg1uq_1",Qt={booleanOutput:Wt};function Zt(m){const{className:a,invalidText:h,value:r}=m,f=rt(Ut);let g;return r===!0?g=f.booleanYesLabel:r===!1?g=f.booleanNoLabel:g=h,e.jsx("div",{className:N(Qt.booleanOutput,a),children:g})}const qt="_date-output_4jzjo_1",Gt={dateOutput:qt};function Yt(m){const{value:a,format:h,className:r,invalidText:f}=m,g=s.useMemo(()=>ft(a,h),[a,h]);return e.jsx("div",{className:N(Gt.dateOutput,r),children:g??f})}const Kt="_dropdown-menu_16hml_1",Xt="_icons_16hml_4",Jt="_content_16hml_5",ea="_actions_16hml_6",ta="_dropdown-icon_16hml_10",aa="_dropdown-content_16hml_16",le={dropdownMenu:Kt,icons:Xt,content:Jt,actions:ea,dropdownIcon:ta,dropdownContent:aa};function na(m){const a=s.useRef(null),{className:h,popupClassName:r,children:f,label:g,activeClassName:b,icons:_,variant:y="secondary",actions:x,withoutDropdownIcon:w,componentRef:C,elementRef:j=a,persistent:v,preferredPopupWidth:S}=m,p=s.useRef(null),[k,I]=s.useState(!1);s.useEffect(()=>{C&&(C.current={setShowDropdown:I})},[C,I]);const R=s.useCallback(()=>{I(re=>!re)},[I]),T=s.useCallback((re,ae)=>{ae||re&&v||I(!1)},[I,v]);vt(k,T,p,j);const G=s.useMemo(()=>({setShowDropdown:I}),[I]),U=!!x||!w;return e.jsxs(pt.Provider,{value:G,children:[e.jsx(Z,{name:void 0,className:N(le.dropdownMenu,k&&b,h),elementRef:j,onClick:R,variant:y,actionsContainerClassName:le.actions,iconsContainerClassName:le.icons,childrenContainerClassName:le.content,actions:U?e.jsxs(e.Fragment,{children:[x,!w&&(k?e.jsx(xt,{className:le.dropdownIcon}):e.jsx(_t,{className:le.dropdownIcon}))]}):void 0,icons:_,children:g}),k&&e.jsx(st,{elementRef:p,className:N(le.dropdownContent,r),parentRef:j,preferredWidth:S,children:f})]})}const sa="_info-popup_i3rna_1",ra="_label_i3rna_2",ia="_icon_i3rna_7",oa="_dropdown-container_i3rna_15",la="_content_i3rna_20",ge={infoPopup:sa,label:ra,icon:ia,dropdownContainer:oa,content:la};function ca(m){const{className:a,icon:h=e.jsx(Pt,{}),infoLabel:r,title:f,description:g,withoutIcon:b,popupClassName:_,descriptionClassName:y}=m;return e.jsx(na,{label:e.jsxs("div",{className:ge.label,children:[r,!b&&h&&e.jsx("div",{className:ge.icon,children:h})]}),popupClassName:N(ge.dropdownContainer,_),className:N(ge.infoPopup,a),variant:"tertiary",withoutDropdownIcon:!0,children:e.jsx(z,{heading:f,childrenContainerClassName:N(y,ge.content),withInternalPadding:!0,children:g})})}const da="_progress-wrapper_x340w_1",ua="_title_x340w_7",ma="_total_x340w_11",ha="_progress_x340w_1",fe={progressWrapper:da,title:ua,total:ma,progress:ha};function Ye(m){const{className:a,title:h,description:r,totalValue:f,value:g,showPercentageInTitle:b,children:_,color:y="var(--go-ui-color-primary-red)"}=m,x=se(g)?g:0,w=se(f)?f:0;let C;return w===0?C=0:C=x/w*100,e.jsxs("div",{className:N(fe.progressWrapper,a),children:[(h||b)&&e.jsxs("div",{className:fe.title,children:[h,b&&e.jsx(we,{value:C,suffix:"%"})]}),e.jsx("div",{className:fe.total,children:e.jsx("div",{className:fe.progress,style:{width:`${C}%`,backgroundColor:y}})}),r&&e.jsx("div",{className:fe.description,children:r}),_]})}const ga="_legend-element_1a9ic_1",fa="_color_1a9ic_7",va="_icon-container_1a9ic_14",pa="_icon_1a9ic_14",xa="_label_1a9ic_31",ve={legendElement:ga,color:fa,iconContainer:va,icon:pa,label:xa};function _a(m){const{className:a,colorClassName:h,iconClassName:r,color:f,label:g,iconSrc:b}=m;return e.jsxs("div",{className:N(ve.legendElement,a),children:[b?e.jsx("div",{style:{backgroundColor:f},className:ve.iconContainer,children:e.jsx("img",{className:N(ve.icon,r),src:b,alt:""})}):e.jsx("div",{style:{backgroundColor:f},className:N(ve.color,h)}),e.jsx("div",{className:ve.label,children:g})]})}const Ca="_text-output_10oza_1",ya="_with-background_10oza_6",ba="_label_10oza_11",ja="_with-colon_10oza_12",Na="_value_10oza_17",wa="_text-type_10oza_18",Sa="_strong_10oza_24",ee={textOutput:Ca,withBackground:ya,label:ba,withColon:ja,value:Na,textType:wa,strong:Sa};function Ke(m){const{className:a,label:h,icon:r,description:f,labelClassName:g,descriptionClassName:b,valueClassName:_,strongLabel:y,strongValue:x,strongDescription:w,withoutLabelColon:C,withBackground:j,invalidText:v=nt,...S}=m,{value:p}=m;let k=v;return S.valueType==="number"?k=e.jsx(we,{...S,invalidText:v}):S.valueType==="date"?k=e.jsx(Yt,{...S,invalidText:v}):S.valueType==="boolean"?k=e.jsx(Zt,{...S,invalidText:v}):p instanceof Date||(k=p||v),e.jsxs("div",{className:N(ee.textOutput,j&&ee.withBackground,a),children:[r,h&&e.jsx("div",{className:N(ee.label,y&&ee.strong,g,!C&&ee.withColon),children:h}),e.jsx("div",{className:N(ee.value,x&&ee.strong,S.valueType==="text"&&ee.textType,_),children:k}),f&&e.jsx("div",{className:N(ee.description,w&&ee.strong,b),children:f})]})}const Ma="_pie-chart_pyr7m_1",Ia="_legend_pyr7m_7",Da="_legend-item_pyr7m_13",pe={pieChart:Ma,legend:Ia,legendItem:Da},Ea=70,Ta=40;function Xe(m,a=1){return Math.round(m*10**a)/10**a}function Je(m,a){const h=(a-90)*Math.PI/180;return{x:Xe(m+m*Math.cos(h)),y:Xe(m+m*Math.sin(h))}}function ka(m,a,h){let r=h;const f=r-a===360;f&&(r-=1);const g=Je(m,a),b=Je(m,r),_=r-a<=180?0:1,y=["M",g.x,g.y,"A",m,m,0,_,1,b.x,b.y];return f?y.push("Z"):y.push("L",m,m,"L",g.x,g.y,"Z"),y.join(" ")}function xe(m){const{className:a,data:h,valueSelector:r,labelSelector:f,keySelector:g,colorSelector:b,colors:_,pieRadius:y=Ea,chartPadding:x=Ta,legendClassName:w,showPercentageInLegend:C}=m,j=Ct(h?.map(p=>r(p))),v=q(j)||j===0?1:j,S=s.useMemo(()=>{let p=0;const k=h?.map(I=>{const R=r(I);if(q(R))return;const T=360*(R/v);return p+=T,{key:g(I),value:R,label:f(I),startAngle:p-T,percentage:yt(R,v),endAngle:p,datum:I}}).filter(se)??[];return b?k.map(({datum:I,...R})=>({...R,color:b(I)})):k.map(({datum:I,...R},T)=>({...R,color:_[T%_.length]}))},[h,g,r,f,v,b,_]);return e.jsxs("div",{className:N(pe.pieChart,a),children:[e.jsx("svg",{className:pe.svg,style:{width:`${x+y*2}px`,height:`${x+y*2}px`},children:e.jsx("g",{style:{transform:`translate(${x/2}px, ${x/2}px)`},children:S.map(p=>e.jsx("path",{className:pe.path,d:ka(y,p.startAngle,p.endAngle),fill:p.color,children:e.jsx(Ht,{description:e.jsx(Ke,{label:p.label,value:p.value})})},p.key))})}),e.jsx("div",{className:N(pe.legend,w),children:S.map(p=>e.jsx(_a,{className:pe.legendItem,label:C?e.jsx(Ke,{label:p.label,value:p.percentage,valueType:"number",prefix:"(",suffix:"%)",withoutLabelColon:!0}):p.label,color:p.color},p.key))})]})}const La="_td_1k4cn_1",Pa={td:La};function Ra(m){const{className:a,children:h,...r}=m;return e.jsx("td",{className:N(a,Pa.td),...r,children:h})}function it(m){const{className:a,children:h,...r}=m;return e.jsx("tr",{className:a,...r,children:h})}const $a="_row_1829z_1",Ba="_cell_1829z_2",et={row:$a,cell:Ba};function Aa(m){const{data:a,keySelector:h,columns:r,rowClassName:f,cellClassName:g,rowModifier:b}=m;return e.jsx(e.Fragment,{children:a?.map((_,y)=>{const x=h(_,y),w=r.map(v=>{const{id:S,cellRenderer:p,cellRendererClassName:k,cellRendererParams:I,cellContainerClassName:R}=v,T=I(x,_,y,a),G=e.jsx(p,{className:k,...T,name:S});return e.jsx(Ra,{className:N(et.cell,R,typeof g=="function"?g(x,_,S):g),children:G},S)}),C=e.jsx(it,{className:N(et.row,typeof f=="function"?f(x,_):f),children:w});let j=C;return b&&(j=b({rowKey:x,row:C,cells:w,columns:r,datum:_})),e.jsx(s.Fragment,{children:j},x)})})}const Fa="_th_cdv41_1",Oa="_resize-handle_cdv41_8",tt={th:Fa,resizeHandle:Oa};function Ha(m){const{className:a,children:h,onResize:r,onResizeComplete:f,name:g,...b}=m,_=s.useRef(null),y=s.useRef(),x=s.useRef(),w=s.useRef(),C=s.useCallback(v=>{var S;if(se(y.current)&&_.current&&r){v.preventDefault(),v.stopPropagation();const p=v.clientX-y.current;if(se(x.current)){const k=x.current+p;w.current=k,r(k,g)}else x.current=(S=_.current)==null?void 0:S.offsetWidth}},[r,g]),j=s.useCallback(v=>{var S;v.preventDefault(),y.current=v.clientX,x.current=(S=_.current)==null?void 0:S.offsetWidth,window.addEventListener("mousemove",C,!0)},[C]);return s.useEffect(()=>{const v=()=>{y.current=void 0,x.current=void 0,f&&se(w.current)&&f(w.current,g),window.removeEventListener("mousemove",C,!0)};return window.addEventListener("mouseup",v,!0),()=>{window.removeEventListener("mouseup",v,!0),window.removeEventListener("mousemove",C,!0)}},[C,g,f]),e.jsxs("th",{ref:_,className:N(a,tt.th),...b,children:[r&&e.jsx("div",{role:"presentation",className:tt.resizeHandle,onMouseDown:j}),h]})}const Va="_table_nilhy_1",za="_table-overflow-wrapper_nilhy_8",Ua="_table-element_nilhy_13",Wa="_header-row_nilhy_23",Qa="_header-element_nilhy_24",Za="_header-component_nilhy_29",ce={table:Va,tableOverflowWrapper:za,tableElement:Ua,headerRow:Wa,headerElement:Qa,headerComponent:Za};function qa(m,a){return a??m.columnWidth??wt}function B(m){const{data:a,keySelector:h,columns:r,caption:f,className:g,captionClassName:b,headerRowClassName:_,headerCellClassName:y,rowClassName:x,cellClassName:w,rowModifier:C,fixedColumnWidth:j,resizableColumn:v,headersHidden:S,pending:p,filtered:k,errored:I=!1}=m,R=s.useRef(null),[T]=he.useState(()=>bt()),[G,U]=he.useState({});s.useEffect(()=>{U(W=>{if(q(R.current))return W;const E=R.current.getBoundingClientRect(),{width:O}=E;let A=r.map(M=>({id:M.id,stretch:!!M.columnStretch,width:qa(M,W[M.id])}));const X=ye(A.filter(M=>M.stretch).map(M=>M.width)),ne=ye(A.filter(M=>!M.stretch).map(M=>M.width)),Y=(O-ne)/X;return Y>1&&(A=A.map(M=>({...M,width:M.stretch?M.width*Y:M.width}))),jt(A,M=>M.id,M=>M.width)})},[r]);const re=he.useCallback((W,E)=>{const O=document.getElementById(`${T}-${E}`),A=Math.max(W,80);if(q(O)||(O.style.width=`${A}px`,!j))return;const X=document.getElementById(T);if(q(X))return;const ne=ye(r.map(Y=>Y.id===E?A:G[Y.id]));X.style.width=`${ne}px`},[T,G,r,j]),ae=he.useCallback((W,E)=>{se(E)&&U(O=>({...O,[E]:Math.max(W,80)}))},[U]),be=he.useMemo(()=>ye(r.map(W=>G[W.id])),[G,r]),K=q(a)||a.length===0||Object.keys(G).length===0;return e.jsxs("div",{ref:R,className:N(ce.table,g),children:[!K&&e.jsx("div",{className:ce.tableOverflowWrapper,children:e.jsxs("table",{className:ce.tableElement,style:j?{width:`${be}px`}:void 0,id:T,children:[f&&e.jsx("caption",{className:b,children:f}),e.jsx("colgroup",{children:r.map(W=>{const{id:E,columnClassName:O}=W,A=G[E],X=j?{width:`${A}px`}:void 0;return e.jsx("col",{id:`${T}-${E}`,style:X,className:N(ce.column,O)},E)})}),!S&&e.jsx("thead",{children:e.jsx(it,{className:N(ce.headerRow,_),children:r.map((W,E)=>{const{id:O,title:A,headerCellRenderer:X,headerCellRendererClassName:ne,headerCellRendererParams:Y,headerContainerClassName:M}=W,ie=e.jsx(X,{...Y,name:O,title:A,index:E,className:N(ne,ce.headerComponent)});return e.jsx(Ha,{scope:"col",name:O,onResize:v?re:void 0,onResizeComplete:v?ae:void 0,className:N(ce.headerElement,typeof y=="function"?y(O):y,M),children:ie},O)})})}),e.jsx("tbody",{children:e.jsx(Aa,{data:a,keySelector:h,columns:r,rowClassName:x,cellClassName:w,rowModifier:C})})]})}),e.jsx(Nt,{filtered:k,empty:K,errored:I,pending:p,overlayPending:!0})]})}function Ga(m){const{className:a,value:h}=m;return q(h)?null:e.jsx("div",{className:a,children:h})}const Ya="common",Ka={sortTableButtonTitle:"Sort Table"},Xa={namespace:Ya,strings:Ka},Ja="_header-cell_vn24d_1",en="_sort-button_vn24d_8",tn="_icon_vn24d_12",an="_info-popup-icon_vn24d_17",de={headerCell:Ja,sortButton:en,icon:tn,infoPopupIcon:an};function ot(m){const{className:a,titleClassName:h,title:r,name:f,sortable:g,defaultSortDirection:b="asc",infoTitle:_,infoDescription:y}=m,{sorting:x,setSorting:w}=s.useContext(St),C=rt(Xa),j=x?.name===f?x.direction:void 0,v=s.useRef(null),S=s.useCallback(()=>{if(q(w))return;let p;q(j)?p=b:j==="asc"?p="dsc":j==="dsc"&&(p="asc"),w(p?{name:f,direction:p}:void 0)},[f,w,j,b]);return e.jsxs("div",{ref:v,className:N(a,de.headerCell),children:[g&&e.jsxs(Z,{name:void 0,variant:"tertiary",onClick:S,title:C.sortTableButtonTitle,className:de.sortButton,children:[q(j)&&e.jsx(Rt,{className:de.icon}),j==="asc"&&e.jsx(Lt,{className:de.icon}),j==="dsc"&&e.jsx(kt,{className:de.icon})]}),e.jsx("div",{className:N(h,de.title),children:r}),_&&y&&e.jsx(ca,{className:de.infoPopupIcon,title:_,description:y})]})}const at={};function Q(m,a,h,r){return{id:m,title:a,columnClassName:r?.columnClassName,headerCellRenderer:ot,headerCellRendererClassName:r?.headerCellRendererClassName,headerContainerClassName:r?.headerContainerClassName,headerCellRendererParams:{sortable:r?.sortable,infoTitle:r?.headerInfoTitle,infoDescription:r?.headerInfoDescription},cellRendererClassName:r?.cellRendererClassName,cellContainerClassName:r?.cellContainerClassName,cellRenderer:Ga,cellRendererParams:(f,g)=>({value:h(g)||"--"}),valueSelector:h,valueComparator:(f,g)=>Mt(h(f),h(g)),columnWidth:r?.columnWidth,columnStretch:r?.columnStretch,columnStyle:r?.columnStyle}}function D(m,a,h,r){return{id:m,title:a,columnClassName:r?.columnClassName,headerCellRenderer:ot,headerCellRendererClassName:N(at.numberCellHeader,r?.headerCellRendererClassName),headerContainerClassName:r?.headerContainerClassName,headerCellRendererParams:{sortable:r?.sortable,infoTitle:r?.headerInfoTitle,infoDescription:r?.headerInfoDescription},cellRendererClassName:N(at.numberCell,r?.cellRendererClassName),cellContainerClassName:r?.cellContainerClassName,cellRenderer:we,cellRendererParams:(f,g)=>({value:h(g),suffix:r?.suffix,maximumFractionDigits:r?.maximumFractionDigits,invalidText:"--"}),valueSelector:h,valueComparator:(f,g)=>It(h(f),h(g)),columnWidth:r?.columnWidth,columnStretch:r?.columnStretch,columnStyle:r?.columnStyle}}const nn="_tabSelector_vlxoe_1",sn="_progressSection_vlxoe_14",rn="_progressLabel_vlxoe_20",on="_chartGrid_vlxoe_28",ln="_chartContainer_vlxoe_40",cn="_tableContainer_vlxoe_51",dn="_modelPerformance_vlxoe_59",un="_loadingContainer_vlxoe_67",mn="_errorContainer_vlxoe_77",hn="_userInteractionCards_vlxoe_96",gn="_userInteractionCard_vlxoe_96",fn="_userInteractionCardValue_vlxoe_116",vn="_userInteractionCardLabel_vlxoe_123",pn="_userInteractionCardButton_vlxoe_130",xn="_summaryStatsCards_vlxoe_148",_n="_summaryStatsCard_vlxoe_148",Cn="_summaryStatsCardValue_vlxoe_169",yn="_summaryStatsCardLabel_vlxoe_176",c={tabSelector:nn,progressSection:sn,progressLabel:rn,chartGrid:on,chartContainer:ln,tableContainer:cn,modelPerformance:dn,loadingContainer:un,errorContainer:mn,userInteractionCards:hn,userInteractionCard:gn,userInteractionCardValue:fn,userInteractionCardLabel:vn,userInteractionCardButton:pn,summaryStatsCards:xn,summaryStatsCard:_n,summaryStatsCardValue:Cn,summaryStatsCardLabel:yn};function jn(){const[m]=Dt(),[a,h]=s.useState(null),[r,f]=s.useState(!0),[g,b]=s.useState("crisis_maps"),[_,y]=s.useState([]),[x,w]=s.useState([]),[C,j]=s.useState([]),[v,S]=s.useState([]),[p,k]=s.useState(!1),[I,R]=s.useState(!1),[T,G]=s.useState(!1),[U,re]=s.useState(!1),[ae,be]=s.useState(!1),[K,W]=s.useState(!1),E=t=>{k(t==="editTime"),R(t==="percentage"),G(t==="delete"),re(t==="regions"),be(t==="sources"),W(t==="types")},O=[{key:"crisis_maps",label:"Crisis Maps"},{key:"drone_images",label:"Drone Images"}],A=s.useCallback((t,l)=>{if(!t||!l)return 0;const i=t.toLowerCase().replace(/[^\w\s]/g,"").split(/\s+/).filter(u=>u.length>0),n=l.toLowerCase().replace(/[^\w\s]/g,"").split(/\s+/).filter(u=>u.length>0);if(i.length===0&&n.length===0)return 1;if(i.length===0||n.length===0)return 0;const o=new Set(i),d=new Set(n),P=new Set([...o].filter(u=>d.has(u))),F=new Set([...o,...d]);return P.size/F.size},[]),X=s.useCallback(async()=>{f(!0);try{const l=await(await fetch("/api/images")).json(),i={},n=l.filter(u=>u.image_type==="crisis_map"),o=l.filter(u=>u.image_type==="drone_image"),d={totalCaptions:l.length,sources:{},types:{},regions:{},models:{},modelEditTimes:i,percentageModified:0,modelPercentageData:{},totalDeleteCount:0,deleteRate:0,crisisMaps:n,droneImages:o};l.forEach(u=>{if(u.source&&(d.sources[u.source]=(d.sources[u.source]||0)+1),u.event_type&&(d.types[u.event_type]=(d.types[u.event_type]||0)+1),u.countries&&u.countries.forEach(L=>{L.r_code&&(d.regions[L.r_code]=(d.regions[L.r_code]||0)+1)}),u.model){const L=u.model,V=d.models[L]||={count:0,avgAccuracy:0,avgContext:0,avgUsability:0,totalScore:0,deleteCount:0};if(V.count++,u.accuracy!=null&&(V.avgAccuracy+=u.accuracy),u.context!=null&&(V.avgContext+=u.context),u.usability!=null&&(V.avgUsability+=u.usability),u.created_at&&u.updated_at){const te=new Date(u.created_at).getTime(),Ce=new Date(u.updated_at).getTime()-te;Ce>0&&(i[L]||(i[L]=[]),i[L].push(Ce))}}}),_.forEach(u=>{u.s_code&&!d.sources[u.s_code]&&(d.sources[u.s_code]=0)}),x.forEach(u=>{u.t_code&&!d.types[u.t_code]&&(d.types[u.t_code]=0)}),C.forEach(u=>{u.r_code&&!d.regions[u.r_code]&&(d.regions[u.r_code]=0)}),["GPT-4","Claude","Gemini","Llama","Other"].forEach(u=>{d.models[u]||(d.models[u]={count:0,avgAccuracy:0,avgContext:0,avgUsability:0,totalScore:0,deleteCount:0})}),Object.values(d.models).forEach(u=>{u.count>0&&(u.avgAccuracy=Math.round(u.avgAccuracy/u.count),u.avgContext=Math.round(u.avgContext/u.count),u.avgUsability=Math.round(u.avgUsability/u.count),u.totalScore=Math.round((u.avgAccuracy+u.avgContext+u.avgUsability)/3))});const F=l.filter(u=>u.generated&&u.edited);if(F.length>0){const L=[...F.map(oe=>A(oe.generated,oe.edited))].sort((oe,Ce)=>oe-Ce),V=Math.floor(L.length/2),te=L.length%2===0?(L[V-1]+L[V])/2:L[V];d.percentageModified=Math.round((1-te)*100)}const H={};l.forEach(u=>{if(u.model&&u.generated&&u.edited){const L=A(u.generated,u.edited),V=Math.round((1-L)*100);H[u.model]||(H[u.model]=[]),H[u.model].push(V)}}),d.modelPercentageData=H;try{const u=await fetch("/api/models");if(u.ok){const L=await u.json();if(L.models){L.models.forEach(te=>{d.models[te.m_code]&&(d.models[te.m_code].deleteCount=te.delete_count||0)});const V=L.models.reduce((te,oe)=>te+(oe.delete_count||0),0);d.totalDeleteCount=V,d.deleteRate=V>0?Math.round(V/(V+l.length)*100):0}}}catch(u){console.log("Could not fetch model delete counts:",u)}h(d)}catch{h(null)}finally{f(!1)}},[_,x,C,A]),ne=s.useCallback(async()=>{try{const[t,l,i,n]=await Promise.all([fetch("/api/sources"),fetch("/api/types"),fetch("/api/regions"),fetch("/api/models")]),o=await t.json(),d=await l.json(),P=await i.json(),F=await n.json();y(o),w(d),j(P),S(F.models||[])}catch(t){console.log("Could not fetch lookup data:",t)}},[]);s.useEffect(()=>{const t=m.get("view");(t==="crisis_maps"||t==="drone_images")&&b(t)},[m]),s.useEffect(()=>{ne()},[ne]),s.useEffect(()=>{_.length>0&&x.length>0&&C.length>0&&v.length>0&&X()},[_,x,C,v,X]);const Y=s.useCallback(t=>{const l=_.find(i=>i.s_code===t);return l?l.label:t},[_]),M=s.useCallback(t=>{if(t.length===0)return 0;const l=[...t].sort((n,o)=>n-o),i=Math.floor(l.length/2);return l.length%2===0?Math.round((l[i-1]+l[i])/2):l[i]},[]),ie=s.useCallback(t=>{const l=Math.floor(t/1e3),i=Math.floor(l/60),n=Math.floor(i/60);return n>0?`${n}h ${i%60}m`:i>0?`${i}m ${l%60}s`:`${l}s`},[]),_e=s.useCallback(t=>{const l=x.find(i=>i.t_code===t);return l?l.label:t},[x]),J=s.useCallback(t=>{const l=v.find(i=>i.m_code===t);return l?l.label:t},[v]),Se=s.useMemo(()=>a?Object.entries(a.modelEditTimes||{}).filter(([,t])=>t.length>0).sort(([,t],[,l])=>M(l)-M(t)).map(([t,l],i)=>({id:i+1,name:J(t),count:l.length,avgEditTime:M(l),minEditTime:Math.min(...l),maxEditTime:Math.max(...l)})):[],[a,M,J]),Me=s.useMemo(()=>a?Object.entries(a.modelPercentageData||{}).filter(([,t])=>t.length>0).sort(([,t],[,l])=>{const i=[...t].sort((H,u)=>H-u),n=[...l].sort((H,u)=>H-u),o=Math.floor(i.length/2),d=Math.floor(n.length/2),P=i.length%2===0?(i[o-1]+i[o])/2:i[o];return(n.length%2===0?(n[d-1]+n[d])/2:n[d])-P}).map(([t,l],i)=>{const n=[...l].sort((P,F)=>P-F),o=Math.floor(n.length/2),d=n.length%2===0?Math.round((n[o-1]+n[o])/2):n[o];return{id:i+1,name:J(t),count:l.length,avgPercentageModified:d,minPercentageModified:Math.min(...l),maxPercentageModified:Math.max(...l)}}):[],[a,J]),Ie=s.useMemo(()=>a?Object.entries(a.models).filter(([,t])=>t.count>0).map(([t,l],i)=>{const n=[l.avgAccuracy,l.avgContext,l.avgUsability],o=n.reduce((F,H)=>F+H,0)/n.length,d=n.reduce((F,H)=>F+Math.pow(H-o,2),0)/n.length,P=Math.round(100-Math.sqrt(d));return{id:i+1,name:J(t),consistency:Math.max(0,P),avgScore:Math.round(o),count:l.count}}).sort((t,l)=>l.consistency-t.consistency):[],[a,J]),De=s.useMemo(()=>[Q("name","Region",t=>t.name),D("count","Count",t=>t.count),D("percentage","% of Total",t=>t.percentage,{suffix:"%",maximumFractionDigits:0})],[]),Ee=s.useMemo(()=>[Q("name","Type",t=>t.name),D("count","Count",t=>t.count),D("percentage","% of Total",t=>t.percentage,{suffix:"%",maximumFractionDigits:0})],[]),lt=s.useMemo(()=>[Q("name","Source",t=>t.name),D("count","Count",t=>t.count),D("percentage","% of Total",t=>t.percentage,{suffix:"%",maximumFractionDigits:0})],[]),Te=s.useMemo(()=>[Q("name","Model",t=>t.name),D("count","Count",t=>t.count),D("accuracy","Accuracy",t=>t.accuracy,{suffix:"%",maximumFractionDigits:0}),D("context","Context",t=>t.context,{suffix:"%",maximumFractionDigits:0}),D("usability","Usability",t=>t.usability,{suffix:"%",maximumFractionDigits:0}),D("totalScore","Total Score",t=>t.totalScore,{suffix:"%",maximumFractionDigits:0})],[]),ke=s.useMemo(()=>[Q("name","Model",t=>t.name),D("count","Count",t=>t.count),Q("avgEditTime","Median Edit Time",t=>ie(t.avgEditTime)),Q("minEditTime","Min Edit Time",t=>ie(t.minEditTime)),Q("maxEditTime","Max Edit Time",t=>ie(t.maxEditTime))],[]),Le=s.useMemo(()=>[Q("name","Model",t=>t.name),D("count","Count",t=>t.count),D("avgPercentageModified","Median % Modified",t=>t.avgPercentageModified,{suffix:"%",maximumFractionDigits:0}),D("minPercentageModified","Min % Modified",t=>t.minPercentageModified,{suffix:"%",maximumFractionDigits:0}),D("maxPercentageModified","Max % Modified",t=>t.maxPercentageModified,{suffix:"%",maximumFractionDigits:0})],[]),Pe=s.useMemo(()=>[Q("name","Model",t=>t.name),D("count","Total Count",t=>t.count),D("deleteCount","Delete Count",t=>t.deleteCount),D("deleteRate","Delete Rate",t=>t.deleteRate,{suffix:"%",maximumFractionDigits:1})],[]),ct=s.useMemo(()=>[Q("source","Source",t=>t.source),D("avgQuality","Average Quality",t=>t.avgQuality,{suffix:"%",maximumFractionDigits:0}),D("count","Count",t=>t.count)],[]),Re=s.useMemo(()=>[Q("eventType","Event Type",t=>t.eventType),D("avgQuality","Average Quality",t=>t.avgQuality,{suffix:"%",maximumFractionDigits:0}),D("count","Count",t=>t.count)],[]),$e=s.useMemo(()=>[Q("name","Model",t=>t.name),D("consistency","Consistency",t=>t.consistency,{suffix:"%",maximumFractionDigits:0}),D("avgScore","Average Score",t=>t.avgScore,{suffix:"%",maximumFractionDigits:0}),D("count","Count",t=>t.count)],[]),ue=s.useCallback(t=>a?t==="crisis_map"?a.crisisMaps.length:t==="drone_image"?a.droneImages.length:0:0,[a]),Be=s.useCallback(t=>{if(!a)return[];const l=t==="crisis_map"?a.crisisMaps:a.droneImages,i={};return l.forEach(n=>{n.countries&&n.countries.forEach(o=>{o.r_code&&(i[o.r_code]=(i[o.r_code]||0)+1)})}),Object.entries(i).filter(([,n])=>n>0).map(([n,o])=>({name:C.find(d=>d.r_code===n)?.label||n,value:o}))},[a,C]),Ae=s.useCallback(t=>{if(!a)return[];const l=t==="crisis_map"?a.crisisMaps:a.droneImages,i={};l.forEach(o=>{o.countries&&o.countries.forEach(d=>{d.r_code&&(i[d.r_code]=(i[d.r_code]||0)+1)})});const n=C.reduce((o,d)=>(d.r_code&&(o[d.r_code]={name:d.label,count:i[d.r_code]||0}),o),{});return Object.entries(n).sort(([,o],[,d])=>d.count-o.count).map(([,{name:o,count:d}],P)=>({id:P+1,name:o,count:d,percentage:l.length>0?Math.round(d/l.length*100):0}))},[a,C]),dt=s.useCallback(t=>{if(!a)return[];const l=t==="crisis_map"?a.crisisMaps:a.droneImages,i={};return l.forEach(n=>{n.source&&(i[n.source]=(i[n.source]||0)+1)}),Object.entries(i).filter(([,n])=>n>0).map(([n,o])=>({name:_.find(d=>d.s_code===n)?.label||n,value:o}))},[a,_]),ut=s.useCallback(t=>{if(!a)return[];const l=t==="crisis_map"?a.crisisMaps:a.droneImages,i={};return l.forEach(n=>{n.source&&(i[n.source]=(i[n.source]||0)+1)}),Object.entries(i).sort(([,n],[,o])=>o-n).map(([n,o],d)=>({id:d+1,name:Y(n),count:o,percentage:l.length>0?Math.round(o/l.length*100):0}))},[a,Y]),Fe=s.useCallback(t=>{if(!a)return[];const l=t==="crisis_map"?a.crisisMaps:a.droneImages,i={};return l.forEach(n=>{n.event_type&&(i[n.event_type]=(i[n.event_type]||0)+1)}),Object.entries(i).filter(([,n])=>n>0).map(([n,o])=>({name:x.find(d=>d.t_code===n)?.label||n,value:o}))},[a,x]),Oe=s.useCallback(t=>{if(!a)return[];const l=t==="crisis_map"?a.crisisMaps:a.droneImages,i={};return l.forEach(n=>{n.event_type&&(i[n.event_type]=(i[n.event_type]||0)+1)}),Object.entries(i).sort(([,n],[,o])=>o-n).map(([n,o],d)=>({id:d+1,name:_e(n),count:o,percentage:l.length>0?Math.round(o/l.length*100):0}))},[a,_e]),He=s.useCallback(t=>{if(!a)return"No data available";const l=t==="crisis_map"?a.crisisMaps:a.droneImages,i=new Set;l.forEach(d=>{d.model&&i.add(d.model)}),console.log(`Debug ${t}:`,{totalImages:l.length,usedModels:Array.from(i),availableEditTimes:Object.keys(a.modelEditTimes),modelEditTimesData:a.modelEditTimes});const o=Object.entries(a.modelEditTimes).filter(([d])=>i.has(d)).flatMap(([,d])=>d);return o.length===0?"No data available":ie(M(o))},[a,ie,M]),Ve=s.useCallback(()=>{if(!a)return"No data available";const t=a.totalCaptions||0,l=a.percentageModified||0;return t>0?Math.round(l/t*100):0},[a]),ze=s.useCallback(()=>a&&a.deleteRate>=0?`${a.deleteRate}%`:"No data available",[a]),Ue=s.useCallback(t=>{if(!a)return[];const l=t==="crisis_map"?a.crisisMaps:a.droneImages,i=new Set;return l.forEach(o=>{o.model&&i.add(o.model)}),Se.filter(o=>{const d=v.find(P=>P.label===o.name)?.m_code;return d&&i.has(d)})},[a,Se,v]),We=s.useCallback(t=>{if(!a)return[];const l=t==="crisis_map"?a.crisisMaps:a.droneImages,i=new Set;return l.forEach(o=>{o.model&&i.add(o.model)}),Me.filter(o=>{const d=v.find(P=>P.label===o.name)?.m_code;return d&&i.has(d)})},[a,Me,v]),Qe=s.useCallback(t=>{if(!a)return[];const l=t==="crisis_map"?a.crisisMaps:a.droneImages,i={};return l.forEach(n=>{n.model&&(i[n.model]||(i[n.model]={count:0,deleteCount:0}),i[n.model].count++)}),Object.entries(i).map(([n,o],d)=>{const F=a.models?.[n]?.deleteCount||0,H=o.count>0?Math.round(F/o.count*100*10)/10:0;return{id:d+1,name:J(n),count:o.count,deleteCount:F,deleteRate:H}}).sort((n,o)=>o.count-n.count)},[a,J]),Ze=s.useCallback(t=>{if(!a)return[];const l=t==="crisis_map"?a.crisisMaps:a.droneImages,i={};return l.forEach(n=>{n.model&&(i[n.model]||(i[n.model]={count:0,totalAccuracy:0,totalContext:0,totalUsability:0}),i[n.model].count++,n.accuracy!=null&&(i[n.model].totalAccuracy+=n.accuracy),n.context!=null&&(i[n.model].totalContext+=n.context),n.usability!=null&&(i[n.model].totalUsability+=n.usability))}),Object.entries(i).map(([n,o],d)=>({id:d+1,name:J(n),count:o.count,accuracy:o.count>0?Math.round(o.totalAccuracy/o.count):0,context:o.count>0?Math.round(o.totalContext/o.count):0,usability:o.count>0?Math.round(o.totalUsability/o.count):0,totalScore:o.count>0?Math.round((o.totalAccuracy+o.totalContext+o.totalUsability)/(3*o.count)):0})).sort((n,o)=>o.totalScore-n.totalScore)},[a,J]),mt=s.useCallback(t=>{if(!a)return[];const l=t==="crisis_map"?a.crisisMaps:a.droneImages,i={};return l.forEach(n=>{n.source&&(i[n.source]||(i[n.source]={total:0,count:0,totalImages:0}),i[n.source].totalImages+=1,n.accuracy!=null&&(i[n.source].total+=n.accuracy,i[n.source].count+=1))}),Object.entries(i).map(([n,o],d)=>({id:d+1,source:Y(n),avgQuality:o.count>0?Math.round(o.total/o.count):0,count:o.totalImages}))},[a,Y]),qe=s.useCallback(t=>{if(!a)return[];const l=t==="crisis_map"?a.crisisMaps:a.droneImages,i={};return l.forEach(n=>{n.event_type&&(i[n.event_type]||(i[n.event_type]={total:0,count:0,totalImages:0}),i[n.event_type].totalImages+=1,n.accuracy!=null&&(i[n.event_type].total+=n.accuracy,i[n.event_type].count+=1))}),Object.entries(i).map(([n,o],d)=>({id:d+1,eventType:_e(n),avgQuality:o.count>0?Math.round(o.total/o.count):0,count:o.totalImages}))},[a,_e]),Ge=s.useCallback(t=>{if(!a)return[];const l=t==="crisis_map"?a.crisisMaps:a.droneImages,i=new Set;return l.forEach(o=>{o.model&&i.add(o.model)}),Ie.filter(o=>{const d=v.find(P=>P.label===o.name)?.m_code;return d&&i.has(d)})},[a,Ie,v]);if(r)return e.jsx(je,{children:e.jsx("div",{className:c.loadingContainer,children:e.jsx(Et,{})})});if(!a)return e.jsx(je,{children:e.jsx("div",{className:c.errorContainer,children:e.jsx("div",{className:"text-red-500",children:"Failed to load analytics data. Please try again."})})});const me=["#F5333F","#F64752","#F75C65","#F87079","#F9858C","#FA999F","#FBADB2","#FCC2C5"];return e.jsx(je,{children:e.jsxs("div",{className:"max-w-7xl mx-auto",children:[e.jsx("div",{className:c.tabSelector,children:e.jsx(Tt,{name:"analytics-view",value:g,onChange:t=>{(t==="crisis_maps"||t==="drone_images")&&b(t)},options:O,keySelector:t=>t.key,labelSelector:t=>t.label})}),g==="crisis_maps"?e.jsxs("div",{className:c.chartGrid,children:[e.jsxs(z,{heading:"Summary Statistics",headingLevel:3,withHeaderBorder:!0,withInternalPadding:!0,children:[e.jsxs("div",{className:c.summaryStatsCards,children:[e.jsxs("div",{className:c.summaryStatsCard,children:[e.jsx("div",{className:c.summaryStatsCardValue,children:ue("crisis_map")}),e.jsx("div",{className:c.summaryStatsCardLabel,children:"Total Crisis Maps"})]}),e.jsxs("div",{className:c.summaryStatsCard,children:[e.jsx("div",{className:c.summaryStatsCardValue,children:"2000"}),e.jsx("div",{className:c.summaryStatsCardLabel,children:"Target Amount"})]})]}),e.jsxs("div",{className:c.progressSection,children:[e.jsxs("div",{className:c.progressLabel,children:[e.jsx("span",{children:"Progress towards target"}),e.jsxs("span",{children:[Math.round(ue("crisis_map")/2e3*100),"%"]})]}),e.jsx(Ye,{value:ue("crisis_map"),totalValue:2e3})]})]}),e.jsxs(z,{heading:"Distribution Analysis",headingLevel:3,withHeaderBorder:!0,withInternalPadding:!0,children:[e.jsxs("div",{className:c.userInteractionCards,children:[e.jsxs("div",{className:c.userInteractionCard,children:[e.jsx("div",{className:c.userInteractionCardLabel,children:"Regions Distribution"}),e.jsx("div",{className:c.chartContainer,children:e.jsx(xe,{data:Be("crisis_map"),valueSelector:t=>t.value,labelSelector:t=>t.name,keySelector:t=>t.name,colors:me,showPercentageInLegend:!0})}),e.jsx(Z,{name:"view-regions-details",variant:U?"primary":"secondary",onClick:()=>E(U?"none":"regions"),className:c.userInteractionCardButton,children:U?"Hide Details":"View Details"})]}),e.jsxs("div",{className:c.userInteractionCard,children:[e.jsx("div",{className:c.userInteractionCardLabel,children:"Sources Distribution"}),e.jsx("div",{className:c.chartContainer,children:e.jsx(xe,{data:dt("crisis_map"),valueSelector:t=>t.value,labelSelector:t=>t.name,keySelector:t=>t.name,colors:me,showPercentageInLegend:!0})}),e.jsx(Z,{name:"view-sources-details",variant:ae?"primary":"secondary",onClick:()=>E(ae?"none":"sources"),className:c.userInteractionCardButton,children:ae?"Hide Details":"View Details"})]}),e.jsxs("div",{className:c.userInteractionCard,children:[e.jsx("div",{className:c.userInteractionCardLabel,children:"Types Distribution"}),e.jsx("div",{className:c.chartContainer,children:e.jsx(xe,{data:Fe("crisis_map"),valueSelector:t=>t.value,labelSelector:t=>t.name,keySelector:t=>t.name,colors:me,showPercentageInLegend:!0})}),e.jsx(Z,{name:"view-types-details",variant:K?"primary":"secondary",onClick:()=>E(K?"none":"types"),className:c.userInteractionCardButton,children:K?"Hide Details":"View Details"})]})]}),U&&e.jsx("div",{className:c.modelPerformance,children:e.jsx(B,{data:Ae("crisis_map"),columns:De,keySelector:$,filtered:!1,pending:!1})}),ae&&e.jsx("div",{className:c.modelPerformance,children:e.jsx(B,{data:ut("crisis_map"),columns:lt,keySelector:$,filtered:!1,pending:!1})}),K&&e.jsx("div",{className:c.modelPerformance,children:e.jsx(B,{data:Oe("crisis_map"),columns:Ee,keySelector:$,filtered:!1,pending:!1})})]}),e.jsxs(z,{heading:"User Interaction Statistics",headingLevel:3,withHeaderBorder:!0,withInternalPadding:!0,children:[e.jsxs("div",{className:c.userInteractionCards,children:[e.jsxs("div",{className:c.userInteractionCard,children:[e.jsx("div",{className:c.userInteractionCardValue,children:He("crisis_map")}),e.jsx("div",{className:c.userInteractionCardLabel,children:"Median Edit Time"}),e.jsx(Z,{name:"view-edit-time-details",variant:p?"primary":"secondary",onClick:()=>E(p?"none":"editTime"),className:c.userInteractionCardButton,children:p?"Hide Details":"View Details"})]}),e.jsxs("div",{className:c.userInteractionCard,children:[e.jsx("div",{className:c.userInteractionCardValue,children:Ve()}),e.jsx("div",{className:c.userInteractionCardLabel,children:"Median % Modified"}),e.jsx(Z,{name:"view-percentage-details",variant:I?"primary":"secondary",onClick:()=>E(I?"none":"percentage"),className:c.userInteractionCardButton,children:I?"Hide Details":"View Details"})]}),e.jsxs("div",{className:c.userInteractionCard,children:[e.jsx("div",{className:c.userInteractionCardValue,children:ze()}),e.jsx("div",{className:c.userInteractionCardLabel,children:"Delete Rate"}),e.jsx(Z,{name:"view-delete-details",variant:T?"primary":"secondary",onClick:()=>E(T?"none":"delete"),className:c.userInteractionCardButton,children:T?"Hide Details":"View Details"})]})]}),p&&e.jsx("div",{className:c.modelPerformance,children:e.jsx(B,{data:Ue("crisis_map"),columns:ke,keySelector:$,filtered:!1,pending:!1})}),I&&e.jsx("div",{className:c.modelPerformance,children:e.jsx(B,{data:We("crisis_map"),columns:Le,keySelector:$,filtered:!1,pending:!1})}),T&&e.jsx("div",{className:c.modelPerformance,children:e.jsx(B,{data:Qe("crisis_map"),columns:Pe,keySelector:$,filtered:!1,pending:!1})})]}),e.jsx(z,{heading:"Model Performance",headingLevel:3,withHeaderBorder:!0,withInternalPadding:!0,children:e.jsx("div",{className:c.modelPerformance,children:e.jsx(B,{data:Ze("crisis_map"),columns:Te,keySelector:$,filtered:!1,pending:!1})})}),e.jsx(z,{heading:"Quality-Source Correlation",headingLevel:3,withHeaderBorder:!0,withInternalPadding:!0,children:e.jsx("div",{className:c.tableContainer,children:e.jsx(B,{data:mt("crisis_map"),columns:ct,keySelector:$,filtered:!1,pending:!1})})}),e.jsx(z,{heading:"Quality-Event Type Correlation",headingLevel:3,withHeaderBorder:!0,withInternalPadding:!0,children:e.jsx("div",{className:c.tableContainer,children:e.jsx(B,{data:qe("crisis_map"),columns:Re,keySelector:$,filtered:!1,pending:!1})})}),e.jsx(z,{heading:"Model Consistency Analysis",headingLevel:3,withHeaderBorder:!0,withInternalPadding:!0,children:e.jsx("div",{className:c.tableContainer,children:e.jsx(B,{data:Ge("crisis_map"),columns:$e,keySelector:$,filtered:!1,pending:!1})})})]}):e.jsxs("div",{className:c.chartGrid,children:[e.jsxs(z,{heading:"Summary Statistics",headingLevel:3,withHeaderBorder:!0,withInternalPadding:!0,children:[e.jsxs("div",{className:c.summaryStatsCards,children:[e.jsxs("div",{className:c.summaryStatsCard,children:[e.jsx("div",{className:c.summaryStatsCardValue,children:ue("drone_image")}),e.jsx("div",{className:c.summaryStatsCardLabel,children:"Total Drone Images"})]}),e.jsxs("div",{className:c.summaryStatsCard,children:[e.jsx("div",{className:c.summaryStatsCardValue,children:"2000"}),e.jsx("div",{className:c.summaryStatsCardLabel,children:"Target Amount"})]})]}),e.jsxs("div",{className:c.progressSection,children:[e.jsxs("div",{className:c.progressLabel,children:[e.jsx("span",{children:"Progress towards target"}),e.jsxs("span",{children:[Math.round(ue("drone_image")/2e3*100),"%"]})]}),e.jsx(Ye,{value:ue("drone_image"),totalValue:2e3})]})]}),e.jsxs(z,{heading:"Distribution Analysis",headingLevel:3,withHeaderBorder:!0,withInternalPadding:!0,children:[e.jsxs("div",{className:c.userInteractionCards,children:[e.jsxs("div",{className:c.userInteractionCard,children:[e.jsx("div",{className:c.userInteractionCardLabel,children:"Regions Distribution"}),e.jsx("div",{className:c.chartContainer,children:e.jsx(xe,{data:Be("drone_image"),valueSelector:t=>t.value,labelSelector:t=>t.name,keySelector:t=>t.name,colors:me,showPercentageInLegend:!0})}),e.jsx(Z,{name:"view-regions-details",variant:U?"primary":"secondary",onClick:()=>E(U?"none":"regions"),className:c.userInteractionCardButton,children:U?"Hide Details":"View Details"})]}),e.jsxs("div",{className:c.userInteractionCard,children:[e.jsx("div",{className:c.userInteractionCardLabel,children:"Types Distribution"}),e.jsx("div",{className:c.chartContainer,children:e.jsx(xe,{data:Fe("drone_image"),valueSelector:t=>t.value,labelSelector:t=>t.name,keySelector:t=>t.name,colors:me,showPercentageInLegend:!0})}),e.jsx(Z,{name:"view-types-details",variant:K?"primary":"secondary",onClick:()=>E(K?"none":"types"),className:c.userInteractionCardButton,children:K?"Hide Details":"View Details"})]})]}),U&&e.jsx("div",{className:c.modelPerformance,children:e.jsx(B,{data:Ae("drone_image"),columns:De,keySelector:$,filtered:!1,pending:!1})}),K&&e.jsx("div",{className:c.modelPerformance,children:e.jsx(B,{data:Oe("drone_image"),columns:Ee,keySelector:$,filtered:!1,pending:!1})})]}),e.jsxs(z,{heading:"User Interaction Statistics",headingLevel:3,withHeaderBorder:!0,withInternalPadding:!0,children:[e.jsxs("div",{className:c.userInteractionCards,children:[e.jsxs("div",{className:c.userInteractionCard,children:[e.jsx("div",{className:c.userInteractionCardValue,children:He("drone_image")}),e.jsx("div",{className:c.userInteractionCardLabel,children:"Median Edit Time"}),e.jsx(Z,{name:"view-edit-time-details",variant:p?"primary":"secondary",onClick:()=>E(p?"none":"editTime"),className:c.userInteractionCardButton,children:p?"Hide Details":"View Details"})]}),e.jsxs("div",{className:c.userInteractionCard,children:[e.jsx("div",{className:c.userInteractionCardValue,children:Ve()}),e.jsx("div",{className:c.userInteractionCardLabel,children:"Median % Modified"}),e.jsx(Z,{name:"view-percentage-details",variant:I?"primary":"secondary",onClick:()=>E(I?"none":"percentage"),className:c.userInteractionCardButton,children:I?"Hide Details":"View Details"})]}),e.jsxs("div",{className:c.userInteractionCard,children:[e.jsx("div",{className:c.userInteractionCardValue,children:ze()}),e.jsx("div",{className:c.userInteractionCardLabel,children:"Delete Rate"}),e.jsx(Z,{name:"view-delete-details",variant:T?"primary":"secondary",onClick:()=>E(T?"none":"delete"),className:c.userInteractionCardButton,children:T?"Hide Details":"View Details"})]})]}),p&&e.jsx("div",{className:c.modelPerformance,children:e.jsx(B,{data:Ue("drone_image"),columns:ke,keySelector:$,filtered:!1,pending:!1})}),I&&e.jsx("div",{className:c.modelPerformance,children:e.jsx(B,{data:We("drone_image"),columns:Le,keySelector:$,filtered:!1,pending:!1})}),T&&e.jsx("div",{className:c.modelPerformance,children:e.jsx(B,{data:Qe("drone_image"),columns:Pe,keySelector:$,filtered:!1,pending:!1})})]}),e.jsx(z,{heading:"Model Performance",headingLevel:3,withHeaderBorder:!0,withInternalPadding:!0,children:e.jsx("div",{className:c.modelPerformance,children:e.jsx(B,{data:Ze("drone_image"),columns:Te,keySelector:$,filtered:!1,pending:!1})})}),e.jsx(z,{heading:"Quality-Event Type Correlation",headingLevel:3,withHeaderBorder:!0,withInternalPadding:!0,children:e.jsx("div",{className:c.tableContainer,children:e.jsx(B,{data:qe("drone_image"),columns:Re,keySelector:$,filtered:!1,pending:!1})})}),e.jsx(z,{heading:"Model Consistency Analysis",headingLevel:3,withHeaderBorder:!0,withInternalPadding:!0,children:e.jsx("div",{className:c.tableContainer,children:e.jsx(B,{data:Ge("drone_image"),columns:$e,keySelector:$,filtered:!1,pending:!1})})})]})]})})}export{jn as default};
|
py_backend/static/assets/{index-DvX--7c_.js β index-DrfgCGTV.js}
RENAMED
@@ -1,3 +1,3 @@
|
|
1 |
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/jszip.min-
|
2 |
-
import{J as Xe,x as Ye,j as a,N as X,n as F,r as m,D as ea,_ as ve,L as aa,z as E,v as se,w as ie,F as ta,K as sa,G as ia}from"./index-LmdVBMha.js";import{u as oa}from"./useAdmin-BGW0gk2h.js";import{F as na,E as ra}from"./ExportModal-k_VKbTpi.js";const la="_tabSelector_usssr_1",ca="_imageContainer_usssr_12",da="_imagePlaceholder_usssr_33",ga="_metadataTags_usssr_45",ma="_metadataTag_usssr_45",ua="_captionContainer_usssr_67",fa="_captionText_usssr_74",pa="_gridLayout_usssr_131",ha="_detailsSection_usssr_155",_a="_loadingContainer_usssr_161",xa="_errorContainer_usssr_171",ya="_fullSizeModalOverlay_usssr_205",va="_fullSizeModalContent_usssr_219",wa="_ratingWarningContent_usssr_230",Ca="_ratingWarningTitle_usssr_236",ja="_ratingWarningText_usssr_243",Ia="_ratingWarningButtons_usssr_250",Na="_carouselContainer_usssr_365",ba="_carouselImageWrapper_usssr_370",Sa="_carouselImage_usssr_370",La="_carouselNavigation_usssr_393",Da="_carouselButton_usssr_405",ka="_carouselIndicators_usssr_429",Ma="_carouselIndicator_usssr_429",Ta="_carouselIndicatorActive_usssr_458",Fa="_singleImageContainer_usssr_488",Pa="_viewImageButtonContainer_usssr_494",f={tabSelector:la,imageContainer:ca,imagePlaceholder:da,metadataTags:ga,metadataTag:ma,captionContainer:ua,captionText:fa,gridLayout:pa,detailsSection:ha,loadingContainer:_a,errorContainer:xa,fullSizeModalOverlay:ya,fullSizeModalContent:va,ratingWarningContent:wa,ratingWarningTitle:Ca,ratingWarningText:ja,ratingWarningButtons:Ia,carouselContainer:Na,carouselImageWrapper:ba,carouselImage:Sa,carouselNavigation:La,carouselButton:Da,carouselIndicators:ka,carouselIndicator:Ma,carouselIndicatorActive:Ta,singleImageContainer:Fa,viewImageButtonContainer:Pa};function at(){const{mapId:p}=Xe(),v=Ye(),{isAuthenticated:oe}=oa();console.log("MapDetailsPage: Current URL:",window.location.href),console.log("MapDetailsPage: Hash:",window.location.hash),console.log("MapDetailsPage: mapId from useParams:",p),console.log("MapDetailsPage: mapId type:",typeof p),console.log("MapDetailsPage: mapId length:",p?.length),console.log("MapDetailsPage: mapId value:",JSON.stringify(p));const we=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;if(!p||p==="undefined"||p==="null"||p.trim()===""||!we.test(p))return a.jsx(X,{children:a.jsxs("div",{className:"flex flex-col items-center gap-4 text-center py-12",children:[a.jsx("div",{className:"text-4xl",children:"β οΈ"}),a.jsx("div",{className:"text-xl font-semibold",children:"Invalid Map ID"}),a.jsx("div",{children:"The map ID provided is not valid."}),a.jsxs("div",{className:"text-sm text-gray-500 mt-2",children:['Debug Info: mapId = "',p,'" (type: ',typeof p,")"]}),a.jsx(F,{name:"back-to-explore",variant:"secondary",onClick:()=>v("/explore"),children:"Return to Explore"})]})});const[ne,Ce]=m.useState("mapDetails"),[e,Y]=m.useState(null),[W,A]=m.useState(!0),[re,O]=m.useState(null),[le,je]=m.useState([]),[ce,Ie]=m.useState([]),[de,Ne]=m.useState([]),[ge,be]=m.useState([]),[Se,Le]=m.useState([]),[De,ke]=m.useState(!1),[Me,Te]=m.useState(!1),[B,G]=m.useState(!1),[Fe,q]=m.useState(!1),[me,K]=m.useState(!1),[Pe,ee]=m.useState(!1),[Ee,ae]=m.useState(!1),[Ea,Ra]=m.useState("standard"),[R,$a]=m.useState(80),[J,Aa]=m.useState(10),[za,Oa]=m.useState(10),[Ua,Wa]=m.useState(!0),[Ba,Ja]=m.useState(!0),[Z,Q]=m.useState(!1),[Re,ue]=m.useState(!1),[$e,fe]=m.useState(null),[x,H]=m.useState([]),[M,z]=m.useState(0),[V,pe]=m.useState(!1),{search:d,setSearch:Ha,srcFilter:w,setSrcFilter:Va,catFilter:C,setCatFilter:Ga,regionFilter:j,setRegionFilter:qa,countryFilter:I,setCountryFilter:Ka,imageTypeFilter:N,setImageTypeFilter:Za,uploadTypeFilter:b,setUploadTypeFilter:Qa,showReferenceExamples:k,setShowReferenceExamples:Ae,clearAllFilters:ze}=ea(),Oe=[{key:"explore",label:"List"},{key:"mapDetails",label:"Carousel"}],he=m.useCallback(async t=>{if(console.log("fetchMapData called with id:",t),console.log("fetchMapData id type:",typeof t),!t||t==="undefined"||t==="null"||t.trim()===""){console.log("fetchMapData: Invalid ID detected:",t),O("Invalid Map ID"),A(!1);return}if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t)){console.log("fetchMapData: Invalid UUID format:",t),O("Invalid Map ID format"),A(!1);return}console.log("fetchMapData: Making API call for id:",t),G(!0),A(!0);try{const h=await fetch(`/api/images/${t}`);if(!h.ok)throw new Error("Map not found");const s=await h.json();if(Y(s),s.all_image_ids&&s.all_image_ids.length>1)await _e(s.all_image_ids);else if(s.image_count&&s.image_count>1){console.log("Multi-upload detected but no all_image_ids, trying grouped endpoint");try{const l=await fetch("/api/images/grouped");if(l.ok){const r=(await l.json()).find(c=>c.all_image_ids&&c.all_image_ids.includes(s.image_id));r&&r.all_image_ids?await _e(r.all_image_ids):(H([s]),z(0))}else H([s]),z(0)}catch(l){console.error("Failed to fetch from grouped endpoint:",l),H([s]),z(0)}}else H([s]),z(0);await te(t)}catch(h){O(h instanceof Error?h.message:"Unknown error occurred")}finally{A(!1),G(!1)}},[]),_e=m.useCallback(async t=>{console.log("fetchAllImages called with imageIds:",t),pe(!0);try{const o=t.map(async s=>{const l=await fetch(`/api/images/${s}`);if(!l.ok)throw new Error(`Failed to fetch image ${s}`);return l.json()}),h=await Promise.all(o);H(h),z(0),console.log("fetchAllImages: Loaded",h.length,"images")}catch(o){console.error("fetchAllImages error:",o),O(o instanceof Error?o.message:"Failed to load all images")}finally{pe(!1)}},[]),Ue=m.useCallback(()=>{x.length>1&&z(t=>t>0?t-1:x.length-1)},[x.length]),We=m.useCallback(()=>{x.length>1&&z(t=>t<x.length-1?t+1:0)},[x.length]),Be=m.useCallback(t=>{t>=0&&t<x.length&&z(t)},[x.length]),xe=m.useCallback(t=>{const o=t||(x.length>0?x[M]:e);o&&(fe(o),ue(!0))},[x,M,e]),Je=m.useCallback(()=>{ue(!1),fe(null)},[]);m.useEffect(()=>{if(console.log("MapDetailsPage: mapId from useParams:",p),console.log("MapDetailsPage: mapId type:",typeof p),console.log("MapDetailsPage: mapId value:",p),!p||p==="undefined"||p==="null"||p.trim()===""||p===void 0||p===null){console.log("MapDetailsPage: Invalid mapId, setting error"),O("Map ID is required"),A(!1);return}if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(p)){console.log("MapDetailsPage: Invalid UUID format:",p),O("Invalid Map ID format"),A(!1);return}console.log("MapDetailsPage: Fetching data for mapId:",p),he(p)},[p,he]),m.useEffect(()=>{if(!e||W||Z)return;if(!p||p==="undefined"||p==="null"||p.trim()===""){console.log("Auto-navigation skipped: Invalid mapId");return}if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(p)){console.log("Auto-navigation skipped: Invalid mapId format");return}(()=>{const h=!d||e.title?.toLowerCase().includes(d.toLowerCase())||e.generated?.toLowerCase().includes(d.toLowerCase())||e.source?.toLowerCase().includes(d.toLowerCase())||e.event_type?.toLowerCase().includes(d.toLowerCase()),s=!w||e.source===w,l=!C||e.event_type===C,i=!j||e.countries.some(T=>T.r_code===j),r=!I||e.countries.some(T=>T.c_code===I),c=!N||e.image_type===N,n=!k||e.starred===!0,y=h&&s&&l&&i&&r&&c&&n;return console.log("Auto-navigation check:",{mapId:p,search:d,srcFilter:w,catFilter:C,regionFilter:j,countryFilter:I,imageTypeFilter:N,showReferenceExamples:k,matchesSearch:h,matchesSource:s,matchesCategory:l,matchesRegion:i,matchesCountry:r,matchesImageType:c,matchesReferenceExamples:n,matches:y}),y})()||(console.log("Current map does not match filters, looking for first matching item"),fetch("/api/images").then(h=>h.json()).then(h=>{console.log("Auto-navigation: Received images from API:",h.length),console.log("Auto-navigation: First few images:",h.slice(0,3).map(l=>({image_id:l.image_id,title:l.title})));const s=h.find(l=>{const i=!d||l.title?.toLowerCase().includes(d.toLowerCase())||l.generated?.toLowerCase().includes(d.toLowerCase())||l.source?.toLowerCase().includes(d.toLowerCase())||l.event_type?.toLowerCase().includes(d.toLowerCase()),r=!w||l.source===w,c=!C||l.event_type===C,n=!j||l.countries?.some(u=>u.r_code===j),y=!I||l.countries?.some(u=>u.c_code===I),T=!N||l.image_type===N,L=!k||l.starred===!0;return i&&r&&c&&n&&y&&T&&L});console.log("Auto-navigation: Found first matching image:",s?{image_id:s.image_id,title:s.title,source:s.source}:"No matching image found"),s&&s.image_id&&s.image_id!=="undefined"&&s.image_id!=="null"&&s.image_id.trim()!==""&&s.image_id!==p&&(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(s.image_id)?(console.log("Auto-navigating to:",s.image_id),v(`/map/${s.image_id}`)):console.error("Auto-navigation blocked: Invalid image_id format:",s.image_id))}).catch(console.error))},[e,d,w,C,j,I,N,k,p,v,W,Z]);const te=async t=>{if(!(!t||t==="undefined"||t==="null"||t.trim()===""))try{const o=await fetch("/api/images/grouped");if(o.ok){const s=(await o.json()).filter(i=>{const r=!d||i.title?.toLowerCase().includes(d.toLowerCase())||i.generated?.toLowerCase().includes(d.toLowerCase())||i.source?.toLowerCase().includes(d.toLowerCase())||i.event_type?.toLowerCase().includes(d.toLowerCase()),c=!w||i.source===w,n=!C||i.event_type===C,y=!j||i.countries?.some(_=>_.r_code===j),T=!I||i.countries?.some(_=>_.c_code===I),L=!N||i.image_type===N,u=!b||b==="single"&&(!i.image_count||i.image_count<=1)||b==="multiple"&&i.image_count&&i.image_count>1,S=!k||i.starred===!0;return r&&c&&n&&y&&T&&L&&u&&S}),l=s.findIndex(i=>i.image_id===t);ke(s.length>1&&l>0),Te(s.length>1&&l<s.length-1)}}catch(o){console.error("Failed to check navigation availability:",o)}},ye=async t=>{if(!B){G(!0);try{const o=await fetch("/api/images/grouped");if(o.ok){const h=await o.json(),s=h.filter(n=>{const y=!d||n.title?.toLowerCase().includes(d.toLowerCase())||n.generated?.toLowerCase().includes(d.toLowerCase())||n.source?.toLowerCase().includes(d.toLowerCase())||n.event_type?.toLowerCase().includes(d.toLowerCase()),T=!w||n.source===w,L=!C||n.event_type===C,u=!j||n.countries?.some($=>$.r_code===j),S=!I||n.countries?.some($=>$.c_code===I),_=!N||n.image_type===N,D=!b||b==="single"&&(!n.image_count||n.image_count<=1)||b==="multiple"&&n.image_count&&n.image_count>1,U=!k||n.starred===!0;return y&&T&&L&&u&&S&&_&&D&&U});if(s.findIndex(n=>n.image_id===p)===-1){const n=h.find(y=>y.image_id===p);n&&s.push(n)}const i=s.findIndex(n=>n.image_id===p);if(i===-1){console.error("Current image not found in filtered list");return}let r;t==="previous"?r=i>0?i-1:s.length-1:r=i<s.length-1?i+1:0;const c=s[r];c&&c.image_id&&c.image_id!=="undefined"&&c.image_id!=="null"&&c.image_id.trim()!==""&&(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(c.image_id)?(console.log("Carousel navigating to:",c.image_id),v(`/map/${c.image_id}`)):console.error("Carousel navigation blocked: Invalid image_id format:",c.image_id))}}catch(o){console.error("Failed to navigate to item:",o)}finally{G(!1)}}};m.useEffect(()=>{e&&p&&!W&&!Z&&te(p)},[e,p,d,w,C,j,I,N,b,k,W,Z,te]),m.useEffect(()=>{Promise.all([fetch("/api/sources").then(t=>t.json()),fetch("/api/types").then(t=>t.json()),fetch("/api/image-types").then(t=>t.json()),fetch("/api/regions").then(t=>t.json()),fetch("/api/countries").then(t=>t.json())]).then(([t,o,h,s,l])=>{je(t),Ie(o),Ne(h),be(s),Le(l)}).catch(console.error)},[]);const He=async()=>{e&&q(!0)},Ve=async()=>{if(e)try{(await fetch(`/api/images/${e.image_id}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({starred:!e.starred})})).ok?Y(o=>o?{...o,starred:!o.starred}:null):console.error("Failed to toggle starred status")}catch(t){console.error("Error toggling starred status:",t)}},Ge=async()=>{if(e){Q(!0);try{if(console.log("Deleting image with ID:",e.image_id),(await fetch(`/api/images/${e.image_id}`,{method:"DELETE"})).ok){Y(o=>o?{...o,starred:!o.starred}:null),q(!1);try{const o=await fetch("/api/images/grouped");if(o.ok){const s=(await o.json()).filter(i=>{const r=!d||i.title?.toLowerCase().includes(d.toLowerCase())||i.generated?.toLowerCase().includes(d.toLowerCase())||i.source?.toLowerCase().includes(d.toLowerCase())||i.event_type?.toLowerCase().includes(d.toLowerCase()),c=!w||i.source===w,n=!C||i.event_type===C,y=!j||i.countries?.some(_=>_.r_code===j),T=!I||i.countries?.some(_=>_.c_code===I),L=!N||i.image_type===N,u=!b||b==="single"&&(!i.image_count||i.image_count<=1)||b==="multiple"&&i.image_count&&i.image_count>1,S=!k||i.starred===!0;return r&&c&&n&&y&&T&&L&&u&&S}),l=s.filter(i=>i.image_id!==e.image_id);if(l.length>0){const i=s.findIndex(c=>c.image_id===e.image_id);let r;if(i===s.length-1?r=i-1:r=i,console.log("Navigation target:",{currentIndex:i,targetIndex:r,targetId:l[r]?.image_id}),r>=0&&r<l.length){const c=l[r];c&&c.image_id&&c.image_id!=="undefined"&&c.image_id!=="null"&&c.image_id.trim()!==""?/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(c.image_id)?(console.log("Navigating to:",c.image_id),v(`/map/${c.image_id}`)):(console.error("Navigation blocked: Invalid image_id format:",c.image_id),v("/explore")):(console.error("Navigation blocked: Invalid image_id:",c?.image_id),v("/explore"))}else l[0]&&l[0].image_id&&l[0].image_id!=="undefined"&&l[0].image_id!=="null"&&l[0].image_id.trim()!==""?/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(l[0].image_id)?(console.log("Fallback navigation to first item:",l[0].image_id),v(`/map/${l[0].image_id}`)):(console.error("Fallback navigation blocked: Invalid image_id format:",l[0].image_id),v("/explore")):(console.log("No valid remaining items, going to explore page"),v("/explore"))}else console.log("No remaining items, going to explore page"),v("/explore")}else v("/explore")}catch(o){console.error("Failed to navigate to next item:",o),v("/explore")}finally{Q(!1)}}else console.error("Delete failed"),Q(!1)}catch(t){console.error("Delete failed:",t),Q(!1)}}},g=m.useMemo(()=>{if(!e)return null;if(!d&&!w&&!C&&!j&&!I&&!N&&!b&&!k)return e;const t=!d||e.title?.toLowerCase().includes(d.toLowerCase())||e.generated?.toLowerCase().includes(d.toLowerCase())||e.source?.toLowerCase().includes(d.toLowerCase())||e.event_type?.toLowerCase().includes(d.toLowerCase()),o=!w||e.source===w,h=!C||e.event_type===C,s=!j||e.countries.some(y=>y.r_code===j),l=!I||e.countries.some(y=>y.c_code===I),i=!N||e.image_type===N,r=!b||b==="single"&&(!e.image_count||e.image_count<=1)||b==="multiple"&&e.image_count&&e.image_count>1,c=!k||e.starred===!0,n=t&&o&&h&&s&&l&&i&&r&&c;return!n&&(d||w||C||j||I||N||b||k)?(setTimeout(()=>{qe()},100),e):n?e:null},[e,d,w,C,j,I,N,b,k]),qe=m.useCallback(async()=>{A(!0);try{const t=await fetch("/api/images/grouped");if(t.ok){const h=(await t.json()).filter(s=>{const l=!d||s.title?.toLowerCase().includes(d.toLowerCase())||s.generated?.toLowerCase().includes(d.toLowerCase())||s.source?.toLowerCase().includes(d.toLowerCase())||s.event_type?.toLowerCase().includes(d.toLowerCase()),i=!w||s.source===w,r=!C||s.event_type===C,c=!j||s.countries?.some(u=>u.r_code===j),n=!I||s.countries?.some(u=>u.c_code===I),y=!N||s.image_type===N,T=!b||b==="single"&&(!s.image_count||s.image_count<=1)||b==="multiple"&&s.image_count&&s.image_count>1,L=!k||s.starred===!0;return l&&i&&r&&c&&n&&y&&T&&L});if(h.length>0){const s=h[0];s&&s.image_id&&v(`/map/${s.image_id}`)}else v("/explore")}}catch(t){console.error("Failed to navigate to matching image:",t),v("/explore")}finally{A(!1)}},[d,w,C,j,I,N,b,k,v]),Ke=()=>{if(!e)return;if(!e.all_image_ids||e.all_image_ids.length<=1){const s=`/upload?step=1&contribute=true&imageIds=${[e.image_id].join(",")}`;v(s);return}const o=`/upload?step=1&contribute=true&imageIds=${e.all_image_ids.join(",")}`;v(o)},P=(t,o)=>({image:`images/${o}`,caption:t.edited||t.generated||"",metadata:{image_id:t.image_count&&t.image_count>1?t.all_image_ids||[t.image_id]:t.image_id,title:t.title,source:t.source,event_type:t.event_type,image_type:t.image_type,countries:t.countries,starred:t.starred,image_count:t.image_count||1}}),Ze=async t=>{if(e){ee(!0),ae(!1);try{const o=(await ia(async()=>{const{default:r}=await import("./jszip.min-DgY44d1h.js").then(c=>c.j);return{default:r}},__vite__mapDeps([0,1,2]))).default,h=new o;if(e.image_type==="crisis_map"){const r=h.folder("crisis_maps_dataset"),c=r?.folder("images");if(c)try{const n=e.image_count&&e.image_count>1?e.all_image_ids||[e.image_id]:[e.image_id],y=n.map(async(u,S)=>{try{const _=await fetch(`/api/images/${u}/file`);if(!_.ok)throw new Error(`Failed to fetch image ${u}`);const D=await _.blob(),U=e.file_key.split(".").pop()||"jpg",$=`0001_${String(S+1).padStart(2,"0")}.${U}`;return c.file($,D),{success:!0,fileName:$,imageId:u}}catch(_){return console.error(`Failed to process image ${u}:`,_),{success:!1,fileName:"",imageId:u}}}),L=(await Promise.all(y)).filter(u=>u.success);if(L.length===0)throw new Error("No images could be processed");if(t==="fine-tuning"){const u=[],S=[],_=[],D=L.map(Qe=>`images/${Qe.fileName}`),U=Math.random(),$={image:D.length===1?D[0]:D,caption:e.edited||e.generated||"",metadata:{image_id:n,title:e.title,source:e.source,event_type:e.event_type,image_type:e.image_type,countries:e.countries,starred:e.starred,image_count:e.image_count||1}};U<R/100?u.push($):U<(R+J)/100?S.push($):_.push($),r&&(r.file("train.jsonl",JSON.stringify(u,null,2)),r.file("test.jsonl",JSON.stringify(S,null,2)),r.file("val.jsonl",JSON.stringify(_,null,2)))}else{const u=L.map(_=>`images/${_.fileName}`),S={image:u.length===1?u[0]:u,caption:e.edited||e.generated||"",metadata:{image_id:n,title:e.title,source:e.source,event_type:e.event_type,image_type:e.image_type,countries:e.countries,starred:e.starred,image_count:e.image_count||1}};r&&r.file("0001.json",JSON.stringify(S,null,2))}}catch(n){throw console.error(`Failed to process image ${e.image_id}:`,n),n}}else if(e.image_type==="drone_image"){const r=h.folder("drone_images_dataset"),c=r?.folder("images");if(c)try{const n=await fetch(`/api/images/${e.image_id}/file`);if(!n.ok)throw new Error(`Failed to fetch image ${e.image_id}`);const y=await n.blob(),L=`0001.${e.file_key.split(".").pop()||"jpg"}`;if(c.file(L,y),t==="fine-tuning"){const u=[],S=[],_=[];if(String(e?.image_type)==="crisis_map"){const D=Math.random();D<R/100?u.push(P(e,"0001")):D<(R+J)/100?S.push(P(e,"0001")):_.push(P(e,"0001"))}else if(String(e?.image_type)==="drone_image"){const D=Math.random();D<R/100?u.push(P(e,"0001")):D<(R+J)/100?S.push(P(e,"0001")):_.push(P(e,"0001"))}r&&(r.file("train.jsonl",JSON.stringify(u,null,2)),r.file("test.jsonl",JSON.stringify(S,null,2)),r.file("val.jsonl",JSON.stringify(_,null,2)))}else{const u={image:`images/${L}`,caption:e.edited||e.generated||"",metadata:{image_id:e.image_count&&e.image_count>1?e.all_image_ids||[e.image_id]:e.image_id,title:e.title,source:e.source,event_type:e.event_type,image_type:e.image_type,countries:e.countries,starred:e.starred,image_count:e.image_count||1}};r&&r.file("0001.json",JSON.stringify(u,null,2))}}catch(n){throw console.error(`Failed to process image ${e.image_id}:`,n),n}}else{const r=h.folder("generic_dataset"),c=r?.folder("images");if(c)try{const n=await fetch(`/api/images/${e.image_id}/file`);if(!n.ok)throw new Error(`Failed to fetch image ${e.image_id}`);const y=await n.blob(),L=`0001.${e.file_key.split(".").pop()||"jpg"}`;if(c.file(L,y),t==="fine-tuning"){const u=[],S=[],_=[];if(String(e?.image_type)==="crisis_map"){const D=Math.random();D<R/100?u.push(P(e,"0001")):D<(R+J)/100?S.push(P(e,"0001")):_.push(P(e,"0001"))}else if(String(e?.image_type)==="drone_image"){const D=Math.random();D<R/100?u.push(P(e,"0001")):D<(R+J)/100?S.push(P(e,"0001")):_.push(P(e,"0001"))}r&&(r.file("train.jsonl",JSON.stringify(u,null,2)),r.file("test.jsonl",JSON.stringify(S,null,2)),r.file("val.jsonl",JSON.stringify(_,null,2)))}else{const u={image:`images/${L}`,caption:e.edited||e.generated||"",metadata:{image_id:e.image_count&&e.image_count>1?e.all_image_ids||[e.image_id]:e.image_id,title:e.title,source:e.source,event_type:e.event_type,image_type:e.image_type,countries:e.countries,starred:e.starred,image_count:e.image_count||1}};r&&r.file("0001.json",JSON.stringify(u,null,2))}}catch(n){throw console.error(`Failed to process image ${e.image_id}:`,n),n}}const s=await h.generateAsync({type:"blob"}),l=URL.createObjectURL(s),i=document.createElement("a");i.href=l,i.download=`dataset_${e.image_type}_${e.image_id}_${t}_${new Date().toISOString().split("T")[0]}.zip`,document.body.appendChild(i),i.click(),document.body.removeChild(i),URL.revokeObjectURL(l),console.log(`Exported ${e.image_type} dataset with 1 image in ${t} mode`),ae(!0)}catch(o){console.error("Export failed:",o),alert("Failed to export dataset. Please try again.")}finally{ee(!1)}}};return W?a.jsx(X,{children:a.jsx("div",{className:f.loadingContainer,children:a.jsxs("div",{className:"flex flex-col items-center gap-4",children:[a.jsx(ve,{className:"text-ifrcRed"}),a.jsx("div",{children:"Loading map details..."})]})})}):re||!e?a.jsx(X,{children:a.jsx("div",{className:f.errorContainer,children:a.jsxs("div",{className:"flex flex-col items-center gap-4 text-center",children:[a.jsx("div",{className:"text-4xl",children:"β οΈ"}),a.jsx("div",{className:"text-xl font-semibold",children:"Unable to load map"}),a.jsx("div",{children:re||"Map not found"}),a.jsx(F,{name:"back-to-explore",variant:"secondary",onClick:()=>v("/explore"),children:"Return to Explore"})]})})}):a.jsxs(X,{children:[a.jsxs("div",{className:"max-w-7xl mx-auto",children:[a.jsxs("div",{className:f.tabSelector,children:[a.jsx(aa,{name:"map-details-view",value:ne,onChange:t=>{(t==="mapDetails"||t==="explore")&&(Ce(t),t==="explore"&&v("/explore"))},options:Oe,keySelector:t=>t.key,labelSelector:t=>t.label}),a.jsxs("div",{className:"flex items-center gap-2 ml-auto",children:[a.jsx(E,{withInternalPadding:!0,className:"bg-white/20 backdrop-blur-sm rounded-md p-2",children:a.jsxs(F,{name:"reference-examples",variant:k?"primary":"secondary",onClick:()=>Ae(!k),className:"whitespace-nowrap",children:[a.jsx("span",{className:"mr-2",children:k?a.jsx("span",{className:"text-yellow-400",children:"β
"}):a.jsx("span",{className:"text-yellow-400",children:"β"})}),"Reference Examples"]})}),a.jsx(F,{name:"export-dataset",variant:"secondary",onClick:()=>K(!0),children:"Export"})]})]}),a.jsx(na,{sources:le,types:ce,regions:ge,countries:Se,imageTypes:de,isLoadingFilters:!1}),ne==="mapDetails"?a.jsx("div",{className:"relative",children:g?a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:f.gridLayout,children:[a.jsxs(E,{heading:a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{children:g.title||"Map Image"}),g.starred&&a.jsx("span",{className:"text-red-500 text-xl",title:"Starred image",children:"β
"})]}),headingLevel:2,withHeaderBorder:!0,withInternalPadding:!0,spacing:"comfortable",children:[a.jsx("div",{className:f.imageContainer,children:e?.image_count&&e.image_count>1||x.length>1?a.jsxs("div",{className:f.carouselContainer,children:[a.jsx("div",{className:f.carouselImageWrapper,children:V?a.jsxs("div",{className:f.imagePlaceholder,children:[a.jsx(ve,{className:"text-ifrcRed"}),a.jsx("div",{children:"Loading images..."})]}):x[M]?.detail_url?a.jsx("img",{src:x[M].detail_url,alt:x[M].file_key,className:f.carouselImage,onError:t=>{console.log("MapDetailsPage: Detail image failed to load, falling back to original:",x[M].detail_url);const o=t.target;x[M].image_url&&(o.src=x[M].image_url)},onLoad:()=>console.log("MapDetailsPage: Detail image loaded successfully:",x[M].detail_url)}):x[M]?.image_url?a.jsx("img",{src:x[M].image_url,alt:x[M].file_key,className:f.carouselImage,onLoad:()=>console.log("MapDetailsPage: Original image loaded successfully:",x[M].image_url)}):a.jsx("div",{className:f.imagePlaceholder,children:"No image available"})}),a.jsxs("div",{className:f.carouselNavigation,children:[a.jsx(F,{name:"previous-image",variant:"tertiary",size:1,onClick:Ue,disabled:V,className:f.carouselButton,children:a.jsx(se,{className:"w-4 h-4"})}),a.jsx("div",{className:f.carouselIndicators,children:x.map((t,o)=>a.jsx("button",{onClick:()=>Be(o),className:`${f.carouselIndicator} ${o===M?f.carouselIndicatorActive:""}`,disabled:V,children:o+1},o))}),a.jsx(F,{name:"next-image",variant:"tertiary",size:1,onClick:We,disabled:V,className:f.carouselButton,children:a.jsx(ie,{className:"w-4 h-4"})})]}),a.jsx("div",{className:f.viewImageButtonContainer,children:a.jsx(F,{name:"view-full-size-carousel",variant:"secondary",size:1,onClick:()=>xe(x[M]),disabled:V||!x[M]?.image_url,children:"View Image"})})]}):a.jsxs("div",{className:f.singleImageContainer,children:[g.detail_url?a.jsx("img",{src:g.detail_url,alt:g.file_key,onError:t=>{console.log("MapDetailsPage: Detail image failed to load, falling back to original:",g.detail_url);const o=t.target;g.image_url&&(o.src=g.image_url)},onLoad:()=>console.log("MapDetailsPage: Detail image loaded successfully:",g.detail_url)}):g.image_url?a.jsx("img",{src:g.image_url,alt:g.file_key,onLoad:()=>console.log("MapDetailsPage: Original image loaded successfully:",g.image_url)}):a.jsx("div",{className:f.imagePlaceholder,children:"No image available"}),a.jsx("div",{className:f.viewImageButtonContainer,children:a.jsx(F,{name:"view-full-size-single",variant:"secondary",size:1,onClick:()=>xe(g),disabled:!g.image_url,children:"View Image"})})]})}),a.jsx(E,{withInternalPadding:!0,className:"bg-white/20 backdrop-blur-sm rounded-md p-2",children:a.jsxs("div",{className:f.metadataTags,children:[g.image_type!=="drone_image"&&a.jsx("span",{className:f.metadataTag,children:le.find(t=>t.s_code===g.source)?.label||g.source}),a.jsx("span",{className:f.metadataTag,children:ce.find(t=>t.t_code===g.event_type)?.label||g.event_type}),a.jsx("span",{className:f.metadataTag,children:de.find(t=>t.image_type===g.image_type)?.label||g.image_type}),g.countries&&g.countries.length>0&&a.jsxs(a.Fragment,{children:[a.jsx("span",{className:f.metadataTag,children:ge.find(t=>t.r_code===g.countries[0].r_code)?.label||"Unknown Region"}),a.jsx("span",{className:f.metadataTag,children:g.countries.map(t=>t.label).join(", ")})]}),g.image_count&&g.image_count>1&&a.jsxs("span",{className:f.metadataTag,title:`Multi-upload with ${g.image_count} images`,children:["π· ",g.image_count]}),(!g.image_count||g.image_count<=1)&&a.jsx("span",{className:f.metadataTag,title:"Single Upload",children:"Single"})]})})]}),a.jsx("div",{className:f.detailsSection,children:g.edited&&g.edited.includes("Description:")||g.generated&&g.generated.includes("Description:")?a.jsx(E,{heading:"AI Generated Content",headingLevel:3,withHeaderBorder:!0,withInternalPadding:!0,spacing:"comfortable",children:a.jsx("div",{className:f.captionContainer,children:a.jsx("div",{className:f.captionText,children:(g.edited||g.generated||"").split(`
|
3 |
`).map((t,o)=>a.jsx("div",{children:t.startsWith("Description:")||t.startsWith("Analysis:")||t.startsWith("Recommended Actions:")?a.jsx("h4",{className:"font-semibold text-gray-800 mt-4 mb-2",children:t}):t.trim()===""?a.jsx("br",{}):a.jsx("p",{className:"mb-2",children:t})},o))})})}):a.jsx(E,{heading:"Description",headingLevel:3,withHeaderBorder:!0,withInternalPadding:!0,spacing:"comfortable",children:a.jsx("div",{className:f.captionContainer,children:g.generated?a.jsx("div",{className:f.captionText,children:a.jsx("p",{children:g.edited||g.generated})}):a.jsx("p",{children:"β no caption yet β"})})})})]}),a.jsx("div",{className:"flex items-center justify-center mt-8",children:a.jsx(E,{withInternalPadding:!0,className:"bg-white/20 backdrop-blur-sm rounded-lg p-4",children:a.jsxs("div",{className:"flex items-center gap-4",children:[De&&a.jsx(E,{withInternalPadding:!0,className:"rounded-md p-2",children:a.jsx(F,{name:"previous-item",variant:"tertiary",size:1,className:`bg-white/90 hover:bg-white shadow-lg border border-gray-200 ${B?"opacity-50 cursor-not-allowed":"hover:scale-110"}`,onClick:()=>ye("previous"),disabled:B,children:a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsxs("div",{className:"flex -space-x-1",children:[a.jsx(se,{className:"w-4 h-4"}),a.jsx(se,{className:"w-4 h-4"})]}),a.jsx("span",{className:"font-semibold",children:"Previous"})]})})}),oe&&a.jsx(E,{withInternalPadding:!0,className:"rounded-md p-2",children:a.jsx(F,{name:"delete",variant:"tertiary",size:1,className:"bg-red-50 hover:bg-red-100 text-red-700 border border-red-200 hover:border-red-300",onClick:He,title:"Delete","aria-label":"Delete saved image",children:a.jsx(ta,{className:"w-4 h-4"})})}),a.jsx(E,{withInternalPadding:!0,className:"rounded-md p-2",children:a.jsx(F,{name:"contribute",onClick:Ke,children:"Contribute"})}),oe&&a.jsx(E,{withInternalPadding:!0,className:"rounded-md p-2",children:a.jsx(F,{name:"toggle-star",variant:"tertiary",size:1,className:`${e?.starred?"bg-red-100 hover:bg-red-200 text-red-800 border-2 border-red-400":"bg-gray-100 hover:bg-gray-200 text-gray-600 border-2 border-gray-300"} w-16 h-8 rounded-full transition-all duration-200 flex items-center justify-center`,onClick:Ve,title:e?.starred?"Unstar image":"Star image","aria-label":e?.starred?"Unstar image":"Star image",children:a.jsx("span",{className:`text-lg transition-all duration-200 ${e?.starred?"text-red-600":"text-gray-500"}`,children:e?.starred?"β
":"β"})})}),Me&&a.jsx(E,{withInternalPadding:!0,className:"rounded-md p-2",children:a.jsx(F,{name:"next-item",variant:"tertiary",size:1,className:`bg-white/90 hover:bg-white shadow-lg border border-gray-200 ${B?"opacity-50 cursor-not-allowed":"hover:scale-110"}`,onClick:()=>ye("next"),disabled:B,children:a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx("span",{className:"font-semibold",children:"Next"}),a.jsxs("div",{className:"flex -space-x-1",children:[a.jsx(ie,{className:"w-4 h-4"}),a.jsx(ie,{className:"w-4 h-4"})]})]})})})]})})})]}):a.jsxs("div",{className:"text-center py-12",children:[a.jsx("div",{className:"text-xl font-semibold text-gray-600 mb-4",children:"No matches found"}),a.jsx("div",{className:"mt-4",children:a.jsx(F,{name:"clear-filters",variant:"secondary",onClick:ze,children:"Clear Filters"})})]})}):null]}),Fe&&a.jsx("div",{className:f.fullSizeModalOverlay,onClick:()=>q(!1),children:a.jsx("div",{className:f.fullSizeModalContent,onClick:t=>t.stopPropagation(),children:a.jsxs("div",{className:f.ratingWarningContent,children:[a.jsx("h3",{className:f.ratingWarningTitle,children:"Delete Image?"}),a.jsx("p",{className:f.ratingWarningText,children:"This action cannot be undone. Are you sure you want to delete this saved image and all related data?"}),a.jsxs("div",{className:f.ratingWarningButtons,children:[a.jsx(F,{name:"confirm-delete",variant:"secondary",onClick:Ge,children:"Delete"}),a.jsx(F,{name:"cancel-delete",variant:"tertiary",onClick:()=>q(!1),children:"Cancel"})]})]})})}),me&&a.jsx(ra,{isOpen:me,onClose:()=>{K(!1),ae(!1),ee(!1)},onExport:(t,o)=>{o.includes(e.image_type)&&Ze(t)},filteredCount:1,totalCount:1,hasFilters:!1,crisisMapsCount:e.image_type==="crisis_map"?1:0,droneImagesCount:e.image_type==="drone_image"?1:0,isLoading:Pe,exportSuccess:Ee,variant:"single",onNavigateToList:()=>{K(!1),v("/explore")},onNavigateAndExport:()=>{K(!1),v("/explore?export=true")}}),a.jsx(sa,{isOpen:Re,imageUrl:$e?.image_url||null,preview:null,selectedImageData:null,onClose:Je})]})}export{at as default};
|
|
|
1 |
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/jszip.min-JNyb8pkO.js","assets/index-BzYyR-qc.js","assets/index-FBu17hMI.css"])))=>i.map(i=>d[i]);
|
2 |
+
import{J as Xe,x as Ye,j as a,N as X,n as F,r as m,D as ea,_ as ve,L as aa,z as E,v as se,w as ie,F as ta,K as sa,G as ia}from"./index-BzYyR-qc.js";import{u as oa}from"./useAdmin-B4TrJLwR.js";import{F as na,E as ra}from"./ExportModal-DJU5iFtN.js";const la="_tabSelector_usssr_1",ca="_imageContainer_usssr_12",da="_imagePlaceholder_usssr_33",ga="_metadataTags_usssr_45",ma="_metadataTag_usssr_45",ua="_captionContainer_usssr_67",fa="_captionText_usssr_74",pa="_gridLayout_usssr_131",ha="_detailsSection_usssr_155",_a="_loadingContainer_usssr_161",xa="_errorContainer_usssr_171",ya="_fullSizeModalOverlay_usssr_205",va="_fullSizeModalContent_usssr_219",wa="_ratingWarningContent_usssr_230",Ca="_ratingWarningTitle_usssr_236",ja="_ratingWarningText_usssr_243",Ia="_ratingWarningButtons_usssr_250",Na="_carouselContainer_usssr_365",ba="_carouselImageWrapper_usssr_370",Sa="_carouselImage_usssr_370",La="_carouselNavigation_usssr_393",Da="_carouselButton_usssr_405",ka="_carouselIndicators_usssr_429",Ma="_carouselIndicator_usssr_429",Ta="_carouselIndicatorActive_usssr_458",Fa="_singleImageContainer_usssr_488",Pa="_viewImageButtonContainer_usssr_494",f={tabSelector:la,imageContainer:ca,imagePlaceholder:da,metadataTags:ga,metadataTag:ma,captionContainer:ua,captionText:fa,gridLayout:pa,detailsSection:ha,loadingContainer:_a,errorContainer:xa,fullSizeModalOverlay:ya,fullSizeModalContent:va,ratingWarningContent:wa,ratingWarningTitle:Ca,ratingWarningText:ja,ratingWarningButtons:Ia,carouselContainer:Na,carouselImageWrapper:ba,carouselImage:Sa,carouselNavigation:La,carouselButton:Da,carouselIndicators:ka,carouselIndicator:Ma,carouselIndicatorActive:Ta,singleImageContainer:Fa,viewImageButtonContainer:Pa};function at(){const{mapId:p}=Xe(),v=Ye(),{isAuthenticated:oe}=oa();console.log("MapDetailsPage: Current URL:",window.location.href),console.log("MapDetailsPage: Hash:",window.location.hash),console.log("MapDetailsPage: mapId from useParams:",p),console.log("MapDetailsPage: mapId type:",typeof p),console.log("MapDetailsPage: mapId length:",p?.length),console.log("MapDetailsPage: mapId value:",JSON.stringify(p));const we=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;if(!p||p==="undefined"||p==="null"||p.trim()===""||!we.test(p))return a.jsx(X,{children:a.jsxs("div",{className:"flex flex-col items-center gap-4 text-center py-12",children:[a.jsx("div",{className:"text-4xl",children:"β οΈ"}),a.jsx("div",{className:"text-xl font-semibold",children:"Invalid Map ID"}),a.jsx("div",{children:"The map ID provided is not valid."}),a.jsxs("div",{className:"text-sm text-gray-500 mt-2",children:['Debug Info: mapId = "',p,'" (type: ',typeof p,")"]}),a.jsx(F,{name:"back-to-explore",variant:"secondary",onClick:()=>v("/explore"),children:"Return to Explore"})]})});const[ne,Ce]=m.useState("mapDetails"),[e,Y]=m.useState(null),[W,A]=m.useState(!0),[re,O]=m.useState(null),[le,je]=m.useState([]),[ce,Ie]=m.useState([]),[de,Ne]=m.useState([]),[ge,be]=m.useState([]),[Se,Le]=m.useState([]),[De,ke]=m.useState(!1),[Me,Te]=m.useState(!1),[B,G]=m.useState(!1),[Fe,q]=m.useState(!1),[me,K]=m.useState(!1),[Pe,ee]=m.useState(!1),[Ee,ae]=m.useState(!1),[Ea,Ra]=m.useState("standard"),[R,$a]=m.useState(80),[J,Aa]=m.useState(10),[za,Oa]=m.useState(10),[Ua,Wa]=m.useState(!0),[Ba,Ja]=m.useState(!0),[Z,Q]=m.useState(!1),[Re,ue]=m.useState(!1),[$e,fe]=m.useState(null),[x,H]=m.useState([]),[M,z]=m.useState(0),[V,pe]=m.useState(!1),{search:d,setSearch:Ha,srcFilter:w,setSrcFilter:Va,catFilter:C,setCatFilter:Ga,regionFilter:j,setRegionFilter:qa,countryFilter:I,setCountryFilter:Ka,imageTypeFilter:N,setImageTypeFilter:Za,uploadTypeFilter:b,setUploadTypeFilter:Qa,showReferenceExamples:k,setShowReferenceExamples:Ae,clearAllFilters:ze}=ea(),Oe=[{key:"explore",label:"List"},{key:"mapDetails",label:"Carousel"}],he=m.useCallback(async t=>{if(console.log("fetchMapData called with id:",t),console.log("fetchMapData id type:",typeof t),!t||t==="undefined"||t==="null"||t.trim()===""){console.log("fetchMapData: Invalid ID detected:",t),O("Invalid Map ID"),A(!1);return}if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t)){console.log("fetchMapData: Invalid UUID format:",t),O("Invalid Map ID format"),A(!1);return}console.log("fetchMapData: Making API call for id:",t),G(!0),A(!0);try{const h=await fetch(`/api/images/${t}`);if(!h.ok)throw new Error("Map not found");const s=await h.json();if(Y(s),s.all_image_ids&&s.all_image_ids.length>1)await _e(s.all_image_ids);else if(s.image_count&&s.image_count>1){console.log("Multi-upload detected but no all_image_ids, trying grouped endpoint");try{const l=await fetch("/api/images/grouped");if(l.ok){const r=(await l.json()).find(c=>c.all_image_ids&&c.all_image_ids.includes(s.image_id));r&&r.all_image_ids?await _e(r.all_image_ids):(H([s]),z(0))}else H([s]),z(0)}catch(l){console.error("Failed to fetch from grouped endpoint:",l),H([s]),z(0)}}else H([s]),z(0);await te(t)}catch(h){O(h instanceof Error?h.message:"Unknown error occurred")}finally{A(!1),G(!1)}},[]),_e=m.useCallback(async t=>{console.log("fetchAllImages called with imageIds:",t),pe(!0);try{const o=t.map(async s=>{const l=await fetch(`/api/images/${s}`);if(!l.ok)throw new Error(`Failed to fetch image ${s}`);return l.json()}),h=await Promise.all(o);H(h),z(0),console.log("fetchAllImages: Loaded",h.length,"images")}catch(o){console.error("fetchAllImages error:",o),O(o instanceof Error?o.message:"Failed to load all images")}finally{pe(!1)}},[]),Ue=m.useCallback(()=>{x.length>1&&z(t=>t>0?t-1:x.length-1)},[x.length]),We=m.useCallback(()=>{x.length>1&&z(t=>t<x.length-1?t+1:0)},[x.length]),Be=m.useCallback(t=>{t>=0&&t<x.length&&z(t)},[x.length]),xe=m.useCallback(t=>{const o=t||(x.length>0?x[M]:e);o&&(fe(o),ue(!0))},[x,M,e]),Je=m.useCallback(()=>{ue(!1),fe(null)},[]);m.useEffect(()=>{if(console.log("MapDetailsPage: mapId from useParams:",p),console.log("MapDetailsPage: mapId type:",typeof p),console.log("MapDetailsPage: mapId value:",p),!p||p==="undefined"||p==="null"||p.trim()===""||p===void 0||p===null){console.log("MapDetailsPage: Invalid mapId, setting error"),O("Map ID is required"),A(!1);return}if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(p)){console.log("MapDetailsPage: Invalid UUID format:",p),O("Invalid Map ID format"),A(!1);return}console.log("MapDetailsPage: Fetching data for mapId:",p),he(p)},[p,he]),m.useEffect(()=>{if(!e||W||Z)return;if(!p||p==="undefined"||p==="null"||p.trim()===""){console.log("Auto-navigation skipped: Invalid mapId");return}if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(p)){console.log("Auto-navigation skipped: Invalid mapId format");return}(()=>{const h=!d||e.title?.toLowerCase().includes(d.toLowerCase())||e.generated?.toLowerCase().includes(d.toLowerCase())||e.source?.toLowerCase().includes(d.toLowerCase())||e.event_type?.toLowerCase().includes(d.toLowerCase()),s=!w||e.source===w,l=!C||e.event_type===C,i=!j||e.countries.some(T=>T.r_code===j),r=!I||e.countries.some(T=>T.c_code===I),c=!N||e.image_type===N,n=!k||e.starred===!0,y=h&&s&&l&&i&&r&&c&&n;return console.log("Auto-navigation check:",{mapId:p,search:d,srcFilter:w,catFilter:C,regionFilter:j,countryFilter:I,imageTypeFilter:N,showReferenceExamples:k,matchesSearch:h,matchesSource:s,matchesCategory:l,matchesRegion:i,matchesCountry:r,matchesImageType:c,matchesReferenceExamples:n,matches:y}),y})()||(console.log("Current map does not match filters, looking for first matching item"),fetch("/api/images").then(h=>h.json()).then(h=>{console.log("Auto-navigation: Received images from API:",h.length),console.log("Auto-navigation: First few images:",h.slice(0,3).map(l=>({image_id:l.image_id,title:l.title})));const s=h.find(l=>{const i=!d||l.title?.toLowerCase().includes(d.toLowerCase())||l.generated?.toLowerCase().includes(d.toLowerCase())||l.source?.toLowerCase().includes(d.toLowerCase())||l.event_type?.toLowerCase().includes(d.toLowerCase()),r=!w||l.source===w,c=!C||l.event_type===C,n=!j||l.countries?.some(u=>u.r_code===j),y=!I||l.countries?.some(u=>u.c_code===I),T=!N||l.image_type===N,L=!k||l.starred===!0;return i&&r&&c&&n&&y&&T&&L});console.log("Auto-navigation: Found first matching image:",s?{image_id:s.image_id,title:s.title,source:s.source}:"No matching image found"),s&&s.image_id&&s.image_id!=="undefined"&&s.image_id!=="null"&&s.image_id.trim()!==""&&s.image_id!==p&&(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(s.image_id)?(console.log("Auto-navigating to:",s.image_id),v(`/map/${s.image_id}`)):console.error("Auto-navigation blocked: Invalid image_id format:",s.image_id))}).catch(console.error))},[e,d,w,C,j,I,N,k,p,v,W,Z]);const te=async t=>{if(!(!t||t==="undefined"||t==="null"||t.trim()===""))try{const o=await fetch("/api/images/grouped");if(o.ok){const s=(await o.json()).filter(i=>{const r=!d||i.title?.toLowerCase().includes(d.toLowerCase())||i.generated?.toLowerCase().includes(d.toLowerCase())||i.source?.toLowerCase().includes(d.toLowerCase())||i.event_type?.toLowerCase().includes(d.toLowerCase()),c=!w||i.source===w,n=!C||i.event_type===C,y=!j||i.countries?.some(_=>_.r_code===j),T=!I||i.countries?.some(_=>_.c_code===I),L=!N||i.image_type===N,u=!b||b==="single"&&(!i.image_count||i.image_count<=1)||b==="multiple"&&i.image_count&&i.image_count>1,S=!k||i.starred===!0;return r&&c&&n&&y&&T&&L&&u&&S}),l=s.findIndex(i=>i.image_id===t);ke(s.length>1&&l>0),Te(s.length>1&&l<s.length-1)}}catch(o){console.error("Failed to check navigation availability:",o)}},ye=async t=>{if(!B){G(!0);try{const o=await fetch("/api/images/grouped");if(o.ok){const h=await o.json(),s=h.filter(n=>{const y=!d||n.title?.toLowerCase().includes(d.toLowerCase())||n.generated?.toLowerCase().includes(d.toLowerCase())||n.source?.toLowerCase().includes(d.toLowerCase())||n.event_type?.toLowerCase().includes(d.toLowerCase()),T=!w||n.source===w,L=!C||n.event_type===C,u=!j||n.countries?.some($=>$.r_code===j),S=!I||n.countries?.some($=>$.c_code===I),_=!N||n.image_type===N,D=!b||b==="single"&&(!n.image_count||n.image_count<=1)||b==="multiple"&&n.image_count&&n.image_count>1,U=!k||n.starred===!0;return y&&T&&L&&u&&S&&_&&D&&U});if(s.findIndex(n=>n.image_id===p)===-1){const n=h.find(y=>y.image_id===p);n&&s.push(n)}const i=s.findIndex(n=>n.image_id===p);if(i===-1){console.error("Current image not found in filtered list");return}let r;t==="previous"?r=i>0?i-1:s.length-1:r=i<s.length-1?i+1:0;const c=s[r];c&&c.image_id&&c.image_id!=="undefined"&&c.image_id!=="null"&&c.image_id.trim()!==""&&(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(c.image_id)?(console.log("Carousel navigating to:",c.image_id),v(`/map/${c.image_id}`)):console.error("Carousel navigation blocked: Invalid image_id format:",c.image_id))}}catch(o){console.error("Failed to navigate to item:",o)}finally{G(!1)}}};m.useEffect(()=>{e&&p&&!W&&!Z&&te(p)},[e,p,d,w,C,j,I,N,b,k,W,Z,te]),m.useEffect(()=>{Promise.all([fetch("/api/sources").then(t=>t.json()),fetch("/api/types").then(t=>t.json()),fetch("/api/image-types").then(t=>t.json()),fetch("/api/regions").then(t=>t.json()),fetch("/api/countries").then(t=>t.json())]).then(([t,o,h,s,l])=>{je(t),Ie(o),Ne(h),be(s),Le(l)}).catch(console.error)},[]);const He=async()=>{e&&q(!0)},Ve=async()=>{if(e)try{(await fetch(`/api/images/${e.image_id}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({starred:!e.starred})})).ok?Y(o=>o?{...o,starred:!o.starred}:null):console.error("Failed to toggle starred status")}catch(t){console.error("Error toggling starred status:",t)}},Ge=async()=>{if(e){Q(!0);try{if(console.log("Deleting image with ID:",e.image_id),(await fetch(`/api/images/${e.image_id}`,{method:"DELETE"})).ok){Y(o=>o?{...o,starred:!o.starred}:null),q(!1);try{const o=await fetch("/api/images/grouped");if(o.ok){const s=(await o.json()).filter(i=>{const r=!d||i.title?.toLowerCase().includes(d.toLowerCase())||i.generated?.toLowerCase().includes(d.toLowerCase())||i.source?.toLowerCase().includes(d.toLowerCase())||i.event_type?.toLowerCase().includes(d.toLowerCase()),c=!w||i.source===w,n=!C||i.event_type===C,y=!j||i.countries?.some(_=>_.r_code===j),T=!I||i.countries?.some(_=>_.c_code===I),L=!N||i.image_type===N,u=!b||b==="single"&&(!i.image_count||i.image_count<=1)||b==="multiple"&&i.image_count&&i.image_count>1,S=!k||i.starred===!0;return r&&c&&n&&y&&T&&L&&u&&S}),l=s.filter(i=>i.image_id!==e.image_id);if(l.length>0){const i=s.findIndex(c=>c.image_id===e.image_id);let r;if(i===s.length-1?r=i-1:r=i,console.log("Navigation target:",{currentIndex:i,targetIndex:r,targetId:l[r]?.image_id}),r>=0&&r<l.length){const c=l[r];c&&c.image_id&&c.image_id!=="undefined"&&c.image_id!=="null"&&c.image_id.trim()!==""?/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(c.image_id)?(console.log("Navigating to:",c.image_id),v(`/map/${c.image_id}`)):(console.error("Navigation blocked: Invalid image_id format:",c.image_id),v("/explore")):(console.error("Navigation blocked: Invalid image_id:",c?.image_id),v("/explore"))}else l[0]&&l[0].image_id&&l[0].image_id!=="undefined"&&l[0].image_id!=="null"&&l[0].image_id.trim()!==""?/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(l[0].image_id)?(console.log("Fallback navigation to first item:",l[0].image_id),v(`/map/${l[0].image_id}`)):(console.error("Fallback navigation blocked: Invalid image_id format:",l[0].image_id),v("/explore")):(console.log("No valid remaining items, going to explore page"),v("/explore"))}else console.log("No remaining items, going to explore page"),v("/explore")}else v("/explore")}catch(o){console.error("Failed to navigate to next item:",o),v("/explore")}finally{Q(!1)}}else console.error("Delete failed"),Q(!1)}catch(t){console.error("Delete failed:",t),Q(!1)}}},g=m.useMemo(()=>{if(!e)return null;if(!d&&!w&&!C&&!j&&!I&&!N&&!b&&!k)return e;const t=!d||e.title?.toLowerCase().includes(d.toLowerCase())||e.generated?.toLowerCase().includes(d.toLowerCase())||e.source?.toLowerCase().includes(d.toLowerCase())||e.event_type?.toLowerCase().includes(d.toLowerCase()),o=!w||e.source===w,h=!C||e.event_type===C,s=!j||e.countries.some(y=>y.r_code===j),l=!I||e.countries.some(y=>y.c_code===I),i=!N||e.image_type===N,r=!b||b==="single"&&(!e.image_count||e.image_count<=1)||b==="multiple"&&e.image_count&&e.image_count>1,c=!k||e.starred===!0,n=t&&o&&h&&s&&l&&i&&r&&c;return!n&&(d||w||C||j||I||N||b||k)?(setTimeout(()=>{qe()},100),e):n?e:null},[e,d,w,C,j,I,N,b,k]),qe=m.useCallback(async()=>{A(!0);try{const t=await fetch("/api/images/grouped");if(t.ok){const h=(await t.json()).filter(s=>{const l=!d||s.title?.toLowerCase().includes(d.toLowerCase())||s.generated?.toLowerCase().includes(d.toLowerCase())||s.source?.toLowerCase().includes(d.toLowerCase())||s.event_type?.toLowerCase().includes(d.toLowerCase()),i=!w||s.source===w,r=!C||s.event_type===C,c=!j||s.countries?.some(u=>u.r_code===j),n=!I||s.countries?.some(u=>u.c_code===I),y=!N||s.image_type===N,T=!b||b==="single"&&(!s.image_count||s.image_count<=1)||b==="multiple"&&s.image_count&&s.image_count>1,L=!k||s.starred===!0;return l&&i&&r&&c&&n&&y&&T&&L});if(h.length>0){const s=h[0];s&&s.image_id&&v(`/map/${s.image_id}`)}else v("/explore")}}catch(t){console.error("Failed to navigate to matching image:",t),v("/explore")}finally{A(!1)}},[d,w,C,j,I,N,b,k,v]),Ke=()=>{if(!e)return;if(!e.all_image_ids||e.all_image_ids.length<=1){const s=`/upload?step=1&contribute=true&imageIds=${[e.image_id].join(",")}`;v(s);return}const o=`/upload?step=1&contribute=true&imageIds=${e.all_image_ids.join(",")}`;v(o)},P=(t,o)=>({image:`images/${o}`,caption:t.edited||t.generated||"",metadata:{image_id:t.image_count&&t.image_count>1?t.all_image_ids||[t.image_id]:t.image_id,title:t.title,source:t.source,event_type:t.event_type,image_type:t.image_type,countries:t.countries,starred:t.starred,image_count:t.image_count||1}}),Ze=async t=>{if(e){ee(!0),ae(!1);try{const o=(await ia(async()=>{const{default:r}=await import("./jszip.min-JNyb8pkO.js").then(c=>c.j);return{default:r}},__vite__mapDeps([0,1,2]))).default,h=new o;if(e.image_type==="crisis_map"){const r=h.folder("crisis_maps_dataset"),c=r?.folder("images");if(c)try{const n=e.image_count&&e.image_count>1?e.all_image_ids||[e.image_id]:[e.image_id],y=n.map(async(u,S)=>{try{const _=await fetch(`/api/images/${u}/file`);if(!_.ok)throw new Error(`Failed to fetch image ${u}`);const D=await _.blob(),U=e.file_key.split(".").pop()||"jpg",$=`0001_${String(S+1).padStart(2,"0")}.${U}`;return c.file($,D),{success:!0,fileName:$,imageId:u}}catch(_){return console.error(`Failed to process image ${u}:`,_),{success:!1,fileName:"",imageId:u}}}),L=(await Promise.all(y)).filter(u=>u.success);if(L.length===0)throw new Error("No images could be processed");if(t==="fine-tuning"){const u=[],S=[],_=[],D=L.map(Qe=>`images/${Qe.fileName}`),U=Math.random(),$={image:D.length===1?D[0]:D,caption:e.edited||e.generated||"",metadata:{image_id:n,title:e.title,source:e.source,event_type:e.event_type,image_type:e.image_type,countries:e.countries,starred:e.starred,image_count:e.image_count||1}};U<R/100?u.push($):U<(R+J)/100?S.push($):_.push($),r&&(r.file("train.jsonl",JSON.stringify(u,null,2)),r.file("test.jsonl",JSON.stringify(S,null,2)),r.file("val.jsonl",JSON.stringify(_,null,2)))}else{const u=L.map(_=>`images/${_.fileName}`),S={image:u.length===1?u[0]:u,caption:e.edited||e.generated||"",metadata:{image_id:n,title:e.title,source:e.source,event_type:e.event_type,image_type:e.image_type,countries:e.countries,starred:e.starred,image_count:e.image_count||1}};r&&r.file("0001.json",JSON.stringify(S,null,2))}}catch(n){throw console.error(`Failed to process image ${e.image_id}:`,n),n}}else if(e.image_type==="drone_image"){const r=h.folder("drone_images_dataset"),c=r?.folder("images");if(c)try{const n=await fetch(`/api/images/${e.image_id}/file`);if(!n.ok)throw new Error(`Failed to fetch image ${e.image_id}`);const y=await n.blob(),L=`0001.${e.file_key.split(".").pop()||"jpg"}`;if(c.file(L,y),t==="fine-tuning"){const u=[],S=[],_=[];if(String(e?.image_type)==="crisis_map"){const D=Math.random();D<R/100?u.push(P(e,"0001")):D<(R+J)/100?S.push(P(e,"0001")):_.push(P(e,"0001"))}else if(String(e?.image_type)==="drone_image"){const D=Math.random();D<R/100?u.push(P(e,"0001")):D<(R+J)/100?S.push(P(e,"0001")):_.push(P(e,"0001"))}r&&(r.file("train.jsonl",JSON.stringify(u,null,2)),r.file("test.jsonl",JSON.stringify(S,null,2)),r.file("val.jsonl",JSON.stringify(_,null,2)))}else{const u={image:`images/${L}`,caption:e.edited||e.generated||"",metadata:{image_id:e.image_count&&e.image_count>1?e.all_image_ids||[e.image_id]:e.image_id,title:e.title,source:e.source,event_type:e.event_type,image_type:e.image_type,countries:e.countries,starred:e.starred,image_count:e.image_count||1}};r&&r.file("0001.json",JSON.stringify(u,null,2))}}catch(n){throw console.error(`Failed to process image ${e.image_id}:`,n),n}}else{const r=h.folder("generic_dataset"),c=r?.folder("images");if(c)try{const n=await fetch(`/api/images/${e.image_id}/file`);if(!n.ok)throw new Error(`Failed to fetch image ${e.image_id}`);const y=await n.blob(),L=`0001.${e.file_key.split(".").pop()||"jpg"}`;if(c.file(L,y),t==="fine-tuning"){const u=[],S=[],_=[];if(String(e?.image_type)==="crisis_map"){const D=Math.random();D<R/100?u.push(P(e,"0001")):D<(R+J)/100?S.push(P(e,"0001")):_.push(P(e,"0001"))}else if(String(e?.image_type)==="drone_image"){const D=Math.random();D<R/100?u.push(P(e,"0001")):D<(R+J)/100?S.push(P(e,"0001")):_.push(P(e,"0001"))}r&&(r.file("train.jsonl",JSON.stringify(u,null,2)),r.file("test.jsonl",JSON.stringify(S,null,2)),r.file("val.jsonl",JSON.stringify(_,null,2)))}else{const u={image:`images/${L}`,caption:e.edited||e.generated||"",metadata:{image_id:e.image_count&&e.image_count>1?e.all_image_ids||[e.image_id]:e.image_id,title:e.title,source:e.source,event_type:e.event_type,image_type:e.image_type,countries:e.countries,starred:e.starred,image_count:e.image_count||1}};r&&r.file("0001.json",JSON.stringify(u,null,2))}}catch(n){throw console.error(`Failed to process image ${e.image_id}:`,n),n}}const s=await h.generateAsync({type:"blob"}),l=URL.createObjectURL(s),i=document.createElement("a");i.href=l,i.download=`dataset_${e.image_type}_${e.image_id}_${t}_${new Date().toISOString().split("T")[0]}.zip`,document.body.appendChild(i),i.click(),document.body.removeChild(i),URL.revokeObjectURL(l),console.log(`Exported ${e.image_type} dataset with 1 image in ${t} mode`),ae(!0)}catch(o){console.error("Export failed:",o),alert("Failed to export dataset. Please try again.")}finally{ee(!1)}}};return W?a.jsx(X,{children:a.jsx("div",{className:f.loadingContainer,children:a.jsxs("div",{className:"flex flex-col items-center gap-4",children:[a.jsx(ve,{className:"text-ifrcRed"}),a.jsx("div",{children:"Loading map details..."})]})})}):re||!e?a.jsx(X,{children:a.jsx("div",{className:f.errorContainer,children:a.jsxs("div",{className:"flex flex-col items-center gap-4 text-center",children:[a.jsx("div",{className:"text-4xl",children:"β οΈ"}),a.jsx("div",{className:"text-xl font-semibold",children:"Unable to load map"}),a.jsx("div",{children:re||"Map not found"}),a.jsx(F,{name:"back-to-explore",variant:"secondary",onClick:()=>v("/explore"),children:"Return to Explore"})]})})}):a.jsxs(X,{children:[a.jsxs("div",{className:"max-w-7xl mx-auto",children:[a.jsxs("div",{className:f.tabSelector,children:[a.jsx(aa,{name:"map-details-view",value:ne,onChange:t=>{(t==="mapDetails"||t==="explore")&&(Ce(t),t==="explore"&&v("/explore"))},options:Oe,keySelector:t=>t.key,labelSelector:t=>t.label}),a.jsxs("div",{className:"flex items-center gap-2 ml-auto",children:[a.jsx(E,{withInternalPadding:!0,className:"bg-white/20 backdrop-blur-sm rounded-md p-2",children:a.jsxs(F,{name:"reference-examples",variant:k?"primary":"secondary",onClick:()=>Ae(!k),className:"whitespace-nowrap",children:[a.jsx("span",{className:"mr-2",children:k?a.jsx("span",{className:"text-yellow-400",children:"β
"}):a.jsx("span",{className:"text-yellow-400",children:"β"})}),"Reference Examples"]})}),a.jsx(F,{name:"export-dataset",variant:"secondary",onClick:()=>K(!0),children:"Export"})]})]}),a.jsx(na,{sources:le,types:ce,regions:ge,countries:Se,imageTypes:de,isLoadingFilters:!1}),ne==="mapDetails"?a.jsx("div",{className:"relative",children:g?a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:f.gridLayout,children:[a.jsxs(E,{heading:a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{children:g.title||"Map Image"}),g.starred&&a.jsx("span",{className:"text-red-500 text-xl",title:"Starred image",children:"β
"})]}),headingLevel:2,withHeaderBorder:!0,withInternalPadding:!0,spacing:"comfortable",children:[a.jsx("div",{className:f.imageContainer,children:e?.image_count&&e.image_count>1||x.length>1?a.jsxs("div",{className:f.carouselContainer,children:[a.jsx("div",{className:f.carouselImageWrapper,children:V?a.jsxs("div",{className:f.imagePlaceholder,children:[a.jsx(ve,{className:"text-ifrcRed"}),a.jsx("div",{children:"Loading images..."})]}):x[M]?.detail_url?a.jsx("img",{src:x[M].detail_url,alt:x[M].file_key,className:f.carouselImage,onError:t=>{console.log("MapDetailsPage: Detail image failed to load, falling back to original:",x[M].detail_url);const o=t.target;x[M].image_url&&(o.src=x[M].image_url)},onLoad:()=>console.log("MapDetailsPage: Detail image loaded successfully:",x[M].detail_url)}):x[M]?.image_url?a.jsx("img",{src:x[M].image_url,alt:x[M].file_key,className:f.carouselImage,onLoad:()=>console.log("MapDetailsPage: Original image loaded successfully:",x[M].image_url)}):a.jsx("div",{className:f.imagePlaceholder,children:"No image available"})}),a.jsxs("div",{className:f.carouselNavigation,children:[a.jsx(F,{name:"previous-image",variant:"tertiary",size:1,onClick:Ue,disabled:V,className:f.carouselButton,children:a.jsx(se,{className:"w-4 h-4"})}),a.jsx("div",{className:f.carouselIndicators,children:x.map((t,o)=>a.jsx("button",{onClick:()=>Be(o),className:`${f.carouselIndicator} ${o===M?f.carouselIndicatorActive:""}`,disabled:V,children:o+1},o))}),a.jsx(F,{name:"next-image",variant:"tertiary",size:1,onClick:We,disabled:V,className:f.carouselButton,children:a.jsx(ie,{className:"w-4 h-4"})})]}),a.jsx("div",{className:f.viewImageButtonContainer,children:a.jsx(F,{name:"view-full-size-carousel",variant:"secondary",size:1,onClick:()=>xe(x[M]),disabled:V||!x[M]?.image_url,children:"View Image"})})]}):a.jsxs("div",{className:f.singleImageContainer,children:[g.detail_url?a.jsx("img",{src:g.detail_url,alt:g.file_key,onError:t=>{console.log("MapDetailsPage: Detail image failed to load, falling back to original:",g.detail_url);const o=t.target;g.image_url&&(o.src=g.image_url)},onLoad:()=>console.log("MapDetailsPage: Detail image loaded successfully:",g.detail_url)}):g.image_url?a.jsx("img",{src:g.image_url,alt:g.file_key,onLoad:()=>console.log("MapDetailsPage: Original image loaded successfully:",g.image_url)}):a.jsx("div",{className:f.imagePlaceholder,children:"No image available"}),a.jsx("div",{className:f.viewImageButtonContainer,children:a.jsx(F,{name:"view-full-size-single",variant:"secondary",size:1,onClick:()=>xe(g),disabled:!g.image_url,children:"View Image"})})]})}),a.jsx(E,{withInternalPadding:!0,className:"bg-white/20 backdrop-blur-sm rounded-md p-2",children:a.jsxs("div",{className:f.metadataTags,children:[g.image_type!=="drone_image"&&a.jsx("span",{className:f.metadataTag,children:le.find(t=>t.s_code===g.source)?.label||g.source}),a.jsx("span",{className:f.metadataTag,children:ce.find(t=>t.t_code===g.event_type)?.label||g.event_type}),a.jsx("span",{className:f.metadataTag,children:de.find(t=>t.image_type===g.image_type)?.label||g.image_type}),g.countries&&g.countries.length>0&&a.jsxs(a.Fragment,{children:[a.jsx("span",{className:f.metadataTag,children:ge.find(t=>t.r_code===g.countries[0].r_code)?.label||"Unknown Region"}),a.jsx("span",{className:f.metadataTag,children:g.countries.map(t=>t.label).join(", ")})]}),g.image_count&&g.image_count>1&&a.jsxs("span",{className:f.metadataTag,title:`Multi-upload with ${g.image_count} images`,children:["π· ",g.image_count]}),(!g.image_count||g.image_count<=1)&&a.jsx("span",{className:f.metadataTag,title:"Single Upload",children:"Single"})]})})]}),a.jsx("div",{className:f.detailsSection,children:g.edited&&g.edited.includes("Description:")||g.generated&&g.generated.includes("Description:")?a.jsx(E,{heading:"AI Generated Content",headingLevel:3,withHeaderBorder:!0,withInternalPadding:!0,spacing:"comfortable",children:a.jsx("div",{className:f.captionContainer,children:a.jsx("div",{className:f.captionText,children:(g.edited||g.generated||"").split(`
|
3 |
`).map((t,o)=>a.jsx("div",{children:t.startsWith("Description:")||t.startsWith("Analysis:")||t.startsWith("Recommended Actions:")?a.jsx("h4",{className:"font-semibold text-gray-800 mt-4 mb-2",children:t}):t.trim()===""?a.jsx("br",{}):a.jsx("p",{className:"mb-2",children:t})},o))})})}):a.jsx(E,{heading:"Description",headingLevel:3,withHeaderBorder:!0,withInternalPadding:!0,spacing:"comfortable",children:a.jsx("div",{className:f.captionContainer,children:g.generated?a.jsx("div",{className:f.captionText,children:a.jsx("p",{children:g.edited||g.generated})}):a.jsx("p",{children:"β no caption yet β"})})})})]}),a.jsx("div",{className:"flex items-center justify-center mt-8",children:a.jsx(E,{withInternalPadding:!0,className:"bg-white/20 backdrop-blur-sm rounded-lg p-4",children:a.jsxs("div",{className:"flex items-center gap-4",children:[De&&a.jsx(E,{withInternalPadding:!0,className:"rounded-md p-2",children:a.jsx(F,{name:"previous-item",variant:"tertiary",size:1,className:`bg-white/90 hover:bg-white shadow-lg border border-gray-200 ${B?"opacity-50 cursor-not-allowed":"hover:scale-110"}`,onClick:()=>ye("previous"),disabled:B,children:a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsxs("div",{className:"flex -space-x-1",children:[a.jsx(se,{className:"w-4 h-4"}),a.jsx(se,{className:"w-4 h-4"})]}),a.jsx("span",{className:"font-semibold",children:"Previous"})]})})}),oe&&a.jsx(E,{withInternalPadding:!0,className:"rounded-md p-2",children:a.jsx(F,{name:"delete",variant:"tertiary",size:1,className:"bg-red-50 hover:bg-red-100 text-red-700 border border-red-200 hover:border-red-300",onClick:He,title:"Delete","aria-label":"Delete saved image",children:a.jsx(ta,{className:"w-4 h-4"})})}),a.jsx(E,{withInternalPadding:!0,className:"rounded-md p-2",children:a.jsx(F,{name:"contribute",onClick:Ke,children:"Contribute"})}),oe&&a.jsx(E,{withInternalPadding:!0,className:"rounded-md p-2",children:a.jsx(F,{name:"toggle-star",variant:"tertiary",size:1,className:`${e?.starred?"bg-red-100 hover:bg-red-200 text-red-800 border-2 border-red-400":"bg-gray-100 hover:bg-gray-200 text-gray-600 border-2 border-gray-300"} w-16 h-8 rounded-full transition-all duration-200 flex items-center justify-center`,onClick:Ve,title:e?.starred?"Unstar image":"Star image","aria-label":e?.starred?"Unstar image":"Star image",children:a.jsx("span",{className:`text-lg transition-all duration-200 ${e?.starred?"text-red-600":"text-gray-500"}`,children:e?.starred?"β
":"β"})})}),Me&&a.jsx(E,{withInternalPadding:!0,className:"rounded-md p-2",children:a.jsx(F,{name:"next-item",variant:"tertiary",size:1,className:`bg-white/90 hover:bg-white shadow-lg border border-gray-200 ${B?"opacity-50 cursor-not-allowed":"hover:scale-110"}`,onClick:()=>ye("next"),disabled:B,children:a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx("span",{className:"font-semibold",children:"Next"}),a.jsxs("div",{className:"flex -space-x-1",children:[a.jsx(ie,{className:"w-4 h-4"}),a.jsx(ie,{className:"w-4 h-4"})]})]})})})]})})})]}):a.jsxs("div",{className:"text-center py-12",children:[a.jsx("div",{className:"text-xl font-semibold text-gray-600 mb-4",children:"No matches found"}),a.jsx("div",{className:"mt-4",children:a.jsx(F,{name:"clear-filters",variant:"secondary",onClick:ze,children:"Clear Filters"})})]})}):null]}),Fe&&a.jsx("div",{className:f.fullSizeModalOverlay,onClick:()=>q(!1),children:a.jsx("div",{className:f.fullSizeModalContent,onClick:t=>t.stopPropagation(),children:a.jsxs("div",{className:f.ratingWarningContent,children:[a.jsx("h3",{className:f.ratingWarningTitle,children:"Delete Image?"}),a.jsx("p",{className:f.ratingWarningText,children:"This action cannot be undone. Are you sure you want to delete this saved image and all related data?"}),a.jsxs("div",{className:f.ratingWarningButtons,children:[a.jsx(F,{name:"confirm-delete",variant:"secondary",onClick:Ge,children:"Delete"}),a.jsx(F,{name:"cancel-delete",variant:"tertiary",onClick:()=>q(!1),children:"Cancel"})]})]})})}),me&&a.jsx(ra,{isOpen:me,onClose:()=>{K(!1),ae(!1),ee(!1)},onExport:(t,o)=>{o.includes(e.image_type)&&Ze(t)},filteredCount:1,totalCount:1,hasFilters:!1,crisisMapsCount:e.image_type==="crisis_map"?1:0,droneImagesCount:e.image_type==="drone_image"?1:0,isLoading:Pe,exportSuccess:Ee,variant:"single",onNavigateToList:()=>{K(!1),v("/explore")},onNavigateAndExport:()=>{K(!1),v("/explore?export=true")}}),a.jsx(sa,{isOpen:Re,imageUrl:$e?.image_url||null,preview:null,selectedImageData:null,onClose:Je})]})}export{at as default};
|
py_backend/static/assets/index-GUsf-iOM.js
DELETED
@@ -1,2 +0,0 @@
|
|
1 |
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/jszip.min-DgY44d1h.js","assets/index-LmdVBMha.js","assets/index-FBu17hMI.css"])))=>i.map(i=>d[i]);
|
2 |
-
import{j as t,z as T,n as I,v as ke,w as Fe,x as De,B as Le,r as c,D as Oe,N as Me,_ as me,L as Re,F as Je,G as ze}from"./index-LmdVBMha.js";import{u as We}from"./useAdmin-BGW0gk2h.js";import{F as Ue,E as Ae}from"./ExportModal-k_VKbTpi.js";const Be="_paginatorContainer_1l5ti_1",He="_paginationControls_1l5ti_19",de={paginatorContainer:Be,paginationControls:He};function Ve({currentPage:j,totalPages:h,totalItems:Y,itemsPerPage:B,onPageChange:$,className:_=""}){if(h<=1)return null;const g=(()=>{const u=[];if(h<=5)for(let f=1;f<=h;f++)u.push(f);else{let f=Math.max(1,j-2),w=Math.min(h,f+5-1);w===h&&(f=Math.max(1,w-5+1));for(let b=f;b<=w;b++)u.push(b)}return u})();return t.jsx("div",{className:`${de.paginatorContainer} ${_}`,children:t.jsxs("div",{className:de.paginationControls,children:[t.jsx(T,{withInternalPadding:!0,className:"bg-white/20 backdrop-blur-sm rounded-md p-2",children:t.jsxs(I,{name:"prev-page",variant:"tertiary",size:1,onClick:()=>$(Math.max(1,j-1)),disabled:j===1,title:"Previous page",children:[t.jsx(ke,{className:"w-4 h-4"}),t.jsx("span",{className:"hidden sm:inline",children:"Previous"})]})}),t.jsxs("div",{className:"flex items-center gap-1",children:[g[0]>1&&t.jsxs(t.Fragment,{children:[t.jsx(T,{withInternalPadding:!0,className:"bg-white/20 backdrop-blur-sm rounded-md p-2",children:t.jsx(I,{name:"page-1",variant:"tertiary",size:1,onClick:()=>$(1),children:"1"})}),g[0]>2&&t.jsx(T,{withInternalPadding:!0,className:"bg-white/20 backdrop-blur-sm rounded-md p-2",children:t.jsx("span",{className:"px-2 text-gray-500",children:"..."})})]}),g.map(u=>t.jsx(T,{withInternalPadding:!0,className:"bg-white/20 backdrop-blur-sm rounded-md p-2",children:t.jsx(I,{name:`page-${u}`,variant:j===u?"primary":"tertiary",size:1,onClick:()=>$(u),children:u})},u)),g[g.length-1]<h&&t.jsxs(t.Fragment,{children:[g[g.length-1]<h-1&&t.jsx(T,{withInternalPadding:!0,className:"bg-white/20 backdrop-blur-sm rounded-md p-2",children:t.jsx("span",{className:"px-2 text-gray-500",children:"..."})}),t.jsx(T,{withInternalPadding:!0,className:"bg-white/20 backdrop-blur-sm rounded-md p-2",children:t.jsx(I,{name:`page-${h}`,variant:"tertiary",size:1,onClick:()=>$(h),children:h})})]})]}),t.jsx(T,{withInternalPadding:!0,className:"bg-white/20 backdrop-blur-sm rounded-md p-2",children:t.jsxs(I,{name:"next-page",variant:"tertiary",size:1,onClick:()=>$(Math.min(h,j+1)),disabled:j===h,title:"Next page",children:[t.jsx("span",{className:"hidden sm:inline",children:"Next"}),t.jsx(Fe,{className:"w-4 h-4"})]})})]})})}const Ge="_tabSelector_o9y1f_1",Ze="_metadataTags_o9y1f_8",qe="_metadataTag_o9y1f_8",Ke="_metadataTagSource_o9y1f_32",Qe="_metadataTagType_o9y1f_43",Xe="_mapItem_o9y1f_54",Ye="_mapItemImage_o9y1f_72",et="_mapItemContent_o9y1f_92",tt="_mapItemTitle_o9y1f_97",at="_mapItemMetadata_o9y1f_105",st="_fullSizeModalOverlay_o9y1f_134",it="_fullSizeModalContent_o9y1f_148",nt="_ratingWarningContent_o9y1f_159",lt="_ratingWarningTitle_o9y1f_165",rt="_ratingWarningText_o9y1f_172",ot="_ratingWarningButtons_o9y1f_179",d={tabSelector:Ge,metadataTags:Ze,metadataTag:qe,metadataTagSource:Ke,metadataTagType:Qe,mapItem:Xe,mapItemImage:Ye,mapItemContent:et,mapItemTitle:tt,mapItemMetadata:at,fullSizeModalOverlay:st,fullSizeModalContent:it,ratingWarningContent:nt,ratingWarningTitle:lt,ratingWarningText:rt,ratingWarningButtons:ot};function gt(){const j=De(),h=Le(),{isAuthenticated:Y}=We(),[B,$]=c.useState("explore"),[_,R]=c.useState([]),{search:g,srcFilter:u,catFilter:P,regionFilter:f,countryFilter:w,imageTypeFilter:b,uploadTypeFilter:M,showReferenceExamples:E,setShowReferenceExamples:ge}=Oe(),[H,pe]=c.useState([]),[V,ue]=c.useState([]),[ee,he]=c.useState([]),[fe,xe]=c.useState([]),[te,_e]=c.useState([]),[ye,ae]=c.useState(!0),[J,se]=c.useState(!0),[je,G]=c.useState(!1),[ve,Z]=c.useState(!1),[Ne,q]=c.useState(!1),[we,z]=c.useState(!1),[W,ie]=c.useState(""),[K,ne]=c.useState(!1),[le,re]=c.useState(1),[U]=c.useState(10),be=[{key:"explore",label:"List"},{key:"mapDetails",label:"Carousel"}],oe=()=>{se(!0),fetch("/api/images/grouped").then(e=>e.ok?e.json():(console.error("ExplorePage: Grouped endpoint failed, trying legacy endpoint"),fetch("/api/captions/legacy").then(s=>s.ok?s.json():(console.error("ExplorePage: Legacy endpoint failed, trying regular images endpoint"),fetch("/api/images").then(i=>{if(!i.ok)throw new Error(`HTTP ${i.status}: ${i.statusText}`);return i.json()}))))).then(e=>{if(console.log("ExplorePage: API response data:",e),Array.isArray(e)){const s=e.filter(i=>{const v=i.generated&&i.model,y=i.image_id&&i.image_id!=="undefined"&&i.image_id!=="null";return y||console.error("ExplorePage: Item missing valid image_id:",i),v&&y});console.log("ExplorePage: Filtered images with captions:",s.length),R(s)}else console.error("ExplorePage: API response is not an array:",e),R([])}).catch(()=>{R([])}).finally(()=>{se(!1)})};c.useEffect(()=>{oe()},[]),c.useEffect(()=>{const e=()=>{document.hidden||oe()};return document.addEventListener("visibilitychange",e),()=>{document.removeEventListener("visibilitychange",e)}},[]),c.useEffect(()=>{new URLSearchParams(h.search).get("export")==="true"&&(G(!0),j("/explore",{replace:!0}))},[h.search,j,g,u,P,f,w,b,E]),c.useEffect(()=>{ae(!0),Promise.all([fetch("/api/sources").then(e=>{if(!e.ok)throw new Error(`HTTP ${e.status}: ${e.statusText}`);return e.json()}),fetch("/api/types").then(e=>{if(!e.ok)throw new Error(`HTTP ${e.status}: ${e.statusText}`);return e.json()}),fetch("/api/regions").then(e=>{if(!e.ok)throw new Error(`HTTP ${e.status}: ${e.statusText}`);return e.json()}),fetch("/api/countries").then(e=>{if(!e.ok)throw new Error(`HTTP ${e.status}: ${e.statusText}`);return e.json()}),fetch("/api/image-types").then(e=>{if(!e.ok)throw new Error(`HTTP ${e.status}: ${e.statusText}`);return e.json()})]).then(([e,s,i,v,y])=>{pe(e),ue(s),he(i),xe(v),_e(y)}).catch(()=>{}).finally(()=>{ae(!1)})},[]);const S=c.useMemo(()=>_.filter(e=>{const s=!g||e.title?.toLowerCase().includes(g.toLowerCase())||e.generated?.toLowerCase().includes(g.toLowerCase())||e.source?.toLowerCase().includes(g.toLowerCase())||e.event_type?.toLowerCase().includes(g.toLowerCase()),i=!u||e.source&&e.source.split(", ").some(C=>C.trim()===u),v=!P||e.event_type&&e.event_type.split(", ").some(C=>C.trim()===P),y=!f||e.countries.some(C=>C.r_code===f),k=!w||e.countries.some(C=>C.c_code===w),Q=!b||e.image_type===b,A=!M||M==="single"&&(!e.image_count||e.image_count<=1)||M==="multiple"&&e.image_count&&e.image_count>1,F=!E||e.starred===!0;return s&&i&&v&&y&&k&&Q&&A&&F}),[_,g,u,P,f,w,b,M,E]),Se=Math.ceil(S.length/U),ce=(le-1)*U,Te=ce+U,Ie=S.slice(ce,Te);c.useEffect(()=>{re(1)},[g,u,P,f,w,b,M,E]);const Ce=async(e,s="fine-tuning")=>{if(e.length===0){alert("No images to export");return}Z(!0),q(!1);try{const i=(await ze(async()=>{const{default:n}=await import("./jszip.min-DgY44d1h.js").then(D=>D.j);return{default:n}},__vite__mapDeps([0,1,2]))).default,v=new i,y=e.filter(n=>n.image_type==="crisis_map"),k=e.filter(n=>n.image_type==="drone_image");if(y.length>0){const n=v.folder("crisis_maps_dataset"),D=n?.folder("images");if(D){let L=1;for(const a of y)try{const N=a.image_count&&a.image_count>1?a.all_image_ids||[a.image_id]:[a.image_id],X=N.map(async(l,x)=>{try{const r=await fetch(`/api/images/${l}/file`);if(!r.ok)throw new Error(`Failed to fetch image ${l}`);const o=await r.blob(),m=a.file_key.split(".").pop()||"jpg",p=`${String(L).padStart(4,"0")}_${String(x+1).padStart(2,"0")}.${m}`;return D.file(p,o),{success:!0,fileName:p,imageId:l}}catch(r){return console.error(`Failed to process image ${l}:`,r),{success:!1,fileName:"",imageId:l}}}),O=(await Promise.all(X)).filter(l=>l.success);if(O.length>0){if(s==="fine-tuning"){const l=O.map(o=>`images/${o.fileName}`),x=Math.random(),r={image:l.length===1?l[0]:l,caption:a.edited||a.generated||"",metadata:{image_id:N,title:a.title,source:a.source,event_type:a.event_type,image_type:a.image_type,countries:a.countries,starred:a.starred,image_count:a.image_count||1}};if(!n)continue;if(x<.8){const o=n.file("train.jsonl");if(o){const m=await o.async("string").then(p=>JSON.parse(p||"[]")).catch(()=>[]);m.push(r),n.file("train.jsonl",JSON.stringify(m,null,2))}else n.file("train.jsonl",JSON.stringify([r],null,2))}else if(x<.9){const o=n.file("test.jsonl");if(o){const m=await o.async("string").then(p=>JSON.parse(p||"[]")).catch(()=>[]);m.push(r),n.file("test.jsonl",JSON.stringify(m,null,2))}else n.file("test.jsonl",JSON.stringify([r],null,2))}else{const o=n.file("val.jsonl");if(o){const m=await o.async("string").then(p=>JSON.parse(p||"[]")).catch(()=>[]);m.push(r),n.file("val.jsonl",JSON.stringify(m,null,2))}else n.file("val.jsonl",JSON.stringify([r],null,2))}}else{const l=O.map(r=>`images/${r.fileName}`),x={image:l.length===1?l[0]:l,caption:a.edited||a.generated||"",metadata:{image_id:N,title:a.title,source:a.source,event_type:a.event_type,image_type:a.image_type,countries:a.countries,starred:a.starred,image_count:a.image_count||1}};n&&n.file(`${String(L).padStart(4,"0")}.json`,JSON.stringify(x,null,2))}L++}}catch(N){console.error(`Failed to process caption ${a.image_id}:`,N)}}}if(k.length>0){const n=v.folder("drone_images_dataset"),D=n?.folder("images");if(D){let L=1;for(const a of k)try{const N=a.image_count&&a.image_count>1?a.all_image_ids||[a.image_id]:[a.image_id],X=N.map(async(l,x)=>{try{const r=await fetch(`/api/images/${l}/file`);if(!r.ok)throw new Error(`Failed to fetch image ${l}`);const o=await r.blob(),m=a.file_key.split(".").pop()||"jpg",p=`${String(L).padStart(4,"0")}_${String(x+1).padStart(2,"0")}.${m}`;return D.file(p,o),{success:!0,fileName:p,imageId:l}}catch(r){return console.error(`Failed to process image ${l}:`,r),{success:!1,fileName:"",imageId:l}}}),O=(await Promise.all(X)).filter(l=>l.success);if(O.length>0){if(s==="fine-tuning"){const l=O.map(o=>`images/${o.fileName}`),x=Math.random(),r={image:l.length===1?l[0]:l,caption:a.edited||a.generated||"",metadata:{image_id:N,title:a.title,source:a.source,event_type:a.event_type,image_type:a.image_type,countries:a.countries,starred:a.starred,image_count:a.image_count||1}};if(!n)continue;if(x<.8){const o=n.file("train.jsonl");if(o){const m=await o.async("string").then(p=>JSON.parse(p||"[]")).catch(()=>[]);m.push(r),n.file("train.jsonl",JSON.stringify(m,null,2))}else n.file("train.jsonl",JSON.stringify([r],null,2))}else if(x<.9){const o=n.file("test.jsonl");if(o){const m=await o.async("string").then(p=>JSON.parse(p||"[]")).catch(()=>[]);m.push(r),n.file("test.jsonl",JSON.stringify(m,null,2))}else n.file("test.jsonl",JSON.stringify([r],null,2))}else{const o=n.file("val.jsonl");if(o){const m=await o.async("string").then(p=>JSON.parse(p||"[]")).catch(()=>[]);m.push(r),n.file("val.jsonl",JSON.stringify(m,null,2))}else n.file("val.jsonl",JSON.stringify([r],null,2))}}else{const l=O.map(r=>`images/${r.fileName}`),x={image:l.length===1?l[0]:l,caption:a.edited||a.generated||"",metadata:{image_id:N,title:a.title,source:a.source,event_type:a.event_type,image_type:a.image_type,countries:a.countries,starred:a.starred,image_count:a.image_count||1}};n&&n.file(`${String(L).padStart(4,"0")}.json`,JSON.stringify(x,null,2))}L++}}catch(N){console.error(`Failed to process caption ${a.image_id}:`,N)}}}const Q=await v.generateAsync({type:"blob"}),A=URL.createObjectURL(Q),F=document.createElement("a");F.href=A,F.download=`datasets_${s}_${new Date().toISOString().split("T")[0]}.zip`,document.body.appendChild(F),F.click(),document.body.removeChild(F),URL.revokeObjectURL(A);const C=(y.length||0)+(k.length||0);console.log(`Exported ${s} datasets with ${C} total images:`),y.length>0&&console.log(`- Crisis maps: ${y.length} images`),k.length>0&&console.log(`- Drone images: ${k.length} images`),q(!0)}catch(i){console.error("Export failed:",i),alert("Failed to export dataset. Please try again.")}finally{Z(!1)}},Ee=e=>{ie(e),z(!0)},$e=async()=>{if(W){ne(!0);try{console.log("Deleting image with ID:",W),(await fetch(`/api/images/${W}`,{method:"DELETE"})).ok?(R(s=>s.filter(i=>i.image_id!==W)),z(!1),ie("")):(console.error("Delete failed"),alert("Failed to delete image. Please try again."))}catch(e){console.error("Delete failed:",e),alert("Failed to delete image. Please try again.")}finally{ne(!1)}}};return t.jsxs(Me,{children:[J?t.jsx("div",{className:"flex flex-col items-center justify-center min-h-[60vh]",children:t.jsxs("div",{className:"flex flex-col items-center gap-4",children:[t.jsx(me,{className:"text-ifrcRed"}),t.jsx("div",{children:"Loading examples..."})]})}):t.jsxs("div",{className:"max-w-7xl mx-auto",children:[t.jsxs("div",{className:d.tabSelector,children:[t.jsx(Re,{name:"explore-view",value:B,onChange:e=>{(e==="explore"||e==="mapDetails")&&($(e),e==="mapDetails"&&_.length>0&&(_[0]?.image_id&&_[0].image_id!=="undefined"&&_[0].image_id!=="null"?j(`/map/${_[0].image_id}`):console.error("Invalid image_id for navigation:",_[0]?.image_id)))},options:be,keySelector:e=>e.key,labelSelector:e=>e.label}),t.jsxs("div",{className:"flex items-center gap-2 ml-auto",children:[t.jsx(T,{withInternalPadding:!0,className:"bg-white/20 backdrop-blur-sm rounded-md p-2",children:t.jsxs(I,{name:"reference-examples",variant:E?"primary":"secondary",onClick:()=>ge(!E),className:"whitespace-nowrap",children:[t.jsx("span",{className:"mr-2",children:E?t.jsx("span",{className:"text-yellow-400",children:"β
"}):t.jsx("span",{className:"text-yellow-400",children:"β"})}),"Reference Examples"]})}),t.jsx(I,{name:"export-dataset",variant:"secondary",onClick:()=>G(!0),children:"Export"})]})]}),B==="explore"?t.jsxs("div",{className:"space-y-6",children:[t.jsx("div",{className:"mb-6 space-y-4",children:t.jsx("div",{className:"flex flex-wrap items-center gap-4",children:t.jsx(T,{withInternalPadding:!0,className:"bg-white/20 backdrop-blur-sm rounded-md p-2 flex-1 min-w-[300px]",children:t.jsx(Ue,{sources:H,types:V,regions:ee,countries:fe,imageTypes:te,isLoadingFilters:ye})})})}),t.jsxs("div",{className:"space-y-4",children:[t.jsx("div",{className:"flex justify-between items-center",children:t.jsxs("p",{className:"text-sm text-gray-600",children:[S.length," of ",_.length," examples"]})}),J&&t.jsx("div",{className:"text-center py-12",children:t.jsxs("div",{className:"flex flex-col items-center gap-4",children:[t.jsx(me,{className:"text-ifrcRed"}),t.jsx("div",{children:"Loading examples..."})]})}),!J&&t.jsxs("div",{className:"space-y-4",children:[Ie.map(e=>t.jsxs("div",{className:"flex items-center gap-4",children:[t.jsxs("div",{className:`${d.mapItem} flex-1`,onClick:()=>{console.log("ExplorePage: Clicking on image with ID:",e.image_id),console.log("ExplorePage: Image data:",e),e.image_id&&e.image_id!=="undefined"&&e.image_id!=="null"?(console.log("ExplorePage: Navigating to:",`/map/${e.image_id}`),console.log("ExplorePage: Full navigation URL:",`/#/map/${e.image_id}`),j(`/map/${e.image_id}`)):(console.error("Invalid image_id for navigation:",e.image_id),console.error("Full item data:",JSON.stringify(e,null,2)),alert(`Cannot navigate: Invalid image ID (${e.image_id})`))},children:[t.jsx("div",{className:d.mapItemImage,style:{width:"120px",height:"80px"},children:e.thumbnail_url?t.jsxs(t.Fragment,{children:[console.log("ExplorePage: Using thumbnail for fast loading:",e.thumbnail_url),t.jsx("img",{src:e.thumbnail_url,alt:e.file_key,onError:s=>{console.error("ExplorePage: Thumbnail failed to load, falling back to original:",e.thumbnail_url);const i=s.target;e.image_url?i.src=e.image_url:(i.style.display="none",i.parentElement.innerHTML="Img")},onLoad:()=>console.log("ExplorePage: Thumbnail loaded successfully:",e.thumbnail_url)})]}):e.image_url?t.jsxs(t.Fragment,{children:[console.log("ExplorePage: No thumbnail available, using original image:",e.image_url),t.jsx("img",{src:e.image_url,alt:e.file_key,onError:s=>{console.error("ExplorePage: Original image failed to load:",e.image_url);const i=s.target;i.style.display="none",i.parentElement.innerHTML="Img"},onLoad:()=>console.log("ExplorePage: Original image loaded successfully:",e.image_url)})]}):t.jsxs(t.Fragment,{children:[console.log("ExplorePage: No image_url or thumbnail provided for item:",e),"'Img'"]})}),t.jsxs("div",{className:d.mapItemContent,children:[t.jsx("h3",{className:d.mapItemTitle,children:t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("span",{children:e.title||"Untitled"}),e.starred&&t.jsx("span",{className:"text-red-500 text-lg",title:"Starred image",children:"β
"})]})}),t.jsx("div",{className:d.mapItemMetadata,children:t.jsxs("div",{className:d.metadataTags,children:[e.image_type!=="drone_image"&&t.jsx("span",{className:d.metadataTagSource,children:e.source&&e.source.includes(", ")?e.source.split(", ").map(s=>H.find(i=>i.s_code===s.trim())?.label||s.trim()).join(", "):H.find(s=>s.s_code===e.source)?.label||e.source}),t.jsx("span",{className:d.metadataTagType,children:e.event_type&&e.event_type.includes(", ")?e.event_type.split(", ").map(s=>V.find(i=>i.t_code===s.trim())?.label||s.trim()).join(", "):V.find(s=>s.t_code===e.event_type)?.label||e.event_type}),t.jsx("span",{className:d.metadataTag,children:te.find(s=>s.image_type===e.image_type)?.label||e.image_type}),e.image_count&&e.image_count>1&&t.jsxs("span",{className:d.metadataTag,title:`Multi-upload with ${e.image_count} images`,children:["π· ",e.image_count]}),(!e.image_count||e.image_count<=1)&&t.jsx("span",{className:d.metadataTag,title:"Single Upload",children:"Single"}),e.countries&&e.countries.length>0&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:d.metadataTag,children:ee.find(s=>s.r_code===e.countries[0].r_code)?.label||"Unknown Region"}),t.jsx("span",{className:d.metadataTag,children:e.countries.map(s=>s.label).join(", ")})]})]})})]})]}),Y&&t.jsx(T,{withInternalPadding:!0,className:"bg-white/20 backdrop-blur-sm rounded-md p-2",children:t.jsx(I,{name:`delete-${e.image_id}`,variant:"tertiary",size:1,className:"bg-red-50 hover:bg-red-100 text-red-700 border border-red-200 hover:border-red-300",onClick:()=>Ee(e.image_id),title:"Delete","aria-label":"Delete saved image",children:t.jsx(Je,{className:"w-4 h-4"})})})]},e.image_id)),!S.length&&t.jsx("div",{className:"text-center py-12",children:t.jsx("p",{className:"text-gray-500",children:"No examples found."})}),!J&&S.length>0&&t.jsx(Ve,{currentPage:le,totalPages:Se,totalItems:S.length,itemsPerPage:U,onPageChange:re})]})]})]}):t.jsx("div",{className:"space-y-6",children:t.jsxs("div",{className:"text-center py-12",children:[t.jsx("p",{className:"text-gray-500",children:"Map Details view coming soon..."}),t.jsx("p",{className:"text-sm text-gray-400 mt-2",children:"This will show detailed information about individual maps"})]})})]}),we&&t.jsx("div",{className:d.fullSizeModalOverlay,onClick:()=>z(!1),children:t.jsx("div",{className:d.fullSizeModalContent,onClick:e=>e.stopPropagation(),children:t.jsxs("div",{className:d.ratingWarningContent,children:[t.jsx("h3",{className:d.ratingWarningTitle,children:"Delete Image?"}),t.jsx("p",{className:d.ratingWarningText,children:"This action cannot be undone. Are you sure you want to delete this saved image and all related data?"}),t.jsxs("div",{className:d.ratingWarningButtons,children:[t.jsx(I,{name:"confirm-delete",variant:"secondary",onClick:$e,disabled:K,children:K?"Deleting...":"Delete"}),t.jsx(I,{name:"cancel-delete",variant:"tertiary",onClick:()=>z(!1),disabled:K,children:"Cancel"})]})]})})}),t.jsx(Ae,{isOpen:je,onClose:()=>{G(!1),q(!1),Z(!1)},onExport:(e,s)=>{const i=S.filter(v=>s.includes(v.image_type));Ce(i,e)},filteredCount:S.length,totalCount:_.length,hasFilters:!!(g||u||P||f||w||b||M||E),crisisMapsCount:S.filter(e=>e.image_type==="crisis_map").length,droneImagesCount:S.filter(e=>e.image_type==="drone_image").length,isLoading:ve,exportSuccess:Ne})]})}export{gt as default};
|
|
|
|
|
|
py_backend/static/assets/{jszip.min-DgY44d1h.js β jszip.min-JNyb8pkO.js}
RENAMED
@@ -1,4 +1,4 @@
|
|
1 |
-
import{W as bt,X as It}from"./index-
|
2 |
|
3 |
JSZip v3.10.1 - A JavaScript class for generating and reading zip files
|
4 |
<http://stuartk.com/jszip>
|
|
|
1 |
+
import{W as bt,X as It}from"./index-BzYyR-qc.js";function vt(yt){throw new Error('Could not dynamically require "'+yt+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var kt={exports:{}};/*!
|
2 |
|
3 |
JSZip v3.10.1 - A JavaScript class for generating and reading zip files
|
4 |
<http://stuartk.com/jszip>
|
py_backend/static/assets/{useAdmin-BGW0gk2h.js β useAdmin-B4TrJLwR.js}
RENAMED
@@ -1 +1 @@
|
|
1 |
-
import{r,V as e}from"./index-
|
|
|
1 |
+
import{r,V as e}from"./index-BzYyR-qc.js";const o=()=>{const t=r.useContext(e);if(t===void 0)throw new Error("useAdmin must be used within an AdminProvider");return t};export{o as u};
|
py_backend/static/index.html
CHANGED
@@ -42,7 +42,7 @@
|
|
42 |
});
|
43 |
}
|
44 |
</script>
|
45 |
-
<script type="module" crossorigin src="/assets/index-
|
46 |
<link rel="stylesheet" crossorigin href="/assets/index-FBu17hMI.css">
|
47 |
</head>
|
48 |
<body>
|
|
|
42 |
});
|
43 |
}
|
44 |
</script>
|
45 |
+
<script type="module" crossorigin src="/assets/index-BzYyR-qc.js"></script>
|
46 |
<link rel="stylesheet" crossorigin href="/assets/index-FBu17hMI.css">
|
47 |
</head>
|
48 |
<body>
|