File size: 26,071 Bytes
b9157b9
 
 
 
 
 
 
 
 
 
 
 
91db1e9
b9157b9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
91db1e9
b9157b9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70178db
b9157b9
 
 
70178db
 
 
 
 
 
 
b9157b9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70178db
 
b9157b9
 
 
 
 
 
 
 
 
7bc1042
b9157b9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70178db
b9157b9
70178db
 
 
b9157b9
 
 
 
 
7bc1042
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b9157b9
 
 
 
 
 
 
70178db
b9157b9
 
7bc1042
 
b9157b9
91db1e9
 
b9157b9
 
 
 
7bc1042
b9157b9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7bc1042
b9157b9
 
 
 
 
 
 
 
 
 
 
 
 
7bc1042
b9157b9
 
 
 
 
 
 
 
 
 
 
 
 
 
7bc1042
b9157b9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7bc1042
b9157b9
 
 
 
 
 
 
 
7bc1042
b9157b9
 
 
 
7bc1042
b9157b9
 
 
 
 
 
 
91db1e9
b9157b9
 
 
 
 
 
 
91db1e9
b9157b9
 
 
 
 
 
 
 
 
 
 
 
 
8b6417b
b9157b9
 
 
 
7bc1042
b9157b9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7bc1042
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b9157b9
 
 
7bc1042
b9157b9
 
 
7bc1042
b9157b9
 
 
 
7bc1042
 
b9157b9
 
 
 
 
 
7bc1042
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b9157b9
 
 
 
7bc1042
 
 
 
 
 
 
 
 
 
 
 
b9157b9
 
 
 
 
7bc1042
b9157b9
 
