Spaces:
Sleeping
Sleeping
Delete script/create_sqlite_db.py
Browse files- script/create_sqlite_db.py +0 -134
script/create_sqlite_db.py
DELETED
|
@@ -1,134 +0,0 @@
|
|
| 1 |
-
##############################################################################################
|
| 2 |
-
### Script de création de la base de données articles à partir du fichier parquet,
|
| 3 |
-
### correspondant au jeu d'essai : https://www.kaggle.com/code/fabiochiusano/medium-articles-simple-data-analysis
|
| 4 |
-
### Téléchargement du csv puis conversion en Parquet avec compression snappy :
|
| 5 |
-
### df = pd.read_csv("medium_articles.csv")
|
| 6 |
-
### df.to_parquet("medium_articles.parquet", engine="pyarrow", compression="snappy")
|
| 7 |
-
###
|
| 8 |
-
### Le fichier a été uploadé dans un dataset HF : Loren/articles_db
|
| 9 |
-
### Le script crée la base SQLite articles.db et l'upload dans le dataset HF
|
| 10 |
-
##############################################################################################
|
| 11 |
-
|
| 12 |
-
import sqlite3
|
| 13 |
-
import pandas as pd
|
| 14 |
-
import os
|
| 15 |
-
from dotenv import load_dotenv
|
| 16 |
-
import itertools
|
| 17 |
-
import ast
|
| 18 |
-
import uuid
|
| 19 |
-
from huggingface_hub import hf_hub_download, upload_file
|
| 20 |
-
from pathlib import Path
|
| 21 |
-
|
| 22 |
-
# Initialisations
|
| 23 |
-
print("Initialisations ...")
|
| 24 |
-
load_dotenv()
|
| 25 |
-
HF_TOKEN = os.getenv('API_HF_TOKEN')
|
| 26 |
-
DATA_DIR = Path("../../Data") # dossier parent du script
|
| 27 |
-
REPO_ID = "Loren/articles_db" # dataset HF
|
| 28 |
-
|
| 29 |
-
parquet_path = hf_hub_download(repo_id=REPO_ID,
|
| 30 |
-
filename="medium_articles.parquet",
|
| 31 |
-
repo_type="dataset")
|
| 32 |
-
|
| 33 |
-
DB_NAME = 'articles.db'
|
| 34 |
-
SQLITE_FILE = DATA_DIR / DB_NAME
|
| 35 |
-
# Créer le dossier data s'il n'existe pas
|
| 36 |
-
DATA_DIR.mkdir(exist_ok=True)
|
| 37 |
-
|
| 38 |
-
# Chargement des données
|
| 39 |
-
print("Chargement des données ...")
|
| 40 |
-
df = pd.read_parquet(parquet_path)
|
| 41 |
-
|
| 42 |
-
# Initialisations de la base SQLite
|
| 43 |
-
print("Initialisations de la base SQLite ...")
|
| 44 |
-
conn = sqlite3.connect(SQLITE_FILE)
|
| 45 |
-
cur = conn.cursor()
|
| 46 |
-
|
| 47 |
-
# Suppression des anciennes tables
|
| 48 |
-
cur.execute("DROP TABLE IF EXISTS tag_article")
|
| 49 |
-
cur.execute("DROP TABLE IF EXISTS tags")
|
| 50 |
-
cur.execute("DROP TABLE IF EXISTS articles")
|
| 51 |
-
|
| 52 |
-
# Création des tables Articles, Tags, et de la table d'association articles <-> tags
|
| 53 |
-
cur.execute("""
|
| 54 |
-
CREATE TABLE articles (
|
| 55 |
-
article_id TEXT PRIMARY KEY, -- UUID
|
| 56 |
-
article_title TEXT,
|
| 57 |
-
article_text TEXT,
|
| 58 |
-
article_url TEXT,
|
| 59 |
-
article_authors TEXT,
|
| 60 |
-
article_date TEXT -- YYYY-MM-DD
|
| 61 |
-
)""")
|
| 62 |
-
|
| 63 |
-
cur.execute("""
|
| 64 |
-
CREATE TABLE tags (
|
| 65 |
-
tag_id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 66 |
-
tag_name TEXT UNIQUE
|
| 67 |
-
)""")
|
| 68 |
-
|
| 69 |
-
cur.execute("""
|
| 70 |
-
CREATE TABLE tag_article (
|
| 71 |
-
tag_article_id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 72 |
-
article_id TEXT,
|
| 73 |
-
tag_id INTEGER,
|
| 74 |
-
FOREIGN KEY(article_id) REFERENCES articles(article_id),
|
| 75 |
-
FOREIGN KEY(tag_id) REFERENCES tags(tag_id)
|
| 76 |
-
)""")
|
| 77 |
-
|
| 78 |
-
# Extraction des tags en une liste unique
|
| 79 |
-
print("Extraction des tags en une liste unique ...")
|
| 80 |
-
df['list_tags'] = df['tags'].apply(lambda x: ast.literal_eval(x) if isinstance(x, str) else [])
|
| 81 |
-
# Extraire tous les tags uniques
|
| 82 |
-
all_tags = list(set(itertools.chain.from_iterable(df['list_tags'])))
|
| 83 |
-
|
| 84 |
-
# Insertion des tags dans la table
|
| 85 |
-
print("Insertion des tags dans la table ...")
|
| 86 |
-
cur.executemany("INSERT INTO tags (tag_name) VALUES (?)", [(tag,) for tag in all_tags])
|
| 87 |
-
|
| 88 |
-
# Récupération des correspondances tag_name -> tag_id
|
| 89 |
-
print("Récupération des correspondances tag_name -> tag_id ...")
|
| 90 |
-
cur.execute("SELECT tag_id, tag_name FROM tags")
|
| 91 |
-
dict_tag_map = {tag_name: tag_id for tag_id, tag_name in cur.fetchall()}
|
| 92 |
-
|
| 93 |
-
# Insertion des articles et table d'association dans les tables
|
| 94 |
-
print("Insertion des articles et table d'association dans les tables ...")
|
| 95 |
-
for _, row in df.iterrows():
|
| 96 |
-
# Détermination de l'id article
|
| 97 |
-
article_id = str(uuid.uuid4())
|
| 98 |
-
|
| 99 |
-
# Extraction de la date du timestamp
|
| 100 |
-
date_value = None
|
| 101 |
-
if pd.notna(row["timestamp"]):
|
| 102 |
-
try:
|
| 103 |
-
date_value = str(pd.to_datetime(row["timestamp"]).date())
|
| 104 |
-
except Exception:
|
| 105 |
-
date_value = None
|
| 106 |
-
|
| 107 |
-
# Insertion dans la table Articles
|
| 108 |
-
cur.execute("""
|
| 109 |
-
INSERT INTO articles (article_id, article_title, article_text, article_url, article_authors, article_date)
|
| 110 |
-
VALUES (?, ?, ?, ?, ?, ?)""",
|
| 111 |
-
(article_id, row["title"], row["text"], row["url"], row["authors"], date_value))
|
| 112 |
-
|
| 113 |
-
# Association aux tags
|
| 114 |
-
for tag_name in row['list_tags']:
|
| 115 |
-
tag_id = dict_tag_map[tag_name]
|
| 116 |
-
cur.execute("INSERT INTO tag_article (article_id, tag_id) VALUES (?, ?)",
|
| 117 |
-
(article_id, tag_id))
|
| 118 |
-
|
| 119 |
-
# Commit et fermeture de la connexion
|
| 120 |
-
print("Commit et fermeture de la connexion ...")
|
| 121 |
-
conn.commit()
|
| 122 |
-
conn.close()
|
| 123 |
-
|
| 124 |
-
# Upload dans le dataset hugging face
|
| 125 |
-
print("Upload dans le dataset hugging face ...")
|
| 126 |
-
upload_file(
|
| 127 |
-
path_or_fileobj=SQLITE_FILE,
|
| 128 |
-
path_in_repo=DB_NAME,
|
| 129 |
-
repo_id=REPO_ID,
|
| 130 |
-
repo_type="dataset",
|
| 131 |
-
token=HF_TOKEN
|
| 132 |
-
)
|
| 133 |
-
|
| 134 |
-
print("Traitement terminé.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|