Dabococo commited on
Commit
316492d
1 Parent(s): fc83033

Upload 2 files

Browse files
Files changed (2) hide show
  1. Untitled6.ipynb +1011 -0
  2. untitled6.py +234 -0
Untitled6.ipynb ADDED
@@ -0,0 +1,1011 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "nbformat": 4,
3
+ "nbformat_minor": 0,
4
+ "metadata": {
5
+ "colab": {
6
+ "provenance": [],
7
+ "gpuType": "T4"
8
+ },
9
+ "kernelspec": {
10
+ "name": "python3",
11
+ "display_name": "Python 3"
12
+ },
13
+ "language_info": {
14
+ "name": "python"
15
+ },
16
+ "accelerator": "GPU",
17
+ "widgets": {
18
+ "application/vnd.jupyter.widget-state+json": {
19
+ "a710457b00a849da9c24e1e1afb9d616": {
20
+ "model_module": "@jupyter-widgets/controls",
21
+ "model_name": "HBoxModel",
22
+ "model_module_version": "1.5.0",
23
+ "state": {
24
+ "_dom_classes": [],
25
+ "_model_module": "@jupyter-widgets/controls",
26
+ "_model_module_version": "1.5.0",
27
+ "_model_name": "HBoxModel",
28
+ "_view_count": null,
29
+ "_view_module": "@jupyter-widgets/controls",
30
+ "_view_module_version": "1.5.0",
31
+ "_view_name": "HBoxView",
32
+ "box_style": "",
33
+ "children": [
34
+ "IPY_MODEL_7b58972d4c704aa3bcc59a7a3c18682f",
35
+ "IPY_MODEL_624e284bf09843a7a0b10256fbc416d0",
36
+ "IPY_MODEL_e5b7191907914d75983b7e4b717b86d3"
37
+ ],
38
+ "layout": "IPY_MODEL_6434432da36a4755981ad001472e0cff"
39
+ }
40
+ },
41
+ "7b58972d4c704aa3bcc59a7a3c18682f": {
42
+ "model_module": "@jupyter-widgets/controls",
43
+ "model_name": "HTMLModel",
44
+ "model_module_version": "1.5.0",
45
+ "state": {
46
+ "_dom_classes": [],
47
+ "_model_module": "@jupyter-widgets/controls",
48
+ "_model_module_version": "1.5.0",
49
+ "_model_name": "HTMLModel",
50
+ "_view_count": null,
51
+ "_view_module": "@jupyter-widgets/controls",
52
+ "_view_module_version": "1.5.0",
53
+ "_view_name": "HTMLView",
54
+ "description": "",
55
+ "description_tooltip": null,
56
+ "layout": "IPY_MODEL_40a3244cfaa4404bb7ce4247564df6ed",
57
+ "placeholder": "​",
58
+ "style": "IPY_MODEL_234f2286e51c4a53b36584b49cd5a01f",
59
+ "value": "Upload file Wheeloh-model_1.pth: 100%"
60
+ }
61
+ },
62
+ "624e284bf09843a7a0b10256fbc416d0": {
63
+ "model_module": "@jupyter-widgets/controls",
64
+ "model_name": "FloatProgressModel",
65
+ "model_module_version": "1.5.0",
66
+ "state": {
67
+ "_dom_classes": [],
68
+ "_model_module": "@jupyter-widgets/controls",
69
+ "_model_module_version": "1.5.0",
70
+ "_model_name": "FloatProgressModel",
71
+ "_view_count": null,
72
+ "_view_module": "@jupyter-widgets/controls",
73
+ "_view_module_version": "1.5.0",
74
+ "_view_name": "ProgressView",
75
+ "bar_style": "success",
76
+ "description": "",
77
+ "description_tooltip": null,
78
+ "layout": "IPY_MODEL_66ade188379547aaae0724b4e3d87051",
79
+ "max": 44782274,
80
+ "min": 0,
81
+ "orientation": "horizontal",
82
+ "style": "IPY_MODEL_4f8c9691cd1b4faab91f7fb34348b716",
83
+ "value": 44782274
84
+ }
85
+ },
86
+ "e5b7191907914d75983b7e4b717b86d3": {
87
+ "model_module": "@jupyter-widgets/controls",
88
+ "model_name": "HTMLModel",
89
+ "model_module_version": "1.5.0",
90
+ "state": {
91
+ "_dom_classes": [],
92
+ "_model_module": "@jupyter-widgets/controls",
93
+ "_model_module_version": "1.5.0",
94
+ "_model_name": "HTMLModel",
95
+ "_view_count": null,
96
+ "_view_module": "@jupyter-widgets/controls",
97
+ "_view_module_version": "1.5.0",
98
+ "_view_name": "HTMLView",
99
+ "description": "",
100
+ "description_tooltip": null,
101
+ "layout": "IPY_MODEL_7e6ba9a0ee6046b8961da2bf09d287ac",
102
+ "placeholder": "​",
103
+ "style": "IPY_MODEL_8ac32f54acd140b483ae523e22a9652b",
104
+ "value": " 42.7M/42.7M [00:03<00:00, 25.0MB/s]"
105
+ }
106
+ },
107
+ "6434432da36a4755981ad001472e0cff": {
108
+ "model_module": "@jupyter-widgets/base",
109
+ "model_name": "LayoutModel",
110
+ "model_module_version": "1.2.0",
111
+ "state": {
112
+ "_model_module": "@jupyter-widgets/base",
113
+ "_model_module_version": "1.2.0",
114
+ "_model_name": "LayoutModel",
115
+ "_view_count": null,
116
+ "_view_module": "@jupyter-widgets/base",
117
+ "_view_module_version": "1.2.0",
118
+ "_view_name": "LayoutView",
119
+ "align_content": null,
120
+ "align_items": null,
121
+ "align_self": null,
122
+ "border": null,
123
+ "bottom": null,
124
+ "display": null,
125
+ "flex": null,
126
+ "flex_flow": null,
127
+ "grid_area": null,
128
+ "grid_auto_columns": null,
129
+ "grid_auto_flow": null,
130
+ "grid_auto_rows": null,
131
+ "grid_column": null,
132
+ "grid_gap": null,
133
+ "grid_row": null,
134
+ "grid_template_areas": null,
135
+ "grid_template_columns": null,
136
+ "grid_template_rows": null,
137
+ "height": null,
138
+ "justify_content": null,
139
+ "justify_items": null,
140
+ "left": null,
141
+ "margin": null,
142
+ "max_height": null,
143
+ "max_width": null,
144
+ "min_height": null,
145
+ "min_width": null,
146
+ "object_fit": null,
147
+ "object_position": null,
148
+ "order": null,
149
+ "overflow": null,
150
+ "overflow_x": null,
151
+ "overflow_y": null,
152
+ "padding": null,
153
+ "right": null,
154
+ "top": null,
155
+ "visibility": null,
156
+ "width": null
157
+ }
158
+ },
159
+ "40a3244cfaa4404bb7ce4247564df6ed": {
160
+ "model_module": "@jupyter-widgets/base",
161
+ "model_name": "LayoutModel",
162
+ "model_module_version": "1.2.0",
163
+ "state": {
164
+ "_model_module": "@jupyter-widgets/base",
165
+ "_model_module_version": "1.2.0",
166
+ "_model_name": "LayoutModel",
167
+ "_view_count": null,
168
+ "_view_module": "@jupyter-widgets/base",
169
+ "_view_module_version": "1.2.0",
170
+ "_view_name": "LayoutView",
171
+ "align_content": null,
172
+ "align_items": null,
173
+ "align_self": null,
174
+ "border": null,
175
+ "bottom": null,
176
+ "display": null,
177
+ "flex": null,
178
+ "flex_flow": null,
179
+ "grid_area": null,
180
+ "grid_auto_columns": null,
181
+ "grid_auto_flow": null,
182
+ "grid_auto_rows": null,
183
+ "grid_column": null,
184
+ "grid_gap": null,
185
+ "grid_row": null,
186
+ "grid_template_areas": null,
187
+ "grid_template_columns": null,
188
+ "grid_template_rows": null,
189
+ "height": null,
190
+ "justify_content": null,
191
+ "justify_items": null,
192
+ "left": null,
193
+ "margin": null,
194
+ "max_height": null,
195
+ "max_width": null,
196
+ "min_height": null,
197
+ "min_width": null,
198
+ "object_fit": null,
199
+ "object_position": null,
200
+ "order": null,
201
+ "overflow": null,
202
+ "overflow_x": null,
203
+ "overflow_y": null,
204
+ "padding": null,
205
+ "right": null,
206
+ "top": null,
207
+ "visibility": null,
208
+ "width": null
209
+ }
210
+ },
211
+ "234f2286e51c4a53b36584b49cd5a01f": {
212
+ "model_module": "@jupyter-widgets/controls",
213
+ "model_name": "DescriptionStyleModel",
214
+ "model_module_version": "1.5.0",
215
+ "state": {
216
+ "_model_module": "@jupyter-widgets/controls",
217
+ "_model_module_version": "1.5.0",
218
+ "_model_name": "DescriptionStyleModel",
219
+ "_view_count": null,
220
+ "_view_module": "@jupyter-widgets/base",
221
+ "_view_module_version": "1.2.0",
222
+ "_view_name": "StyleView",
223
+ "description_width": ""
224
+ }
225
+ },
226
+ "66ade188379547aaae0724b4e3d87051": {
227
+ "model_module": "@jupyter-widgets/base",
228
+ "model_name": "LayoutModel",
229
+ "model_module_version": "1.2.0",
230
+ "state": {
231
+ "_model_module": "@jupyter-widgets/base",
232
+ "_model_module_version": "1.2.0",
233
+ "_model_name": "LayoutModel",
234
+ "_view_count": null,
235
+ "_view_module": "@jupyter-widgets/base",
236
+ "_view_module_version": "1.2.0",
237
+ "_view_name": "LayoutView",
238
+ "align_content": null,
239
+ "align_items": null,
240
+ "align_self": null,
241
+ "border": null,
242
+ "bottom": null,
243
+ "display": null,
244
+ "flex": null,
245
+ "flex_flow": null,
246
+ "grid_area": null,
247
+ "grid_auto_columns": null,
248
+ "grid_auto_flow": null,
249
+ "grid_auto_rows": null,
250
+ "grid_column": null,
251
+ "grid_gap": null,
252
+ "grid_row": null,
253
+ "grid_template_areas": null,
254
+ "grid_template_columns": null,
255
+ "grid_template_rows": null,
256
+ "height": null,
257
+ "justify_content": null,
258
+ "justify_items": null,
259
+ "left": null,
260
+ "margin": null,
261
+ "max_height": null,
262
+ "max_width": null,
263
+ "min_height": null,
264
+ "min_width": null,
265
+ "object_fit": null,
266
+ "object_position": null,
267
+ "order": null,
268
+ "overflow": null,
269
+ "overflow_x": null,
270
+ "overflow_y": null,
271
+ "padding": null,
272
+ "right": null,
273
+ "top": null,
274
+ "visibility": null,
275
+ "width": null
276
+ }
277
+ },
278
+ "4f8c9691cd1b4faab91f7fb34348b716": {
279
+ "model_module": "@jupyter-widgets/controls",
280
+ "model_name": "ProgressStyleModel",
281
+ "model_module_version": "1.5.0",
282
+ "state": {
283
+ "_model_module": "@jupyter-widgets/controls",
284
+ "_model_module_version": "1.5.0",
285
+ "_model_name": "ProgressStyleModel",
286
+ "_view_count": null,
287
+ "_view_module": "@jupyter-widgets/base",
288
+ "_view_module_version": "1.2.0",
289
+ "_view_name": "StyleView",
290
+ "bar_color": null,
291
+ "description_width": ""
292
+ }
293
+ },
294
+ "7e6ba9a0ee6046b8961da2bf09d287ac": {
295
+ "model_module": "@jupyter-widgets/base",
296
+ "model_name": "LayoutModel",
297
+ "model_module_version": "1.2.0",
298
+ "state": {
299
+ "_model_module": "@jupyter-widgets/base",
300
+ "_model_module_version": "1.2.0",
301
+ "_model_name": "LayoutModel",
302
+ "_view_count": null,
303
+ "_view_module": "@jupyter-widgets/base",
304
+ "_view_module_version": "1.2.0",
305
+ "_view_name": "LayoutView",
306
+ "align_content": null,
307
+ "align_items": null,
308
+ "align_self": null,
309
+ "border": null,
310
+ "bottom": null,
311
+ "display": null,
312
+ "flex": null,
313
+ "flex_flow": null,
314
+ "grid_area": null,
315
+ "grid_auto_columns": null,
316
+ "grid_auto_flow": null,
317
+ "grid_auto_rows": null,
318
+ "grid_column": null,
319
+ "grid_gap": null,
320
+ "grid_row": null,
321
+ "grid_template_areas": null,
322
+ "grid_template_columns": null,
323
+ "grid_template_rows": null,
324
+ "height": null,
325
+ "justify_content": null,
326
+ "justify_items": null,
327
+ "left": null,
328
+ "margin": null,
329
+ "max_height": null,
330
+ "max_width": null,
331
+ "min_height": null,
332
+ "min_width": null,
333
+ "object_fit": null,
334
+ "object_position": null,
335
+ "order": null,
336
+ "overflow": null,
337
+ "overflow_x": null,
338
+ "overflow_y": null,
339
+ "padding": null,
340
+ "right": null,
341
+ "top": null,
342
+ "visibility": null,
343
+ "width": null
344
+ }
345
+ },
346
+ "8ac32f54acd140b483ae523e22a9652b": {
347
+ "model_module": "@jupyter-widgets/controls",
348
+ "model_name": "DescriptionStyleModel",
349
+ "model_module_version": "1.5.0",
350
+ "state": {
351
+ "_model_module": "@jupyter-widgets/controls",
352
+ "_model_module_version": "1.5.0",
353
+ "_model_name": "DescriptionStyleModel",
354
+ "_view_count": null,
355
+ "_view_module": "@jupyter-widgets/base",
356
+ "_view_module_version": "1.2.0",
357
+ "_view_name": "StyleView",
358
+ "description_width": ""
359
+ }
360
+ }
361
+ }
362
+ }
363
+ },
364
+ "cells": [
365
+ {
366
+ "cell_type": "code",
367
+ "source": [
368
+ "!pip install requests transformers"
369
+ ],
370
+ "metadata": {
371
+ "colab": {
372
+ "base_uri": "https://localhost:8080/"
373
+ },
374
+ "id": "qgjLhqhtRoYL",
375
+ "outputId": "6bb6ee0e-a189-4fe5-c2f9-7e043734db1e"
376
+ },
377
+ "execution_count": 1,
378
+ "outputs": [
379
+ {
380
+ "output_type": "stream",
381
+ "name": "stdout",
382
+ "text": [
383
+ "Requirement already satisfied: requests in /usr/local/lib/python3.10/dist-packages (2.31.0)\n",
384
+ "Requirement already satisfied: transformers in /usr/local/lib/python3.10/dist-packages (4.41.0)\n",
385
+ "Requirement already satisfied: charset-normalizer<4,>=2 in /usr/local/lib/python3.10/dist-packages (from requests) (3.3.2)\n",
386
+ "Requirement already satisfied: idna<4,>=2.5 in /usr/local/lib/python3.10/dist-packages (from requests) (3.7)\n",
387
+ "Requirement already satisfied: urllib3<3,>=1.21.1 in /usr/local/lib/python3.10/dist-packages (from requests) (2.0.7)\n",
388
+ "Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.10/dist-packages (from requests) (2024.2.2)\n",
389
+ "Requirement already satisfied: filelock in /usr/local/lib/python3.10/dist-packages (from transformers) (3.14.0)\n",
390
+ "Requirement already satisfied: huggingface-hub<1.0,>=0.23.0 in /usr/local/lib/python3.10/dist-packages (from transformers) (0.23.0)\n",
391
+ "Requirement already satisfied: numpy>=1.17 in /usr/local/lib/python3.10/dist-packages (from transformers) (1.25.2)\n",
392
+ "Requirement already satisfied: packaging>=20.0 in /usr/local/lib/python3.10/dist-packages (from transformers) (24.0)\n",
393
+ "Requirement already satisfied: pyyaml>=5.1 in /usr/local/lib/python3.10/dist-packages (from transformers) (6.0.1)\n",
394
+ "Requirement already satisfied: regex!=2019.12.17 in /usr/local/lib/python3.10/dist-packages (from transformers) (2023.12.25)\n",
395
+ "Requirement already satisfied: tokenizers<0.20,>=0.19 in /usr/local/lib/python3.10/dist-packages (from transformers) (0.19.1)\n",
396
+ "Requirement already satisfied: safetensors>=0.4.1 in /usr/local/lib/python3.10/dist-packages (from transformers) (0.4.3)\n",
397
+ "Requirement already satisfied: tqdm>=4.27 in /usr/local/lib/python3.10/dist-packages (from transformers) (4.66.4)\n",
398
+ "Requirement already satisfied: fsspec>=2023.5.0 in /usr/local/lib/python3.10/dist-packages (from huggingface-hub<1.0,>=0.23.0->transformers) (2023.6.0)\n",
399
+ "Requirement already satisfied: typing-extensions>=3.7.4.3 in /usr/local/lib/python3.10/dist-packages (from huggingface-hub<1.0,>=0.23.0->transformers) (4.11.0)\n"
400
+ ]
401
+ }
402
+ ]
403
+ },
404
+ {
405
+ "cell_type": "code",
406
+ "source": [
407
+ "import requests\n",
408
+ "import zipfile\n",
409
+ "import os\n",
410
+ "\n",
411
+ "# URL du fichier zip sur Hugging Face\n",
412
+ "zip_url = 'https://huggingface.co/datasets/Dabococo/wheeloh_dataset/images'\n",
413
+ "\n",
414
+ "# Nom local du fichier zip\n",
415
+ "zip_file = 'images.zip'\n",
416
+ "\n",
417
+ "# Télécharger le fichier zip\n",
418
+ "response = requests.get(zip_url)\n",
419
+ "content_type = response.headers.get('Content-Type')\n",
420
+ "\n",
421
+ "# Vérifier que le fichier est un fichier zip\n",
422
+ "if 'zip' not in content_type:\n",
423
+ " raise ValueError(\"Le fichier téléchargé n'est pas un fichier zip. Content-Type: {}\".format(content_type))\n",
424
+ "\n",
425
+ "# Sauvegarder le contenu téléchargé dans un fichier\n",
426
+ "with open(zip_file, 'wb') as f:\n",
427
+ " f.write(response.content)\n",
428
+ "\n",
429
+ "# Vérifier la taille du fichier\n",
430
+ "file_size = os.path.getsize(zip_file)\n",
431
+ "print(\"Taille du fichier téléchargé:\", file_size, \"octets\")\n",
432
+ "\n",
433
+ "# Afficher le début du contenu du fichier pour vérifier\n",
434
+ "with open(zip_file, 'rb') as f:\n",
435
+ " print(f.read(100)) # Lire les 100 premiers octets\n",
436
+ "\n",
437
+ "# Créer un répertoire pour extraire les fichiers\n",
438
+ "extract_dir = 'extracted_files'\n",
439
+ "os.makedirs(extract_dir, exist_ok=True)\n",
440
+ "\n",
441
+ "# Extraire le contenu du fichier zip\n",
442
+ "try:\n",
443
+ " with zipfile.ZipFile(zip_file, 'r') as zip_ref:\n",
444
+ " zip_ref.extractall(extract_dir)\n",
445
+ " # Afficher les fichiers extraits\n",
446
+ " extracted_files = os.listdir(extract_dir)\n",
447
+ " print(\"Fichiers extraits :\", extracted_files)\n",
448
+ "except zipfile.BadZipFile:\n",
449
+ " print(\"Erreur : le fichier téléchargé n'est pas un fichier zip valide.\")"
450
+ ],
451
+ "metadata": {
452
+ "colab": {
453
+ "base_uri": "https://localhost:8080/",
454
+ "height": 241
455
+ },
456
+ "id": "WX_U7Z6GRpTR",
457
+ "outputId": "5efdb53c-196c-4692-91ff-e9c131fce1f4"
458
+ },
459
+ "execution_count": 22,
460
+ "outputs": [
461
+ {
462
+ "output_type": "error",
463
+ "ename": "ValueError",
464
+ "evalue": "Le fichier téléchargé n'est pas un fichier zip. Content-Type: text/html; charset=utf-8",
465
+ "traceback": [
466
+ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
467
+ "\u001b[0;31mValueError\u001b[0m Traceback (most recent call last)",
468
+ "\u001b[0;32m<ipython-input-22-9e950cb9106e>\u001b[0m in \u001b[0;36m<cell line: 16>\u001b[0;34m()\u001b[0m\n\u001b[1;32m 15\u001b[0m \u001b[0;31m# Vérifier que le fichier est un fichier zip\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 16\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0;34m'zip'\u001b[0m \u001b[0;32mnot\u001b[0m \u001b[0;32min\u001b[0m \u001b[0mcontent_type\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 17\u001b[0;31m \u001b[0;32mraise\u001b[0m \u001b[0mValueError\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"Le fichier téléchargé n'est pas un fichier zip. Content-Type: {}\"\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mformat\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mcontent_type\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 18\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 19\u001b[0m \u001b[0;31m# Sauvegarder le contenu téléchargé dans un fichier\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
469
+ "\u001b[0;31mValueError\u001b[0m: Le fichier téléchargé n'est pas un fichier zip. Content-Type: text/html; charset=utf-8"
470
+ ]
471
+ }
472
+ ]
473
+ },
474
+ {
475
+ "cell_type": "code",
476
+ "source": [
477
+ "from torchvision.datasets import ImageFolder\n",
478
+ "import os\n",
479
+ "from torchvision.datasets.folder import has_file_allowed_extension, IMG_EXTENSIONS, default_loader\n",
480
+ "\n",
481
+ "class CustomImageFolder(ImageFolder):\n",
482
+ " def __init__(self, root, transform=None, loader=default_loader, is_valid_file=None):\n",
483
+ " super().__init__(root, transform=transform, loader=loader, is_valid_file=is_valid_file)\n",
484
+ "\n",
485
+ " def find_classes(self, directory):\n",
486
+ " # Ignorer les répertoires cachés\n",
487
+ " classes = [d.name for d in os.scandir(directory) if d.is_dir() and not d.name.startswith('.')]\n",
488
+ " classes.sort()\n",
489
+ " class_to_idx = {cls_name: i for i, cls_name in enumerate(classes)}\n",
490
+ " return classes, class_to_idx\n",
491
+ "\n",
492
+ " def make_dataset(self, directory, class_to_idx, extensions=None, is_valid_file=None, allow_empty=False):\n",
493
+ " instances = []\n",
494
+ " directory = os.path.expanduser(directory)\n",
495
+ " both_none = extensions is None and is_valid_file is None\n",
496
+ " if both_none:\n",
497
+ " raise ValueError(\"Both extensions and is_valid_file cannot be None\")\n",
498
+ " if extensions is not None:\n",
499
+ " def is_valid_file(x):\n",
500
+ " return has_file_allowed_extension(x, extensions)\n",
501
+ "\n",
502
+ " for target_class in sorted(class_to_idx.keys()):\n",
503
+ " class_index = class_to_idx[target_class]\n",
504
+ " target_dir = os.path.join(directory, target_class)\n",
505
+ " if not os.path.isdir(target_dir):\n",
506
+ " continue\n",
507
+ " for root, _, fnames in sorted(os.walk(target_dir)):\n",
508
+ " for fname in sorted(fnames):\n",
509
+ " path = os.path.join(root, fname)\n",
510
+ " if is_valid_file(path) and not fname.startswith('.'):\n",
511
+ " item = path, class_index\n",
512
+ " instances.append(item)\n",
513
+ "\n",
514
+ " if not allow_empty and len(instances) == 0:\n",
515
+ " raise RuntimeError(f\"Found 0 files in subfolders of: {directory}. Supported extensions are: {','.join(extensions)}\")\n",
516
+ "\n",
517
+ " return instances"
518
+ ],
519
+ "metadata": {
520
+ "id": "5y-PWXOnoH-k"
521
+ },
522
+ "execution_count": 7,
523
+ "outputs": []
524
+ },
525
+ {
526
+ "cell_type": "code",
527
+ "execution_count": 9,
528
+ "metadata": {
529
+ "colab": {
530
+ "base_uri": "https://localhost:8080/"
531
+ },
532
+ "id": "CuyZBWiyP88V",
533
+ "outputId": "fdef3381-9464-4433-c96d-2343bc22a1f6"
534
+ },
535
+ "outputs": [
536
+ {
537
+ "output_type": "stream",
538
+ "name": "stderr",
539
+ "text": [
540
+ "100%|██████████| 16/16 [00:08<00:00, 1.86it/s]\n"
541
+ ]
542
+ },
543
+ {
544
+ "output_type": "stream",
545
+ "name": "stdout",
546
+ "text": [
547
+ "Epoch [1/10], Loss: 0.2799\n"
548
+ ]
549
+ },
550
+ {
551
+ "output_type": "stream",
552
+ "name": "stderr",
553
+ "text": [
554
+ "100%|██████████| 16/16 [00:08<00:00, 1.96it/s]\n"
555
+ ]
556
+ },
557
+ {
558
+ "output_type": "stream",
559
+ "name": "stdout",
560
+ "text": [
561
+ "Epoch [2/10], Loss: 0.0916\n"
562
+ ]
563
+ },
564
+ {
565
+ "output_type": "stream",
566
+ "name": "stderr",
567
+ "text": [
568
+ "100%|██████████| 16/16 [00:07<00:00, 2.08it/s]\n"
569
+ ]
570
+ },
571
+ {
572
+ "output_type": "stream",
573
+ "name": "stdout",
574
+ "text": [
575
+ "Epoch [3/10], Loss: 0.0356\n"
576
+ ]
577
+ },
578
+ {
579
+ "output_type": "stream",
580
+ "name": "stderr",
581
+ "text": [
582
+ "100%|██████████| 16/16 [00:08<00:00, 1.86it/s]\n"
583
+ ]
584
+ },
585
+ {
586
+ "output_type": "stream",
587
+ "name": "stdout",
588
+ "text": [
589
+ "Epoch [4/10], Loss: 0.0253\n"
590
+ ]
591
+ },
592
+ {
593
+ "output_type": "stream",
594
+ "name": "stderr",
595
+ "text": [
596
+ "100%|██████████| 16/16 [00:07<00:00, 2.25it/s]\n"
597
+ ]
598
+ },
599
+ {
600
+ "output_type": "stream",
601
+ "name": "stdout",
602
+ "text": [
603
+ "Epoch [5/10], Loss: 0.0101\n"
604
+ ]
605
+ },
606
+ {
607
+ "output_type": "stream",
608
+ "name": "stderr",
609
+ "text": [
610
+ "100%|██████████| 16/16 [00:09<00:00, 1.73it/s]\n"
611
+ ]
612
+ },
613
+ {
614
+ "output_type": "stream",
615
+ "name": "stdout",
616
+ "text": [
617
+ "Epoch [6/10], Loss: 0.0089\n"
618
+ ]
619
+ },
620
+ {
621
+ "output_type": "stream",
622
+ "name": "stderr",
623
+ "text": [
624
+ "100%|██████████| 16/16 [00:08<00:00, 1.81it/s]\n"
625
+ ]
626
+ },
627
+ {
628
+ "output_type": "stream",
629
+ "name": "stdout",
630
+ "text": [
631
+ "Epoch [7/10], Loss: 0.0096\n"
632
+ ]
633
+ },
634
+ {
635
+ "output_type": "stream",
636
+ "name": "stderr",
637
+ "text": [
638
+ "100%|██████████| 16/16 [00:07<00:00, 2.23it/s]\n"
639
+ ]
640
+ },
641
+ {
642
+ "output_type": "stream",
643
+ "name": "stdout",
644
+ "text": [
645
+ "Epoch [8/10], Loss: 0.0101\n"
646
+ ]
647
+ },
648
+ {
649
+ "output_type": "stream",
650
+ "name": "stderr",
651
+ "text": [
652
+ "100%|██████████| 16/16 [00:08<00:00, 1.85it/s]\n"
653
+ ]
654
+ },
655
+ {
656
+ "output_type": "stream",
657
+ "name": "stdout",
658
+ "text": [
659
+ "Epoch [9/10], Loss: 0.0631\n"
660
+ ]
661
+ },
662
+ {
663
+ "output_type": "stream",
664
+ "name": "stderr",
665
+ "text": [
666
+ "100%|██████████| 16/16 [00:07<00:00, 2.20it/s]\n"
667
+ ]
668
+ },
669
+ {
670
+ "output_type": "stream",
671
+ "name": "stdout",
672
+ "text": [
673
+ "Epoch [10/10], Loss: 0.0186\n",
674
+ "Finished Training\n"
675
+ ]
676
+ }
677
+ ],
678
+ "source": [
679
+ "import torch\n",
680
+ "import torch.nn as nn\n",
681
+ "import torch.optim as optim\n",
682
+ "from torch.utils.data import DataLoader\n",
683
+ "from torchvision import transforms, models\n",
684
+ "from tqdm import tqdm\n",
685
+ "\n",
686
+ "# Configuration\n",
687
+ "batch_size = 32\n",
688
+ "num_epochs = 10\n",
689
+ "learning_rate = 0.001\n",
690
+ "num_classes = 2\n",
691
+ "\n",
692
+ "# Préparer les transformations\n",
693
+ "transform = transforms.Compose([\n",
694
+ " transforms.Resize((224, 224)),\n",
695
+ " transforms.ToTensor(),\n",
696
+ " transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])\n",
697
+ "])\n",
698
+ "\n",
699
+ "# Charger les données d'entraînement avec CustomImageFolder\n",
700
+ "train_dataset = CustomImageFolder(root='/content/dataset/train', transform=transform)\n",
701
+ "train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True, num_workers=4, pin_memory=True)\n",
702
+ "\n",
703
+ "# Définir le modèle\n",
704
+ "model = models.resnet18(pretrained=True)\n",
705
+ "model.fc = nn.Linear(model.fc.in_features, num_classes)\n",
706
+ "model = model.to('cuda')\n",
707
+ "\n",
708
+ "# Définir la perte et l'optimiseur\n",
709
+ "criterion = nn.CrossEntropyLoss()\n",
710
+ "optimizer = optim.Adam(model.parameters(), lr=learning_rate)\n",
711
+ "\n",
712
+ "# Utiliser le scaler pour l'AMP\n",
713
+ "scaler = torch.cuda.amp.GradScaler()\n",
714
+ "\n",
715
+ "# Entraînement\n",
716
+ "for epoch in range(num_epochs):\n",
717
+ " model.train()\n",
718
+ " running_loss = 0.0\n",
719
+ " for inputs, labels in tqdm(train_loader):\n",
720
+ " inputs, labels = inputs.to('cuda'), labels.to('cuda')\n",
721
+ "\n",
722
+ " # Zero the parameter gradients\n",
723
+ " optimizer.zero_grad()\n",
724
+ "\n",
725
+ " # Forward pass with autocast\n",
726
+ " with torch.cuda.amp.autocast():\n",
727
+ " outputs = model(inputs)\n",
728
+ " loss = criterion(outputs, labels)\n",
729
+ "\n",
730
+ " # Backward pass with scaler\n",
731
+ " scaler.scale(loss).backward()\n",
732
+ " scaler.step(optimizer)\n",
733
+ " scaler.update()\n",
734
+ "\n",
735
+ " running_loss += loss.item() * inputs.size(0)\n",
736
+ "\n",
737
+ " epoch_loss = running_loss / len(train_loader.dataset)\n",
738
+ " print(f'Epoch [{epoch + 1}/{num_epochs}], Loss: {epoch_loss:.4f}')\n",
739
+ "\n",
740
+ "print('Finished Training')\n",
741
+ "\n",
742
+ "# Sauvegarder le modèle\n",
743
+ "torch.save(model.state_dict(), 'model.pth')"
744
+ ]
745
+ },
746
+ {
747
+ "cell_type": "code",
748
+ "source": [
749
+ "#Ici pour charger le modèle"
750
+ ],
751
+ "metadata": {
752
+ "id": "aJBYukdNfx8P"
753
+ },
754
+ "execution_count": null,
755
+ "outputs": []
756
+ },
757
+ {
758
+ "cell_type": "code",
759
+ "source": [
760
+ "import torch\n",
761
+ "import torch.nn as nn\n",
762
+ "from torchvision import models, transforms\n",
763
+ "from PIL import Image\n",
764
+ "\n",
765
+ "# Définir le modèle\n",
766
+ "num_classes = 2 # Canard et Perroquet\n",
767
+ "model = models.resnet18(pretrained=False)\n",
768
+ "model.fc = nn.Linear(model.fc.in_features, num_classes)\n",
769
+ "model = model.to('cuda')\n",
770
+ "\n",
771
+ "# Charger les poids du modèle enregistré\n",
772
+ "model.load_state_dict(torch.load('model.pth'))\n",
773
+ "model.eval() # Mettre le modèle en mode évaluation\n",
774
+ "\n",
775
+ "# Définir les transformations\n",
776
+ "transform = transforms.Compose([\n",
777
+ " transforms.Resize((224, 224)),\n",
778
+ " transforms.ToTensor(),\n",
779
+ " transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])\n",
780
+ "])\n",
781
+ "\n",
782
+ "# Charger et transformer une nouvelle image\n",
783
+ "def load_image(image_path):\n",
784
+ " image = Image.open(image_path).convert('RGB')\n",
785
+ " image = transform(image)\n",
786
+ " image = image.unsqueeze(0) # Ajouter une dimension pour le batch\n",
787
+ " return image\n",
788
+ "\n",
789
+ "# Exemple de chargement d'une image\n",
790
+ "image_path = '/content/lg.jpeg'\n",
791
+ "image = load_image(image_path).to('cuda')\n",
792
+ "\n",
793
+ "# Passer l'image dans le modèle pour obtenir des prédictions\n",
794
+ "with torch.no_grad(): # Désactiver la grad pour l'inférence\n",
795
+ " outputs = model(image)\n",
796
+ " _, predicted = torch.max(outputs, 1)\n",
797
+ "\n",
798
+ " classes = ['Alpine', 'Bugatti']\n",
799
+ " predicted_class = classes[predicted.item()]\n",
800
+ " print(f'Predicted class: {predicted_class}')"
801
+ ],
802
+ "metadata": {
803
+ "colab": {
804
+ "base_uri": "https://localhost:8080/"
805
+ },
806
+ "id": "oj0pgYdyQFXz",
807
+ "outputId": "13c95418-6dcd-440c-cb78-2edbfdb8b386"
808
+ },
809
+ "execution_count": 22,
810
+ "outputs": [
811
+ {
812
+ "output_type": "stream",
813
+ "name": "stdout",
814
+ "text": [
815
+ "Predicted class: Bugatti\n"
816
+ ]
817
+ }
818
+ ]
819
+ },
820
+ {
821
+ "cell_type": "code",
822
+ "source": [
823
+ "!pip install transformers huggingface_hub"
824
+ ],
825
+ "metadata": {
826
+ "colab": {
827
+ "base_uri": "https://localhost:8080/"
828
+ },
829
+ "id": "cksp1PveZU22",
830
+ "outputId": "eb8bdf38-4cc2-42ce-a047-d02b22c004bb"
831
+ },
832
+ "execution_count": 23,
833
+ "outputs": [
834
+ {
835
+ "output_type": "stream",
836
+ "name": "stdout",
837
+ "text": [
838
+ "Requirement already satisfied: transformers in /usr/local/lib/python3.10/dist-packages (4.41.0)\n",
839
+ "Requirement already satisfied: huggingface_hub in /usr/local/lib/python3.10/dist-packages (0.23.0)\n",
840
+ "Requirement already satisfied: filelock in /usr/local/lib/python3.10/dist-packages (from transformers) (3.14.0)\n",
841
+ "Requirement already satisfied: numpy>=1.17 in /usr/local/lib/python3.10/dist-packages (from transformers) (1.25.2)\n",
842
+ "Requirement already satisfied: packaging>=20.0 in /usr/local/lib/python3.10/dist-packages (from transformers) (24.0)\n",
843
+ "Requirement already satisfied: pyyaml>=5.1 in /usr/local/lib/python3.10/dist-packages (from transformers) (6.0.1)\n",
844
+ "Requirement already satisfied: regex!=2019.12.17 in /usr/local/lib/python3.10/dist-packages (from transformers) (2023.12.25)\n",
845
+ "Requirement already satisfied: requests in /usr/local/lib/python3.10/dist-packages (from transformers) (2.31.0)\n",
846
+ "Requirement already satisfied: tokenizers<0.20,>=0.19 in /usr/local/lib/python3.10/dist-packages (from transformers) (0.19.1)\n",
847
+ "Requirement already satisfied: safetensors>=0.4.1 in /usr/local/lib/python3.10/dist-packages (from transformers) (0.4.3)\n",
848
+ "Requirement already satisfied: tqdm>=4.27 in /usr/local/lib/python3.10/dist-packages (from transformers) (4.66.4)\n",
849
+ "Requirement already satisfied: fsspec>=2023.5.0 in /usr/local/lib/python3.10/dist-packages (from huggingface_hub) (2023.6.0)\n",
850
+ "Requirement already satisfied: typing-extensions>=3.7.4.3 in /usr/local/lib/python3.10/dist-packages (from huggingface_hub) (4.11.0)\n",
851
+ "Requirement already satisfied: charset-normalizer<4,>=2 in /usr/local/lib/python3.10/dist-packages (from requests->transformers) (3.3.2)\n",
852
+ "Requirement already satisfied: idna<4,>=2.5 in /usr/local/lib/python3.10/dist-packages (from requests->transformers) (3.7)\n",
853
+ "Requirement already satisfied: urllib3<3,>=1.21.1 in /usr/local/lib/python3.10/dist-packages (from requests->transformers) (2.0.7)\n",
854
+ "Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.10/dist-packages (from requests->transformers) (2024.2.2)\n"
855
+ ]
856
+ }
857
+ ]
858
+ },
859
+ {
860
+ "cell_type": "code",
861
+ "source": [
862
+ "!huggingface-cli login"
863
+ ],
864
+ "metadata": {
865
+ "colab": {
866
+ "base_uri": "https://localhost:8080/"
867
+ },
868
+ "id": "c-3Qxby1ZWFV",
869
+ "outputId": "66148da3-bf28-4fa4-baf6-0034b8b5b35e"
870
+ },
871
+ "execution_count": 11,
872
+ "outputs": [
873
+ {
874
+ "output_type": "stream",
875
+ "name": "stdout",
876
+ "text": [
877
+ "\n",
878
+ " _| _| _| _| _|_|_| _|_|_| _|_|_| _| _| _|_|_| _|_|_|_| _|_| _|_|_| _|_|_|_|\n",
879
+ " _| _| _| _| _| _| _| _|_| _| _| _| _| _| _| _|\n",
880
+ " _|_|_|_| _| _| _| _|_| _| _|_| _| _| _| _| _| _|_| _|_|_| _|_|_|_| _| _|_|_|\n",
881
+ " _| _| _| _| _| _| _| _| _| _| _|_| _| _| _| _| _| _| _|\n",
882
+ " _| _| _|_| _|_|_| _|_|_| _|_|_| _| _| _|_|_| _| _| _| _|_|_| _|_|_|_|\n",
883
+ "\n",
884
+ " To login, `huggingface_hub` requires a token generated from https://huggingface.co/settings/tokens .\n",
885
+ "Enter your token (input will not be visible): \n",
886
+ "Add token as git credential? (Y/n) Y\n",
887
+ "Token is valid (permission: read).\n",
888
+ "\u001b[1m\u001b[31mCannot authenticate through git-credential as no helper is defined on your machine.\n",
889
+ "You might have to re-authenticate when pushing to the Hugging Face Hub.\n",
890
+ "Run the following command in your terminal in case you want to set the 'store' credential helper as default.\n",
891
+ "\n",
892
+ "git config --global credential.helper store\n",
893
+ "\n",
894
+ "Read https://git-scm.com/book/en/v2/Git-Tools-Credential-Storage for more details.\u001b[0m\n",
895
+ "Token has not been saved to git credential helper.\n",
896
+ "Your token has been saved to /root/.cache/huggingface/token\n",
897
+ "Login successful\n"
898
+ ]
899
+ }
900
+ ]
901
+ },
902
+ {
903
+ "cell_type": "code",
904
+ "source": [
905
+ "from huggingface_hub import HfApi, HfFolder, Repository\n",
906
+ "\n",
907
+ "# Variables\n",
908
+ "model_path = \"Wheeloh-model_1.pth\"\n",
909
+ "repo_name = \"Wheeloh-model_1\" # Remplacez par le nom de votre dépôt\n",
910
+ "commit_message = \"Initial commit\"\n",
911
+ "\n",
912
+ "# Se connecter à l'API\n",
913
+ "api = HfApi()\n",
914
+ "\n",
915
+ "# Obtenir le token d'authentification\n",
916
+ "token = HfFolder.get_token()\n",
917
+ "\n",
918
+ "# Cloner le dépôt Hugging Face\n",
919
+ "repo_url = api.create_repo(repo_name, token=token, exist_ok=True)\n",
920
+ "repo = Repository(local_dir=repo_name, clone_from=repo_url)\n",
921
+ "\n",
922
+ "# Copier le fichier du modèle dans le dépôt local\n",
923
+ "import shutil\n",
924
+ "shutil.copy(model_path, repo_name)\n",
925
+ "\n",
926
+ "# Pousser le modèle sur le hub\n",
927
+ "repo.push_to_hub(commit_message=commit_message)\n"
928
+ ],
929
+ "metadata": {
930
+ "colab": {
931
+ "base_uri": "https://localhost:8080/",
932
+ "height": 421,
933
+ "referenced_widgets": [
934
+ "a710457b00a849da9c24e1e1afb9d616",
935
+ "7b58972d4c704aa3bcc59a7a3c18682f",
936
+ "624e284bf09843a7a0b10256fbc416d0",
937
+ "e5b7191907914d75983b7e4b717b86d3",
938
+ "6434432da36a4755981ad001472e0cff",
939
+ "40a3244cfaa4404bb7ce4247564df6ed",
940
+ "234f2286e51c4a53b36584b49cd5a01f",
941
+ "66ade188379547aaae0724b4e3d87051",
942
+ "4f8c9691cd1b4faab91f7fb34348b716",
943
+ "7e6ba9a0ee6046b8961da2bf09d287ac",
944
+ "8ac32f54acd140b483ae523e22a9652b"
945
+ ]
946
+ },
947
+ "id": "LDyh9-MfZiMX",
948
+ "outputId": "e0e9ab72-d5df-4f21-eb3a-5226263071de"
949
+ },
950
+ "execution_count": 25,
951
+ "outputs": [
952
+ {
953
+ "output_type": "stream",
954
+ "name": "stderr",
955
+ "text": [
956
+ "/usr/local/lib/python3.10/dist-packages/huggingface_hub/utils/_token.py:89: UserWarning: \n",
957
+ "The secret `HF_TOKEN` does not exist in your Colab secrets.\n",
958
+ "To authenticate with the Hugging Face Hub, create a token in your settings tab (https://huggingface.co/settings/tokens), set it as secret in your Google Colab and restart your session.\n",
959
+ "You will be able to reuse this secret in all of your notebooks.\n",
960
+ "Please note that authentication is recommended but still optional to access public models or datasets.\n",
961
+ " warnings.warn(\n",
962
+ "/usr/local/lib/python3.10/dist-packages/huggingface_hub/utils/_deprecation.py:131: FutureWarning: 'Repository' (from 'huggingface_hub.repository') is deprecated and will be removed from version '1.0'. Please prefer the http-based alternatives instead. Given its large adoption in legacy code, the complete removal is only planned on next major release.\n",
963
+ "For more details, please read https://huggingface.co/docs/huggingface_hub/concepts/git_vs_http.\n",
964
+ " warnings.warn(warning_message, FutureWarning)\n",
965
+ "Cloning https://huggingface.co/Dabococo/Wheeloh-model_1 into local empty directory.\n",
966
+ "WARNING:huggingface_hub.repository:Cloning https://huggingface.co/Dabococo/Wheeloh-model_1 into local empty directory.\n"
967
+ ]
968
+ },
969
+ {
970
+ "output_type": "display_data",
971
+ "data": {
972
+ "text/plain": [
973
+ "Upload file Wheeloh-model_1.pth: 0%| | 1.00/42.7M [00:00<?, ?B/s]"
974
+ ],
975
+ "application/vnd.jupyter.widget-view+json": {
976
+ "version_major": 2,
977
+ "version_minor": 0,
978
+ "model_id": "a710457b00a849da9c24e1e1afb9d616"
979
+ }
980
+ },
981
+ "metadata": {}
982
+ },
983
+ {
984
+ "output_type": "stream",
985
+ "name": "stderr",
986
+ "text": [
987
+ "To https://huggingface.co/Dabococo/Wheeloh-model_1\n",
988
+ " 09e573f..8606a55 main -> main\n",
989
+ "\n",
990
+ "WARNING:huggingface_hub.repository:To https://huggingface.co/Dabococo/Wheeloh-model_1\n",
991
+ " 09e573f..8606a55 main -> main\n",
992
+ "\n"
993
+ ]
994
+ },
995
+ {
996
+ "output_type": "execute_result",
997
+ "data": {
998
+ "text/plain": [
999
+ "'https://huggingface.co/Dabococo/Wheeloh-model_1/commit/8606a554a318e75a54b8b841b31825c29f577de8'"
1000
+ ],
1001
+ "application/vnd.google.colaboratory.intrinsic+json": {
1002
+ "type": "string"
1003
+ }
1004
+ },
1005
+ "metadata": {},
1006
+ "execution_count": 25
1007
+ }
1008
+ ]
1009
+ }
1010
+ ]
1011
+ }
untitled6.py ADDED
@@ -0,0 +1,234 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """Untitled6.ipynb
3
+
4
+ Automatically generated by Colab.
5
+
6
+ Original file is located at
7
+ https://colab.research.google.com/drive/1b3-0ogrDvdw3WtHwOta0Ihlo46MAwDsk
8
+ """
9
+
10
+ !pip install requests transformers
11
+
12
+ import requests
13
+ import zipfile
14
+ import os
15
+
16
+ # URL du fichier zip sur Hugging Face
17
+ zip_url = 'https://huggingface.co/datasets/Dabococo/wheeloh_dataset/images'
18
+
19
+ # Nom local du fichier zip
20
+ zip_file = 'images.zip'
21
+
22
+ # Télécharger le fichier zip
23
+ response = requests.get(zip_url)
24
+ content_type = response.headers.get('Content-Type')
25
+
26
+ # Vérifier que le fichier est un fichier zip
27
+ if 'zip' not in content_type:
28
+ raise ValueError("Le fichier téléchargé n'est pas un fichier zip. Content-Type: {}".format(content_type))
29
+
30
+ # Sauvegarder le contenu téléchargé dans un fichier
31
+ with open(zip_file, 'wb') as f:
32
+ f.write(response.content)
33
+
34
+ # Vérifier la taille du fichier
35
+ file_size = os.path.getsize(zip_file)
36
+ print("Taille du fichier téléchargé:", file_size, "octets")
37
+
38
+ # Afficher le début du contenu du fichier pour vérifier
39
+ with open(zip_file, 'rb') as f:
40
+ print(f.read(100)) # Lire les 100 premiers octets
41
+
42
+ # Créer un répertoire pour extraire les fichiers
43
+ extract_dir = 'extracted_files'
44
+ os.makedirs(extract_dir, exist_ok=True)
45
+
46
+ # Extraire le contenu du fichier zip
47
+ try:
48
+ with zipfile.ZipFile(zip_file, 'r') as zip_ref:
49
+ zip_ref.extractall(extract_dir)
50
+ # Afficher les fichiers extraits
51
+ extracted_files = os.listdir(extract_dir)
52
+ print("Fichiers extraits :", extracted_files)
53
+ except zipfile.BadZipFile:
54
+ print("Erreur : le fichier téléchargé n'est pas un fichier zip valide.")
55
+
56
+ from torchvision.datasets import ImageFolder
57
+ import os
58
+ from torchvision.datasets.folder import has_file_allowed_extension, IMG_EXTENSIONS, default_loader
59
+
60
+ class CustomImageFolder(ImageFolder):
61
+ def __init__(self, root, transform=None, loader=default_loader, is_valid_file=None):
62
+ super().__init__(root, transform=transform, loader=loader, is_valid_file=is_valid_file)
63
+
64
+ def find_classes(self, directory):
65
+ # Ignorer les répertoires cachés
66
+ classes = [d.name for d in os.scandir(directory) if d.is_dir() and not d.name.startswith('.')]
67
+ classes.sort()
68
+ class_to_idx = {cls_name: i for i, cls_name in enumerate(classes)}
69
+ return classes, class_to_idx
70
+
71
+ def make_dataset(self, directory, class_to_idx, extensions=None, is_valid_file=None, allow_empty=False):
72
+ instances = []
73
+ directory = os.path.expanduser(directory)
74
+ both_none = extensions is None and is_valid_file is None
75
+ if both_none:
76
+ raise ValueError("Both extensions and is_valid_file cannot be None")
77
+ if extensions is not None:
78
+ def is_valid_file(x):
79
+ return has_file_allowed_extension(x, extensions)
80
+
81
+ for target_class in sorted(class_to_idx.keys()):
82
+ class_index = class_to_idx[target_class]
83
+ target_dir = os.path.join(directory, target_class)
84
+ if not os.path.isdir(target_dir):
85
+ continue
86
+ for root, _, fnames in sorted(os.walk(target_dir)):
87
+ for fname in sorted(fnames):
88
+ path = os.path.join(root, fname)
89
+ if is_valid_file(path) and not fname.startswith('.'):
90
+ item = path, class_index
91
+ instances.append(item)
92
+
93
+ if not allow_empty and len(instances) == 0:
94
+ raise RuntimeError(f"Found 0 files in subfolders of: {directory}. Supported extensions are: {','.join(extensions)}")
95
+
96
+ return instances
97
+
98
+ import torch
99
+ import torch.nn as nn
100
+ import torch.optim as optim
101
+ from torch.utils.data import DataLoader
102
+ from torchvision import transforms, models
103
+ from tqdm import tqdm
104
+
105
+ # Configuration
106
+ batch_size = 32
107
+ num_epochs = 10
108
+ learning_rate = 0.001
109
+ num_classes = 2
110
+
111
+ # Préparer les transformations
112
+ transform = transforms.Compose([
113
+ transforms.Resize((224, 224)),
114
+ transforms.ToTensor(),
115
+ transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
116
+ ])
117
+
118
+ # Charger les données d'entraînement avec CustomImageFolder
119
+ train_dataset = CustomImageFolder(root='/content/dataset/train', transform=transform)
120
+ train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True, num_workers=4, pin_memory=True)
121
+
122
+ # Définir le modèle
123
+ model = models.resnet18(pretrained=True)
124
+ model.fc = nn.Linear(model.fc.in_features, num_classes)
125
+ model = model.to('cuda')
126
+
127
+ # Définir la perte et l'optimiseur
128
+ criterion = nn.CrossEntropyLoss()
129
+ optimizer = optim.Adam(model.parameters(), lr=learning_rate)
130
+
131
+ # Utiliser le scaler pour l'AMP
132
+ scaler = torch.cuda.amp.GradScaler()
133
+
134
+ # Entraînement
135
+ for epoch in range(num_epochs):
136
+ model.train()
137
+ running_loss = 0.0
138
+ for inputs, labels in tqdm(train_loader):
139
+ inputs, labels = inputs.to('cuda'), labels.to('cuda')
140
+
141
+ # Zero the parameter gradients
142
+ optimizer.zero_grad()
143
+
144
+ # Forward pass with autocast
145
+ with torch.cuda.amp.autocast():
146
+ outputs = model(inputs)
147
+ loss = criterion(outputs, labels)
148
+
149
+ # Backward pass with scaler
150
+ scaler.scale(loss).backward()
151
+ scaler.step(optimizer)
152
+ scaler.update()
153
+
154
+ running_loss += loss.item() * inputs.size(0)
155
+
156
+ epoch_loss = running_loss / len(train_loader.dataset)
157
+ print(f'Epoch [{epoch + 1}/{num_epochs}], Loss: {epoch_loss:.4f}')
158
+
159
+ print('Finished Training')
160
+
161
+ # Sauvegarder le modèle
162
+ torch.save(model.state_dict(), 'model.pth')
163
+
164
+ #Ici pour charger le modèle
165
+
166
+ import torch
167
+ import torch.nn as nn
168
+ from torchvision import models, transforms
169
+ from PIL import Image
170
+
171
+ # Définir le modèle
172
+ num_classes = 2 # Canard et Perroquet
173
+ model = models.resnet18(pretrained=False)
174
+ model.fc = nn.Linear(model.fc.in_features, num_classes)
175
+ model = model.to('cuda')
176
+
177
+ # Charger les poids du modèle enregistré
178
+ model.load_state_dict(torch.load('model.pth'))
179
+ model.eval() # Mettre le modèle en mode évaluation
180
+
181
+ # Définir les transformations
182
+ transform = transforms.Compose([
183
+ transforms.Resize((224, 224)),
184
+ transforms.ToTensor(),
185
+ transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
186
+ ])
187
+
188
+ # Charger et transformer une nouvelle image
189
+ def load_image(image_path):
190
+ image = Image.open(image_path).convert('RGB')
191
+ image = transform(image)
192
+ image = image.unsqueeze(0) # Ajouter une dimension pour le batch
193
+ return image
194
+
195
+ # Exemple de chargement d'une image
196
+ image_path = '/content/lg.jpeg'
197
+ image = load_image(image_path).to('cuda')
198
+
199
+ # Passer l'image dans le modèle pour obtenir des prédictions
200
+ with torch.no_grad(): # Désactiver la grad pour l'inférence
201
+ outputs = model(image)
202
+ _, predicted = torch.max(outputs, 1)
203
+
204
+ classes = ['Alpine', 'Bugatti']
205
+ predicted_class = classes[predicted.item()]
206
+ print(f'Predicted class: {predicted_class}')
207
+
208
+ !pip install transformers huggingface_hub
209
+
210
+ !huggingface-cli login
211
+
212
+ from huggingface_hub import HfApi, HfFolder, Repository
213
+
214
+ # Variables
215
+ model_path = "Wheeloh-model_1.pth"
216
+ repo_name = "Wheeloh-model_1" # Remplacez par le nom de votre dépôt
217
+ commit_message = "Initial commit"
218
+
219
+ # Se connecter à l'API
220
+ api = HfApi()
221
+
222
+ # Obtenir le token d'authentification
223
+ token = HfFolder.get_token()
224
+
225
+ # Cloner le dépôt Hugging Face
226
+ repo_url = api.create_repo(repo_name, token=token, exist_ok=True)
227
+ repo = Repository(local_dir=repo_name, clone_from=repo_url)
228
+
229
+ # Copier le fichier du modèle dans le dépôt local
230
+ import shutil
231
+ shutil.copy(model_path, repo_name)
232
+
233
+ # Pousser le modèle sur le hub
234
+ repo.push_to_hub(commit_message=commit_message)