{ "nbformat": 4, "nbformat_minor": 5, "metadata": { "kernelspec": { "display_name": "Python 3", "name": "python3" }, "language_info": { "name": "python", "version": "3.10.12" }, "accelerator": "GPU", "widgets": { "application/vnd.jupyter.widget-state+json": { "75fd8ceed80b46cc9316e0d190b09e97": { "model_module": "@jupyter-widgets/controls", "model_name": "HBoxModel", "model_module_version": "1.5.0", "state": { "_dom_classes": [], "_model_module": "@jupyter-widgets/controls", "_model_module_version": "1.5.0", "_model_name": "HBoxModel", "_view_count": null, "_view_module": "@jupyter-widgets/controls", "_view_module_version": "1.5.0", "_view_name": "HBoxView", "box_style": "", "children": [ "IPY_MODEL_3a5c9407a75f499ba9aa9a069f378319", "IPY_MODEL_15dc17d4c77846b19dd7a2d984afe4c4", "IPY_MODEL_f0232c57358e46c39c28e4b036213573" ], "layout": "IPY_MODEL_6d4b35e65c524ed6a2a39a474b97210d" } }, "3a5c9407a75f499ba9aa9a069f378319": { "model_module": "@jupyter-widgets/controls", "model_name": "HTMLModel", "model_module_version": "1.5.0", "state": { "_dom_classes": [], "_model_module": "@jupyter-widgets/controls", "_model_module_version": "1.5.0", "_model_name": "HTMLModel", "_view_count": null, "_view_module": "@jupyter-widgets/controls", "_view_module_version": "1.5.0", "_view_name": "HTMLView", "description": "", "description_tooltip": null, "layout": "IPY_MODEL_abc32cd804ee4abc975ce284e5aa5b82", "placeholder": "​", "style": "IPY_MODEL_e70698a7ec2a4721bcc7579ce5a1871a", "value": "model.safetensors: 100%" } }, "15dc17d4c77846b19dd7a2d984afe4c4": { "model_module": "@jupyter-widgets/controls", "model_name": "FloatProgressModel", "model_module_version": "1.5.0", "state": { "_dom_classes": [], "_model_module": "@jupyter-widgets/controls", "_model_module_version": "1.5.0", "_model_name": "FloatProgressModel", "_view_count": null, "_view_module": "@jupyter-widgets/controls", "_view_module_version": "1.5.0", "_view_name": "ProgressView", "bar_style": "success", "description": "", "description_tooltip": null, "layout": "IPY_MODEL_c330713056e046d8b625383abbd204a3", "max": 1119825680, "min": 0, "orientation": "horizontal", "style": "IPY_MODEL_b45075fd72e041309383b9435ce9bd0f", "value": 1119825680 } }, "f0232c57358e46c39c28e4b036213573": { "model_module": "@jupyter-widgets/controls", "model_name": "HTMLModel", "model_module_version": "1.5.0", "state": { "_dom_classes": [], "_model_module": "@jupyter-widgets/controls", "_model_module_version": "1.5.0", "_model_name": "HTMLModel", "_view_count": null, "_view_module": "@jupyter-widgets/controls", "_view_module_version": "1.5.0", "_view_name": "HTMLView", "description": "", "description_tooltip": null, "layout": "IPY_MODEL_9c6a8c0d72d54333a3374720c3c49a7e", "placeholder": "​", "style": "IPY_MODEL_41fd9688de884e748f5a19d0a1aa8660", "value": " 1.12G/1.12G [00:02<00:00, 755MB/s]" } }, "6d4b35e65c524ed6a2a39a474b97210d": { "model_module": "@jupyter-widgets/base", "model_name": "LayoutModel", "model_module_version": "1.2.0", "state": { "_model_module": "@jupyter-widgets/base", "_model_module_version": "1.2.0", "_model_name": "LayoutModel", "_view_count": null, "_view_module": "@jupyter-widgets/base", "_view_module_version": "1.2.0", "_view_name": "LayoutView", "align_content": null, "align_items": null, "align_self": null, "border": null, "bottom": null, "display": null, "flex": null, "flex_flow": null, "grid_area": null, "grid_auto_columns": null, "grid_auto_flow": null, "grid_auto_rows": null, "grid_column": null, "grid_gap": null, "grid_row": null, "grid_template_areas": null, "grid_template_columns": null, "grid_template_rows": null, "height": null, "justify_content": null, "justify_items": null, "left": null, "margin": null, "max_height": null, "max_width": null, "min_height": null, "min_width": null, "object_fit": null, "object_position": null, "order": null, "overflow": null, "overflow_x": null, "overflow_y": null, "padding": null, "right": null, "top": null, "visibility": null, "width": null } }, "abc32cd804ee4abc975ce284e5aa5b82": { "model_module": "@jupyter-widgets/base", "model_name": "LayoutModel", "model_module_version": "1.2.0", "state": { "_model_module": "@jupyter-widgets/base", "_model_module_version": "1.2.0", "_model_name": "LayoutModel", "_view_count": null, "_view_module": "@jupyter-widgets/base", "_view_module_version": "1.2.0", "_view_name": "LayoutView", "align_content": null, "align_items": null, "align_self": null, "border": null, "bottom": null, "display": null, "flex": null, "flex_flow": null, "grid_area": null, "grid_auto_columns": null, "grid_auto_flow": null, "grid_auto_rows": null, "grid_column": null, "grid_gap": null, "grid_row": null, "grid_template_areas": null, "grid_template_columns": null, "grid_template_rows": null, "height": null, "justify_content": null, "justify_items": null, "left": null, "margin": null, "max_height": null, "max_width": null, "min_height": null, "min_width": null, "object_fit": null, "object_position": null, "order": null, "overflow": null, "overflow_x": null, "overflow_y": null, "padding": null, "right": null, "top": null, "visibility": null, "width": null } }, "e70698a7ec2a4721bcc7579ce5a1871a": { "model_module": "@jupyter-widgets/controls", "model_name": "DescriptionStyleModel", "model_module_version": "1.5.0", "state": { "_model_module": "@jupyter-widgets/controls", "_model_module_version": "1.5.0", "_model_name": "DescriptionStyleModel", "_view_count": null, "_view_module": "@jupyter-widgets/base", "_view_module_version": "1.2.0", "_view_name": "StyleView", "description_width": "" } }, "c330713056e046d8b625383abbd204a3": { "model_module": "@jupyter-widgets/base", "model_name": "LayoutModel", "model_module_version": "1.2.0", "state": { "_model_module": "@jupyter-widgets/base", "_model_module_version": "1.2.0", "_model_name": "LayoutModel", "_view_count": null, "_view_module": "@jupyter-widgets/base", "_view_module_version": "1.2.0", "_view_name": "LayoutView", "align_content": null, "align_items": null, "align_self": null, "border": null, "bottom": null, "display": null, "flex": null, "flex_flow": null, "grid_area": null, "grid_auto_columns": null, "grid_auto_flow": null, "grid_auto_rows": null, "grid_column": null, "grid_gap": null, "grid_row": null, "grid_template_areas": null, "grid_template_columns": null, "grid_template_rows": null, "height": null, "justify_content": null, "justify_items": null, "left": null, "margin": null, "max_height": null, "max_width": null, "min_height": null, "min_width": null, "object_fit": null, "object_position": null, "order": null, "overflow": null, "overflow_x": null, "overflow_y": null, "padding": null, "right": null, "top": null, "visibility": null, "width": null } }, "b45075fd72e041309383b9435ce9bd0f": { "model_module": "@jupyter-widgets/controls", "model_name": "ProgressStyleModel", "model_module_version": "1.5.0", "state": { "_model_module": "@jupyter-widgets/controls", "_model_module_version": "1.5.0", "_model_name": "ProgressStyleModel", "_view_count": null, "_view_module": "@jupyter-widgets/base", "_view_module_version": "1.2.0", "_view_name": "StyleView", "bar_color": null, "description_width": "" } }, "9c6a8c0d72d54333a3374720c3c49a7e": { "model_module": "@jupyter-widgets/base", "model_name": "LayoutModel", "model_module_version": "1.2.0", "state": { "_model_module": "@jupyter-widgets/base", "_model_module_version": "1.2.0", "_model_name": "LayoutModel", "_view_count": null, "_view_module": "@jupyter-widgets/base", "_view_module_version": "1.2.0", "_view_name": "LayoutView", "align_content": null, "align_items": null, "align_self": null, "border": null, "bottom": null, "display": null, "flex": null, "flex_flow": null, "grid_area": null, "grid_auto_columns": null, "grid_auto_flow": null, "grid_auto_rows": null, "grid_column": null, "grid_gap": null, "grid_row": null, "grid_template_areas": null, "grid_template_columns": null, "grid_template_rows": null, "height": null, "justify_content": null, "justify_items": null, "left": null, "margin": null, "max_height": null, "max_width": null, "min_height": null, "min_width": null, "object_fit": null, "object_position": null, "order": null, "overflow": null, "overflow_x": null, "overflow_y": null, "padding": null, "right": null, "top": null, "visibility": null, "width": null } }, "41fd9688de884e748f5a19d0a1aa8660": { "model_module": "@jupyter-widgets/controls", "model_name": "DescriptionStyleModel", "model_module_version": "1.5.0", "state": { "_model_module": "@jupyter-widgets/controls", "_model_module_version": "1.5.0", "_model_name": "DescriptionStyleModel", "_view_count": null, "_view_module": "@jupyter-widgets/base", "_view_module_version": "1.2.0", "_view_name": "StyleView", "description_width": "" } }, "60ecde232e7245a6b583430039141075": { "model_module": "@jupyter-widgets/controls", "model_name": "HBoxModel", "model_module_version": "1.5.0", "state": { "_dom_classes": [], "_model_module": "@jupyter-widgets/controls", "_model_module_version": "1.5.0", "_model_name": "HBoxModel", "_view_count": null, "_view_module": "@jupyter-widgets/controls", "_view_module_version": "1.5.0", "_view_name": "HBoxView", "box_style": "", "children": [ "IPY_MODEL_9c3680037fc048b0a1cbf9b3c246209d", "IPY_MODEL_3136129c68ac4935a4ee90432835f0aa", "IPY_MODEL_8898e0a54d8f413b9d6d73012500bac6" ], "layout": "IPY_MODEL_058948e259e24d27b102fa9f271aebe1" } }, "9c3680037fc048b0a1cbf9b3c246209d": { "model_module": "@jupyter-widgets/controls", "model_name": "HTMLModel", "model_module_version": "1.5.0", "state": { "_dom_classes": [], "_model_module": "@jupyter-widgets/controls", "_model_module_version": "1.5.0", "_model_name": "HTMLModel", "_view_count": null, "_view_module": "@jupyter-widgets/controls", "_view_module_version": "1.5.0", "_view_name": "HTMLView", "description": "", "description_tooltip": null, "layout": "IPY_MODEL_ed8eee0411fe4b74854002f40a9ee075", "placeholder": "​", "style": "IPY_MODEL_f28402394e22420284b682864f882b1f", "value": "Loading weights: 100%" } }, "3136129c68ac4935a4ee90432835f0aa": { "model_module": "@jupyter-widgets/controls", "model_name": "FloatProgressModel", "model_module_version": "1.5.0", "state": { "_dom_classes": [], "_model_module": "@jupyter-widgets/controls", "_model_module_version": "1.5.0", "_model_name": "FloatProgressModel", "_view_count": null, "_view_module": "@jupyter-widgets/controls", "_view_module_version": "1.5.0", "_view_name": "ProgressView", "bar_style": "success", "description": "", "description_tooltip": null, "layout": "IPY_MODEL_b994f42cb0314ea289f0f62ee2b2e79b", "max": 391, "min": 0, "orientation": "horizontal", "style": "IPY_MODEL_cf1f016e6eb44ca299b5a196ca316b0d", "value": 391 } }, "8898e0a54d8f413b9d6d73012500bac6": { "model_module": "@jupyter-widgets/controls", "model_name": "HTMLModel", "model_module_version": "1.5.0", "state": { "_dom_classes": [], "_model_module": "@jupyter-widgets/controls", "_model_module_version": "1.5.0", "_model_name": "HTMLModel", "_view_count": null, "_view_module": "@jupyter-widgets/controls", "_view_module_version": "1.5.0", "_view_name": "HTMLView", "description": "", "description_tooltip": null, "layout": "IPY_MODEL_b4bf53c373794d1a9871fba79f6fdc96", "placeholder": "​", "style": "IPY_MODEL_cbc8c57282704e3da44f269b10f12fc1", "value": " 391/391 [00:00<00:00, 1160.70it/s, Materializing param=pooler.dense.weight]" } }, "058948e259e24d27b102fa9f271aebe1": { "model_module": "@jupyter-widgets/base", "model_name": "LayoutModel", "model_module_version": "1.2.0", "state": { "_model_module": "@jupyter-widgets/base", "_model_module_version": "1.2.0", "_model_name": "LayoutModel", "_view_count": null, "_view_module": "@jupyter-widgets/base", "_view_module_version": "1.2.0", "_view_name": "LayoutView", "align_content": null, "align_items": null, "align_self": null, "border": null, "bottom": null, "display": null, "flex": null, "flex_flow": null, "grid_area": null, "grid_auto_columns": null, "grid_auto_flow": null, "grid_auto_rows": null, "grid_column": null, "grid_gap": null, "grid_row": null, "grid_template_areas": null, "grid_template_columns": null, "grid_template_rows": null, "height": null, "justify_content": null, "justify_items": null, "left": null, "margin": null, "max_height": null, "max_width": null, "min_height": null, "min_width": null, "object_fit": null, "object_position": null, "order": null, "overflow": null, "overflow_x": null, "overflow_y": null, "padding": null, "right": null, "top": null, "visibility": null, "width": null } }, "ed8eee0411fe4b74854002f40a9ee075": { "model_module": "@jupyter-widgets/base", "model_name": "LayoutModel", "model_module_version": "1.2.0", "state": { "_model_module": "@jupyter-widgets/base", "_model_module_version": "1.2.0", "_model_name": "LayoutModel", "_view_count": null, "_view_module": "@jupyter-widgets/base", "_view_module_version": "1.2.0", "_view_name": "LayoutView", "align_content": null, "align_items": null, "align_self": null, "border": null, "bottom": null, "display": null, "flex": null, "flex_flow": null, "grid_area": null, "grid_auto_columns": null, "grid_auto_flow": null, "grid_auto_rows": null, "grid_column": null, "grid_gap": null, "grid_row": null, "grid_template_areas": null, "grid_template_columns": null, "grid_template_rows": null, "height": null, "justify_content": null, "justify_items": null, "left": null, "margin": null, "max_height": null, "max_width": null, "min_height": null, "min_width": null, "object_fit": null, "object_position": null, "order": null, "overflow": null, "overflow_x": null, "overflow_y": null, "padding": null, "right": null, "top": null, "visibility": null, "width": null } }, "f28402394e22420284b682864f882b1f": { "model_module": "@jupyter-widgets/controls", "model_name": "DescriptionStyleModel", "model_module_version": "1.5.0", "state": { "_model_module": "@jupyter-widgets/controls", "_model_module_version": "1.5.0", "_model_name": "DescriptionStyleModel", "_view_count": null, "_view_module": "@jupyter-widgets/base", "_view_module_version": "1.2.0", "_view_name": "StyleView", "description_width": "" } }, "b994f42cb0314ea289f0f62ee2b2e79b": { "model_module": "@jupyter-widgets/base", "model_name": "LayoutModel", "model_module_version": "1.2.0", "state": { "_model_module": "@jupyter-widgets/base", "_model_module_version": "1.2.0", "_model_name": "LayoutModel", "_view_count": null, "_view_module": "@jupyter-widgets/base", "_view_module_version": "1.2.0", "_view_name": "LayoutView", "align_content": null, "align_items": null, "align_self": null, "border": null, "bottom": null, "display": null, "flex": null, "flex_flow": null, "grid_area": null, "grid_auto_columns": null, "grid_auto_flow": null, "grid_auto_rows": null, "grid_column": null, "grid_gap": null, "grid_row": null, "grid_template_areas": null, "grid_template_columns": null, "grid_template_rows": null, "height": null, "justify_content": null, "justify_items": null, "left": null, "margin": null, "max_height": null, "max_width": null, "min_height": null, "min_width": null, "object_fit": null, "object_position": null, "order": null, "overflow": null, "overflow_x": null, "overflow_y": null, "padding": null, "right": null, "top": null, "visibility": null, "width": null } }, "cf1f016e6eb44ca299b5a196ca316b0d": { "model_module": "@jupyter-widgets/controls", "model_name": "ProgressStyleModel", "model_module_version": "1.5.0", "state": { "_model_module": "@jupyter-widgets/controls", "_model_module_version": "1.5.0", "_model_name": "ProgressStyleModel", "_view_count": null, "_view_module": "@jupyter-widgets/base", "_view_module_version": "1.2.0", "_view_name": "StyleView", "bar_color": null, "description_width": "" } }, "b4bf53c373794d1a9871fba79f6fdc96": { "model_module": "@jupyter-widgets/base", "model_name": "LayoutModel", "model_module_version": "1.2.0", "state": { "_model_module": "@jupyter-widgets/base", "_model_module_version": "1.2.0", "_model_name": "LayoutModel", "_view_count": null, "_view_module": "@jupyter-widgets/base", "_view_module_version": "1.2.0", "_view_name": "LayoutView", "align_content": null, "align_items": null, "align_self": null, "border": null, "bottom": null, "display": null, "flex": null, "flex_flow": null, "grid_area": null, "grid_auto_columns": null, "grid_auto_flow": null, "grid_auto_rows": null, "grid_column": null, "grid_gap": null, "grid_row": null, "grid_template_areas": null, "grid_template_columns": null, "grid_template_rows": null, "height": null, "justify_content": null, "justify_items": null, "left": null, "margin": null, "max_height": null, "max_width": null, "min_height": null, "min_width": null, "object_fit": null, "object_position": null, "order": null, "overflow": null, "overflow_x": null, "overflow_y": null, "padding": null, "right": null, "top": null, "visibility": null, "width": null } }, "cbc8c57282704e3da44f269b10f12fc1": { "model_module": "@jupyter-widgets/controls", "model_name": "DescriptionStyleModel", "model_module_version": "1.5.0", "state": { "_model_module": "@jupyter-widgets/controls", "_model_module_version": "1.5.0", "_model_name": "DescriptionStyleModel", "_view_count": null, "_view_module": "@jupyter-widgets/base", "_view_module_version": "1.2.0", "_view_name": "StyleView", "description_width": "" } }, "1453c8aa2d384771a978111c02f736c4": { "model_module": "@jupyter-widgets/controls", "model_name": "HBoxModel", "model_module_version": "1.5.0", "state": { "_dom_classes": [], "_model_module": "@jupyter-widgets/controls", "_model_module_version": "1.5.0", "_model_name": "HBoxModel", "_view_count": null, "_view_module": "@jupyter-widgets/controls", "_view_module_version": "1.5.0", "_view_name": "HBoxView", "box_style": "", "children": [ "IPY_MODEL_1d575282112f41d7a1344a834920aae8", "IPY_MODEL_b7a1d489a8024130b329c9051c58561b", "IPY_MODEL_852322f92a1241b1a80afe8acc1df566" ], "layout": "IPY_MODEL_022a9b83f80b481685033a35c34799f1" } }, "1d575282112f41d7a1344a834920aae8": { "model_module": "@jupyter-widgets/controls", "model_name": "HTMLModel", "model_module_version": "1.5.0", "state": { "_dom_classes": [], "_model_module": "@jupyter-widgets/controls", "_model_module_version": "1.5.0", "_model_name": "HTMLModel", "_view_count": null, "_view_module": "@jupyter-widgets/controls", "_view_module_version": "1.5.0", "_view_name": "HTMLView", "description": "", "description_tooltip": null, "layout": "IPY_MODEL_e2cdd60ddaea4d8fb3df1cbf7d254488", "placeholder": "​", "style": "IPY_MODEL_d516376960914adf8e0f990ca0d96373", "value": "model.safetensors: 100%" } }, "b7a1d489a8024130b329c9051c58561b": { "model_module": "@jupyter-widgets/controls", "model_name": "FloatProgressModel", "model_module_version": "1.5.0", "state": { "_dom_classes": [], "_model_module": "@jupyter-widgets/controls", "_model_module_version": "1.5.0", "_model_name": "FloatProgressModel", "_view_count": null, "_view_module": "@jupyter-widgets/controls", "_view_module_version": "1.5.0", "_view_name": "ProgressView", "bar_style": "success", "description": "", "description_tooltip": null, "layout": "IPY_MODEL_2e6cc4bbb2da4e0ab9823fd39a936907", "max": 470641600, "min": 0, "orientation": "horizontal", "style": "IPY_MODEL_93f2f11984c544feb0947b3a17f5d12a", "value": 470641600 } }, "852322f92a1241b1a80afe8acc1df566": { "model_module": "@jupyter-widgets/controls", "model_name": "HTMLModel", "model_module_version": "1.5.0", "state": { "_dom_classes": [], "_model_module": "@jupyter-widgets/controls", "_model_module_version": "1.5.0", "_model_name": "HTMLModel", "_view_count": null, "_view_module": "@jupyter-widgets/controls", "_view_module_version": "1.5.0", "_view_name": "HTMLView", "description": "", "description_tooltip": null, "layout": "IPY_MODEL_94c9894597bd49cdba615870a7bfa6a8", "placeholder": "​", "style": "IPY_MODEL_fb730c40b4454ce6ae6091f7b180dfa5", "value": " 471M/471M [00:01<00:00, 715MB/s]" } }, "022a9b83f80b481685033a35c34799f1": { "model_module": "@jupyter-widgets/base", "model_name": "LayoutModel", "model_module_version": "1.2.0", "state": { "_model_module": "@jupyter-widgets/base", "_model_module_version": "1.2.0", "_model_name": "LayoutModel", "_view_count": null, "_view_module": "@jupyter-widgets/base", "_view_module_version": "1.2.0", "_view_name": "LayoutView", "align_content": null, "align_items": null, "align_self": null, "border": null, "bottom": null, "display": null, "flex": null, "flex_flow": null, "grid_area": null, "grid_auto_columns": null, "grid_auto_flow": null, "grid_auto_rows": null, "grid_column": null, "grid_gap": null, "grid_row": null, "grid_template_areas": null, "grid_template_columns": null, "grid_template_rows": null, "height": null, "justify_content": null, "justify_items": null, "left": null, "margin": null, "max_height": null, "max_width": null, "min_height": null, "min_width": null, "object_fit": null, "object_position": null, "order": null, "overflow": null, "overflow_x": null, "overflow_y": null, "padding": null, "right": null, "top": null, "visibility": null, "width": null } }, "e2cdd60ddaea4d8fb3df1cbf7d254488": { "model_module": "@jupyter-widgets/base", "model_name": "LayoutModel", "model_module_version": "1.2.0", "state": { "_model_module": "@jupyter-widgets/base", "_model_module_version": "1.2.0", "_model_name": "LayoutModel", "_view_count": null, "_view_module": "@jupyter-widgets/base", "_view_module_version": "1.2.0", "_view_name": "LayoutView", "align_content": null, "align_items": null, "align_self": null, "border": null, "bottom": null, "display": null, "flex": null, "flex_flow": null, "grid_area": null, "grid_auto_columns": null, "grid_auto_flow": null, "grid_auto_rows": null, "grid_column": null, "grid_gap": null, "grid_row": null, "grid_template_areas": null, "grid_template_columns": null, "grid_template_rows": null, "height": null, "justify_content": null, "justify_items": null, "left": null, "margin": null, "max_height": null, "max_width": null, "min_height": null, "min_width": null, "object_fit": null, "object_position": null, "order": null, "overflow": null, "overflow_x": null, "overflow_y": null, "padding": null, "right": null, "top": null, "visibility": null, "width": null } }, "d516376960914adf8e0f990ca0d96373": { "model_module": "@jupyter-widgets/controls", "model_name": "DescriptionStyleModel", "model_module_version": "1.5.0", "state": { "_model_module": "@jupyter-widgets/controls", "_model_module_version": "1.5.0", "_model_name": "DescriptionStyleModel", "_view_count": null, "_view_module": "@jupyter-widgets/base", "_view_module_version": "1.2.0", "_view_name": "StyleView", "description_width": "" } }, "2e6cc4bbb2da4e0ab9823fd39a936907": { "model_module": "@jupyter-widgets/base", "model_name": "LayoutModel", "model_module_version": "1.2.0", "state": { "_model_module": "@jupyter-widgets/base", "_model_module_version": "1.2.0", "_model_name": "LayoutModel", "_view_count": null, "_view_module": "@jupyter-widgets/base", "_view_module_version": "1.2.0", "_view_name": "LayoutView", "align_content": null, "align_items": null, "align_self": null, "border": null, "bottom": null, "display": null, "flex": null, "flex_flow": null, "grid_area": null, "grid_auto_columns": null, "grid_auto_flow": null, "grid_auto_rows": null, "grid_column": null, "grid_gap": null, "grid_row": null, "grid_template_areas": null, "grid_template_columns": null, "grid_template_rows": null, "height": null, "justify_content": null, "justify_items": null, "left": null, "margin": null, "max_height": null, "max_width": null, "min_height": null, "min_width": null, "object_fit": null, "object_position": null, "order": null, "overflow": null, "overflow_x": null, "overflow_y": null, "padding": null, "right": null, "top": null, "visibility": null, "width": null } }, "93f2f11984c544feb0947b3a17f5d12a": { "model_module": "@jupyter-widgets/controls", "model_name": "ProgressStyleModel", "model_module_version": "1.5.0", "state": { "_model_module": "@jupyter-widgets/controls", "_model_module_version": "1.5.0", "_model_name": "ProgressStyleModel", "_view_count": null, "_view_module": "@jupyter-widgets/base", "_view_module_version": "1.2.0", "_view_name": "StyleView", "bar_color": null, "description_width": "" } }, "94c9894597bd49cdba615870a7bfa6a8": { "model_module": "@jupyter-widgets/base", "model_name": "LayoutModel", "model_module_version": "1.2.0", "state": { "_model_module": "@jupyter-widgets/base", "_model_module_version": "1.2.0", "_model_name": "LayoutModel", "_view_count": null, "_view_module": "@jupyter-widgets/base", "_view_module_version": "1.2.0", "_view_name": "LayoutView", "align_content": null, "align_items": null, "align_self": null, "border": null, "bottom": null, "display": null, "flex": null, "flex_flow": null, "grid_area": null, "grid_auto_columns": null, "grid_auto_flow": null, "grid_auto_rows": null, "grid_column": null, "grid_gap": null, "grid_row": null, "grid_template_areas": null, "grid_template_columns": null, "grid_template_rows": null, "height": null, "justify_content": null, "justify_items": null, "left": null, "margin": null, "max_height": null, "max_width": null, "min_height": null, "min_width": null, "object_fit": null, "object_position": null, "order": null, "overflow": null, "overflow_x": null, "overflow_y": null, "padding": null, "right": null, "top": null, "visibility": null, "width": null } }, "fb730c40b4454ce6ae6091f7b180dfa5": { "model_module": "@jupyter-widgets/controls", "model_name": "DescriptionStyleModel", "model_module_version": "1.5.0", "state": { "_model_module": "@jupyter-widgets/controls", "_model_module_version": "1.5.0", "_model_name": "DescriptionStyleModel", "_view_count": null, "_view_module": "@jupyter-widgets/base", "_view_module_version": "1.2.0", "_view_name": "StyleView", "description_width": "" } }, "169fb6583d474ad7a4252257fd9fe18c": { "model_module": "@jupyter-widgets/controls", "model_name": "HBoxModel", "model_module_version": "1.5.0", "state": { "_dom_classes": [], "_model_module": "@jupyter-widgets/controls", "_model_module_version": "1.5.0", "_model_name": "HBoxModel", "_view_count": null, "_view_module": "@jupyter-widgets/controls", "_view_module_version": "1.5.0", "_view_name": "HBoxView", "box_style": "", "children": [ "IPY_MODEL_ad52ef92adc448059bffeefac0a87e07", "IPY_MODEL_5a3eb963562c484599004c9964253758", "IPY_MODEL_581367823524457cbcc96597d972fae5" ], "layout": "IPY_MODEL_67387c399fd547cd8329aa1ab1eefd6a" } }, "ad52ef92adc448059bffeefac0a87e07": { "model_module": "@jupyter-widgets/controls", "model_name": "HTMLModel", "model_module_version": "1.5.0", "state": { "_dom_classes": [], "_model_module": "@jupyter-widgets/controls", "_model_module_version": "1.5.0", "_model_name": "HTMLModel", "_view_count": null, "_view_module": "@jupyter-widgets/controls", "_view_module_version": "1.5.0", "_view_name": "HTMLView", "description": "", "description_tooltip": null, "layout": "IPY_MODEL_0f20601bcb2d4504be6d1ada6290dbbf", "placeholder": "​", "style": "IPY_MODEL_1133a53587cf4a378473762fbf5ea6a1", "value": "Loading weights: 100%" } }, "5a3eb963562c484599004c9964253758": { "model_module": "@jupyter-widgets/controls", "model_name": "FloatProgressModel", "model_module_version": "1.5.0", "state": { "_dom_classes": [], "_model_module": "@jupyter-widgets/controls", "_model_module_version": "1.5.0", "_model_name": "FloatProgressModel", "_view_count": null, "_view_module": "@jupyter-widgets/controls", "_view_module_version": "1.5.0", "_view_name": "ProgressView", "bar_style": "success", "description": "", "description_tooltip": null, "layout": "IPY_MODEL_8c378dd3edcc4cdcb802fb06a6f98dd6", "max": 199, "min": 0, "orientation": "horizontal", "style": "IPY_MODEL_05b36af000d44dde8d4b19e50643f7bc", "value": 199 } }, "581367823524457cbcc96597d972fae5": { "model_module": "@jupyter-widgets/controls", "model_name": "HTMLModel", "model_module_version": "1.5.0", "state": { "_dom_classes": [], "_model_module": "@jupyter-widgets/controls", "_model_module_version": "1.5.0", "_model_name": "HTMLModel", "_view_count": null, "_view_module": "@jupyter-widgets/controls", "_view_module_version": "1.5.0", "_view_name": "HTMLView", "description": "", "description_tooltip": null, "layout": "IPY_MODEL_65f0f7e32c4247d184e42781a18c1c4a", "placeholder": "​", "style": "IPY_MODEL_02552998a5454811ad9cf9d05ff0e993", "value": " 199/199 [00:00<00:00, 979.99it/s, Materializing param=pooler.dense.weight]" } }, "67387c399fd547cd8329aa1ab1eefd6a": { "model_module": "@jupyter-widgets/base", "model_name": "LayoutModel", "model_module_version": "1.2.0", "state": { "_model_module": "@jupyter-widgets/base", "_model_module_version": "1.2.0", "_model_name": "LayoutModel", "_view_count": null, "_view_module": "@jupyter-widgets/base", "_view_module_version": "1.2.0", "_view_name": "LayoutView", "align_content": null, "align_items": null, "align_self": null, "border": null, "bottom": null, "display": null, "flex": null, "flex_flow": null, "grid_area": null, "grid_auto_columns": null, "grid_auto_flow": null, "grid_auto_rows": null, "grid_column": null, "grid_gap": null, "grid_row": null, "grid_template_areas": null, "grid_template_columns": null, "grid_template_rows": null, "height": null, "justify_content": null, "justify_items": null, "left": null, "margin": null, "max_height": null, "max_width": null, "min_height": null, "min_width": null, "object_fit": null, "object_position": null, "order": null, "overflow": null, "overflow_x": null, "overflow_y": null, "padding": null, "right": null, "top": null, "visibility": null, "width": null } }, "0f20601bcb2d4504be6d1ada6290dbbf": { "model_module": "@jupyter-widgets/base", "model_name": "LayoutModel", "model_module_version": "1.2.0", "state": { "_model_module": "@jupyter-widgets/base", "_model_module_version": "1.2.0", "_model_name": "LayoutModel", "_view_count": null, "_view_module": "@jupyter-widgets/base", "_view_module_version": "1.2.0", "_view_name": "LayoutView", "align_content": null, "align_items": null, "align_self": null, "border": null, "bottom": null, "display": null, "flex": null, "flex_flow": null, "grid_area": null, "grid_auto_columns": null, "grid_auto_flow": null, "grid_auto_rows": null, "grid_column": null, "grid_gap": null, "grid_row": null, "grid_template_areas": null, "grid_template_columns": null, "grid_template_rows": null, "height": null, "justify_content": null, "justify_items": null, "left": null, "margin": null, "max_height": null, "max_width": null, "min_height": null, "min_width": null, "object_fit": null, "object_position": null, "order": null, "overflow": null, "overflow_x": null, "overflow_y": null, "padding": null, "right": null, "top": null, "visibility": null, "width": null } }, "1133a53587cf4a378473762fbf5ea6a1": { "model_module": "@jupyter-widgets/controls", "model_name": "DescriptionStyleModel", "model_module_version": "1.5.0", "state": { "_model_module": "@jupyter-widgets/controls", "_model_module_version": "1.5.0", "_model_name": "DescriptionStyleModel", "_view_count": null, "_view_module": "@jupyter-widgets/base", "_view_module_version": "1.2.0", "_view_name": "StyleView", "description_width": "" } }, "8c378dd3edcc4cdcb802fb06a6f98dd6": { "model_module": "@jupyter-widgets/base", "model_name": "LayoutModel", "model_module_version": "1.2.0", "state": { "_model_module": "@jupyter-widgets/base", "_model_module_version": "1.2.0", "_model_name": "LayoutModel", "_view_count": null, "_view_module": "@jupyter-widgets/base", "_view_module_version": "1.2.0", "_view_name": "LayoutView", "align_content": null, "align_items": null, "align_self": null, "border": null, "bottom": null, "display": null, "flex": null, "flex_flow": null, "grid_area": null, "grid_auto_columns": null, "grid_auto_flow": null, "grid_auto_rows": null, "grid_column": null, "grid_gap": null, "grid_row": null, "grid_template_areas": null, "grid_template_columns": null, "grid_template_rows": null, "height": null, "justify_content": null, "justify_items": null, "left": null, "margin": null, "max_height": null, "max_width": null, "min_height": null, "min_width": null, "object_fit": null, "object_position": null, "order": null, "overflow": null, "overflow_x": null, "overflow_y": null, "padding": null, "right": null, "top": null, "visibility": null, "width": null } }, "05b36af000d44dde8d4b19e50643f7bc": { "model_module": "@jupyter-widgets/controls", "model_name": "ProgressStyleModel", "model_module_version": "1.5.0", "state": { "_model_module": "@jupyter-widgets/controls", "_model_module_version": "1.5.0", "_model_name": "ProgressStyleModel", "_view_count": null, "_view_module": "@jupyter-widgets/base", "_view_module_version": "1.2.0", "_view_name": "StyleView", "bar_color": null, "description_width": "" } }, "65f0f7e32c4247d184e42781a18c1c4a": { "model_module": "@jupyter-widgets/base", "model_name": "LayoutModel", "model_module_version": "1.2.0", "state": { "_model_module": "@jupyter-widgets/base", "_model_module_version": "1.2.0", "_model_name": "LayoutModel", "_view_count": null, "_view_module": "@jupyter-widgets/base", "_view_module_version": "1.2.0", "_view_name": "LayoutView", "align_content": null, "align_items": null, "align_self": null, "border": null, "bottom": null, "display": null, "flex": null, "flex_flow": null, "grid_area": null, "grid_auto_columns": null, "grid_auto_flow": null, "grid_auto_rows": null, "grid_column": null, "grid_gap": null, "grid_row": null, "grid_template_areas": null, "grid_template_columns": null, "grid_template_rows": null, "height": null, "justify_content": null, "justify_items": null, "left": null, "margin": null, "max_height": null, "max_width": null, "min_height": null, "min_width": null, "object_fit": null, "object_position": null, "order": null, "overflow": null, "overflow_x": null, "overflow_y": null, "padding": null, "right": null, "top": null, "visibility": null, "width": null } }, "02552998a5454811ad9cf9d05ff0e993": { "model_module": "@jupyter-widgets/controls", "model_name": "DescriptionStyleModel", "model_module_version": "1.5.0", "state": { "_model_module": "@jupyter-widgets/controls", "_model_module_version": "1.5.0", "_model_name": "DescriptionStyleModel", "_view_count": null, "_view_module": "@jupyter-widgets/base", "_view_module_version": "1.2.0", "_view_name": "StyleView", "description_width": "" } }, "66649cde5de74be082a8ffc3f3c6ea49": { "model_module": "@jupyter-widgets/controls", "model_name": "HBoxModel", "model_module_version": "1.5.0", "state": { "_dom_classes": [], "_model_module": "@jupyter-widgets/controls", "_model_module_version": "1.5.0", "_model_name": "HBoxModel", "_view_count": null, "_view_module": "@jupyter-widgets/controls", "_view_module_version": "1.5.0", "_view_name": "HBoxView", "box_style": "", "children": [ "IPY_MODEL_46a5865a2bd840f8b7d89e6d2d7c8ae4", "IPY_MODEL_0641048995aa4f4b828a2a01633dad6e", "IPY_MODEL_275ecf2a6f254f99a75821b7665f0614" ], "layout": "IPY_MODEL_b89aa36eec53441ea56f7e9b1c4363b4" } }, "46a5865a2bd840f8b7d89e6d2d7c8ae4": { "model_module": "@jupyter-widgets/controls", "model_name": "HTMLModel", "model_module_version": "1.5.0", "state": { "_dom_classes": [], "_model_module": "@jupyter-widgets/controls", "_model_module_version": "1.5.0", "_model_name": "HTMLModel", "_view_count": null, "_view_module": "@jupyter-widgets/controls", "_view_module_version": "1.5.0", "_view_name": "HTMLView", "description": "", "description_tooltip": null, "layout": "IPY_MODEL_301126f6a39c4f06b7239c05b1682406", "placeholder": "​", "style": "IPY_MODEL_fad9f0bb863a40059b899b570207a060", "value": "tokenizer_config.json: 100%" } }, "0641048995aa4f4b828a2a01633dad6e": { "model_module": "@jupyter-widgets/controls", "model_name": "FloatProgressModel", "model_module_version": "1.5.0", "state": { "_dom_classes": [], "_model_module": "@jupyter-widgets/controls", "_model_module_version": "1.5.0", "_model_name": "FloatProgressModel", "_view_count": null, "_view_module": "@jupyter-widgets/controls", "_view_module_version": "1.5.0", "_view_name": "ProgressView", "bar_style": "success", "description": "", "description_tooltip": null, "layout": "IPY_MODEL_705a5b84a03e4cac85d9be4f99aa2d32", "max": 526, "min": 0, "orientation": "horizontal", "style": "IPY_MODEL_69082a02d35343a48c150a969fe92fd0", "value": 526 } }, "275ecf2a6f254f99a75821b7665f0614": { "model_module": "@jupyter-widgets/controls", "model_name": "HTMLModel", "model_module_version": "1.5.0", "state": { "_dom_classes": [], "_model_module": "@jupyter-widgets/controls", "_model_module_version": "1.5.0", "_model_name": "HTMLModel", "_view_count": null, "_view_module": "@jupyter-widgets/controls", "_view_module_version": "1.5.0", "_view_name": "HTMLView", "description": "", "description_tooltip": null, "layout": "IPY_MODEL_6fe93398d47c40da8055da147a4afbd3", "placeholder": "​", "style": "IPY_MODEL_717f889a149c4d69983ced8ad81a3ae6", "value": " 526/526 [00:00<00:00, 53.3kB/s]" } }, "b89aa36eec53441ea56f7e9b1c4363b4": { "model_module": "@jupyter-widgets/base", "model_name": "LayoutModel", "model_module_version": "1.2.0", "state": { "_model_module": "@jupyter-widgets/base", "_model_module_version": "1.2.0", "_model_name": "LayoutModel", "_view_count": null, "_view_module": "@jupyter-widgets/base", "_view_module_version": "1.2.0", "_view_name": "LayoutView", "align_content": null, "align_items": null, "align_self": null, "border": null, "bottom": null, "display": null, "flex": null, "flex_flow": null, "grid_area": null, "grid_auto_columns": null, "grid_auto_flow": null, "grid_auto_rows": null, "grid_column": null, "grid_gap": null, "grid_row": null, "grid_template_areas": null, "grid_template_columns": null, "grid_template_rows": null, "height": null, "justify_content": null, "justify_items": null, "left": null, "margin": null, "max_height": null, "max_width": null, "min_height": null, "min_width": null, "object_fit": null, "object_position": null, "order": null, "overflow": null, "overflow_x": null, "overflow_y": null, "padding": null, "right": null, "top": null, "visibility": null, "width": null } }, "301126f6a39c4f06b7239c05b1682406": { "model_module": "@jupyter-widgets/base", "model_name": "LayoutModel", "model_module_version": "1.2.0", "state": { "_model_module": "@jupyter-widgets/base", "_model_module_version": "1.2.0", "_model_name": "LayoutModel", "_view_count": null, "_view_module": "@jupyter-widgets/base", "_view_module_version": "1.2.0", "_view_name": "LayoutView", "align_content": null, "align_items": null, "align_self": null, "border": null, "bottom": null, "display": null, "flex": null, "flex_flow": null, "grid_area": null, "grid_auto_columns": null, "grid_auto_flow": null, "grid_auto_rows": null, "grid_column": null, "grid_gap": null, "grid_row": null, "grid_template_areas": null, "grid_template_columns": null, "grid_template_rows": null, "height": null, "justify_content": null, "justify_items": null, "left": null, "margin": null, "max_height": null, "max_width": null, "min_height": null, "min_width": null, "object_fit": null, "object_position": null, "order": null, "overflow": null, "overflow_x": null, "overflow_y": null, "padding": null, "right": null, "top": null, "visibility": null, "width": null } }, "fad9f0bb863a40059b899b570207a060": { "model_module": "@jupyter-widgets/controls", "model_name": "DescriptionStyleModel", "model_module_version": "1.5.0", "state": { "_model_module": "@jupyter-widgets/controls", "_model_module_version": "1.5.0", "_model_name": "DescriptionStyleModel", "_view_count": null, "_view_module": "@jupyter-widgets/base", "_view_module_version": "1.2.0", "_view_name": "StyleView", "description_width": "" } }, "705a5b84a03e4cac85d9be4f99aa2d32": { "model_module": "@jupyter-widgets/base", "model_name": "LayoutModel", "model_module_version": "1.2.0", "state": { "_model_module": "@jupyter-widgets/base", "_model_module_version": "1.2.0", "_model_name": "LayoutModel", "_view_count": null, "_view_module": "@jupyter-widgets/base", "_view_module_version": "1.2.0", "_view_name": "LayoutView", "align_content": null, "align_items": null, "align_self": null, "border": null, "bottom": null, "display": null, "flex": null, "flex_flow": null, "grid_area": null, "grid_auto_columns": null, "grid_auto_flow": null, "grid_auto_rows": null, "grid_column": null, "grid_gap": null, "grid_row": null, "grid_template_areas": null, "grid_template_columns": null, "grid_template_rows": null, "height": null, "justify_content": null, "justify_items": null, "left": null, "margin": null, "max_height": null, "max_width": null, "min_height": null, "min_width": null, "object_fit": null, "object_position": null, "order": null, "overflow": null, "overflow_x": null, "overflow_y": null, "padding": null, "right": null, "top": null, "visibility": null, "width": null } }, "69082a02d35343a48c150a969fe92fd0": { "model_module": "@jupyter-widgets/controls", "model_name": "ProgressStyleModel", "model_module_version": "1.5.0", "state": { "_model_module": "@jupyter-widgets/controls", "_model_module_version": "1.5.0", "_model_name": "ProgressStyleModel", "_view_count": null, "_view_module": "@jupyter-widgets/base", "_view_module_version": "1.2.0", "_view_name": "StyleView", "bar_color": null, "description_width": "" } }, "6fe93398d47c40da8055da147a4afbd3": { "model_module": "@jupyter-widgets/base", "model_name": "LayoutModel", "model_module_version": "1.2.0", "state": { "_model_module": "@jupyter-widgets/base", "_model_module_version": "1.2.0", "_model_name": "LayoutModel", "_view_count": null, "_view_module": "@jupyter-widgets/base", "_view_module_version": "1.2.0", "_view_name": "LayoutView", "align_content": null, "align_items": null, "align_self": null, "border": null, "bottom": null, "display": null, "flex": null, "flex_flow": null, "grid_area": null, "grid_auto_columns": null, "grid_auto_flow": null, "grid_auto_rows": null, "grid_column": null, "grid_gap": null, "grid_row": null, "grid_template_areas": null, "grid_template_columns": null, "grid_template_rows": null, "height": null, "justify_content": null, "justify_items": null, "left": null, "margin": null, "max_height": null, "max_width": null, "min_height": null, "min_width": null, "object_fit": null, "object_position": null, "order": null, "overflow": null, "overflow_x": null, "overflow_y": null, "padding": null, "right": null, "top": null, "visibility": null, "width": null } }, "717f889a149c4d69983ced8ad81a3ae6": { "model_module": "@jupyter-widgets/controls", "model_name": "DescriptionStyleModel", "model_module_version": "1.5.0", "state": { "_model_module": "@jupyter-widgets/controls", "_model_module_version": "1.5.0", "_model_name": "DescriptionStyleModel", "_view_count": null, "_view_module": "@jupyter-widgets/base", "_view_module_version": "1.2.0", "_view_name": "StyleView", "description_width": "" } }, "1834743b8c0a49da80be8fa5a927e7fb": { "model_module": "@jupyter-widgets/controls", "model_name": "HBoxModel", "model_module_version": "1.5.0", "state": { "_dom_classes": [], "_model_module": "@jupyter-widgets/controls", "_model_module_version": "1.5.0", "_model_name": "HBoxModel", "_view_count": null, "_view_module": "@jupyter-widgets/controls", "_view_module_version": "1.5.0", "_view_name": "HBoxView", "box_style": "", "children": [ "IPY_MODEL_d73ee3e2876e468399e21a2186885d81", "IPY_MODEL_7a6b2e3c45c14282a20dae0fa921177a", "IPY_MODEL_6a93b5beccad4fdea1052b9a63dfe67a" ], "layout": "IPY_MODEL_ffcafdc0eec2428dab5d398438b57663" } }, "d73ee3e2876e468399e21a2186885d81": { "model_module": "@jupyter-widgets/controls", "model_name": "HTMLModel", "model_module_version": "1.5.0", "state": { "_dom_classes": [], "_model_module": "@jupyter-widgets/controls", "_model_module_version": "1.5.0", "_model_name": "HTMLModel", "_view_count": null, "_view_module": "@jupyter-widgets/controls", "_view_module_version": "1.5.0", "_view_name": "HTMLView", "description": "", "description_tooltip": null, "layout": "IPY_MODEL_39d2fd7c7cc74498b8803634c4a82e4c", "placeholder": "​", "style": "IPY_MODEL_98614e86922b4421bcddba60a008e0a4", "value": "tokenizer.json: 100%" } }, "7a6b2e3c45c14282a20dae0fa921177a": { "model_module": "@jupyter-widgets/controls", "model_name": "FloatProgressModel", "model_module_version": "1.5.0", "state": { "_dom_classes": [], "_model_module": "@jupyter-widgets/controls", "_model_module_version": "1.5.0", "_model_name": "FloatProgressModel", "_view_count": null, "_view_module": "@jupyter-widgets/controls", "_view_module_version": "1.5.0", "_view_name": "ProgressView", "bar_style": "success", "description": "", "description_tooltip": null, "layout": "IPY_MODEL_08749a0b05da4f798fac504cfcc17538", "max": 9081518, "min": 0, "orientation": "horizontal", "style": "IPY_MODEL_67fdc937b50f4cef81368fc7077eba5a", "value": 9081518 } }, "6a93b5beccad4fdea1052b9a63dfe67a": { "model_module": "@jupyter-widgets/controls", "model_name": "HTMLModel", "model_module_version": "1.5.0", "state": { "_dom_classes": [], "_model_module": "@jupyter-widgets/controls", "_model_module_version": "1.5.0", "_model_name": "HTMLModel", "_view_count": null, "_view_module": "@jupyter-widgets/controls", "_view_module_version": "1.5.0", "_view_name": "HTMLView", "description": "", "description_tooltip": null, "layout": "IPY_MODEL_2ea3e03acce84bfc8f70ac9039f8b3ce", "placeholder": "​", "style": "IPY_MODEL_b04e2ba272bf45bb96500df947b1e8f3", "value": " 9.08M/9.08M [00:00<00:00, 41.3MB/s]" } }, "ffcafdc0eec2428dab5d398438b57663": { "model_module": "@jupyter-widgets/base", "model_name": "LayoutModel", "model_module_version": "1.2.0", "state": { "_model_module": "@jupyter-widgets/base", "_model_module_version": "1.2.0", "_model_name": "LayoutModel", "_view_count": null, "_view_module": "@jupyter-widgets/base", "_view_module_version": "1.2.0", "_view_name": "LayoutView", "align_content": null, "align_items": null, "align_self": null, "border": null, "bottom": null, "display": null, "flex": null, "flex_flow": null, "grid_area": null, "grid_auto_columns": null, "grid_auto_flow": null, "grid_auto_rows": null, "grid_column": null, "grid_gap": null, "grid_row": null, "grid_template_areas": null, "grid_template_columns": null, "grid_template_rows": null, "height": null, "justify_content": null, "justify_items": null, "left": null, "margin": null, "max_height": null, "max_width": null, "min_height": null, "min_width": null, "object_fit": null, "object_position": null, "order": null, "overflow": null, "overflow_x": null, "overflow_y": null, "padding": null, "right": null, "top": null, "visibility": null, "width": null } }, "39d2fd7c7cc74498b8803634c4a82e4c": { "model_module": "@jupyter-widgets/base", "model_name": "LayoutModel", "model_module_version": "1.2.0", "state": { "_model_module": "@jupyter-widgets/base", "_model_module_version": "1.2.0", "_model_name": "LayoutModel", "_view_count": null, "_view_module": "@jupyter-widgets/base", "_view_module_version": "1.2.0", "_view_name": "LayoutView", "align_content": null, "align_items": null, "align_self": null, "border": null, "bottom": null, "display": null, "flex": null, "flex_flow": null, "grid_area": null, "grid_auto_columns": null, "grid_auto_flow": null, "grid_auto_rows": null, "grid_column": null, "grid_gap": null, "grid_row": null, "grid_template_areas": null, "grid_template_columns": null, "grid_template_rows": null, "height": null, "justify_content": null, "justify_items": null, "left": null, "margin": null, "max_height": null, "max_width": null, "min_height": null, "min_width": null, "object_fit": null, "object_position": null, "order": null, "overflow": null, "overflow_x": null, "overflow_y": null, "padding": null, "right": null, "top": null, "visibility": null, "width": null } }, "98614e86922b4421bcddba60a008e0a4": { "model_module": "@jupyter-widgets/controls", "model_name": "DescriptionStyleModel", "model_module_version": "1.5.0", "state": { "_model_module": "@jupyter-widgets/controls", "_model_module_version": "1.5.0", "_model_name": "DescriptionStyleModel", "_view_count": null, "_view_module": "@jupyter-widgets/base", "_view_module_version": "1.2.0", "_view_name": "StyleView", "description_width": "" } }, "08749a0b05da4f798fac504cfcc17538": { "model_module": "@jupyter-widgets/base", "model_name": "LayoutModel", "model_module_version": "1.2.0", "state": { "_model_module": "@jupyter-widgets/base", "_model_module_version": "1.2.0", "_model_name": "LayoutModel", "_view_count": null, "_view_module": "@jupyter-widgets/base", "_view_module_version": "1.2.0", "_view_name": "LayoutView", "align_content": null, "align_items": null, "align_self": null, "border": null, "bottom": null, "display": null, "flex": null, "flex_flow": null, "grid_area": null, "grid_auto_columns": null, "grid_auto_flow": null, "grid_auto_rows": null, "grid_column": null, "grid_gap": null, "grid_row": null, "grid_template_areas": null, "grid_template_columns": null, "grid_template_rows": null, "height": null, "justify_content": null, "justify_items": null, "left": null, "margin": null, "max_height": null, "max_width": null, "min_height": null, "min_width": null, "object_fit": null, "object_position": null, "order": null, "overflow": null, "overflow_x": null, "overflow_y": null, "padding": null, "right": null, "top": null, "visibility": null, "width": null } }, "67fdc937b50f4cef81368fc7077eba5a": { "model_module": "@jupyter-widgets/controls", "model_name": "ProgressStyleModel", "model_module_version": "1.5.0", "state": { "_model_module": "@jupyter-widgets/controls", "_model_module_version": "1.5.0", "_model_name": "ProgressStyleModel", "_view_count": null, "_view_module": "@jupyter-widgets/base", "_view_module_version": "1.2.0", "_view_name": "StyleView", "bar_color": null, "description_width": "" } }, "2ea3e03acce84bfc8f70ac9039f8b3ce": { "model_module": "@jupyter-widgets/base", "model_name": "LayoutModel", "model_module_version": "1.2.0", "state": { "_model_module": "@jupyter-widgets/base", "_model_module_version": "1.2.0", "_model_name": "LayoutModel", "_view_count": null, "_view_module": "@jupyter-widgets/base", "_view_module_version": "1.2.0", "_view_name": "LayoutView", "align_content": null, "align_items": null, "align_self": null, "border": null, "bottom": null, "display": null, "flex": null, "flex_flow": null, "grid_area": null, "grid_auto_columns": null, "grid_auto_flow": null, "grid_auto_rows": null, "grid_column": null, "grid_gap": null, "grid_row": null, "grid_template_areas": null, "grid_template_columns": null, "grid_template_rows": null, "height": null, "justify_content": null, "justify_items": null, "left": null, "margin": null, "max_height": null, "max_width": null, "min_height": null, "min_width": null, "object_fit": null, "object_position": null, "order": null, "overflow": null, "overflow_x": null, "overflow_y": null, "padding": null, "right": null, "top": null, "visibility": null, "width": null } }, "b04e2ba272bf45bb96500df947b1e8f3": { "model_module": "@jupyter-widgets/controls", "model_name": "DescriptionStyleModel", "model_module_version": "1.5.0", "state": { "_model_module": "@jupyter-widgets/controls", "_model_module_version": "1.5.0", "_model_name": "DescriptionStyleModel", "_view_count": null, "_view_module": "@jupyter-widgets/base", "_view_module_version": "1.2.0", "_view_name": "StyleView", "description_width": "" } }, "d8fd227f6caf4e078a39a76446d15d5e": { "model_module": "@jupyter-widgets/controls", "model_name": "HBoxModel", "model_module_version": "1.5.0", "state": { "_dom_classes": [], "_model_module": "@jupyter-widgets/controls", "_model_module_version": "1.5.0", "_model_name": "HBoxModel", "_view_count": null, "_view_module": "@jupyter-widgets/controls", "_view_module_version": "1.5.0", "_view_name": "HBoxView", "box_style": "", "children": [ "IPY_MODEL_924220abbab84ece913e9a2abcee4f99", "IPY_MODEL_8a00c517335b45efa9551fcc66b20fe7", "IPY_MODEL_55e00b8255034a038494937c46eb493b" ], "layout": "IPY_MODEL_c971923b953f45ae8612e20fe8fd38c7" } }, "924220abbab84ece913e9a2abcee4f99": { "model_module": "@jupyter-widgets/controls", "model_name": "HTMLModel", "model_module_version": "1.5.0", "state": { "_dom_classes": [], "_model_module": "@jupyter-widgets/controls", "_model_module_version": "1.5.0", "_model_name": "HTMLModel", "_view_count": null, "_view_module": "@jupyter-widgets/controls", "_view_module_version": "1.5.0", "_view_name": "HTMLView", "description": "", "description_tooltip": null, "layout": "IPY_MODEL_2326d31eb2664798b01549a943bc74f4", "placeholder": "​", "style": "IPY_MODEL_98ff725d4ac94667a9184e793524801d", "value": "special_tokens_map.json: 100%" } }, "8a00c517335b45efa9551fcc66b20fe7": { "model_module": "@jupyter-widgets/controls", "model_name": "FloatProgressModel", "model_module_version": "1.5.0", "state": { "_dom_classes": [], "_model_module": "@jupyter-widgets/controls", "_model_module_version": "1.5.0", "_model_name": "FloatProgressModel", "_view_count": null, "_view_module": "@jupyter-widgets/controls", "_view_module_version": "1.5.0", "_view_name": "ProgressView", "bar_style": "success", "description": "", "description_tooltip": null, "layout": "IPY_MODEL_75410c4faefa437695d04feda32d6757", "max": 239, "min": 0, "orientation": "horizontal", "style": "IPY_MODEL_ca6136c4fb7b4dfda7c00e943367ecd6", "value": 239 } }, "55e00b8255034a038494937c46eb493b": { "model_module": "@jupyter-widgets/controls", "model_name": "HTMLModel", "model_module_version": "1.5.0", "state": { "_dom_classes": [], "_model_module": "@jupyter-widgets/controls", "_model_module_version": "1.5.0", "_model_name": "HTMLModel", "_view_count": null, "_view_module": "@jupyter-widgets/controls", "_view_module_version": "1.5.0", "_view_name": "HTMLView", "description": "", "description_tooltip": null, "layout": "IPY_MODEL_4917f8bd1249462a8b2555b2979a48b4", "placeholder": "​", "style": "IPY_MODEL_7ac2764930be4f0782c23a857df11299", "value": " 239/239 [00:00<00:00, 29.5kB/s]" } }, "c971923b953f45ae8612e20fe8fd38c7": { "model_module": "@jupyter-widgets/base", "model_name": "LayoutModel", "model_module_version": "1.2.0", "state": { "_model_module": "@jupyter-widgets/base", "_model_module_version": "1.2.0", "_model_name": "LayoutModel", "_view_count": null, "_view_module": "@jupyter-widgets/base", "_view_module_version": "1.2.0", "_view_name": "LayoutView", "align_content": null, "align_items": null, "align_self": null, "border": null, "bottom": null, "display": null, "flex": null, "flex_flow": null, "grid_area": null, "grid_auto_columns": null, "grid_auto_flow": null, "grid_auto_rows": null, "grid_column": null, "grid_gap": null, "grid_row": null, "grid_template_areas": null, "grid_template_columns": null, "grid_template_rows": null, "height": null, "justify_content": null, "justify_items": null, "left": null, "margin": null, "max_height": null, "max_width": null, "min_height": null, "min_width": null, "object_fit": null, "object_position": null, "order": null, "overflow": null, "overflow_x": null, "overflow_y": null, "padding": null, "right": null, "top": null, "visibility": null, "width": null } }, "2326d31eb2664798b01549a943bc74f4": { "model_module": "@jupyter-widgets/base", "model_name": "LayoutModel", "model_module_version": "1.2.0", "state": { "_model_module": "@jupyter-widgets/base", "_model_module_version": "1.2.0", "_model_name": "LayoutModel", "_view_count": null, "_view_module": "@jupyter-widgets/base", "_view_module_version": "1.2.0", "_view_name": "LayoutView", "align_content": null, "align_items": null, "align_self": null, "border": null, "bottom": null, "display": null, "flex": null, "flex_flow": null, "grid_area": null, "grid_auto_columns": null, "grid_auto_flow": null, "grid_auto_rows": null, "grid_column": null, "grid_gap": null, "grid_row": null, "grid_template_areas": null, "grid_template_columns": null, "grid_template_rows": null, "height": null, "justify_content": null, "justify_items": null, "left": null, "margin": null, "max_height": null, "max_width": null, "min_height": null, "min_width": null, "object_fit": null, "object_position": null, "order": null, "overflow": null, "overflow_x": null, "overflow_y": null, "padding": null, "right": null, "top": null, "visibility": null, "width": null } }, "98ff725d4ac94667a9184e793524801d": { "model_module": "@jupyter-widgets/controls", "model_name": "DescriptionStyleModel", "model_module_version": "1.5.0", "state": { "_model_module": "@jupyter-widgets/controls", "_model_module_version": "1.5.0", "_model_name": "DescriptionStyleModel", "_view_count": null, "_view_module": "@jupyter-widgets/base", "_view_module_version": "1.2.0", "_view_name": "StyleView", "description_width": "" } }, "75410c4faefa437695d04feda32d6757": { "model_module": "@jupyter-widgets/base", "model_name": "LayoutModel", "model_module_version": "1.2.0", "state": { "_model_module": "@jupyter-widgets/base", "_model_module_version": "1.2.0", "_model_name": "LayoutModel", "_view_count": null, "_view_module": "@jupyter-widgets/base", "_view_module_version": "1.2.0", "_view_name": "LayoutView", "align_content": null, "align_items": null, "align_self": null, "border": null, "bottom": null, "display": null, "flex": null, "flex_flow": null, "grid_area": null, "grid_auto_columns": null, "grid_auto_flow": null, "grid_auto_rows": null, "grid_column": null, "grid_gap": null, "grid_row": null, "grid_template_areas": null, "grid_template_columns": null, "grid_template_rows": null, "height": null, "justify_content": null, "justify_items": null, "left": null, "margin": null, "max_height": null, "max_width": null, "min_height": null, "min_width": null, "object_fit": null, "object_position": null, "order": null, "overflow": null, "overflow_x": null, "overflow_y": null, "padding": null, "right": null, "top": null, "visibility": null, "width": null } }, "ca6136c4fb7b4dfda7c00e943367ecd6": { "model_module": "@jupyter-widgets/controls", "model_name": "ProgressStyleModel", "model_module_version": "1.5.0", "state": { "_model_module": "@jupyter-widgets/controls", "_model_module_version": "1.5.0", "_model_name": "ProgressStyleModel", "_view_count": null, "_view_module": "@jupyter-widgets/base", "_view_module_version": "1.2.0", "_view_name": "StyleView", "bar_color": null, "description_width": "" } }, "4917f8bd1249462a8b2555b2979a48b4": { "model_module": "@jupyter-widgets/base", "model_name": "LayoutModel", "model_module_version": "1.2.0", "state": { "_model_module": "@jupyter-widgets/base", "_model_module_version": "1.2.0", "_model_name": "LayoutModel", "_view_count": null, "_view_module": "@jupyter-widgets/base", "_view_module_version": "1.2.0", "_view_name": "LayoutView", "align_content": null, "align_items": null, "align_self": null, "border": null, "bottom": null, "display": null, "flex": null, "flex_flow": null, "grid_area": null, "grid_auto_columns": null, "grid_auto_flow": null, "grid_auto_rows": null, "grid_column": null, "grid_gap": null, "grid_row": null, "grid_template_areas": null, "grid_template_columns": null, "grid_template_rows": null, "height": null, "justify_content": null, "justify_items": null, "left": null, "margin": null, "max_height": null, "max_width": null, "min_height": null, "min_width": null, "object_fit": null, "object_position": null, "order": null, "overflow": null, "overflow_x": null, "overflow_y": null, "padding": null, "right": null, "top": null, "visibility": null, "width": null } }, "7ac2764930be4f0782c23a857df11299": { "model_module": "@jupyter-widgets/controls", "model_name": "DescriptionStyleModel", "model_module_version": "1.5.0", "state": { "_model_module": "@jupyter-widgets/controls", "_model_module_version": "1.5.0", "_model_name": "DescriptionStyleModel", "_view_count": null, "_view_module": "@jupyter-widgets/base", "_view_module_version": "1.2.0", "_view_name": "StyleView", "description_width": "" } }, "26f459270301431e89ef9869bc0d2231": { "model_module": "@jupyter-widgets/controls", "model_name": "HBoxModel", "model_module_version": "1.5.0", "state": { "_dom_classes": [], "_model_module": "@jupyter-widgets/controls", "_model_module_version": "1.5.0", "_model_name": "HBoxModel", "_view_count": null, "_view_module": "@jupyter-widgets/controls", "_view_module_version": "1.5.0", "_view_name": "HBoxView", "box_style": "", "children": [ "IPY_MODEL_a77a0395cd82455289ddf21c7be4235a", "IPY_MODEL_e4a94d14ad9a481d8b44200dd068572d", "IPY_MODEL_bbfa28706ee84bf098a27d9f4285e897" ], "layout": "IPY_MODEL_22c387e0c9ce4a0d9e4704f3996b1ab3" } }, "a77a0395cd82455289ddf21c7be4235a": { "model_module": "@jupyter-widgets/controls", "model_name": "HTMLModel", "model_module_version": "1.5.0", "state": { "_dom_classes": [], "_model_module": "@jupyter-widgets/controls", "_model_module_version": "1.5.0", "_model_name": "HTMLModel", "_view_count": null, "_view_module": "@jupyter-widgets/controls", "_view_module_version": "1.5.0", "_view_name": "HTMLView", "description": "", "description_tooltip": null, "layout": "IPY_MODEL_9635e80426c04f9a85759e2c9f21a987", "placeholder": "​", "style": "IPY_MODEL_6c4bd816c7a9408caa8d316a81adffd0", "value": "config.json: 100%" } }, "e4a94d14ad9a481d8b44200dd068572d": { "model_module": "@jupyter-widgets/controls", "model_name": "FloatProgressModel", "model_module_version": "1.5.0", "state": { "_dom_classes": [], "_model_module": "@jupyter-widgets/controls", "_model_module_version": "1.5.0", "_model_name": "FloatProgressModel", "_view_count": null, "_view_module": "@jupyter-widgets/controls", "_view_module_version": "1.5.0", "_view_name": "ProgressView", "bar_style": "success", "description": "", "description_tooltip": null, "layout": "IPY_MODEL_b56ea06fbf0147de9ffa71d6c7c15a78", "max": 190, "min": 0, "orientation": "horizontal", "style": "IPY_MODEL_ebff00f53e6843d08fafe630939a8e71", "value": 190 } }, "bbfa28706ee84bf098a27d9f4285e897": { "model_module": "@jupyter-widgets/controls", "model_name": "HTMLModel", "model_module_version": "1.5.0", "state": { "_dom_classes": [], "_model_module": "@jupyter-widgets/controls", "_model_module_version": "1.5.0", "_model_name": "HTMLModel", "_view_count": null, "_view_module": "@jupyter-widgets/controls", "_view_module_version": "1.5.0", "_view_name": "HTMLView", "description": "", "description_tooltip": null, "layout": "IPY_MODEL_7971cd54c01d461b8f10719b2c2dd87b", "placeholder": "​", "style": "IPY_MODEL_13b30b8ea75f45a1be65bdb9b49ab52d", "value": " 190/190 [00:00<00:00, 24.8kB/s]" } }, "22c387e0c9ce4a0d9e4704f3996b1ab3": { "model_module": "@jupyter-widgets/base", "model_name": "LayoutModel", "model_module_version": "1.2.0", "state": { "_model_module": "@jupyter-widgets/base", "_model_module_version": "1.2.0", "_model_name": "LayoutModel", "_view_count": null, "_view_module": "@jupyter-widgets/base", "_view_module_version": "1.2.0", "_view_name": "LayoutView", "align_content": null, "align_items": null, "align_self": null, "border": null, "bottom": null, "display": null, "flex": null, "flex_flow": null, "grid_area": null, "grid_auto_columns": null, "grid_auto_flow": null, "grid_auto_rows": null, "grid_column": null, "grid_gap": null, "grid_row": null, "grid_template_areas": null, "grid_template_columns": null, "grid_template_rows": null, "height": null, "justify_content": null, "justify_items": null, "left": null, "margin": null, "max_height": null, "max_width": null, "min_height": null, "min_width": null, "object_fit": null, "object_position": null, "order": null, "overflow": null, "overflow_x": null, "overflow_y": null, "padding": null, "right": null, "top": null, "visibility": null, "width": null } }, "9635e80426c04f9a85759e2c9f21a987": { "model_module": "@jupyter-widgets/base", "model_name": "LayoutModel", "model_module_version": "1.2.0", "state": { "_model_module": "@jupyter-widgets/base", "_model_module_version": "1.2.0", "_model_name": "LayoutModel", "_view_count": null, "_view_module": "@jupyter-widgets/base", "_view_module_version": "1.2.0", "_view_name": "LayoutView", "align_content": null, "align_items": null, "align_self": null, "border": null, "bottom": null, "display": null, "flex": null, "flex_flow": null, "grid_area": null, "grid_auto_columns": null, "grid_auto_flow": null, "grid_auto_rows": null, "grid_column": null, "grid_gap": null, "grid_row": null, "grid_template_areas": null, "grid_template_columns": null, "grid_template_rows": null, "height": null, "justify_content": null, "justify_items": null, "left": null, "margin": null, "max_height": null, "max_width": null, "min_height": null, "min_width": null, "object_fit": null, "object_position": null, "order": null, "overflow": null, "overflow_x": null, "overflow_y": null, "padding": null, "right": null, "top": null, "visibility": null, "width": null } }, "6c4bd816c7a9408caa8d316a81adffd0": { "model_module": "@jupyter-widgets/controls", "model_name": "DescriptionStyleModel", "model_module_version": "1.5.0", "state": { "_model_module": "@jupyter-widgets/controls", "_model_module_version": "1.5.0", "_model_name": "DescriptionStyleModel", "_view_count": null, "_view_module": "@jupyter-widgets/base", "_view_module_version": "1.2.0", "_view_name": "StyleView", "description_width": "" } }, "b56ea06fbf0147de9ffa71d6c7c15a78": { "model_module": "@jupyter-widgets/base", "model_name": "LayoutModel", "model_module_version": "1.2.0", "state": { "_model_module": "@jupyter-widgets/base", "_model_module_version": "1.2.0", "_model_name": "LayoutModel", "_view_count": null, "_view_module": "@jupyter-widgets/base", "_view_module_version": "1.2.0", "_view_name": "LayoutView", "align_content": null, "align_items": null, "align_self": null, "border": null, "bottom": null, "display": null, "flex": null, "flex_flow": null, "grid_area": null, "grid_auto_columns": null, "grid_auto_flow": null, "grid_auto_rows": null, "grid_column": null, "grid_gap": null, "grid_row": null, "grid_template_areas": null, "grid_template_columns": null, "grid_template_rows": null, "height": null, "justify_content": null, "justify_items": null, "left": null, "margin": null, "max_height": null, "max_width": null, "min_height": null, "min_width": null, "object_fit": null, "object_position": null, "order": null, "overflow": null, "overflow_x": null, "overflow_y": null, "padding": null, "right": null, "top": null, "visibility": null, "width": null } }, "ebff00f53e6843d08fafe630939a8e71": { "model_module": "@jupyter-widgets/controls", "model_name": "ProgressStyleModel", "model_module_version": "1.5.0", "state": { "_model_module": "@jupyter-widgets/controls", "_model_module_version": "1.5.0", "_model_name": "ProgressStyleModel", "_view_count": null, "_view_module": "@jupyter-widgets/base", "_view_module_version": "1.2.0", "_view_name": "StyleView", "bar_color": null, "description_width": "" } }, "7971cd54c01d461b8f10719b2c2dd87b": { "model_module": "@jupyter-widgets/base", "model_name": "LayoutModel", "model_module_version": "1.2.0", "state": { "_model_module": "@jupyter-widgets/base", "_model_module_version": "1.2.0", "_model_name": "LayoutModel", "_view_count": null, "_view_module": "@jupyter-widgets/base", "_view_module_version": "1.2.0", "_view_name": "LayoutView", "align_content": null, "align_items": null, "align_self": null, "border": null, "bottom": null, "display": null, "flex": null, "flex_flow": null, "grid_area": null, "grid_auto_columns": null, "grid_auto_flow": null, "grid_auto_rows": null, "grid_column": null, "grid_gap": null, "grid_row": null, "grid_template_areas": null, "grid_template_columns": null, "grid_template_rows": null, "height": null, "justify_content": null, "justify_items": null, "left": null, "margin": null, "max_height": null, "max_width": null, "min_height": null, "min_width": null, "object_fit": null, "object_position": null, "order": null, "overflow": null, "overflow_x": null, "overflow_y": null, "padding": null, "right": null, "top": null, "visibility": null, "width": null } }, "13b30b8ea75f45a1be65bdb9b49ab52d": { "model_module": "@jupyter-widgets/controls", "model_name": "DescriptionStyleModel", "model_module_version": "1.5.0", "state": { "_model_module": "@jupyter-widgets/controls", "_model_module_version": "1.5.0", "_model_name": "DescriptionStyleModel", "_view_count": null, "_view_module": "@jupyter-widgets/base", "_view_module_version": "1.2.0", "_view_name": "StyleView", "description_width": "" } } } } }, "cells": [ { "cell_type": "markdown", "metadata": { "id": "c0" }, "source": [ "# Community Notes Brasil — BERTopic + Marco-Mini-Instruct (pipeline revisado)\n", "\n", "## Arquitetura do pipeline\n", "\n", "| Fase | Etapa | Descrição |\n", "|------|-------|-----------|\n", "| 0 | Embeddings | E5-Large multilingual → 1024d (pré-computado, .npy no Drive) |\n", "| 1 | Calibração | Grid search UMAP × HDBSCAN sobre os embeddings (DBCV, outliers, max_cluster) |\n", "| 2 | Clustering | BERTopic: UMAP 10d → HDBSCAN (mcs=30, ms=5) → c-TF-IDF → KeyBERTInspired + MMR |\n", "| 3 | Redução outliers | reduce_outliers() → update_topics()|\n", "| 4 | Rotulagem | Marco-Mini-Instruct Q4_K_M via llama.cpp + gramática GBNF → JSON estruturado por tópico |\n", "| 5 | Macroagregação | Linkage hierárquico (cosseno dos embeddings) → corte por dendrograma → LLM rotula macrotemas |\n", "| 6 | Análise | Tópico × status de publicação, grafo semântico, evolução temporal |\n", "\n", "## Destaques\n", "\n", "1. Grid search para calibrar UMAP/HDBSCAN antes do fit (evita megaclusters espúrios)\n", "2. KeyBERTInspired + MMR como representação dual (keywords semânticas + diversificadas)\n", "3. Saída JSON estruturada com gramática GBNF (contexto_central, categoria_ampla, rotulo_curto)\n", "4. Prompt com restrição explícita contra rótulos genéricos (\"desinformação\", \"manipulação\")\n", "5. Macroagregação hierárquica via scipy\n", "6. Grafo de visualização semântica\n" ], "id": "c0" }, { "cell_type": "markdown", "metadata": { "id": "c1" }, "source": [ "## 0 — Instalação e ambiente" ], "id": "c1" }, { "cell_type": "code", "metadata": { "colab": {}, "id": "c2" }, "source": [ "!nvidia-smi --query-gpu=name,memory.total --format=csv,noheader\n", "\n", "# Core\n", "!pip install -q bertopic[visualization] sentence-transformers umap-learn hdbscan scikit-learn nltk gdown huggingface-hub scipy\n", "\n", "# llama.cpp com CUDA\n", "!pip install -q llama-cpp-python --extra-index-url https://abetlen.github.io/llama-cpp-python/whl/cu124" ], "outputs": [], "execution_count": null, "id": "c2" }, { "cell_type": "markdown", "metadata": { "id": "c3" }, "source": [ "## 1 — Configuração" ], "id": "c3" }, { "cell_type": "code", "metadata": { "colab": {}, "id": "c4" }, "source": [ "from pathlib import Path\n", "\n", "# ──────────── Dados ────────────\n", "ZIP_ID = \"1LiaXkZpLygZqukdiz9TXZVafMgge4Ha7\"\n", "DATA_DIR = Path(\"output_pt_v4\")\n", "\n", "# ──────────── Documento ────────────\n", "DOC_VIEW = \"tagged\" # summary_only | tweet_only | tagged\n", "MIN_DOC_CHARS = 30\n", "\n", "# ──────────── Embeddings ────────────\n", "EMBED_BACKEND = \"e5-instruct\" # e5-instruct | e5-large | minilm\n", "FORCE_RECOMPUTE_EMBEDDINGS = True # True para gerar novos embeddings\n", "BATCH_SIZE = 32\n", "MAX_SEQ_LENGTH = 512\n", "\n", "# ──────────── BERTopic / clustering ────────────\n", "UMAP_NEIGHBORS = 15\n", "UMAP_COMPONENTS = 10 # era 5\n", "HDBSCAN_MIN_CLUSTER = 30 # mantém\n", "HDBSCAN_MIN_SAMPLES = 5 # era 10\n", "VECTOR_MIN_DF = 5\n", "TOP_N_WORDS = 10\n", "\n", "# ──────────── LLM local (Marco-Nano-Instruct MoE) ────────────\n", "GGUF_REPO = \"mradermacher/Marco-Mini-Instruct-i1-GGUF\"\n", "GGUF_FILE = \"Marco-Mini-Instruct.i1-Q6_K.gguf\"\n", "LLM_CTX = 8192\n", "LLM_MAX_TOPIC_TOKENS = 256 # JSON estruturado precisa de mais espaço\n", "LLM_MAX_MACRO_TOKENS = 64\n", "\n", "# ──────────── Macroagregação hierárquica ────────────\n", "HIERARCHY_METHOD = \"average\" # linkage method sobre cosseno\n", "HIERARCHY_DISTANCE_THRESHOLD = None # None = inspecionar dendrograma antes de definir\n", "\n", "# ──────────── Grafo de visualização ────────────\n", "GRAPH_K = 6\n", "GRAPH_MIN_SEM_SIM = 0.60\n", "\n", "# ──────────── Saída ────────────\n", "ARTIFACT_DIR = Path(\"bertopic_cn_pt_v3\")\n", "ARTIFACT_DIR.mkdir(exist_ok=True)\n", "\n", "print({k: v for k, v in locals().items() if k.isupper() and not k.startswith(\"_\")})" ], "outputs": [], "execution_count": null, "id": "c4" }, { "cell_type": "markdown", "metadata": { "id": "c5" }, "source": [ "## 2 — Download dos dados e do modelo GGUF" ], "id": "c5" }, { "cell_type": "code", "metadata": { "colab": {}, "id": "c6" }, "source": [ "!gdown \"$ZIP_ID\" -O community_notes_pt_br.zip --fuzzy\n", "!unzip -q -o community_notes_pt_br.zip" ], "outputs": [], "execution_count": null, "id": "c6" }, { "cell_type": "code", "metadata": { "id": "c7" }, "source": [ "!pip install -q hf_transfer\n", "import os\n", "os.environ[\"HF_HUB_ENABLE_HF_TRANSFER\"] = \"1\"\n", "\n", "from huggingface_hub import hf_hub_download\n", "\n", "try:\n", " MODEL_PATH = hf_hub_download(\n", " repo_id=GGUF_REPO,\n", " filename=GGUF_FILE,\n", " local_dir=\"./models\",\n", " )\n", " print(f\"Modelo baixado: {MODEL_PATH}\")\n", "except Exception as e:\n", " print(f\"Erro: {e}\")\n", " print(\"Tentando fallback Q4_K_M...\")\n", " MODEL_PATH = hf_hub_download(\n", " repo_id=\"mradermacher/Marco-Mini-Instruct-i1-GGUF\",\n", " filename=\"Marco-Mini-Instruct.i1-Q4_K_M.gguf\",\n", " local_dir=\"./models\",\n", " )\n", " print(f\"Modelo baixado (fallback): {MODEL_PATH}\")" ], "outputs": [], "execution_count": null, "id": "c7" }, { "cell_type": "markdown", "metadata": { "id": "c8" }, "source": [ "## 3 — Leitura e preparação dos dados" ], "id": "c8" }, { "cell_type": "code", "metadata": { "colab": {}, "id": "c9" }, "source": [ "import gc, re, json\n", "import torch\n", "import numpy as np\n", "import pandas as pd\n", "import matplotlib.pyplot as plt\n", "import seaborn as sns\n", "from IPython.display import display\n", "\n", "sns.set_theme(style=\"whitegrid\")\n", "plt.rcParams[\"figure.dpi\"] = 120\n", "\n", "notas = pd.read_parquet(DATA_DIR / \"notas_pt.parquet\")\n", "status = pd.read_parquet(DATA_DIR / \"status_pt_latest.parquet\")\n", "tweets = pd.read_parquet(DATA_DIR / \"tweets_hidratados.parquet\")\n", "\n", "# Datas e ids\n", "notas[\"created_at\"] = pd.to_datetime(\n", " notas[\"createdAtMillis\"].astype(float), unit=\"ms\", errors=\"coerce\"\n", ")\n", "notas[\"year_month\"] = notas[\"created_at\"].dt.to_period(\"M\")\n", "notas[\"tweet_id\"] = (\n", " notas[\"tweetId\"].astype(\"string\").str.strip().str.replace(r\"\\.0$\", \"\", regex=True)\n", ")\n", "tweets[\"tweet_id\"] = tweets[\"tweet_id\"].astype(str)\n", "\n", "# Último status\n", "last_status = (\n", " status.sort_values(\"createdAtMillis\")\n", " .drop_duplicates(\"noteId\", keep=\"last\")\n", " [[\"noteId\", \"currentStatus\"]]\n", " .rename(columns={\"currentStatus\": \"status_final\"})\n", ")\n", "notas = notas.merge(last_status, on=\"noteId\", how=\"left\")\n", "notas = notas.merge(\n", " tweets[[\"tweet_id\", \"text\"]].rename(columns={\"text\": \"tweet_text\"}),\n", " on=\"tweet_id\", how=\"left\",\n", ")\n", "\n", "STATUS_MAP = {\n", " \"CURRENTLY_RATED_HELPFUL\": \"Publicada\",\n", " \"NEEDS_MORE_RATINGS\": \"Pendente\",\n", " \"CURRENTLY_RATED_NOT_HELPFUL\": \"Não publicada\",\n", "}\n", "notas[\"status_pub\"] = notas[\"status_final\"].map(STATUS_MAP).fillna(\"Outro\")\n", "\n", "def limpa_texto(x):\n", " if pd.isna(x): return \"\"\n", " return re.sub(r\"\\s+\", \" \", str(x)).strip()\n", "\n", "def montar_documento(row, view=\"tagged\"):\n", " summary = limpa_texto(row.get(\"summary\"))\n", " tweet = limpa_texto(row.get(\"tweet_text\"))\n", " if view == \"summary_only\": return summary\n", " if view == \"tweet_only\": return tweet\n", " if view == \"tagged\":\n", " partes = []\n", " if summary: partes.append(f\"[NOTA] {summary}\")\n", " if tweet: partes.append(f\"[TWEET] {tweet}\")\n", " return \" \".join(partes).strip()\n", " raise ValueError(f\"DOC_VIEW inválido: {view}\")\n", "\n", "notas[\"doc\"] = notas.apply(lambda r: montar_documento(r, DOC_VIEW), axis=1)\n", "mask_valid = notas[\"doc\"].str.len().fillna(0) >= MIN_DOC_CHARS\n", "df = notas.loc[mask_valid].copy().reset_index(drop=True)\n", "docs = df[\"doc\"].tolist()\n", "\n", "print(f\"Notas: {len(notas):,} | Válidos: {len(df):,}\")\n", "print(notas[\"status_pub\"].value_counts(dropna=False).to_string())" ], "outputs": [], "execution_count": null, "id": "c9" }, { "cell_type": "markdown", "metadata": { "id": "c10" }, "source": [ "## 4 — Embeddings semânticos (pode saltar pois já foram gerados)" ], "id": "c10" }, { "cell_type": "code", "metadata": { "id": "c11", "colab": {} }, "source": [ "from transformers import AutoTokenizer, AutoModel\n", "\n", "\n", "def mean_pooling(last_hidden_state, attention_mask):\n", " mask = attention_mask.unsqueeze(-1).expand(last_hidden_state.size()).float()\n", " return (last_hidden_state * mask).sum(1) / mask.sum(1).clamp(min=1e-9)\n", "\n", "\n", "# Instrução que orienta o embedding para o assunto factual, não a forma discursiva\n", "EMBED_INSTRUCTION = (\n", " \"Instruct: Identifique o assunto factual em disputa neste texto, \"\n", " \"ignorando aspectos procedurais sobre a plataforma ou sobre como as notas funcionam.\\n\"\n", " \"Query: \"\n", ")\n", "\n", "\n", "def encode_e5_instruct(texts, batch_size=32, max_length=512):\n", " tokenizer = AutoTokenizer.from_pretrained(\"intfloat/multilingual-e5-large-instruct\")\n", " model = AutoModel.from_pretrained(\"intfloat/multilingual-e5-large-instruct\")\n", " model = model.to(\"cuda\" if torch.cuda.is_available() else \"cpu\").eval()\n", "\n", " all_emb = []\n", " for i in range(0, len(texts), batch_size):\n", " batch = [f\"{EMBED_INSTRUCTION}{t}\" for t in texts[i:i+batch_size]]\n", " enc = tokenizer(batch, padding=True, truncation=True,\n", " max_length=max_length, return_tensors=\"pt\")\n", " enc = {k: v.to(model.device) for k, v in enc.items()}\n", " with torch.no_grad():\n", " emb = mean_pooling(model(**enc).last_hidden_state, enc[\"attention_mask\"])\n", " emb = torch.nn.functional.normalize(emb, p=2, dim=1)\n", " all_emb.append(emb.cpu().numpy())\n", "\n", " del model; torch.cuda.empty_cache(); gc.collect()\n", " return np.vstack(all_emb)\n", "\n", "\n", "embed_cache = ARTIFACT_DIR / f\"embeddings_{DOC_VIEW}_e5-instruct.npy\"\n", "\n", "if embed_cache.exists() and not FORCE_RECOMPUTE_EMBEDDINGS:\n", " embeddings = np.load(embed_cache)\n", " print(\"Cache:\", embeddings.shape)\n", "else:\n", " embeddings = encode_e5_instruct(docs, batch_size=BATCH_SIZE, max_length=MAX_SEQ_LENGTH)\n", " np.save(embed_cache, embeddings)\n", " print(\"Gerados:\", embeddings.shape)" ], "outputs": [], "execution_count": null, "id": "c11" }, { "cell_type": "code", "source": [ "from google.colab import drive\n", "from pathlib import Path\n", "import numpy as np\n", "\n", "drive.mount(\"/content/drive\")\n", "\n", "EMBED_PATH = Path(\"/content/drive/MyDrive/Compartilhados/community_notes_pt/sessao_bertopic/embeddings_tagged_e5-instruct.npy\")\n", "\n", "embeddings = np.load(EMBED_PATH)\n", "print(f\"Embeddings carregados: {embeddings.shape}\")" ], "metadata": { "colab": {}, "id": "x2LbzshWRAM5" }, "id": "x2LbzshWRAM5", "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": { "id": "c13" }, "source": [ "## 5 — BERTopic: descoberta inicial dos tópicos" ], "id": "c13" }, { "cell_type": "code", "metadata": { "id": "c14", "colab": {} }, "source": [ "import nltk\n", "from nltk.corpus import stopwords\n", "from sklearn.feature_extraction.text import CountVectorizer\n", "from umap import UMAP\n", "from hdbscan import HDBSCAN\n", "from bertopic import BERTopic\n", "from bertopic.representation import MaximalMarginalRelevance, KeyBERTInspired\n", "from sentence_transformers import SentenceTransformer\n", "\n", "nltk.download(\"stopwords\", quiet=True)\n", "\n", "stop_pt = set(stopwords.words(\"portuguese\"))\n", "stop_extra = {\n", " \"nota\", \"notas\", \"tweet\", \"tweets\", \"usuario\", \"usuário\", \"post\", \"posts\",\n", " \"isso\", \"essa\", \"esse\", \"aqui\", \"ali\", \"ser\", \"estar\", \"ter\", \"vai\",\n", " \"pra\", \"pro\", \"porque\", \"sobre\", \"ainda\", \"também\", \"apenas\", \"pode\",\n", " \"[nota]\", \"[tweet]\",\n", "}\n", "\n", "vectorizer_model = CountVectorizer(\n", " stop_words=sorted(stop_pt | stop_extra),\n", " ngram_range=(1, 2), min_df=VECTOR_MIN_DF,\n", ")\n", "\n", "umap_model = UMAP(\n", " n_neighbors=UMAP_NEIGHBORS, n_components=UMAP_COMPONENTS,\n", " min_dist=0.0, metric=\"cosine\", random_state=42, low_memory=True,\n", ")\n", "\n", "hdbscan_model = HDBSCAN(\n", " min_cluster_size=HDBSCAN_MIN_CLUSTER, min_samples=HDBSCAN_MIN_SAMPLES,\n", " metric=\"euclidean\", prediction_data=True,\n", ")\n", "\n", "# Modelo leve só para o KeyBERTInspired ranquear palavras\n", "# Não substitui os E5-Large do clustering\n", "embedding_model = SentenceTransformer(\"paraphrase-multilingual-MiniLM-L12-v2\")\n", "\n", "topic_model = BERTopic(\n", " embedding_model=embedding_model,\n", " umap_model=umap_model,\n", " hdbscan_model=hdbscan_model,\n", " vectorizer_model=vectorizer_model,\n", " representation_model={\n", " \"Main\": KeyBERTInspired(top_n_words=TOP_N_WORDS),\n", " \"MMR\": MaximalMarginalRelevance(diversity=0.3, top_n_words=TOP_N_WORDS),\n", " },\n", " top_n_words=TOP_N_WORDS,\n", " language=\"multilingual\",\n", " nr_topics=None,\n", " calculate_probabilities=False,\n", " verbose=True,\n", ")\n", "\n", "topics, _ = topic_model.fit_transform(docs, embeddings)\n", "\n", "n_topics = len(set(topics)) - (1 if -1 in topics else 0)\n", "n_outliers = sum(1 for t in topics if t == -1)\n", "print(f\"Tópicos: {n_topics} | Outliers: {n_outliers:,} ({100*n_outliers/len(topics):.1f}%)\")\n", "display(topic_model.get_topic_info().head(25))" ], "outputs": [], "execution_count": null, "id": "c14" }, { "cell_type": "code", "source": [ "SAVE_DIR = Path(\"/content/drive/MyDrive/Compartilhados/community_notes_pt/sessao_bertopic/e5_instruct\")\n", "SAVE_DIR.mkdir(parents=True, exist_ok=True)\n", "\n", "# Modelo BERTopic\n", "topic_model.save(str(SAVE_DIR / \"model\"), serialization=\"safetensors\", save_ctfidf=True)\n", "\n", "print(f\"Modelo salvo: {len(set(topics))-1} tópicos, {sum(1 for t in topics if t == -1):,} outliers\")\n", "print(f\"Local: {SAVE_DIR}\")" ], "metadata": { "colab": {}, "id": "r6Ds6gM8YpwV" }, "id": "r6Ds6gM8YpwV", "execution_count": null, "outputs": [] }, { "cell_type": "code", "source": [ "# ── Redução de outliers (diagnóstico) ──\n", "\n", "topics = topic_model.topics_\n", "\n", "n_outliers_antes = sum(1 for t in topics if t == -1)\n", "print(f\"Outliers antes: {n_outliers_antes:,} ({100*n_outliers_antes/len(topics):.1f}%)\")\n", "\n", "new_topics = topic_model.reduce_outliers(\n", " docs, topics,\n", " strategy=\"embeddings\",\n", " embeddings=embeddings,\n", " threshold=0.975,\n", ")\n", "\n", "n_outliers_depois = sum(1 for t in new_topics if t == -1)\n", "n_topics = len(set(new_topics)) - (1 if -1 in new_topics else 0)\n", "\n", "print(f\"Outliers depois: {n_outliers_depois:,} ({100*n_outliers_depois/len(new_topics):.1f}%)\")\n", "print(f\"Recuperados: {n_outliers_antes - n_outliers_depois:,}\")\n", "print(f\"Tópicos ativos: {n_topics}\")\n", "print(\"\\nSe satisfeito, rode a próxima célula para confirmar.\")" ], "metadata": { "colab": {}, "id": "O0djsXoLY5hp" }, "id": "O0djsXoLY5hp", "execution_count": null, "outputs": [] }, { "cell_type": "code", "source": [ "# ── Confirmar redução ──\n", "\n", "topic_model.update_topics(docs, topics=new_topics)\n", "topics = new_topics\n", "print(\"Atualizado.\")" ], "metadata": { "colab": {}, "id": "ZgQQ6l7dZXa9" }, "id": "ZgQQ6l7dZXa9", "execution_count": null, "outputs": [] }, { "cell_type": "code", "source": [ "# ── Visualização pós-redução de outliers (antes do LLM) ──\n", "\n", "import re\n", "\n", "def limpa_label_bertopic(name):\n", " \"\"\"Remove prefixo numérico e underscores do rótulo padrão do BERTopic\"\"\"\n", " name = str(name)\n", " name = re.sub(r\"^-?\\d+_\", \"\", name) # remove \"0_\", \"12_\", \"-1_\"\n", " name = name.replace(\"_\", \" \").strip() # underscores → espaços\n", " name = re.sub(r\"\\s+\", \" \", name) # espaços múltiplos\n", " return name[:42] if len(name) > 42 else name\n", "\n", "# Injeta rótulos limpos no modelo\n", "topic_info = topic_model.get_topic_info()\n", "clean_labels = {}\n", "for _, row in topic_info.iterrows():\n", " tid = row[\"Topic\"]\n", " if tid == -1:\n", " clean_labels[tid] = \"Outliers\"\n", " else:\n", " clean_labels[tid] = limpa_label_bertopic(row[\"Name\"])\n", "\n", "topic_model.set_topic_labels(clean_labels)\n", "\n", "# ── 1. Mapa intertópico ──\n", "fig = topic_model.visualize_topics(\n", " title=\"Mapa intertópico — pós-redução de outliers (sem LLM)\",\n", " custom_labels=True,\n", " width=950, height=720,\n", ")\n", "fig.show()\n", "\n", "# ── 2. Hierarquia dos tópicos (top 30 por volume) ──\n", "fig = topic_model.visualize_hierarchy(\n", " top_n_topics=30,\n", " custom_labels=True,\n", " title=\"Hierarquia dos 30 maiores tópicos\",\n", " width=1000, height=600,\n", ")\n", "fig.show()\n", "\n", "# ── 3. Heatmap de similaridade (top 20) ──\n", "fig = topic_model.visualize_heatmap(\n", " top_n_topics=20,\n", " custom_labels=True,\n", " title=\"Similaridade entre os 20 maiores tópicos\",\n", " width=800, height=800,\n", ")\n", "fig.show()\n", "\n", "# ── 4. Barchart de palavras-chave (top 12) ──\n", "fig = topic_model.visualize_barchart(\n", " top_n_topics=12,\n", " custom_labels=True,\n", " title=\"Palavras-chave dos 12 maiores tópicos\",\n", " width=1000, height=600,\n", ")\n", "fig.show()\n", "\n", "# Resumo\n", "n_topics = len(set(topics)) - (1 if -1 in topics else 0)\n", "n_outliers = sum(1 for t in topics if t == -1)\n", "print(f\"\\nResumo: {n_topics} tópicos | {n_outliers:,} outliers restantes ({100*n_outliers/len(topics):.1f}%)\")\n", "print(\"Rótulos acima são keywords do BERTopic. O LLM substituirá na próxima etapa.\")" ], "metadata": { "colab": {}, "id": "ecLEYeqAASiA" }, "id": "ecLEYeqAASiA", "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": { "id": "c15" }, "source": [ "## 6 — Rotulagem estruturada com Marco-Mini + gramática GBNF\n", "\n", "Em vez de pedir apenas um rótulo curto, o LLM gera\n", "um JSON com três campos por tópico:\n", "\n", "- `contexto_central`: uma frase descrevendo a dinâmica entre tweets e notas.\n", "- `categoria_ampla`: classificação temática de alto nível.\n", "- `rotulo_curto`: rótulo legível de até 6 palavras.\n", "\n", "A gramática GBNF garante que a saída é sempre JSON válido, independentemente\n", "do comportamento do modelo." ], "id": "c15" }, { "cell_type": "code", "source": [ "from pathlib import Path\n", "import glob\n", "\n", "DRIVE_BASE = Path(\"/content/drive/MyDrive/Compartilhados/community_notes_pt\")\n", "\n", "# Encontrar o GGUF no diretório\n", "gguf_files = list(DRIVE_BASE.rglob(\"*.gguf\"))\n", "for f in gguf_files:\n", " print(f\"{f.name} ({f.stat().st_size/1e9:.1f} GB)\")\n", "\n", "MODEL_PATH = str(gguf_files[0]) # ajusta o índice se listar mais de um\n", "print(f\"\\nMODEL_PATH = {MODEL_PATH}\")" ], "metadata": { "colab": {}, "id": "Z5DyXxlfaukT" }, "id": "Z5DyXxlfaukT", "execution_count": null, "outputs": [] }, { "cell_type": "code", "metadata": { "colab": {}, "id": "c16" }, "source": [ "import gc, torch, json\n", "from llama_cpp import Llama, LlamaGrammar\n", "\n", "if \"llm\" in globals():\n", " del llm; gc.collect()\n", " if torch.cuda.is_available(): torch.cuda.empty_cache()\n", "\n", "llm = Llama(\n", " model_path=MODEL_PATH,\n", " n_gpu_layers=-1,\n", " n_ctx=LLM_CTX,\n", " verbose=False,\n", ")\n", "\n", "# ── Gramática GBNF: garante JSON válido com exatamente 3 campos ──\n", "GBNF_TOPIC = r'''\n", "root ::= \"{\" ws ctx-kv \",\" ws cat-kv \",\" ws rot-kv ws \"}\"\n", "ctx-kv ::= \"\\\"contexto_central\\\"\" ws \":\" ws string\n", "cat-kv ::= \"\\\"categoria_ampla\\\"\" ws \":\" ws string\n", "rot-kv ::= \"\\\"rotulo_curto\\\"\" ws \":\" ws string\n", "string ::= \"\\\"\" chars \"\\\"\"\n", "chars ::= char*\n", "char ::= [^\"\\\\\\x00-\\x1f] | \"\\\\\" escape\n", "escape ::= [\"\\\\/bfnrt]\n", "ws ::= [ \\t\\n]*\n", "'''\n", "\n", "grammar_topic = LlamaGrammar.from_string(GBNF_TOPIC)\n", "\n", "print(f\"Marco-Mini-Instruct carregado | n_ctx={LLM_CTX}\")\n", "print(\"Gramática GBNF compilada com sucesso.\")" ], "outputs": [], "execution_count": null, "id": "c16" }, { "cell_type": "code", "metadata": { "colab": {}, "id": "c17" }, "source": [ "# ── Prompt e função de rotulagem por tópico ──\n", "\n", "PROMPT_TOPICO = \"\"\"<|im_start|>system\n", "Você é um analista de dados avaliando notas da comunidade (Community Notes) do X/Twitter no Brasil.\n", "Leve em consideração o contexto sociopolítico e cultural brasileiro.\n", "\n", "IMPORTANTE: Como TODOS os tópicos envolvem verificação de fatos por natureza,\n", "NÃO use palavras genéricas como \"desinformação\", \"manipulação\", \"fake news\" ou\n", "\"verificação\" no rótulo. Foque no ASSUNTO CONCRETO: o evento, a pessoa, a política\n", "pública ou o fenômeno específico.\n", "\n", "Analise as palavras-chave e documentos representativos e responda EXATAMENTE em JSON com três campos:\n", "- \"contexto_central\": uma frase curta explicando a dinâmica central entre os tweets e as notas neste tópico.\n", "- \"categoria_ampla\": uma das seguintes categorias: Política, Saúde, Economia, Entretenimento, Golpes e Fraudes, Ciência, Segurança, Esporte, Educação, Meio Ambiente, Tecnologia, Desinformação, Outro.\n", "- \"rotulo_curto\": um rótulo descritivo de até 6 palavras, SEM usar \"desinformação\" ou \"manipulação\".\n", "<|im_end|>\n", "<|im_start|>user\n", "Palavras-chave: {keywords}\n", "\n", "Documentos representativos:\n", "{documents}\n", "\n", "Responda APENAS com o JSON, sem explicações.\n", "<|im_end|>\n", "<|im_start|>assistant\n", "\"\"\"\n", "\n", "\n", "def get_representative_docs(topic_id, n=3, max_chars=200):\n", " try:\n", " rep = topic_model.get_representative_docs(topic_id)\n", " if rep:\n", " return [d[:max_chars] for d in rep[:n]]\n", " except Exception:\n", " pass\n", " mask = [i for i, t in enumerate(topics) if t == topic_id]\n", " if not mask:\n", " return []\n", " chosen = mask[:n]\n", " return [docs[i][:max_chars] for i in chosen]\n", "\n", "\n", "def label_topic_structured(topic_id):\n", " # Keywords do KeyBERTInspired (Main)\n", " main_words = topic_model.get_topic(topic_id)\n", " if not main_words:\n", " return {\"contexto_central\": \"\", \"categoria_ampla\": \"Outro\", \"rotulo_curto\": \"Sem rótulo\"}\n", "\n", " main_kw = [w for w, _ in main_words[:TOP_N_WORDS]]\n", "\n", " # Keywords do MMR (representação secundária)\n", " mmr_kw = []\n", " try:\n", " full = topic_model.get_topic_info()\n", " row = full[full[\"Topic\"] == topic_id]\n", " if \"MMR\" in row.columns and len(row):\n", " mmr_raw = row[\"MMR\"].iloc[0]\n", " if isinstance(mmr_raw, list):\n", " mmr_kw = [w for w, _ in mmr_raw[:TOP_N_WORDS]]\n", " except Exception:\n", " pass\n", "\n", " # Combina sem duplicatas, preservando ordem\n", " combined = list(dict.fromkeys(main_kw + mmr_kw))\n", " kw_str = \", \".join(combined)\n", "\n", " rep_docs = get_representative_docs(topic_id, n=3, max_chars=200)\n", " doc_str = \"\\n\".join(f\"- {d}\" for d in rep_docs) if rep_docs else \"(nenhum)\"\n", "\n", " prompt = PROMPT_TOPICO.format(keywords=kw_str, documents=doc_str)\n", "\n", " out = llm(\n", " prompt,\n", " max_tokens=LLM_MAX_TOPIC_TOKENS,\n", " temperature=0.1,\n", " repeat_penalty=1.12,\n", " stop=[\"<|im_end|>\"],\n", " grammar=grammar_topic,\n", " )\n", "\n", " raw = out[\"choices\"][0][\"text\"].strip()\n", " try:\n", " parsed = json.loads(raw)\n", " for key in (\"contexto_central\", \"categoria_ampla\", \"rotulo_curto\"):\n", " if key not in parsed or not str(parsed[key]).strip():\n", " parsed[key] = {\"contexto_central\": \"\", \"categoria_ampla\": \"Outro\", \"rotulo_curto\": \"Sem rótulo\"}[key]\n", " parsed[\"rotulo_curto\"] = parsed[\"rotulo_curto\"][:45]\n", " return parsed\n", " except json.JSONDecodeError:\n", " return {\"contexto_central\": raw[:120], \"categoria_ampla\": \"Outro\", \"rotulo_curto\": raw[:45]}\n", "\n", "\n", "# ── Rotular todos os tópicos ──\n", "valid_topic_ids = sorted(t for t in set(topics) if t != -1)\n", "\n", "topic_metadata = {}\n", "for i, tid in enumerate(valid_topic_ids):\n", " meta = label_topic_structured(tid)\n", " topic_metadata[tid] = meta\n", " if (i + 1) % 10 == 0 or i == 0:\n", " print(f\"[{i+1}/{len(valid_topic_ids)}] T{tid}: {meta['rotulo_curto']}\")\n", "\n", "print(f\"\\nRotulagem concluída: {len(topic_metadata)} tópicos.\")\n", "\n", "# Construir dataframe de metadados\n", "topic_meta_df = pd.DataFrame([\n", " {\"topic\": tid, **meta} for tid, meta in topic_metadata.items()\n", "]).sort_values(\"topic\").reset_index(drop=True)\n", "\n", "display(topic_meta_df.head(15))" ], "outputs": [], "execution_count": null, "id": "c17" }, { "cell_type": "code", "metadata": { "colab": {}, "id": "c18" }, "source": [ "# ── Atualizar rótulos no modelo BERTopic ──\n", "\n", "label_map = {tid: meta[\"rotulo_curto\"] for tid, meta in topic_metadata.items()}\n", "\n", "if hasattr(topic_model, \"topic_labels_\"):\n", " for tid, label in label_map.items():\n", " topic_model.topic_labels_[tid] = label\n", "\n", "# Sincronizar com o dataframe\n", "df[\"topic\"] = topics\n", "df[\"topic_name\"] = df[\"topic\"].map(label_map)\n", "df[\"categoria_ampla\"] = df[\"topic\"].map({tid: m[\"categoria_ampla\"] for tid, m in topic_metadata.items()})\n", "df[\"contexto_central\"] = df[\"topic\"].map({tid: m[\"contexto_central\"] for tid, m in topic_metadata.items()})\n", "df_topics = df[df[\"topic\"] != -1].copy()\n", "\n", "print(f\"Docs com tópico: {len(df_topics):,} de {len(df):,}\")" ], "outputs": [], "execution_count": null, "id": "c18" }, { "cell_type": "markdown", "metadata": { "id": "c19" }, "source": [ "## 7 — Macroagregação hierárquica\n", "\n", "Em vez de construir um grafo com similaridade mista e rodar Louvain,\n", "usamos linkage aglomerativo diretamente sobre a similaridade cosseno dos\n", "embeddings dos tópicos. O dendrograma permite escolher o ponto de corte\n", "com inspeção visual." ], "id": "c19" }, { "cell_type": "code", "metadata": { "colab": {}, "id": "c20" }, "source": [ "from scipy.cluster.hierarchy import linkage, fcluster, dendrogram\n", "from scipy.spatial.distance import pdist\n", "from sklearn.metrics.pairwise import cosine_similarity\n", "\n", "# ── Embeddings dos tópicos (fonte primária: BERTopic) ──\n", "valid_topic_ids = sorted(t for t in set(topics) if t != -1)\n", "\n", "if hasattr(topic_model, \"topic_embeddings_\") and topic_model.topic_embeddings_ is not None:\n", " raw_emb = np.asarray(topic_model.topic_embeddings_)\n", " # topic_embeddings_ inclui -1 no índice 0 em algumas versões do BERTopic\n", " # Verificar alinhamento\n", " topic_info_tmp = topic_model.get_topic_info()\n", " tid_to_idx = dict(zip(topic_info_tmp[\"Topic\"], range(len(topic_info_tmp))))\n", " topic_embs = np.vstack([raw_emb[tid_to_idx[t]] for t in valid_topic_ids])\n", " print(f\"Embeddings dos tópicos via topic_model.topic_embeddings_: {topic_embs.shape}\")\n", "else:\n", " # Fallback: centróides manuais (normalizados)\n", " emb = np.asarray(embeddings)\n", " centroids = []\n", " for tid in valid_topic_ids:\n", " mask = np.array(topics) == tid\n", " c = emb[mask].mean(axis=0)\n", " c /= max(np.linalg.norm(c), 1e-9)\n", " centroids.append(c)\n", " topic_embs = np.vstack(centroids)\n", " print(f\"Embeddings dos tópicos via centróides manuais: {topic_embs.shape}\")\n", "\n", "# ── Linkage hierárquico ──\n", "dist_matrix = pdist(topic_embs, metric=\"cosine\")\n", "Z = linkage(dist_matrix, method=HIERARCHY_METHOD)\n", "\n", "# ── Dendrograma para inspeção ──\n", "topic_labels_short = [\n", " topic_metadata.get(t, {}).get(\"rotulo_curto\", str(t))[:30]\n", " for t in valid_topic_ids\n", "]\n", "\n", "fig, ax = plt.subplots(figsize=(18, 8))\n", "dendrogram(\n", " Z, labels=topic_labels_short, ax=ax,\n", " leaf_rotation=90, leaf_font_size=6,\n", " color_threshold=0.0,\n", ")\n", "ax.set_ylabel(\"Distância cosseno\")\n", "ax.set_title(\"Dendrograma dos tópicos — inspecione para escolher o limiar de corte\", fontsize=13)\n", "ax.axhline(y=0.5, color=\"red\", linestyle=\"--\", alpha=0.5, label=\"Exemplo: corte em 0.5\")\n", "ax.legend()\n", "plt.tight_layout()\n", "plt.show()\n", "\n", "print(\"\\nDefina HIERARCHY_DISTANCE_THRESHOLD na seção 1 e reexecute, ou continue com o valor abaixo.\")" ], "outputs": [], "execution_count": null, "id": "c20" }, { "cell_type": "code", "metadata": { "colab": {}, "id": "c21" }, "source": [ "# ── Cortar a hierarquia e atribuir macrotemas ──\n", "\n", "HIERARCHY_DISTANCE_THRESHOLD = 0.05\n", "\n", "macro_raw = fcluster(Z, t=HIERARCHY_DISTANCE_THRESHOLD, criterion=\"distance\")\n", "\n", "# Mapear para IDs ordenados por volume\n", "tid_to_macro_raw = dict(zip(valid_topic_ids, macro_raw.astype(int)))\n", "\n", "topic_info_full = topic_model.get_topic_info().copy()\n", "topic_info_full = topic_info_full[topic_info_full[\"Topic\"] != -1].copy()\n", "topic_info_full[\"macrotheme_raw\"] = topic_info_full[\"Topic\"].map(tid_to_macro_raw)\n", "topic_info_full[\"rotulo_curto\"] = topic_info_full[\"Topic\"].map(\n", " {t: topic_metadata.get(t, {}).get(\"rotulo_curto\", \"\") for t in valid_topic_ids}\n", ")\n", "\n", "# Reordenar por volume\n", "macro_volume = (\n", " topic_info_full.groupby(\"macrotheme_raw\")[\"Count\"].sum()\n", " .sort_values(ascending=False)\n", " .reset_index()\n", ")\n", "macro_volume[\"macrotheme_id\"] = range(len(macro_volume))\n", "remap = dict(zip(macro_volume[\"macrotheme_raw\"], macro_volume[\"macrotheme_id\"]))\n", "\n", "topic_info_full[\"macrotheme_id\"] = topic_info_full[\"macrotheme_raw\"].map(remap)\n", "\n", "# Sincronizar com df\n", "df[\"macrotheme_id\"] = df[\"topic\"].map(dict(zip(topic_info_full[\"Topic\"], topic_info_full[\"macrotheme_id\"])))\n", "df_topics = df[df[\"topic\"] != -1].copy()\n", "\n", "n_macros = topic_info_full[\"macrotheme_id\"].nunique()\n", "print(f\"Macrotemas encontrados: {n_macros} (limiar={HIERARCHY_DISTANCE_THRESHOLD:.4f})\")\n", "display(\n", " topic_info_full.groupby(\"macrotheme_id\")\n", " .agg(n_topics=(\"Topic\", \"count\"), total_docs=(\"Count\", \"sum\"),\n", " topicos=(\"rotulo_curto\", lambda x: \" | \".join(x.head(5))))\n", " .sort_values(\"total_docs\", ascending=False)\n", " .head(15)\n", ")" ], "outputs": [], "execution_count": null, "id": "c21" }, { "cell_type": "markdown", "metadata": { "id": "c22" }, "source": [ "## 8 — Rotulagem dos macrotemas com contexto rico\n", "\n", "O segundo LLM recebe os `contexto_central` e `categoria_ampla` gerados na\n", "seção 6, em vez de apenas listas de palavras-chave. Isso elimina a \"amnésia\"\n", "do pipeline anterior." ], "id": "c22" }, { "cell_type": "code", "metadata": { "colab": {}, "id": "c23" }, "source": [ "# ── Gramática GBNF para macrotema ──\n", "GBNF_MACRO = r'''\n", "root ::= \"{\" ws lbl-kv \",\" ws cat-kv ws \"}\"\n", "lbl-kv ::= \"\\\"rotulo_macro\\\"\" ws \":\" ws string\n", "cat-kv ::= \"\\\"categoria_dominante\\\"\" ws \":\" ws string\n", "string ::= \"\\\"\" chars \"\\\"\"\n", "chars ::= char*\n", "char ::= [^\"\\\\\\x00-\\x1f] | \"\\\\\" escape\n", "escape ::= [\"\\\\/bfnrt]\n", "ws ::= [ \\t\\n]*\n", "'''\n", "\n", "grammar_macro = LlamaGrammar.from_string(GBNF_MACRO)\n", "\n", "PROMPT_MACRO = \"\"\"<|im_start|>system\n", "Você é um analista temático. Receberá informações sobre um grupo de tópicos\n", "extraídos de Community Notes do X/Twitter no Brasil.\n", "\n", "Regras:\n", "1. NÃO use \"Desinformação\" ou \"Manipulação\" no rótulo.\n", "2. Máximo 4 palavras. Seja direto: \"Vacinas e Saúde\", \"Apostas Online\", \"Crise Venezuela\".\n", "3. Se o grupo trata da plataforma em si (como usar notas, opiniões genéricas, sátira sem alvo),\n", " classifique como \"Procedural\".\n", "<|im_end|>\n", "<|im_start|>user\n", "Rótulos dos tópicos: {rotulos}\n", "\n", "Categorias: {categorias}\n", "\n", "Responda em JSON com:\n", "- \"rotulo_macro\": máximo 4 palavras\n", "- \"categoria_dominante\": Política, Saúde, Economia, Entretenimento, Golpes e Fraudes, Ciência, Segurança, Esporte, Educação, Meio Ambiente, Tecnologia, Procedural, Outro\n", "<|im_end|>\n", "<|im_start|>assistant\n", "\"\"\"\n", "\n", "\n", "def label_macrotheme(macro_id, topic_info_full, topic_metadata):\n", " group = topic_info_full[topic_info_full[\"macrotheme_id\"] == macro_id]\n", " tids = group[\"Topic\"].astype(int).tolist()\n", "\n", " contextos = [topic_metadata[t][\"contexto_central\"] for t in tids\n", " if t in topic_metadata and topic_metadata[t][\"contexto_central\"]]\n", " categorias = list({topic_metadata[t][\"categoria_ampla\"] for t in tids if t in topic_metadata})\n", " rotulos = [topic_metadata[t][\"rotulo_curto\"] for t in tids if t in topic_metadata]\n", "\n", " prompt = PROMPT_MACRO.format(\n", " contextos=\"\\n\".join(f\"- {c}\" for c in contextos[:10]) or \"(nenhum)\",\n", " categorias=\", \".join(categorias[:8]) or \"Outro\",\n", " rotulos=\", \".join(rotulos[:10]) or \"(nenhum)\",\n", " )\n", "\n", " out = llm(\n", " prompt, max_tokens=LLM_MAX_MACRO_TOKENS,\n", " temperature=0.1, repeat_penalty=1.12,\n", " stop=[\"<|im_end|>\"], grammar=grammar_macro,\n", " )\n", "\n", " raw = out[\"choices\"][0][\"text\"].strip()\n", " try:\n", " parsed = json.loads(raw)\n", " return {\n", " \"rotulo_macro\": parsed.get(\"rotulo_macro\", \"Sem rótulo\")[:60],\n", " \"categoria_dominante\": parsed.get(\"categoria_dominante\", \"Outro\"),\n", " }\n", " except json.JSONDecodeError:\n", " return {\"rotulo_macro\": raw[:60], \"categoria_dominante\": \"Outro\"}\n", "\n", "\n", "# ── Gerar rótulos para cada macrotema ──\n", "macro_ids = sorted(topic_info_full[\"macrotheme_id\"].unique())\n", "\n", "macro_labels = {}\n", "for mid in macro_ids:\n", " result = label_macrotheme(mid, topic_info_full, topic_metadata)\n", " macro_labels[mid] = result\n", " print(f\"Macro {mid}: {result['rotulo_macro']} [{result['categoria_dominante']}]\")\n", "\n", "macro_label_map = {mid: v[\"rotulo_macro\"] for mid, v in macro_labels.items()}\n", "macro_cat_map = {mid: v[\"categoria_dominante\"] for mid, v in macro_labels.items()}\n", "\n", "# Sincronizar\n", "topic_info_full[\"macrotheme_label\"] = topic_info_full[\"macrotheme_id\"].map(macro_label_map)\n", "df[\"macrotheme_label\"] = df[\"macrotheme_id\"].map(macro_label_map)\n", "df_topics = df[df[\"topic\"] != -1].copy()\n", "\n", "print(f\"\\nMacrotemas rotulados: {len(macro_labels)}\")\n" ], "outputs": [], "execution_count": null, "id": "c23" }, { "cell_type": "code", "source": [ "# ── Identificar procedurais em duas camadas ──\n", "\n", "# Camada 1: tópicos individuais por keywords no rótulo/contexto\n", "procedural_keywords = [\"comunidade\", \"comentário\", \"opinião pessoal\", \"nota da comunidade\",\n", " \"communitynotes\", \"sátira sem\", \"resposta em comentário\",\n", " \"contribuição da comunidade\", \"guia de notas\", \"uso das notas\"]\n", "\n", "def is_procedural(row):\n", " text = f\"{row['rotulo_curto']} {row['contexto_central']}\".lower()\n", " return any(kw in text for kw in procedural_keywords)\n", "\n", "topic_meta_df[\"categoria_ampla\"] = topic_meta_df.apply(\n", " lambda r: \"Procedural\" if is_procedural(r) else r[\"categoria_ampla\"], axis=1\n", ")\n", "\n", "# Atualizar topic_metadata para refletir\n", "for _, row in topic_meta_df.iterrows():\n", " tid = row[\"topic\"]\n", " if tid in topic_metadata:\n", " topic_metadata[tid][\"categoria_ampla\"] = row[\"categoria_ampla\"]\n", "\n", "n_proc_topicos = (topic_meta_df[\"categoria_ampla\"] == \"Procedural\").sum()\n", "print(f\"Tópicos procedurais (keywords): {n_proc_topicos} de {len(topic_meta_df)}\")\n", "\n", "# Camada 2: macrotemas inteiros classificados pelo LLM\n", "proc_macros = [mid for mid, cat in macro_cat_map.items() if cat == \"Procedural\"]\n", "print(f\"Macrotemas procedurais (LLM): {len(proc_macros)} de {len(macro_labels)}\")\n", "\n", "# Combinar: um tópico é procedural se ele próprio OU seu macrotema é procedural\n", "proc_topics_all = set(topic_meta_df[topic_meta_df[\"categoria_ampla\"] == \"Procedural\"][\"topic\"])\n", "proc_topics_macro = set(topic_info_full[topic_info_full[\"macrotheme_id\"].isin(proc_macros)][\"Topic\"])\n", "proc_topics_combined = proc_topics_all | proc_topics_macro\n", "\n", "print(f\"\\nTotal procedurais combinados: {len(proc_topics_combined)} tópicos\")\n", "\n", "# Dataframes filtrados\n", "df_substantivo = df_topics[~df_topics[\"topic\"].isin(proc_topics_combined)].copy()\n", "topic_info_substantivo = topic_info_full[~topic_info_full[\"Topic\"].isin(proc_topics_combined)].copy()\n", "\n", "print(f\"Docs substantivos: {len(df_substantivo):,} ({100*len(df_substantivo)/len(df_topics):.1f}%)\")\n", "print(f\"Docs procedurais: {len(df_topics)-len(df_substantivo):,}\")\n", "print(\"\\nUse df_substantivo e topic_info_substantivo nas visualizações.\")" ], "metadata": { "colab": {}, "id": "jD54d2MWr2r7" }, "id": "jD54d2MWr2r7", "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": { "id": "c24" }, "source": [ "## 9 — Visualizações e cruzamentos" ], "id": "c24" }, { "cell_type": "markdown", "source": [ "Tópicos Marco-Mini" ], "metadata": { "id": "srq1hg8nox_0" }, "id": "srq1hg8nox_0" }, { "cell_type": "code", "source": [ "# Injeta rótulos do LLM no modelo\n", "topic_model.set_topic_labels(\n", " {tid: meta[\"rotulo_curto\"] for tid, meta in topic_metadata.items()}\n", ")\n", "\n", "fig = topic_model.visualize_topics(\n", " title=\"Mapa intertópico — Community Notes Brasil\",\n", " custom_labels=True,\n", " width=950,\n", " height=720,\n", ")\n", "fig.show()" ], "metadata": { "colab": {}, "id": "JcvIpPV0ofAK" }, "id": "JcvIpPV0ofAK", "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "Intertópico por Macros" ], "metadata": { "id": "bV1fKuLfpDvh" }, "id": "bV1fKuLfpDvh" }, { "cell_type": "code", "source": [ "from umap import UMAP as UMAP2D\n", "import plotly.graph_objects as go\n", "\n", "# Filtrar macrotemas procedurais\n", "macro_ids_filtered = [m for m in sorted(topic_info_full[\"macrotheme_id\"].unique())\n", " if m not in proc_macros]\n", "\n", "macro_centroids = []\n", "macro_sizes = []\n", "macro_names = []\n", "macro_cats = []\n", "\n", "for mid in macro_ids_filtered:\n", " tids = topic_info_full.loc[topic_info_full[\"macrotheme_id\"] == mid, \"Topic\"].tolist()\n", " idxs = [valid_topic_ids.index(t) for t in tids if t in valid_topic_ids]\n", " centroid = topic_embs[idxs].mean(axis=0)\n", " centroid /= max(np.linalg.norm(centroid), 1e-9)\n", " macro_centroids.append(centroid)\n", " macro_sizes.append(topic_info_full.loc[topic_info_full[\"macrotheme_id\"] == mid, \"Count\"].sum())\n", " macro_names.append(macro_label_map.get(mid, f\"Macro {mid}\")[:40])\n", " macro_cats.append(macro_cat_map.get(mid, \"Outro\"))\n", "\n", "macro_centroids = np.vstack(macro_centroids)\n", "\n", "# Projeção 2D\n", "coords = UMAP2D(\n", " n_neighbors=min(10, len(macro_centroids) - 1),\n", " n_components=2, min_dist=0.3, metric=\"cosine\", random_state=42,\n", ").fit_transform(macro_centroids)\n", "\n", "# Cores por categoria\n", "CAT_COLORS = {\n", " \"Política\": \"#4E79A7\",\n", " \"Saúde\": \"#59A14F\",\n", " \"Economia\": \"#F28E2B\",\n", " \"Entretenimento\": \"#B07AA1\",\n", " \"Golpes e Fraudes\": \"#E15759\",\n", " \"Ciência\": \"#76B7B2\",\n", " \"Segurança\": \"#9C755F\",\n", " \"Esporte\": \"#EDC948\",\n", " \"Educação\": \"#FF9DA7\",\n", " \"Meio Ambiente\": \"#8CD17D\",\n", " \"Tecnologia\": \"#86BCB6\",\n", " \"Outro\": \"#BAB0AC\",\n", "}\n", "\n", "sizes = np.array(macro_sizes, dtype=float)\n", "sizes_norm = 20 + 55 * (sizes - sizes.min()) / max(sizes.max() - sizes.min(), 1)\n", "\n", "# Um trace por categoria (para legenda agrupada)\n", "fig = go.Figure()\n", "cats_plotted = set()\n", "\n", "for i, (x, y, name, cat, sz) in enumerate(zip(\n", " coords[:, 0], coords[:, 1], macro_names, macro_cats, sizes_norm\n", ")):\n", " color = CAT_COLORS.get(cat, \"#BAB0AC\")\n", " show_legend = cat not in cats_plotted\n", " cats_plotted.add(cat)\n", "\n", " fig.add_trace(go.Scatter(\n", " x=[x], y=[y],\n", " mode=\"markers+text\",\n", " marker=dict(size=sz, color=color, opacity=0.75,\n", " line=dict(width=1.5, color=\"white\")),\n", " text=name,\n", " textposition=\"top center\",\n", " textfont=dict(size=9, color=\"#333\"),\n", " hovertext=f\"{name}
{cat}
{int(sizes[i]):,} docs\",\n", " hoverinfo=\"text\",\n", " legendgroup=cat,\n", " name=cat,\n", " showlegend=show_legend,\n", " ))\n", "\n", "fig.update_layout(\n", " title=dict(text=\"Mapa Intertópico — Macrotemas Substantivos\",\n", " font=dict(size=16), x=0.5),\n", " width=1100, height=750,\n", " xaxis=dict(visible=False),\n", " yaxis=dict(visible=False),\n", " plot_bgcolor=\"white\",\n", " paper_bgcolor=\"white\",\n", " legend=dict(title=\"Categoria\", font=dict(size=10),\n", " bgcolor=\"rgba(255,255,255,0.8)\",\n", " bordercolor=\"#ddd\", borderwidth=1),\n", " margin=dict(l=20, r=20, t=60, b=20),\n", ")\n", "\n", "fig.show()" ], "metadata": { "colab": {}, "id": "qM9lRwnfpILL" }, "id": "qM9lRwnfpILL", "execution_count": null, "outputs": [] }, { "cell_type": "code", "metadata": { "colab": {}, "id": "c25" }, "source": [ "# ── 9.1 Top 25 tópicos por volume (sem procedurais) ──\n", "\n", "top25 = topic_info_substantivo.sort_values(\"Count\", ascending=False).head(25)\n", "labels_viz = [topic_metadata.get(t, {}).get(\"rotulo_curto\", str(t))[:42]\n", " for t in top25[\"Topic\"]]\n", "\n", "fig, ax = plt.subplots(figsize=(12, max(6, 25 * 0.35)))\n", "bars = ax.barh(range(len(labels_viz)), top25[\"Count\"].values,\n", " color=\"#a8dadc\", edgecolor=\"white\", linewidth=0.5)\n", "ax.set_yticks(range(len(labels_viz)))\n", "ax.set_yticklabels(labels_viz, fontsize=9)\n", "ax.invert_yaxis()\n", "ax.set_xlabel(\"Nº de notas\")\n", "ax.set_title(\"Top 25 tópicos por volume (substantivos)\", fontsize=14, pad=12)\n", "for bar, count in zip(bars, top25[\"Count\"].values):\n", " ax.text(bar.get_width() + top25[\"Count\"].max() * 0.01,\n", " bar.get_y() + bar.get_height() / 2,\n", " f\"{count:,}\", va=\"center\", fontsize=8, color=\"#555\")\n", "plt.tight_layout()\n", "plt.show()" ], "outputs": [], "execution_count": null, "id": "c25" }, { "cell_type": "code", "metadata": { "colab": {}, "id": "c26" }, "source": [ "# ── 9.2 Heatmap: tópico × status (top 30) ──\n", "\n", "CORES_STATUS = {\"Publicada\": \"#a8dadc\", \"Pendente\": \"#ffd6a5\", \"Não publicada\": \"#f4978e\"}\n", "\n", "top30 = df_substantivo[\"topic_name\"].value_counts().head(30).index\n", "df30 = df_substantivo[df_substantivo[\"topic_name\"].isin(top30)]\n", "\n", "cross = pd.crosstab(df30[\"topic_name\"], df30[\"status_pub\"], normalize=\"index\") * 100\n", "for col in [\"Publicada\", \"Pendente\", \"Não publicada\"]:\n", " if col not in cross.columns: cross[col] = 0.0\n", "cross = cross[[\"Publicada\", \"Pendente\", \"Não publicada\"]].sort_values(\"Publicada\", ascending=True)\n", "\n", "fig, ax = plt.subplots(figsize=(10, max(6, len(cross) * 0.4)))\n", "sns.heatmap(cross, annot=True, fmt=\".1f\", cmap=\"YlOrRd\",\n", " linewidths=0.5, linecolor=\"white\",\n", " cbar_kws={\"label\": \"% das notas\"}, ax=ax)\n", "ax.set_title(\"Tópico × destino da nota (top 30, % por tópico)\", fontsize=13, pad=12)\n", "ax.set_xlabel(\"\"); ax.set_ylabel(\"\")\n", "plt.tight_layout()\n", "plt.show()" ], "outputs": [], "execution_count": null, "id": "c26" }, { "cell_type": "code", "metadata": { "colab": {}, "id": "c27" }, "source": [ "# ── 9.3 Taxa de publicação por tópico (dot plot, ≥ 50 notas) ──\n", "\n", "topic_stats = (\n", " df_substantivo.groupby(\"topic_name\")\n", " .agg(n_notas=(\"noteId\", \"count\"), n_pub=(\"status_pub\", lambda s: (s == \"Publicada\").sum()))\n", " .reset_index()\n", ")\n", "topic_stats[\"taxa_%\"] = (100 * topic_stats[\"n_pub\"] / topic_stats[\"n_notas\"]).round(1)\n", "topic_stats_f = topic_stats[topic_stats[\"n_notas\"] >= 50].sort_values(\"taxa_%\")\n", "\n", "fig, ax = plt.subplots(figsize=(10, max(6, len(topic_stats_f) * 0.28)))\n", "colors = [\"#e76f51\" if t < 8 else \"#a8dadc\" if t > 15 else \"#ffd6a5\" for t in topic_stats_f[\"taxa_%\"]]\n", "ax.scatter(topic_stats_f[\"taxa_%\"], range(len(topic_stats_f)), c=colors, s=50, edgecolors=\"white\", linewidth=0.5, zorder=3)\n", "ax.set_yticks(range(len(topic_stats_f)))\n", "ax.set_yticklabels(topic_stats_f[\"topic_name\"].str[:40], fontsize=7)\n", "ax.set_xlabel(\"Taxa de publicação (%)\")\n", "ax.set_title(\"Taxa de publicação por tópico (≥ 50 notas)\", fontsize=13, pad=10)\n", "mediana = topic_stats_f[\"taxa_%\"].median()\n", "ax.axvline(mediana, color=\"#264653\", linestyle=\"--\", linewidth=1, alpha=0.6, label=f\"Mediana: {mediana:.1f}%\")\n", "ax.legend(fontsize=9); ax.grid(axis=\"x\", alpha=0.3)\n", "plt.tight_layout()\n", "plt.show()" ], "outputs": [], "execution_count": null, "id": "c27" }, { "cell_type": "markdown", "metadata": { "id": "c28" }, "source": [ "## 9.4 — Grafo de similaridade semântica\n", "\n", "O grafo agora reflete apenas proximidade conceitual (cosseno dos embeddings).\n", "A coloração dos nós vem da hierarquia da seção 7." ], "id": "c28" }, { "cell_type": "code", "metadata": { "colab": {}, "id": "c29" }, "source": [ "import networkx as nx\n", "import plotly.graph_objects as go\n", "from umap import UMAP as UMAP2D\n", "from sklearn.metrics.pairwise import cosine_similarity\n", "\n", "# ── Similaridade puramente semântica ──\n", "sem_sim = cosine_similarity(topic_embs)\n", "np.fill_diagonal(sem_sim, -1.0)\n", "\n", "# ── Construir grafo k-NN ──\n", "G = nx.Graph()\n", "for i, tid in enumerate(valid_topic_ids):\n", " G.add_node(tid,\n", " label=topic_metadata.get(tid, {}).get(\"rotulo_curto\", str(tid)),\n", " count=int(topic_info_full.loc[topic_info_full[\"Topic\"] == tid, \"Count\"].iloc[0]),\n", " macrotheme=int(topic_info_full.loc[topic_info_full[\"Topic\"] == tid, \"macrotheme_id\"].iloc[0]),\n", " categoria=topic_metadata.get(tid, {}).get(\"categoria_ampla\", \"Outro\"),\n", " )\n", "\n", "for i, tid_i in enumerate(valid_topic_ids):\n", " neighbors = np.argsort(-sem_sim[i])[:GRAPH_K]\n", " for j in neighbors:\n", " if i == j: continue\n", " score = float(sem_sim[i, j])\n", " if score < GRAPH_MIN_SEM_SIM: continue\n", " tid_j = valid_topic_ids[j]\n", " if not G.has_edge(tid_i, tid_j):\n", " G.add_edge(tid_i, tid_j, weight=score)\n", "\n", "print(f\"Grafo: {G.number_of_nodes()} nós, {G.number_of_edges()} arestas\")\n", "\n", "# ── Layout UMAP 2D (mais espalhado) ──\n", "n = len(valid_topic_ids)\n", "coords_2d = UMAP2D(\n", " n_neighbors=min(15, n-1), n_components=2,\n", " min_dist=0.5, metric=\"cosine\", random_state=42,\n", ").fit_transform(topic_embs)\n", "\n", "pos = {tid: (float(coords_2d[i, 0]), float(coords_2d[i, 1]))\n", " for i, tid in enumerate(valid_topic_ids)}\n", "\n", "# ── Paleta por macrotema ──\n", "_PALETTE = [\n", " \"#4E79A7\", \"#F28E2B\", \"#E15759\", \"#76B7B2\", \"#59A14F\",\n", " \"#EDC948\", \"#B07AA1\", \"#FF9DA7\", \"#9C755F\", \"#BAB0AC\",\n", " \"#AF7AA1\", \"#D37295\", \"#FABFD2\", \"#86BCB6\", \"#8CD17D\",\n", " \"#B6992D\", \"#499894\", \"#F1CE63\", \"#D4A6C8\", \"#79706E\",\n", "]\n", "macro_ids_sorted = sorted(topic_info_full[\"macrotheme_id\"].unique())\n", "macro_to_color = {m: _PALETTE[i % len(_PALETTE)] for i, m in enumerate(macro_ids_sorted)}\n", "\n", "# ── Arestas ──\n", "edge_x, edge_y = [], []\n", "for u, v in G.edges():\n", " x0, y0 = pos[u]\n", " x1, y1 = pos[v]\n", " edge_x += [x0, x1, None]\n", " edge_y += [y0, y1, None]\n", "\n", "edge_trace = go.Scatter(\n", " x=edge_x, y=edge_y, mode=\"lines\",\n", " line=dict(width=0.3, color=\"#ccc\"),\n", " hoverinfo=\"none\",\n", ")\n", "\n", "# ── Nós (um trace por macrotema para legenda) ──\n", "nodes_by_macro = {}\n", "for n in G.nodes():\n", " mid = G.nodes[n][\"macrotheme\"]\n", " if mid not in nodes_by_macro:\n", " nodes_by_macro[mid] = []\n", " nodes_by_macro[mid].append(n)\n", "\n", "counts = np.array([G.nodes[n][\"count\"] for n in G.nodes()], dtype=float)\n", "sq = np.sqrt(counts)\n", "size_map = {n: 6 + 30 * (np.sqrt(G.nodes[n][\"count\"]) - sq.min()) / max(sq.max() - sq.min(), 1)\n", " for n in G.nodes()}\n", "\n", "node_traces = []\n", "macros_shown = set()\n", "\n", "for mid in macro_ids_sorted:\n", " if mid not in nodes_by_macro:\n", " continue\n", " nodes = nodes_by_macro[mid]\n", " color = macro_to_color[mid]\n", " macro_name = macro_label_map.get(mid, f\"Macro {mid}\")[:35]\n", " show = mid not in macros_shown\n", " macros_shown.add(mid)\n", "\n", " node_traces.append(go.Scatter(\n", " x=[pos[n][0] for n in nodes],\n", " y=[pos[n][1] for n in nodes],\n", " mode=\"markers\",\n", " marker=dict(\n", " size=[size_map[n] for n in nodes],\n", " color=color, opacity=0.8,\n", " line=dict(width=1, color=\"white\"),\n", " ),\n", " text=[f\"{G.nodes[n]['label']}
\"\n", " f\"Macro: {macro_name}
\"\n", " f\"Categoria: {G.nodes[n]['categoria']}
\"\n", " f\"Docs: {G.nodes[n]['count']:,}\"\n", " for n in nodes],\n", " hoverinfo=\"text\",\n", " legendgroup=macro_name,\n", " name=macro_name,\n", " showlegend=show,\n", " ))\n", "\n", "# ── Figure ──\n", "fig = go.Figure(data=[edge_trace] + node_traces)\n", "fig.update_layout(\n", " title=dict(text=\"Grafo de similaridade semântica — colorido por macrotema\", font=dict(size=15), x=0.5),\n", " width=1200, height=850,\n", " xaxis=dict(visible=False), yaxis=dict(visible=False),\n", " plot_bgcolor=\"white\", paper_bgcolor=\"white\",\n", " legend=dict(title=\"Macrotemas\", font=dict(size=8), bgcolor=\"rgba(255,255,255,0.9)\",\n", " bordercolor=\"#ddd\", borderwidth=1, itemsizing=\"constant\"),\n", " margin=dict(l=10, r=10, t=50, b=10),\n", " hovermode=\"closest\",\n", ")\n", "fig.show()" ], "outputs": [], "execution_count": null, "id": "c29" }, { "cell_type": "code", "metadata": { "id": "c30", "colab": {} }, "source": [ "import pandas as pd\n", "\n", "# ── Bloco: visão temporal com labels do LLM ──\n", "\n", "def build_custom_labels(\n", " topic_model,\n", " topic_meta_df,\n", " label_col=\"rotulo_curto\",\n", " include_topic_id=False,\n", " max_chars=45,\n", " fallback_from_keywords=True,\n", "):\n", " meta = topic_meta_df.copy()\n", "\n", " if \"topic\" not in meta.columns:\n", " raise ValueError(\"topic_meta_df precisa ter a coluna 'topic'.\")\n", "\n", " if label_col not in meta.columns:\n", " meta[label_col] = \"\"\n", "\n", " meta[\"topic\"] = pd.to_numeric(meta[\"topic\"], errors=\"coerce\")\n", " meta = meta.dropna(subset=[\"topic\"]).copy()\n", " meta[\"topic\"] = meta[\"topic\"].astype(int)\n", " meta = meta.drop_duplicates(subset=[\"topic\"], keep=\"first\")\n", "\n", " topic_info = topic_model.get_topic_info()\n", " valid_topic_ids = sorted(t for t in topic_info[\"Topic\"].tolist() if t != -1)\n", "\n", " custom_labels = {}\n", "\n", " for tid in valid_topic_ids:\n", " row = meta.loc[meta[\"topic\"] == tid]\n", "\n", " label = \"\"\n", " if not row.empty:\n", " label = str(row.iloc[0][label_col]).strip()\n", " if label.lower() in {\"\", \"nan\", \"none\"}:\n", " label = \"\"\n", "\n", " if not label and fallback_from_keywords:\n", " kws = topic_model.get_topic(tid)\n", " if kws:\n", " label = \", \".join([w for w, _ in kws[:3]])\n", " else:\n", " label = f\"Tópico {tid}\"\n", " elif not label:\n", " label = f\"Tópico {tid}\"\n", "\n", " if include_topic_id:\n", " label = f\"{tid} - {label}\"\n", "\n", " if max_chars and len(label) > max_chars:\n", " label = label[: max_chars - 1].rstrip() + \"…\"\n", "\n", " custom_labels[tid] = label\n", "\n", " return custom_labels\n", "\n", "\n", "# 1) Monta labels customizadas a partir do dataframe gerado pelo LLM\n", "custom_labels = build_custom_labels(\n", " topic_model,\n", " topic_meta_df,\n", " label_col=\"rotulo_curto\",\n", " include_topic_id=False,\n", " max_chars=45,\n", ")\n", "\n", "# 2) Registra as labels no modelo\n", "topic_model.set_topic_labels(custom_labels)\n", "\n", "# 3) Prepara timestamps válidos\n", "timestamps = pd.to_datetime(df[\"created_at\"], errors=\"coerce\")\n", "mask_valid = timestamps.notna()\n", "\n", "docs_valid = [docs[i] for i in range(len(docs)) if mask_valid.iloc[i]]\n", "timestamps_valid = timestamps[mask_valid].tolist()\n", "\n", "# 4) Calcula evolução temporal\n", "topics_over_time = topic_model.topics_over_time(\n", " docs_valid,\n", " timestamps_valid,\n", " nr_bins=30,\n", ")\n", "\n", "# 5) Substituir labels do BERTopic pelas do LLM no dataframe temporal\n", "topics_over_time[\"Name\"] = topics_over_time[\"Topic\"].map(\n", " lambda t: custom_labels.get(t, f\"Tópico {t}\")\n", ")\n", "\n", "# 6) Gera a figura\n", "fig = topic_model.visualize_topics_over_time(\n", " topics_over_time,\n", " top_n_topics=12,\n", " custom_labels=True,\n", " title=\"Evolução temporal dos principais tópicos\",\n", " width=1000,\n", " height=520,\n", ")\n", "\n", "# 7) Sobrescrever hover com labels do LLM\n", "for trace in fig.data:\n", " if hasattr(trace, \"hovertext\") and trace.hovertext is not None:\n", " trace.hovertext = [\n", " t.split(\"
\")[0] if \"
\" in str(t) else t\n", " for t in trace.hovertext\n", " ]\n", " if hasattr(trace, \"name\") and trace.name:\n", " # O name do trace já tem a label correta via custom_labels\n", " # Mas o hovertemplate pode ter o formato antigo\n", " trace.hovertemplate = \"%{text}
Frequência: %{y}\"\n", " trace.text = [trace.name] * len(trace.x) if trace.x is not None else []\n", "\n", "fig.show()" ], "outputs": [], "execution_count": null, "id": "c30" }, { "cell_type": "markdown", "metadata": { "id": "c31" }, "source": [ "## 10 — Exportação" ], "id": "c31" }, { "cell_type": "code", "metadata": { "colab": {}, "id": "c32" }, "source": [ "SESSION_DIR = ARTIFACT_DIR / \"marco-mini-i1\"\n", "SESSION_DIR.mkdir(parents=True, exist_ok=True)\n", "\n", "# 1) Modelo BERTopic\n", "model_dir = SESSION_DIR / \"model\"\n", "topic_model.save(str(model_dir), serialization=\"safetensors\", save_ctfidf=True)\n", "\n", "# 2) Metadados estruturados por tópico (JSON do LLM)\n", "topic_meta_df.to_parquet(SESSION_DIR / \"topic_metadata_structured.parquet\", index=False)\n", "topic_meta_df.to_csv(SESSION_DIR / \"topic_metadata_structured.csv\", index=False)\n", "\n", "# 3) Resumo dos macrotemas\n", "macro_summary = pd.DataFrame([\n", " {\"macrotheme_id\": mid,\n", " \"rotulo_macro\": macro_labels[mid][\"rotulo_macro\"],\n", " \"categoria_dominante\": macro_labels[mid][\"categoria_dominante\"],\n", " \"n_topics\": int((topic_info_full[\"macrotheme_id\"] == mid).sum()),\n", " \"total_docs\": int(topic_info_full.loc[topic_info_full[\"macrotheme_id\"] == mid, \"Count\"].sum()),\n", " \"topicos\": \" | \".join(\n", " topic_info_full.loc[topic_info_full[\"macrotheme_id\"] == mid]\n", " .sort_values(\"Count\", ascending=False)[\"rotulo_curto\"].head(8).tolist()\n", " )}\n", " for mid in sorted(macro_labels.keys())\n", "]).sort_values(\"total_docs\", ascending=False).reset_index(drop=True)\n", "\n", "macro_summary.to_csv(SESSION_DIR / \"macro_summary.csv\", index=False)\n", "\n", "# 4) Documentos anotados\n", "export_cols = [c for c in [\n", " \"noteId\", \"tweet_id\", \"created_at\", \"status_pub\",\n", " \"topic\", \"topic_name\", \"categoria_ampla\", \"contexto_central\",\n", " \"macrotheme_id\", \"macrotheme_label\", \"summary\", \"tweet_text\", \"doc\",\n", "] if c in df.columns]\n", "df[export_cols].to_parquet(SESSION_DIR / \"notas_com_topicos_v3.parquet\", index=False)\n", "\n", "# 5) Grafo\n", "nx.write_graphml(G, str(SESSION_DIR / \"grafo_topicos_semantico.graphml\"))\n", "\n", "print(f\"Artefatos salvos em {SESSION_DIR}/\")\n", "for f in sorted(SESSION_DIR.rglob(\"*\")):\n", " if f.is_file():\n", " print(f\" {f.relative_to(SESSION_DIR)}\")" ], "outputs": [], "execution_count": null, "id": "c32" }, { "cell_type": "code", "source": [ "SAVE_DIR = Path(\"/content/drive/MyDrive/Compartilhados/community_notes_pt/sessao_bertopic/marco_mini_i1\")\n", "SAVE_DIR.mkdir(parents=True, exist_ok=True)\n", "\n", "topic_meta_df.to_parquet(SAVE_DIR / \"topic_metadata_marco_mini.parquet\", index=False)\n", "topic_meta_df.to_csv(SAVE_DIR / \"topic_metadata_marco_mini.csv\", index=False)\n", "\n", "print(f\"Salvo: {len(topic_meta_df)} tópicos em {SAVE_DIR}\")" ], "metadata": { "colab": {}, "id": "LxLMfGeHFjrJ" }, "id": "LxLMfGeHFjrJ", "execution_count": null, "outputs": [] }, { "cell_type": "code", "source": [ "from pathlib import Path\n", "\n", "SAVE_DIR = Path(\"/content/drive/MyDrive/Compartilhados/community_notes_pt/sessao_bertopic/marco_mini\")\n", "SAVE_DIR.mkdir(parents=True, exist_ok=True)\n", "\n", "# 1) Modelo BERTopic\n", "topic_model.save(str(SAVE_DIR / \"model\"), serialization=\"safetensors\", save_ctfidf=True)\n", "\n", "# 2) Metadados por tópico\n", "topic_meta_df.to_parquet(SAVE_DIR / \"topic_metadata_marco_mini.parquet\", index=False)\n", "topic_meta_df.to_csv(SAVE_DIR / \"topic_metadata_marco_mini.csv\", index=False)\n", "\n", "# 3) Resumo dos macrotemas\n", "macro_summary = pd.DataFrame([\n", " {\"macrotheme_id\": mid,\n", " \"rotulo_macro\": macro_labels[mid][\"rotulo_macro\"],\n", " \"categoria_dominante\": macro_labels[mid][\"categoria_dominante\"],\n", " \"n_topics\": int((topic_info_full[\"macrotheme_id\"] == mid).sum()),\n", " \"total_docs\": int(topic_info_full.loc[topic_info_full[\"macrotheme_id\"] == mid, \"Count\"].sum()),\n", " \"topicos\": \" | \".join(\n", " topic_info_full.loc[topic_info_full[\"macrotheme_id\"] == mid]\n", " .sort_values(\"Count\", ascending=False)[\"rotulo_curto\"].head(8).tolist()\n", " )}\n", " for mid in sorted(macro_labels.keys())\n", "]).sort_values(\"total_docs\", ascending=False).reset_index(drop=True)\n", "macro_summary.to_csv(SAVE_DIR / \"macro_summary.csv\", index=False)\n", "\n", "# 4) Documentos anotados\n", "export_cols = [c for c in [\n", " \"noteId\", \"tweet_id\", \"created_at\", \"status_pub\",\n", " \"topic\", \"topic_name\", \"categoria_ampla\", \"contexto_central\",\n", " \"macrotheme_id\", \"macrotheme_label\", \"summary\", \"tweet_text\", \"doc\",\n", "] if c in df.columns]\n", "df[export_cols].to_parquet(SAVE_DIR / \"notas_com_topicos_v3.parquet\", index=False)\n", "\n", "# 5) Grafo\n", "nx.write_graphml(G, str(SAVE_DIR / \"grafo_topicos_semantico.graphml\"))\n", "\n", "print(f\"Artefatos salvos em {SAVE_DIR}/\")\n", "for f in sorted(SAVE_DIR.rglob(\"*\")):\n", " if f.is_file():\n", " size_mb = f.stat().st_size / 1e6\n", " print(f\" {f.relative_to(SAVE_DIR)} ({size_mb:.1f} MB)\")" ], "metadata": { "id": "JFpFGlqAnzwP" }, "id": "JFpFGlqAnzwP", "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "#Apenas para registro do experimento para escolha dos paramentros do BERTopic" ], "metadata": { "id": "x7CbaCCIer5Q" }, "id": "x7CbaCCIer5Q" }, { "cell_type": "code", "source": [ "import numpy as np\n", "import pandas as pd\n", "from itertools import product\n", "from umap import UMAP\n", "from hdbscan import HDBSCAN\n", "\n", "# Grade de parâmetros\n", "GRID = {\n", " \"n_components\": [5, 10, 15],\n", " \"min_cluster_size\": [15, 30, 50, 80],\n", " \"min_samples\": [5, 10, 15, 20],\n", "}\n", "\n", "UMAP_NEIGHBORS = 15\n", "results = []\n", "\n", "# UMAP é o passo caro: roda uma vez por n_components, reutiliza para cada combo HDBSCAN\n", "for nc in GRID[\"n_components\"]:\n", " print(f\"\\n── UMAP n_components={nc} ──\")\n", " proj = UMAP(\n", " n_neighbors=UMAP_NEIGHBORS, n_components=nc,\n", " min_dist=0.0, metric=\"cosine\", random_state=42, low_memory=True,\n", " ).fit_transform(embeddings)\n", "\n", " for mcs, ms in product(GRID[\"min_cluster_size\"], GRID[\"min_samples\"]):\n", " hdb = HDBSCAN(\n", " min_cluster_size=mcs, min_samples=ms,\n", " metric=\"euclidean\", prediction_data=True,\n", " gen_min_span_tree=True, # Adicionado para calcular relative_validity_\n", " ).fit(proj)\n", "\n", " labels = hdb.labels_\n", " n_topics = len(set(labels)) - (1 if -1 in labels else 0)\n", " n_outliers = (labels == -1).sum()\n", " pct_outliers = 100 * n_outliers / len(labels)\n", " max_cluster = max(np.bincount(labels[labels >= 0])) if n_topics > 0 else 0\n", " dbcv = float(hdb.relative_validity_)\n", "\n", " results.append({\n", " \"n_components\": nc,\n", " \"min_cluster_size\": mcs,\n", " \"min_samples\": ms,\n", " \"n_topics\": n_topics,\n", " \"outliers_%\": round(pct_outliers, 1),\n", " \"max_cluster\": max_cluster,\n", " \"dbcv\": round(dbcv, 4),\n", " })\n", " print(f\" mcs={mcs:3d} ms={ms:2d} → {n_topics:4d} tópicos | \"\n", " f\"outliers={pct_outliers:5.1f}% | max={max_cluster:5d} | dbcv={dbcv:.4f}\")\n", "\n", "grid_df = pd.DataFrame(results).sort_values(\"dbcv\", ascending=False).reset_index(drop=True)\n", "\n", "print(f\"\\n{'='*70}\")\n", "print(f\"Total de combinações: {len(grid_df)}\")\n", "print(f\"\\n── Top 10 por DBCV ──\")\n", "display(grid_df.head(10))\n", "\n", "print(f\"\\n── Top 10 por menor max_cluster (com ≥100 tópicos) ──\")\n", "display(grid_df[grid_df[\"n_topics\"] >= 100].sort_values(\"max_cluster\").head(10))" ], "metadata": { "colab": {}, "id": "eP0amjGzGAgF" }, "id": "eP0amjGzGAgF", "execution_count": null, "outputs": [] }, { "cell_type": "code", "source": [ "# ── Dashboard HTML completo ──\n", "\n", "import plotly.graph_objects as go\n", "import plotly.express as px\n", "import plotly.io as pio\n", "import numpy as np\n", "from pathlib import Path\n", "\n", "# ══════════════════════════════════════════════════\n", "# Métricas resumo\n", "# ══════════════════════════════════════════════════\n", "n_docs_total = len(df)\n", "n_docs_topico = len(df_topics)\n", "n_docs_sub = len(df_substantivo)\n", "n_topics = len(set(topics)) - (1 if -1 in topics else 0)\n", "n_macros = len(macro_labels)\n", "n_proc = len(proc_topics_combined)\n", "n_outliers = sum(1 for t in topics if t == -1)\n", "\n", "summary_html = f\"\"\"\n", "
\n", "
\n", "
{n_docs_total:,}
Documentos
\n", "
\n", "
{n_topics}
Tópicos
\n", "
\n", "
{n_macros}
Macrotemas
\n", "
\n", "
{n_proc}
Procedurais
\n", "
\n", "
{100*n_outliers/n_docs_total:.0f}%
Outliers
\n", "
\n", "
{n_docs_sub:,}
Docs Substantivos
\n", "
\n", "\"\"\"\n", "\n", "# ══════════════════════════════════════════════════\n", "# 1. Top 25 tópicos\n", "# ══════════════════════════════════════════════════\n", "top25 = topic_info_substantivo.sort_values(\"Count\", ascending=False).head(25)\n", "labels_25 = [topic_metadata.get(t, {}).get(\"rotulo_curto\", str(t))[:42] for t in top25[\"Topic\"]]\n", "\n", "fig_top25 = go.Figure(go.Bar(\n", " y=labels_25[::-1], x=top25[\"Count\"].values[::-1],\n", " orientation=\"h\", marker_color=\"#a8dadc\",\n", " text=top25[\"Count\"].values[::-1], textposition=\"outside\", textfont=dict(size=9),\n", "))\n", "fig_top25.update_layout(\n", " title=\"Top 25 tópicos por volume (substantivos)\", height=700, width=950,\n", " xaxis_title=\"Nº de notas\", yaxis=dict(tickfont=dict(size=9)),\n", " margin=dict(l=250, r=60, t=50, b=40), plot_bgcolor=\"white\",\n", ")\n", "\n", "# ══════════════════════════════════════════════════\n", "# 2. Heatmap tópico × status\n", "# ══════════════════════════════════════════════════\n", "top30 = df_substantivo[\"topic_name\"].value_counts().head(30).index\n", "df30 = df_substantivo[df_substantivo[\"topic_name\"].isin(top30)]\n", "\n", "cross = pd.crosstab(df30[\"topic_name\"], df30[\"status_pub\"], normalize=\"index\") * 100\n", "for col in [\"Publicada\", \"Pendente\", \"Não publicada\"]:\n", " if col not in cross.columns: cross[col] = 0.0\n", "cross = cross[[\"Publicada\", \"Pendente\", \"Não publicada\"]].sort_values(\"Publicada\", ascending=True)\n", "\n", "fig_heatmap = px.imshow(\n", " cross.values, x=cross.columns.tolist(), y=cross.index.tolist(),\n", " color_continuous_scale=\"YlOrRd\", aspect=\"auto\",\n", " labels=dict(color=\"% das notas\"), text_auto=\".1f\",\n", ")\n", "fig_heatmap.update_layout(\n", " title=\"Tópico × destino da nota (top 30, % por tópico)\",\n", " height=max(500, len(cross) * 25), width=850,\n", " yaxis=dict(tickfont=dict(size=8)), margin=dict(l=250, t=50, b=40),\n", ")\n", "\n", "# ══════════════════════════════════════════════════\n", "# 3. Dot plot taxa de publicação\n", "# ══════════════════════════════════════════════════\n", "topic_stats = (\n", " df_substantivo.groupby(\"topic_name\")\n", " .agg(n_notas=(\"noteId\", \"count\"), n_pub=(\"status_pub\", lambda s: (s == \"Publicada\").sum()))\n", " .reset_index()\n", ")\n", "topic_stats[\"taxa_%\"] = (100 * topic_stats[\"n_pub\"] / topic_stats[\"n_notas\"]).round(1)\n", "topic_stats_f = topic_stats[topic_stats[\"n_notas\"] >= 50].sort_values(\"taxa_%\")\n", "\n", "colors_dot = [\"#e76f51\" if t < 8 else \"#a8dadc\" if t > 15 else \"#ffd6a5\"\n", " for t in topic_stats_f[\"taxa_%\"]]\n", "\n", "fig_dotplot = go.Figure(go.Scatter(\n", " x=topic_stats_f[\"taxa_%\"], y=topic_stats_f[\"topic_name\"].str[:40],\n", " mode=\"markers\", marker=dict(size=8, color=colors_dot, line=dict(width=0.5, color=\"white\")),\n", " hovertext=[f\"{n}
{t}% ({p}/{tot})\" for n, t, p, tot in\n", " zip(topic_stats_f[\"topic_name\"], topic_stats_f[\"taxa_%\"],\n", " topic_stats_f[\"n_pub\"], topic_stats_f[\"n_notas\"])],\n", " hoverinfo=\"text\",\n", "))\n", "mediana = topic_stats_f[\"taxa_%\"].median()\n", "fig_dotplot.add_vline(x=mediana, line_dash=\"dash\", line_color=\"#264653\",\n", " annotation_text=f\"Mediana: {mediana:.1f}%\")\n", "fig_dotplot.update_layout(\n", " title=\"Taxa de publicação por tópico (≥ 50 notas)\",\n", " height=max(500, len(topic_stats_f) * 15), width=950,\n", " xaxis_title=\"Taxa de publicação (%)\", yaxis=dict(tickfont=dict(size=7)),\n", " margin=dict(l=250, t=50, b=40), plot_bgcolor=\"white\",\n", ")\n", "\n", "# ══════════════════════════════════════════════════\n", "# 4. Mapa intertópico BERTopic (sem LLM labels)\n", "# ══════════════════════════════════════════════════\n", "fig_inter_bert = topic_model.visualize_topics(\n", " title=\"Mapa intertópico — labels BERTopic\",\n", " custom_labels=False,\n", " width=950, height=720,\n", ")\n", "\n", "# ══════════════════════════════════════════════════\n", "# 5. Mapa intertópico com labels LLM\n", "# ══════════════════════════════════════════════════\n", "topic_model.set_topic_labels(\n", " {tid: meta[\"rotulo_curto\"] for tid, meta in topic_metadata.items()}\n", ")\n", "fig_inter_llm = topic_model.visualize_topics(\n", " title=\"Mapa intertópico — labels Marco-Mini\",\n", " custom_labels=True,\n", " width=950, height=720,\n", ")\n", "\n", "# ══════════════════════════════════════════════════\n", "# 6. Mapa intertópico por macrotemas\n", "# ══════════════════════════════════════════════════\n", "from umap import UMAP as UMAP2D\n", "\n", "CAT_COLORS = {\n", " \"Política\": \"#4E79A7\", \"Saúde\": \"#59A14F\", \"Economia\": \"#F28E2B\",\n", " \"Entretenimento\": \"#B07AA1\", \"Golpes e Fraudes\": \"#E15759\", \"Ciência\": \"#76B7B2\",\n", " \"Segurança\": \"#9C755F\", \"Esporte\": \"#EDC948\", \"Educação\": \"#FF9DA7\",\n", " \"Meio Ambiente\": \"#8CD17D\", \"Tecnologia\": \"#86BCB6\", \"Outro\": \"#BAB0AC\",\n", " \"Procedural\": \"#D4D4D4\",\n", "}\n", "\n", "macro_ids_filtered = [m for m in sorted(topic_info_full[\"macrotheme_id\"].unique())\n", " if m not in proc_macros]\n", "\n", "m_centroids, m_sizes, m_names, m_cats = [], [], [], []\n", "for mid in macro_ids_filtered:\n", " tids = topic_info_full.loc[topic_info_full[\"macrotheme_id\"] == mid, \"Topic\"].tolist()\n", " idxs = [valid_topic_ids.index(t) for t in tids if t in valid_topic_ids]\n", " c = topic_embs[idxs].mean(axis=0)\n", " c /= max(np.linalg.norm(c), 1e-9)\n", " m_centroids.append(c)\n", " m_sizes.append(topic_info_full.loc[topic_info_full[\"macrotheme_id\"] == mid, \"Count\"].sum())\n", " m_names.append(macro_label_map.get(mid, f\"Macro {mid}\")[:40])\n", " m_cats.append(macro_cat_map.get(mid, \"Outro\"))\n", "\n", "m_centroids = np.vstack(m_centroids)\n", "m_coords = UMAP2D(n_neighbors=min(10, len(m_centroids)-1), n_components=2,\n", " min_dist=0.3, metric=\"cosine\", random_state=42).fit_transform(m_centroids)\n", "\n", "m_sz = np.array(m_sizes, dtype=float)\n", "m_sz_norm = 20 + 55 * (m_sz - m_sz.min()) / max(m_sz.max() - m_sz.min(), 1)\n", "\n", "fig_macro = go.Figure()\n", "cats_plotted = set()\n", "for i, (x, y, name, cat, sz) in enumerate(zip(\n", " m_coords[:, 0], m_coords[:, 1], m_names, m_cats, m_sz_norm\n", ")):\n", " color = CAT_COLORS.get(cat, \"#BAB0AC\")\n", " show = cat not in cats_plotted\n", " cats_plotted.add(cat)\n", " fig_macro.add_trace(go.Scatter(\n", " x=[x], y=[y], mode=\"markers+text\",\n", " marker=dict(size=sz, color=color, opacity=0.75, line=dict(width=1.5, color=\"white\")),\n", " text=name, textposition=\"top center\", textfont=dict(size=9, color=\"#333\"),\n", " hovertext=f\"{name}
{cat}
{int(m_sz[i]):,} docs\", hoverinfo=\"text\",\n", " legendgroup=cat, name=cat, showlegend=show,\n", " ))\n", "fig_macro.update_layout(\n", " title=dict(text=\"Mapa intertópico — Macrotemas Substantivos\", font=dict(size=15), x=0.5),\n", " width=1100, height=750, xaxis=dict(visible=False), yaxis=dict(visible=False),\n", " plot_bgcolor=\"white\", paper_bgcolor=\"white\",\n", " legend=dict(title=\"Categoria\", font=dict(size=10), bgcolor=\"rgba(255,255,255,0.8)\"),\n", " margin=dict(l=20, r=20, t=60, b=20),\n", ")\n", "\n", "# ══════════════════════════════════════════════════\n", "# 7. Grafo semântico interativo\n", "# ══════════════════════════════════════════════════\n", "from sklearn.metrics.pairwise import cosine_similarity\n", "import networkx as nx\n", "\n", "sem_sim = cosine_similarity(topic_embs)\n", "np.fill_diagonal(sem_sim, -1.0)\n", "\n", "G = nx.Graph()\n", "for i, tid in enumerate(valid_topic_ids):\n", " G.add_node(tid,\n", " label=topic_metadata.get(tid, {}).get(\"rotulo_curto\", str(tid)),\n", " count=int(topic_info_full.loc[topic_info_full[\"Topic\"] == tid, \"Count\"].iloc[0]),\n", " macrotheme=int(topic_info_full.loc[topic_info_full[\"Topic\"] == tid, \"macrotheme_id\"].iloc[0]),\n", " categoria=topic_metadata.get(tid, {}).get(\"categoria_ampla\", \"Outro\"),\n", " )\n", "\n", "for i, tid_i in enumerate(valid_topic_ids):\n", " neighbors = np.argsort(-sem_sim[i])[:GRAPH_K]\n", " for j in neighbors:\n", " if i == j: continue\n", " score = float(sem_sim[i, j])\n", " if score < GRAPH_MIN_SEM_SIM: continue\n", " tid_j = valid_topic_ids[j]\n", " if not G.has_edge(tid_i, tid_j):\n", " G.add_edge(tid_i, tid_j, weight=score)\n", "\n", "n_g = len(valid_topic_ids)\n", "g_coords = UMAP2D(n_neighbors=min(15, n_g-1), n_components=2,\n", " min_dist=0.5, metric=\"cosine\", random_state=42).fit_transform(topic_embs)\n", "g_pos = {tid: (float(g_coords[i, 0]), float(g_coords[i, 1])) for i, tid in enumerate(valid_topic_ids)}\n", "\n", "_PALETTE = [\"#4E79A7\",\"#F28E2B\",\"#E15759\",\"#76B7B2\",\"#59A14F\",\"#EDC948\",\"#B07AA1\",\n", " \"#FF9DA7\",\"#9C755F\",\"#BAB0AC\",\"#AF7AA1\",\"#D37295\",\"#FABFD2\",\"#86BCB6\",\n", " \"#8CD17D\",\"#B6992D\",\"#499894\",\"#F1CE63\",\"#D4A6C8\",\"#79706E\"]\n", "macro_ids_sorted = sorted(topic_info_full[\"macrotheme_id\"].unique())\n", "macro_to_color = {m: _PALETTE[i % len(_PALETTE)] for i, m in enumerate(macro_ids_sorted)}\n", "\n", "edge_x, edge_y = [], []\n", "for u, v in G.edges():\n", " x0, y0 = g_pos[u]; x1, y1 = g_pos[v]\n", " edge_x += [x0, x1, None]; edge_y += [y0, y1, None]\n", "\n", "counts_g = np.array([G.nodes[n][\"count\"] for n in G.nodes()], dtype=float)\n", "sq_g = np.sqrt(counts_g)\n", "size_map = {n: 6 + 30 * (np.sqrt(G.nodes[n][\"count\"]) - sq_g.min()) / max(sq_g.max() - sq_g.min(), 1)\n", " for n in G.nodes()}\n", "\n", "nodes_by_macro = {}\n", "for n in G.nodes():\n", " mid = G.nodes[n][\"macrotheme\"]\n", " nodes_by_macro.setdefault(mid, []).append(n)\n", "\n", "fig_grafo = go.Figure()\n", "fig_grafo.add_trace(go.Scatter(x=edge_x, y=edge_y, mode=\"lines\",\n", " line=dict(width=0.3, color=\"#ccc\"), hoverinfo=\"none\"))\n", "\n", "macros_shown = set()\n", "for mid in macro_ids_sorted:\n", " if mid not in nodes_by_macro: continue\n", " nodes = nodes_by_macro[mid]\n", " color = macro_to_color[mid]\n", " mname = macro_label_map.get(mid, f\"Macro {mid}\")[:35]\n", " show = mid not in macros_shown; macros_shown.add(mid)\n", " fig_grafo.add_trace(go.Scatter(\n", " x=[g_pos[n][0] for n in nodes], y=[g_pos[n][1] for n in nodes],\n", " mode=\"markers\",\n", " marker=dict(size=[size_map[n] for n in nodes], color=color, opacity=0.8,\n", " line=dict(width=1, color=\"white\")),\n", " text=[f\"{G.nodes[n]['label']}
Macro: {mname}
{G.nodes[n]['categoria']}
{G.nodes[n]['count']:,} docs\"\n", " for n in nodes],\n", " hoverinfo=\"text\", legendgroup=mname, name=mname, showlegend=show,\n", " ))\n", "\n", "fig_grafo.update_layout(\n", " title=dict(text=\"Grafo de similaridade semântica\", font=dict(size=15), x=0.5),\n", " width=1200, height=850, xaxis=dict(visible=False), yaxis=dict(visible=False),\n", " plot_bgcolor=\"white\", paper_bgcolor=\"white\", hovermode=\"closest\",\n", " legend=dict(title=\"Macrotemas\", font=dict(size=8), bgcolor=\"rgba(255,255,255,0.9)\",\n", " itemsizing=\"constant\"),\n", " margin=dict(l=10, r=10, t=50, b=10),\n", ")\n", "\n", "# ══════════════════════════════════════════════════\n", "# 8. Evolução temporal\n", "# ══════════════════════════════════════════════════\n", "custom_labels = {tid: meta[\"rotulo_curto\"] for tid, meta in topic_metadata.items()}\n", "topic_model.set_topic_labels(custom_labels)\n", "\n", "timestamps = pd.to_datetime(df[\"created_at\"], errors=\"coerce\")\n", "mask_valid = timestamps.notna()\n", "docs_valid = [docs[i] for i in range(len(docs)) if mask_valid.iloc[i]]\n", "timestamps_valid = timestamps[mask_valid].tolist()\n", "\n", "topics_over_time = topic_model.topics_over_time(docs_valid, timestamps_valid, nr_bins=30)\n", "topics_over_time[\"Name\"] = topics_over_time[\"Topic\"].map(\n", " lambda t: custom_labels.get(t, f\"Tópico {t}\")\n", ")\n", "\n", "fig_temporal = topic_model.visualize_topics_over_time(\n", " topics_over_time, top_n_topics=12, custom_labels=True,\n", " title=\"Evolução temporal dos principais tópicos\",\n", " width=1000, height=520,\n", ")\n", "\n", "# ══════════════════════════════════════════════════\n", "# MONTAR HTML\n", "# ══════════════════════════════════════════════════\n", "figs = [\n", " (\"Top 25 Tópicos\", fig_top25),\n", " (\"Tópico × Status\", fig_heatmap),\n", " (\"Taxa Publicação\", fig_dotplot),\n", " (\"Evolução Temporal\", fig_temporal),\n", " (\"Intertópico BERTopic\", fig_inter_bert),\n", " (\"Intertópico LLM\", fig_inter_llm),\n", " (\"Macrotemas\", fig_macro),\n", " (\"Grafo Semântico\", fig_grafo),\n", "]\n", "\n", "tabs_html = '
'\n", "panels_html = \"\"\n", "\n", "for idx, (name, fig) in enumerate(figs):\n", " active = \"background:#4E79A7; color:white;\" if idx == 0 else \"background:#eee; color:#333;\"\n", " display = \"block\" if idx == 0 else \"none\"\n", " tabs_html += f''\n", " fig_html = pio.to_html(fig, include_plotlyjs=False, full_html=False)\n", " panels_html += f'
{fig_html}
'\n", "\n", "tabs_html += \"
\"\n", "\n", "js = f\"\"\"\n", "\n", "\"\"\"\n", "\n", "full_html = f\"\"\"\n", "\n", "\n", "Community Notes Brasil — Dashboard\n", "\n", "\n", "\n", "

Community Notes Brasil — Dashboard de Tópicos

\n", "

Pipeline: E5-Large-Instruct → BERTopic (UMAP 10d, HDBSCAN mcs=30/ms=5, KeyBERT+MMR) → Marco-Mini-Instruct i1-Q6_K

\n", "{summary_html}\n", "{tabs_html}\n", "{panels_html}\n", "{js}\n", "\n", "\"\"\"\n", "\n", "dashboard_path = Path(\"/content/drive/MyDrive/Compartilhados/community_notes_pt/sessao_bertopic/dashboard_community_notes.html\")\n", "dashboard_path.write_text(full_html, encoding=\"utf-8\")\n", "print(f\"Dashboard salvo: {dashboard_path}\")\n", "print(f\"Tamanho: {dashboard_path.stat().st_size / 1e6:.1f} MB\")\n", "print(f\"Abas: {', '.join(name for name, _ in figs)}\")" ], "metadata": { "colab": {}, "id": "ckjgfzR-3nRh" }, "id": "ckjgfzR-3nRh", "execution_count": null, "outputs": [] }, { "cell_type": "code", "source": [ "from google.colab import drive\n", "from pathlib import Path\n", "from bertopic import BERTopic\n", "import numpy as np\n", "import pandas as pd\n", "\n", "drive.mount(\"/content/drive\")\n", "\n", "BASE = Path(\"/content/drive/MyDrive/Compartilhados/community_notes_pt/sessao_bertopic\")\n", "SESSION = BASE / \"marco_mini_i1\"\n", "E5_SESSION = SESSION / \"e5_instruct\"\n", "\n", "# ── 1. Embeddings e5-instruct ──\n", "embeddings = np.load(SESSION / \"embeddings_tagged_e5-instruct.npy\")\n", "print(f\"Embeddings: {embeddings.shape}\")\n", "\n", "# ── 2. Modelo BERTopic (e5-instruct, 898 tópicos) ──\n", "topic_model = BERTopic.load(str(E5_SESSION / \"model\"))\n", "topics = topic_model.topics_\n", "print(f\"Modelo: {len(set(topics))-1} tópicos\")\n", "\n", "# ── 3. Metadados dos tópicos ──\n", "topic_meta_df = pd.read_parquet(E5_SESSION / \"topic_metadata_marco_mini.parquet\")\n", "topic_metadata = {\n", " int(row[\"topic\"]): {\n", " \"contexto_central\": row.get(\"contexto_central\", \"\"),\n", " \"categoria_ampla\": row.get(\"categoria_ampla\", \"Outro\"),\n", " \"rotulo_curto\": row.get(\"rotulo_curto\", \"\"),\n", " }\n", " for _, row in topic_meta_df.iterrows()\n", "}\n", "print(f\"Metadados: {len(topic_metadata)} tópicos\")\n", "\n", "# ── 4. Documentos anotados ──\n", "df = pd.read_parquet(E5_SESSION / \"notas_com_topicos_v3.parquet\")\n", "docs = df[\"doc\"].tolist()\n", "df_topics = df[df[\"topic\"] != -1].copy()\n", "print(f\"Docs: {len(df):,} | Com tópico: {len(df_topics):,}\")\n", "\n", "# ── 5. Macrotemas ──\n", "macro_summary = pd.read_csv(SESSION / \"macro_summary.csv\")\n", "macro_labels = {\n", " int(row[\"macrotheme_id\"]): {\n", " \"rotulo_macro\": row[\"rotulo_macro\"],\n", " \"categoria_dominante\": row[\"categoria_dominante\"],\n", " }\n", " for _, row in macro_summary.iterrows()\n", "}\n", "macro_label_map = {mid: v[\"rotulo_macro\"] for mid, v in macro_labels.items()}\n", "macro_cat_map = {mid: v[\"categoria_dominante\"] for mid, v in macro_labels.items()}\n", "print(f\"Macrotemas: {len(macro_labels)}\")\n", "\n", "# ── 6. Reconstruir topic_info_full ──\n", "valid_topic_ids = sorted(t for t in set(topics) if t != -1)\n", "topic_info_full = topic_model.get_topic_info().copy()\n", "topic_info_full = topic_info_full[topic_info_full[\"Topic\"] != -1].copy()\n", "\n", "tid_to_macro = df_topics.drop_duplicates(\"topic\").set_index(\"topic\")[\"macrotheme_id\"].to_dict()\n", "topic_info_full[\"macrotheme_id\"] = topic_info_full[\"Topic\"].map(tid_to_macro)\n", "topic_info_full[\"rotulo_curto\"] = topic_info_full[\"Topic\"].map(\n", " {t: topic_metadata.get(t, {}).get(\"rotulo_curto\", \"\") for t in valid_topic_ids}\n", ")\n", "\n", "# ── 7. Embeddings dos tópicos ──\n", "if hasattr(topic_model, \"topic_embeddings_\") and topic_model.topic_embeddings_ is not None:\n", " raw_emb = np.asarray(topic_model.topic_embeddings_)\n", " topic_info_tmp = topic_model.get_topic_info()\n", " tid_to_idx = dict(zip(topic_info_tmp[\"Topic\"], range(len(topic_info_tmp))))\n", " topic_embs = np.vstack([raw_emb[tid_to_idx[t]] for t in valid_topic_ids])\n", "else:\n", " centroids = []\n", " for tid in valid_topic_ids:\n", " mask = np.array(topics) == tid\n", " c = embeddings[mask].mean(axis=0)\n", " c /= max(np.linalg.norm(c), 1e-9)\n", " centroids.append(c)\n", " topic_embs = np.vstack(centroids)\n", "print(f\"Topic embeddings: {topic_embs.shape}\")\n", "\n", "# ── 8. Procedurais ──\n", "procedural_keywords = [\"comunidade\", \"comentário\", \"opinião pessoal\", \"nota da comunidade\",\n", " \"communitynotes\", \"sátira sem\", \"resposta em comentário\",\n", " \"contribuição da comunidade\", \"guia de notas\", \"uso das notas\"]\n", "\n", "for _, row in topic_meta_df.iterrows():\n", " tid = int(row[\"topic\"])\n", " text = f\"{row.get('rotulo_curto','')} {row.get('contexto_central','')}\".lower()\n", " if any(kw in text for kw in procedural_keywords):\n", " if tid in topic_metadata:\n", " topic_metadata[tid][\"categoria_ampla\"] = \"Procedural\"\n", "\n", "proc_macros = [mid for mid, cat in macro_cat_map.items() if cat == \"Procedural\"]\n", "proc_topics_kw = {tid for tid, m in topic_metadata.items() if m[\"categoria_ampla\"] == \"Procedural\"}\n", "proc_topics_macro = set(topic_info_full[topic_info_full[\"macrotheme_id\"].isin(proc_macros)][\"Topic\"])\n", "proc_topics_combined = proc_topics_kw | proc_topics_macro\n", "\n", "df_substantivo = df_topics[~df_topics[\"topic\"].isin(proc_topics_combined)].copy()\n", "topic_info_substantivo = topic_info_full[~topic_info_full[\"Topic\"].isin(proc_topics_combined)].copy()\n", "\n", "print(f\"Procedurais: {len(proc_topics_combined)} tópicos | {len(proc_macros)} macros\")\n", "print(f\"Substantivos: {len(df_substantivo):,} docs\")\n", "\n", "# ── 9. Config ──\n", "GRAPH_K = 6\n", "GRAPH_MIN_SEM_SIM = 0.60\n", "TOP_N_WORDS = 10\n", "\n", "print(\"\\nTudo carregado. Rode o bloco do dashboard.\")" ], "metadata": { "colab": {}, "id": "sHCJ1Mdk7Zy6" }, "id": "sHCJ1Mdk7Zy6", "execution_count": null, "outputs": [] } ] }