Spaces:
Sleeping
Sleeping
Upload 6 files
Browse files- app/database.py +61 -61
- requirements.txt +5 -5
- script/create_sqlite_db.py +40 -15
app/database.py
CHANGED
|
@@ -1,61 +1,61 @@
|
|
| 1 |
-
import sqlite3
|
| 2 |
-
from typing import List, Dict
|
| 3 |
-
import os
|
| 4 |
-
from huggingface_hub import hf_hub_download
|
| 5 |
-
|
| 6 |
-
# Télécharger le fichier SQLite depuis le dataset
|
| 7 |
-
# Créer un dossier temporaire pour le cache
|
| 8 |
-
# Répertoire writable dans le Space
|
| 9 |
-
cache_dir = "/tmp"
|
| 10 |
-
os.makedirs(cache_dir, exist_ok=True)
|
| 11 |
-
REPO_ID = "Loren/articles_db" # dataset HF
|
| 12 |
-
DB_NAME = 'articles.db'
|
| 13 |
-
hf_token = os.environ["API_HF_TOKEN"]
|
| 14 |
-
sqlite_path = hf_hub_download(
|
| 15 |
-
repo_id=REPO_ID,
|
| 16 |
-
filename=DB_NAME,
|
| 17 |
-
repo_type="dataset",
|
| 18 |
-
token=hf_token,
|
| 19 |
-
cache_dir=cache_dir
|
| 20 |
-
)
|
| 21 |
-
|
| 22 |
-
def get_connection(sqlite_path):
|
| 23 |
-
conn = sqlite3.connect(sqlite_path)
|
| 24 |
-
conn.row_factory = sqlite3.Row
|
| 25 |
-
return conn
|
| 26 |
-
|
| 27 |
-
def fetch_tags() -> List[str]:
|
| 28 |
-
"""Retourne tous les tags"""
|
| 29 |
-
conn = get_connection()
|
| 30 |
-
cur = conn.cursor()
|
| 31 |
-
cur.execute("SELECT tag_name FROM tags ORDER BY tag_name")
|
| 32 |
-
tags = [row["tag_name"] for row in cur.fetchall()]
|
| 33 |
-
conn.close()
|
| 34 |
-
return tags
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
def fetch_articles_by_tags(tags: List[str]) -> List[Dict]:
|
| 38 |
-
"""
|
| 39 |
-
Retourne les articles correspondant aux tags.
|
| 40 |
-
"""
|
| 41 |
-
if not tags:
|
| 42 |
-
return []
|
| 43 |
-
|
| 44 |
-
conn = get_connection()
|
| 45 |
-
conn.row_factory = sqlite3.Row
|
| 46 |
-
cur = conn.cursor()
|
| 47 |
-
|
| 48 |
-
# Créer la liste de placeholders "?" dynamiquement
|
| 49 |
-
placeholders = ",".join(["?"] * len(tags))
|
| 50 |
-
|
| 51 |
-
query = ("""SELECT a.article_id, a.article_title, a.article_url
|
| 52 |
-
FROM tags t, articles a, tag_article ta
|
| 53 |
-
WHERE ta.tag_id = t.tag_id
|
| 54 |
-
AND ta.article_id = a.article_id
|
| 55 |
-
AND t.tag_name IN (""" + placeholders + """)"""
|
| 56 |
-
)
|
| 57 |
-
|
| 58 |
-
cur.execute(query, tags)
|
| 59 |
-
results = [dict(row) for row in cur.fetchall()]
|
| 60 |
-
conn.close()
|
| 61 |
-
return results
|
|
|
|
| 1 |
+
import sqlite3
|
| 2 |
+
from typing import List, Dict
|
| 3 |
+
import os
|
| 4 |
+
from huggingface_hub import hf_hub_download
|
| 5 |
+
|
| 6 |
+
# Télécharger le fichier SQLite depuis le dataset
|
| 7 |
+
# Créer un dossier temporaire pour le cache
|
| 8 |
+
# Répertoire writable dans le Space
|
| 9 |
+
cache_dir = "/tmp"
|
| 10 |
+
os.makedirs(cache_dir, exist_ok=True)
|
| 11 |
+
REPO_ID = "Loren/articles_db" # dataset HF
|
| 12 |
+
DB_NAME = 'articles.db'
|
| 13 |
+
hf_token = os.environ["API_HF_TOKEN"]
|
| 14 |
+
sqlite_path = hf_hub_download(
|
| 15 |
+
repo_id=REPO_ID,
|
| 16 |
+
filename=DB_NAME,
|
| 17 |
+
repo_type="dataset",
|
| 18 |
+
token=hf_token,
|
| 19 |
+
cache_dir=cache_dir
|
| 20 |
+
)
|
| 21 |
+
|
| 22 |
+
def get_connection(sqlite_path):
|
| 23 |
+
conn = sqlite3.connect(sqlite_path)
|
| 24 |
+
conn.row_factory = sqlite3.Row
|
| 25 |
+
return conn
|
| 26 |
+
|
| 27 |
+
def fetch_tags() -> List[str]:
|
| 28 |
+
"""Retourne tous les tags"""
|
| 29 |
+
conn = get_connection()
|
| 30 |
+
cur = conn.cursor()
|
| 31 |
+
cur.execute("SELECT tag_name FROM tags ORDER BY tag_name")
|
| 32 |
+
tags = [row["tag_name"] for row in cur.fetchall()]
|
| 33 |
+
conn.close()
|
| 34 |
+
return tags
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def fetch_articles_by_tags(tags: List[str]) -> List[Dict]:
|
| 38 |
+
"""
|
| 39 |
+
Retourne les articles correspondant aux tags.
|
| 40 |
+
"""
|
| 41 |
+
if not tags:
|
| 42 |
+
return []
|
| 43 |
+
|
| 44 |
+
conn = get_connection()
|
| 45 |
+
conn.row_factory = sqlite3.Row
|
| 46 |
+
cur = conn.cursor()
|
| 47 |
+
|
| 48 |
+
# Créer la liste de placeholders "?" dynamiquement
|
| 49 |
+
placeholders = ",".join(["?"] * len(tags))
|
| 50 |
+
|
| 51 |
+
query = ("""SELECT a.article_id, a.article_title, a.article_url
|
| 52 |
+
FROM tags t, articles a, tag_article ta
|
| 53 |
+
WHERE ta.tag_id = t.tag_id
|
| 54 |
+
AND ta.article_id = a.article_id
|
| 55 |
+
AND t.tag_name IN (""" + placeholders + """)"""
|
| 56 |
+
)
|
| 57 |
+
|
| 58 |
+
cur.execute(query, tags)
|
| 59 |
+
results = [dict(row) for row in cur.fetchall()]
|
| 60 |
+
conn.close()
|
| 61 |
+
return results
|
requirements.txt
CHANGED
|
@@ -1,5 +1,5 @@
|
|
| 1 |
-
fastapi==0.109.2
|
| 2 |
-
uvicorn[standard]==0.23.2
|
| 3 |
-
pandas==2.1.1
|
| 4 |
-
pyarrow==12.0.1
|
| 5 |
-
huggingface_hub
|
|
|
|
| 1 |
+
fastapi==0.109.2
|
| 2 |
+
uvicorn[standard]==0.23.2
|
| 3 |
+
pandas==2.1.1
|
| 4 |
+
pyarrow==12.0.1
|
| 5 |
+
huggingface_hub==0.18.1
|
script/create_sqlite_db.py
CHANGED
|
@@ -1,6 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import sqlite3
|
| 2 |
import pandas as pd
|
| 3 |
import os
|
|
|
|
| 4 |
import itertools
|
| 5 |
import ast
|
| 6 |
import uuid
|
|
@@ -9,11 +21,15 @@ from pathlib import Path
|
|
| 9 |
|
| 10 |
# Initialisations
|
| 11 |
print("Initialisations ...")
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
filename="mon_fichier.parquet")
|
| 16 |
REPO_ID = "Loren/articles_db" # dataset HF
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
DB_NAME = 'articles.db'
|
| 18 |
SQLITE_FILE = DATA_DIR / DB_NAME
|
| 19 |
# Créer le dossier data s'il n'existe pas
|
|
@@ -64,10 +80,14 @@ print("Extraction des tags en une liste unique ...")
|
|
| 64 |
df['list_tags'] = df['tags'].apply(lambda x: ast.literal_eval(x) if isinstance(x, str) else [])
|
| 65 |
# Extraire tous les tags uniques
|
| 66 |
all_tags = list(set(itertools.chain.from_iterable(df['list_tags'])))
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
|
| 68 |
# Insertion des tags dans la table
|
| 69 |
print("Insertion des tags dans la table ...")
|
| 70 |
-
cur.executemany("INSERT INTO tags (tag_name) VALUES (?)", [(tag,) for tag in
|
| 71 |
|
| 72 |
# Récupération des correspondances tag_name -> tag_id
|
| 73 |
print("Récupération des correspondances tag_name -> tag_id ...")
|
|
@@ -88,17 +108,22 @@ for _, row in df.iterrows():
|
|
| 88 |
except Exception:
|
| 89 |
date_value = None
|
| 90 |
|
| 91 |
-
# Insertion dans la table Articles
|
| 92 |
-
cur.execute("""
|
| 93 |
-
INSERT INTO articles (article_id, article_title, article_text, article_url, article_authors, article_date)
|
| 94 |
-
VALUES (?, ?, ?, ?, ?, ?)""",
|
| 95 |
-
(article_id, row["title"], row["text"], row["url"], row["authors"], date_value))
|
| 96 |
-
|
| 97 |
# Association aux tags
|
|
|
|
| 98 |
for tag_name in row['list_tags']:
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 102 |
|
| 103 |
conn.commit()
|
| 104 |
conn.close()
|
|
@@ -110,7 +135,7 @@ upload_file(
|
|
| 110 |
path_in_repo=DB_NAME,
|
| 111 |
repo_id=REPO_ID,
|
| 112 |
repo_type="dataset",
|
| 113 |
-
token=
|
| 114 |
)
|
| 115 |
|
| 116 |
print("Traitement terminé.")
|
|
|
|
| 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
|
| 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
|
|
|
|
| 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
|
|
|
|
| 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 |
+
# Exclusion de certains tags pour question de volume de la database (il faut= 1 Go)
|
| 84 |
+
list_exclude = ['Politics', 'Startup', 'Covid 19', 'JavaScript', 'Business', 'Blockchain',
|
| 85 |
+
'Cryptocurrency', 'Bitcoin']
|
| 86 |
+
list_tags = [t for t in all_tags if t not in list_exclude]
|
| 87 |
|
| 88 |
# Insertion des tags dans la table
|
| 89 |
print("Insertion des tags dans la table ...")
|
| 90 |
+
cur.executemany("INSERT INTO tags (tag_name) VALUES (?)", [(tag,) for tag in list_tags])
|
| 91 |
|
| 92 |
# Récupération des correspondances tag_name -> tag_id
|
| 93 |
print("Récupération des correspondances tag_name -> tag_id ...")
|
|
|
|
| 108 |
except Exception:
|
| 109 |
date_value = None
|
| 110 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 111 |
# Association aux tags
|
| 112 |
+
ind_ok = True
|
| 113 |
for tag_name in row['list_tags']:
|
| 114 |
+
try:
|
| 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 |
+
except:
|
| 119 |
+
ind_ok = False
|
| 120 |
+
|
| 121 |
+
if ind_ok:
|
| 122 |
+
# Insertion dans la table Articles
|
| 123 |
+
cur.execute("""
|
| 124 |
+
INSERT INTO articles (article_id, article_title, article_text, article_url, article_authors, article_date)
|
| 125 |
+
VALUES (?, ?, ?, ?, ?, ?)""",
|
| 126 |
+
(article_id, row["title"], row["text"], row["url"], row["authors"], date_value))
|
| 127 |
|
| 128 |
conn.commit()
|
| 129 |
conn.close()
|
|
|
|
| 135 |
path_in_repo=DB_NAME,
|
| 136 |
repo_id=REPO_ID,
|
| 137 |
repo_type="dataset",
|
| 138 |
+
token=HF_TOKEN
|
| 139 |
)
|
| 140 |
|
| 141 |
print("Traitement terminé.")
|