7bc1042
a8586cd
7bc1042
b9157b9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "fce70006-809b-4c98-b89c-00910b8bbea1",
   "metadata": {},
   "source": [
    "Implementation for blog post"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "1eaa3a9f-0b39-4d77-91d6-f935d226ac98",
   "metadata": {},
   "outputs": [],
   "source": [
    "import math\n",
    "import pickle\n",
    "import os\n",
    "import time\n",
    "import matplotlib.pyplot as plt\n",
    "from tabulate import tabulate\n",
    "\n",
    "from transformers import pipeline\n",
    "import json\n",
    "import pandas as pd\n",
    "\n",
    "# Get candidate labels\n",
    "with open(\"packing_label_structure.json\", \"r\") as file:\n",
    "    candidate_labels = json.load(file)\n",
    "keys_list = list(candidate_labels.keys())\n",
    "\n",
    "# Load test data (list of dictionaries)\n",
    "# with open(\"test_data.json\", \"r\") as file:\n",
    "#     packing_data = json.load(file)\n",
    "# Extract trip descriptions and classification (trip_types)\n",
    "# trip_descriptions = [trip['description'] for trip in packing_data]\n",
    "# trip_types = [trip['trip_types'] for trip in packing_data]\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "bb1bc7ed-227e-4c0b-b769-ead4daf01c57",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      " activity_type :\n",
      "\t hut trek (summer)\n",
      "\t hut trek (winter)\n",
      "\t camping trip (wild camping)\n",
      "\t camping trip (campground)\n",
      "\t ski tour / skitour\n",
      "\t snowboard / splitboard trip\n",
      "\t long-distance hike / thru-hike\n",
      "\t digital nomad trip\n",
      "\t city trip\n",
      "\t road trip (car/camper)\n",
      "\t festival trip\n",
      "\t yoga / wellness retreat\n",
      "\t micro-adventure / weekend trip\n",
      "\t beach vacation\n",
      "\t cultural exploration\n",
      "\t nature escape\n",
      "\n",
      " activities :\n",
      "\t swimming\n",
      "\t going to the beach\n",
      "\t relaxing\n",
      "\t sightseeing\n",
      "\t biking\n",
      "\t running\n",
      "\t skiing\n",
      "\t cross-country skiing\n",
      "\t ski touring\n",
      "\t hiking\n",
      "\t hut-to-hut hiking\n",
      "\t rock climbing\n",
      "\t ice climbing\n",
      "\t snowshoe hiking\n",
      "\t kayaking / canoeing\n",
      "\t stand-up paddleboarding (SUP)\n",
      "\t snorkeling\n",
      "\t scuba diving\n",
      "\t surfing\n",
      "\t paragliding\n",
      "\t horseback riding\n",
      "\t photography\n",
      "\t fishing\n",
      "\t rafting\n",
      "\t yoga\n",
      "\n",
      " climate_or_season :\n",
      "\t cold destination / winter\n",
      "\t warm destination / summer\n",
      "\t variable weather / spring / autumn\n",
      "\t tropical / humid\n",
      "\t dry / desert-like\n",
      "\t rainy climate\n",
      "\n",
      " style_or_comfort :\n",
      "\t ultralight\n",
      "\t lightweight (but comfortable)\n",
      "\t luxury (including evening wear)\n",
      "\t minimalist\n",
      "\n",
      " dress_code :\n",
      "\t casual\n",
      "\t formal (business trip)\n",
      "\t conservative\n",
      "\n",
      " accommodation :\n",
      "\t indoor\n",
      "\t huts with half board\n",
      "\t sleeping in a tent\n",
      "\t sleeping in a car\n",
      "\n",
      " transportation :\n",
      "\t own vehicle\n",
      "\t no own vehicle\n",
      "\n",
      " special_conditions :\n",
      "\t off-grid / no electricity\n",
      "\t self-supported (bring your own cooking gear)\n",
      "\t travel with children\n",
      "\t pet-friendly\n",
      "\t snow and ice\n",
      "\t high alpine terrain\n",
      "\t snow, ice and avalanche-prone terrain\n",
      "\t no special conditions to consider\n",
      "\n",
      " trip_length_days :\n",
      "\t 1 day\n",
      "\t 2 days\n",
      "\t 3 days\n",
      "\t 4 days\n",
      "\t 5 days\n",
      "\t 6 days\n",
      "\t 7 days\n",
      "\t 7+ days\n"
     ]
    }
   ],
   "source": [
    "for key in candidate_labels:\n",
    "    print(\"\\n\", key, \":\")\n",
    "    for item in candidate_labels[key]:\n",
    "        print(\"\\t\", item)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "4b3a1bcb-3450-4128-b941-952f145baf99",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "activity_type\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Hardware accelerator e.g. GPU is available in the environment, but no `device` argument is passed to the `Pipeline` object. Model will be on CPU.\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "                             Label     Score\n",
      "0                   beach vacation  0.376311\n",
      "1   micro-adventure / weekend trip  0.350168\n",
      "2                    nature escape  0.133974\n",
      "3               digital nomad trip  0.031636\n",
      "4             cultural exploration  0.031271\n",
      "5          yoga / wellness retreat  0.012846\n",
      "6                    festival trip  0.012700\n",
      "7   long-distance hike / thru-hike  0.009527\n",
      "8                hut trek (summer)  0.008148\n",
      "9                        city trip  0.007793\n",
      "10          road trip (car/camper)  0.006512\n",
      "11              ski tour / skitour  0.005670\n",
      "12       camping trip (campground)  0.004448\n",
      "13     snowboard / splitboard trip  0.004113\n",
      "14     camping trip (wild camping)  0.002714\n",
      "15               hut trek (winter)  0.002170\n"
     ]
    }
   ],
   "source": [
    "model_name = \"facebook/bart-large-mnli\"\n",
    "trip_descr = \"I am planning a trip to Greece with my boyfriend, where we will visit two islands. We have booked an apartment on each island for a few days and plan to spend most of our time relaxing. Our main goals are to enjoy the beach, try delicious local food, and possibly go on a hike—if it’s not too hot. We will be relying solely on public transport. We’re in our late 20s and traveling from the Netherlands.\"\n",
    "classifier = pipeline(\"zero-shot-classification\", model = model_name)\n",
    "result = classifier(trip_descr, candidate_labels[\"activity_type\"])\n",
    "\n",
    "df = pd.DataFrame({\n",
    "    \"Label\": result[\"labels\"],\n",
    "    \"Score\": result[\"scores\"]\n",
    "})\n",
    "print(df)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "04208f9e-59bb-408b-92c6-941d064bf43d",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "beach vacation\n"
     ]
    }
   ],
   "source": [
    "# the labels are sorted by score. We choose the first one as our best guess for a class label\n",
    "class_label = result[\"labels\"][0]\n",
    "print(class_label)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "9f5f1c45-b411-4de1-a0a6-a7ecde5d8eae",
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "                            Label     Score\n",
      "0              going to the beach  0.991486\n",
      "1                        relaxing  0.977136\n",
      "2                          hiking  0.942628\n",
      "3                        swimming  0.219020\n",
      "4                     sightseeing  0.175862\n",
      "5                         running  0.098545\n",
      "6               hut-to-hut hiking  0.083704\n",
      "7                          biking  0.036792\n",
      "8                     photography  0.036690\n",
      "9                         surfing  0.030993\n",
      "10  stand-up paddleboarding (SUP)  0.025300\n",
      "11                     snorkeling  0.021451\n",
      "12                           yoga  0.011070\n",
      "13            kayaking / canoeing  0.007511\n",
      "14                  rock climbing  0.006307\n",
      "15                        fishing  0.003497\n",
      "16                    paragliding  0.002656\n",
      "17                        rafting  0.001970\n",
      "18               horseback riding  0.001560\n",
      "19                snowshoe hiking  0.001528\n",
      "20           cross-country skiing  0.001502\n",
      "21                   ice climbing  0.001434\n",
      "22                         skiing  0.001169\n",
      "23                   scuba diving  0.000789\n",
      "24                    ski touring  0.000491\n",
      "['going to the beach', 'relaxing', 'hiking']\n"
     ]
    }
   ],
   "source": [
    "# we do this for each superclass and receive a list of class labels for our trip. We did do things differently for activities\n",
    "cut_off = 0.5\n",
    "result_activ = classifier(trip_descr, candidate_labels[\"activities\"], multi_label=True)\n",
    "classes = df.loc[df[\"Score\"] > 0.5, \"Label\"].tolist()\n",
    "\n",
    "df = pd.DataFrame({\n",
    "    \"Label\": result_activ[\"labels\"],\n",
    "    \"Score\": result_activ[\"scores\"]\n",
    "})\n",
    "print(df)\n",
    "print(classes)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "3a7287c2-78f0-4a53-af72-1bc0f62da36f",
   "metadata": {},
   "outputs": [],
   "source": [
    "# doing this for all superclasses, depending on local machine this might take a while\n",
    "def pred_trip(model_name, trip_descr, cut_off = 0.5):\n",
    "    \"\"\"\n",
    "    Classifies trip\n",
    "    \n",
    "    Parameters:\n",
    "    model_name: name of hugging-face model\n",
    "    trip_descr: text describing the trip\n",
    "    cut_off: cut_off for choosing activities\n",
    "\n",
    "    Returns:\n",
    "    pd Dataframe: with class predictions and true values\n",
    "    \"\"\"\n",
    "    \n",
    "    classifier = pipeline(\"zero-shot-classification\", model=model_name)\n",
    "    df = pd.DataFrame(columns=['superclass', 'pred_class'])\n",
    "    for i, key in enumerate(keys_list):\n",
    "        # print(f\"\\rProcessing {i + 1}/{len(keys_list)}\", end=\"\", flush=True)\n",
    "        if key == 'activities':\n",
    "            result = classifier(trip_descr, candidate_labels[key], multi_label=True)\n",
    "            indices = [i for i, score in enumerate(result['scores']) if score > cut_off]\n",
    "            classes = [result['labels'][i] for i in indices]\n",
    "        else:\n",
    "            result = classifier(trip_descr, candidate_labels[key])\n",
    "            classes = result[\"labels\"][0]\n",
    "        df.loc[i] = [key, classes]\n",
    "    return df"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "43481d4c-039a-4a37-bd6d-dfe638bf9732",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Hardware accelerator e.g. GPU is available in the environment, but no `device` argument is passed to the `Pipeline` object. Model will be on CPU.\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "           superclass                              pred_class\n",
      "0       activity_type                          beach vacation\n",
      "1          activities  [going to the beach, relaxing, hiking]\n",
      "2   climate_or_season               warm destination / summer\n",
      "3    style_or_comfort                              minimalist\n",
      "4          dress_code                                  casual\n",
      "5       accommodation                    huts with half board\n",
      "6      transportation                          no own vehicle\n",
      "7  special_conditions               off-grid / no electricity\n",
      "8    trip_length_days                                 7+ days\n"
     ]
    }
   ],
   "source": [
    "result = pred_trip(model_name, trip_descr, cut_off = 0.5)\n",
    "print(result)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c4799d6b-6ab5-42da-a992-afe3666d0015",
   "metadata": {},
   "source": [
    "Now use gradio app"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "35e14ac8-4445-4586-a115-081cf1ef2686",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Prerequisites\n",
    "from transformers import pipeline\n",
    "import json\n",
    "import pandas as pd\n",
    "import gradio as gr"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "8eefd4cc-c375-4cc0-956b-472b36bafdb7",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Running on local URL:  http://127.0.0.1:7860\n",
      "\n",
      "To create a public link, set `share=True` in `launch()`.\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div><iframe src=\"http://127.0.0.1:7860/\" width=\"100%\" height=\"500\" allow=\"autoplay; camera; microphone; clipboard-read; clipboard-write;\" frameborder=\"0\" allowfullscreen></iframe></div>"
      ],
      "text/plain": [
       "<IPython.core.display.HTML object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "demo = gr.Interface(\n",
    "    fn=pred_trip,\n",
    "    inputs=[\n",
    "        gr.Textbox(label=\"Model name\", value = \"MoritzLaurer/DeBERTa-v3-large-mnli-fever-anli-ling-wanli\"),\n",
    "        gr.Textbox(label=\"Trip description\"),\n",
    "        gr.Number(label=\"Activity cut-off\", value = 0.5),\n",
    "    ],\n",
    "    # outputs=\"dataframe\",\n",
    "    outputs=[gr.Dataframe(label=\"DataFrame\")],\n",
    "    title=\"Trip classification\",\n",
    "    description=\"Enter a text describing your trip\",\n",
    ")\n",
    "\n",
    "# Launch the Gradio app\n",
    "if __name__ == \"__main__\":\n",
    "    demo.launch()\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 46,
   "id": "11006b67-bfd5-42a7-99c4-36c3db3affac",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Hardware accelerator e.g. GPU is available in the environment, but no `device` argument is passed to the `Pipeline` object. Model will be on CPU.\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Processing 9/9"
     ]
    }
   ],
   "source": [
    "test = pred_trip(model_name, trip_descr, cut_off = 0.5)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "39920553-27d3-4a63-8381-8310566c4874",
   "metadata": {},
   "source": [
    "All code for gradio app file"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "4ffc76d5-60c3-4bc8-bd4f-a9636077f01d",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Running on local URL:  http://127.0.0.1:7861\n",
      "\n",
      "To create a public link, set `share=True` in `launch()`.\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div><iframe src=\"http://127.0.0.1:7861/\" width=\"100%\" height=\"500\" allow=\"autoplay; camera; microphone; clipboard-read; clipboard-write;\" frameborder=\"0\" allowfullscreen></iframe></div>"
      ],
      "text/plain": [
       "<IPython.core.display.HTML object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Hardware accelerator e.g. GPU is available in the environment, but no `device` argument is passed to the `Pipeline` object. Model will be on CPU.\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Processing 9/9"
     ]
    }
   ],
   "source": [
    "# Prerequisites\n",
    "from transformers import pipeline\n",
    "import json\n",
    "import pandas as pd\n",
    "import gradio as gr\n",
    "\n",
    "# Get candidate labels\n",
    "with open(\"packing_label_structure.json\", \"r\") as file:\n",
    "    candidate_labels = json.load(file)\n",
    "keys_list = list(candidate_labels.keys())\n",
    "\n",
    "def pred_trip(model_name, trip_descr, cut_off = 0.5):\n",
    "    \"\"\"\n",
    "    Classifies trip\n",
    "    \n",
    "    Parameters:\n",
    "    model_name: name of hugging-face model\n",
    "    trip_descr: text describing the trip\n",
    "    cut_off: cut_off for choosing activities\n",
    "\n",
    "    Returns:\n",
    "    pd Dataframe: with class predictions and true values\n",
    "    \"\"\"\n",
    "    \n",
    "    classifier = pipeline(\"zero-shot-classification\", model=model_name)\n",
    "    df = pd.DataFrame(columns=['superclass', 'pred_class'])\n",
    "    for i, key in enumerate(keys_list):\n",
    "        print(f\"\\rProcessing {i + 1}/{len(keys_list)}\", end=\"\", flush=True)\n",
    "        if key == 'activities':\n",
    "            result = classifier(trip_descr, candidate_labels[key], multi_label=True)\n",
    "            indices = [i for i, score in enumerate(result['scores']) if score > cut_off]\n",
    "            classes = [result['labels'][i] for i in indices]\n",
    "        else:\n",
    "            result = classifier(trip_descr, candidate_labels[key])\n",
    "            classes = result[\"labels\"][0]\n",
    "        df.loc[i] = [key, classes]\n",
    "    return df\n",
    "\n",
    "demo = gr.Interface(\n",
    "    fn=pred_trip,\n",
    "    inputs=[\n",
    "        gr.Textbox(label=\"Model name\", value = \"MoritzLaurer/DeBERTa-v3-large-mnli-fever-anli-ling-wanli\"),\n",
    "        gr.Textbox(label=\"Trip description\"),\n",
    "        gr.Number(label=\"Activity cut-off\", value = 0.5),\n",
    "    ],\n",
    "    # outputs=\"dataframe\",\n",
    "    outputs=[gr.Dataframe(label=\"DataFrame\")],\n",
    "    title=\"Trip classification\",\n",
    "    description=\"Enter a text describing your trip\",\n",
    ")\n",
    "\n",
    "# Launch the Gradio app\n",
    "if __name__ == \"__main__\":\n",
    "    demo.launch()\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "fb115832-d9c9-4cfd-8a2a-85916ce3a04a",
   "metadata": {},
   "outputs": [],
   "source": [
    "Print test data set"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "f25e1462-ca48-4853-ae44-dfc096c5011d",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0 . I am planning a trip to Greece with my boyfriend, where we will visit two islands. We have booked an apartment on each island for a few days and plan to spend most of our time relaxing. Our main goals are to enjoy the beach, try delicious local food, and possibly go on a hike—if it’s not too hot. We will be relying solely on public transport. We’re in our late 20s and traveling from the Netherlands. \n",
      "\n",
      "beach vacation\n",
      "['swimming', 'going to the beach', 'relaxing', 'hiking']\n",
      "warm destination / summer\n",
      "lightweight (but comfortable)\n",
      "casual\n",
      "indoor\n",
      "no own vehicle\n",
      "no special conditions to consider\n",
      "7+ days\n",
      "\n",
      "\n",
      "1 . We are a couple in our thirties traveling to Vienna for a three-day city trip. We’ll be staying at a friend’s house and plan to explore the city by sightseeing, strolling through the streets, visiting markets, and trying out great restaurants and cafés. We also hope to attend a classical music concert. Our journey to Vienna will be by train. \n",
      "\n",
      "city trip\n",
      "['sightseeing']\n",
      "variable weather / spring / autumn\n",
      "luxury (including evening wear)\n",
      "casual\n",
      "indoor\n",
      "no own vehicle\n",
      "no special conditions to consider\n",
      "3 days\n",
      "\n",
      "\n",
      "2 . My partner and I are traveling to the Netherlands and Germany to spend Christmas with our family. We are in our late twenties and will start our journey with a two-hour flight to the Netherlands. From there, we will take a 5.5-hour train ride to northern Germany. \n",
      "\n",
      "city trip\n",
      "['relaxing']\n",
      "cold destination / winter\n",
      "lightweight (but comfortable)\n",
      "casual\n",
      "indoor\n",
      "no own vehicle\n",
      "no special conditions to consider\n",
      "7+ days\n",
      "\n",
      "\n",
      "3 . I’m in my twenties and will be traveling to Peru for three weeks. I’m going solo but will meet up with a friend to explore the Sacred Valley and take part in a Machu Picchu tour. We plan to hike, go rafting, and explore the remnants of the ancient Inca Empire. We’re also excited to try Peruvian cuisine and immerse ourselves in the local culture. Depending on our plans, we might also visit the rainforest region, such as Tarapoto. I’ll be flying to Peru on a long-haul flight and will be traveling in August. \n",
      "\n",
      "cultural exploration\n",
      "['sightseeing', 'hiking', 'rafting']\n",
      "variable weather / spring / autumn\n",
      "lightweight (but comfortable)\n",
      "casual\n",
      "indoor\n",
      "no own vehicle\n",
      "rainy climate\n",
      "7+ days\n",
      "\n",
      "\n",
      "4 . We’re planning a 10-day trip to Austria in the summer, combining hiking with relaxation by the lake. We love exploring scenic trails and enjoying the outdoors, but we also want to unwind and swim in the lake. It’s the perfect mix of adventure and relaxation. \n",
      "\n",
      "nature escape\n",
      "['swimming', 'relaxing', 'hiking']\n",
      "warm destination / summer\n",
      "lightweight (but comfortable)\n",
      "casual\n",
      "indoor\n",
      "no own vehicle\n",
      "no special conditions to consider\n",
      "7+ days\n",
      "\n",
      "\n",
      "5 . I am going on a multiple day hike and passing though mountains and the beach in Croatia. I like to pack light and will stay in refugios/huts with half board and travel to the start of the hike by car. It will be 6-7 days. \n",
      "\n",
      "long-distance hike / thru-hike\n",
      "['going to the beach']\n",
      "tropical / humid\n",
      "minimalist\n",
      "casual\n",
      "huts with half board\n",
      "own vehicle\n",
      "off-grid / no electricity\n",
      "6 days\n",
      "\n",
      "\n",
      "6 . I will go with a friend on a beach holiday and we will do stand-up paddling, and surfing in the North of Spain. The destination is windy and can get cold, but is generally sunny. We will go by car and bring a tent to sleep in. It will be two weeks. \n",
      "\n",
      "beach vacation\n",
      "['stand-up paddleboarding (SUP)', 'surfing']\n",
      "cold destination / winter\n",
      "ultralight\n",
      "casual\n",
      "sleeping in a tent\n",
      "own vehicle\n",
      "off-grid / no electricity\n",
      "6 days\n",
      "\n",
      "\n",
      "7 . We will go to Sweden in the winter, to go for a yoga and sauna/wellness retreat. I prefer lightweight packing and also want clothes to go for fancy dinners and maybe on a winter hike. We stay in hotels. \n",
      "\n",
      "yoga / wellness retreat\n",
      "['hiking', 'yoga']\n",
      "cold destination / winter\n",
      "lightweight (but comfortable)\n",
      "casual\n",
      "indoor\n",
      "no own vehicle\n",
      "snow and ice\n",
      "7 days\n",
      "\n",
      "\n",
      "8 . I go on a skitouring trip where we also make videos/photos and the destination is Japan. Mainly sports clothes and isolation are needed (it is winter). We stay in a guesthouse. It will be 10 days. \n",
      "\n",
      "ski tour / skitour\n",
      "['ski touring', 'photography']\n",
      "cold destination / winter\n",
      "minimalist\n",
      "conservative\n",
      "indoor\n",
      "no own vehicle\n",
      "avalanche-prone terrain\n",
      "7+ days\n",
      "\n",
      "\n",
      "9 . We plan a wild camping trip with activities such as snorkeling, kayaking and canoeing. It is a warm place and we want to bring little stuff. We stay in tents and hammocks and travel with a car, it will be 3 days. \n",
      "\n",
      "camping trip (wild camping)\n",
      "['scuba diving', 'kayaking / canoeing']\n",
      "tropical / humid\n",
      "lightweight (but comfortable)\n",
      "casual\n",
      "sleeping in a tent\n",
      "own vehicle\n",
      "self-supported (bring your own cooking gear)\n",
      "3 days\n",
      "\n",
      "\n"
     ]
    }
   ],
   "source": [
    "# Load test data (list of dictionaries)\n",
    "with open(\"test_data.json\", \"r\") as file:\n",
    "    packing_data = json.load(file)\n",
    "    # Extract trip descriptions and classification (trip_types)\n",
    "trip_descriptions = [trip['description'] for trip in packing_data]\n",
    "trip_types = [trip['trip_types'] for trip in packing_data]\n",
    "\n",
    "for i, item in enumerate(trip_descriptions):\n",
    "    print(i, \".\", item, \"\\n\")\n",
    "    for elem in trip_types[i]:\n",
    "        print(elem)\n",
    "    print(\"\\n\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "23a306bc-5dac-4569-a727-d140e1b8da7a",
   "metadata": {},
   "outputs": [],
   "source": [
    "# "
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python (huggingface_env)",
   "language": "python",
   "name": "huggingface_env"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.20"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}