om4r932 commited on
Commit
f2f17e7
·
1 Parent(s): 962e47e

Final version

Browse files
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ *.json filter=lfs diff=lfs merge=lfs -text
README.md CHANGED
@@ -1,11 +1,14 @@
1
  ---
2
- title: 3GPPindexers
3
- emoji: 💻
4
- colorFrom: purple
5
- colorTo: green
6
- sdk: docker
7
- pinned: false
 
 
8
  license: gpl-3.0
 
9
  ---
10
 
11
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
1
  ---
2
+ title: 3GPPIndexers
3
+ emoji: ⚙️
4
+ colorFrom: blue
5
+ colorTo: red
6
+ sdk: gradio
7
+ sdk_version: 5.29.0
8
+ app_file: app.py
9
+ pinned: true
10
  license: gpl-3.0
11
+ short_description: A Gradio app for indexing documents and specifications
12
  ---
13
 
14
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app.py ADDED
@@ -0,0 +1,264 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import datetime
2
+ import os
3
+ import warnings
4
+ import traceback
5
+ import gradio as gr
6
+ import subprocess
7
+ from huggingface_hub import Repository
8
+ from git import Repo
9
+ import requests
10
+
11
+ warnings.filterwarnings('ignore')
12
+
13
+ DOC_INDEXER = "indexer_multi.py"
14
+ SPEC_INDEXER = "spec_indexer_multi.py"
15
+ SPEC_DOC_INDEXER = "spec_doc_indexer_multi.py"
16
+ BM25_INDEXER = "bm25_maker.py"
17
+
18
+ DOC_INDEX_FILE = "indexed_docs.json"
19
+ SPEC_INDEX_FILE = "indexed_specifications.json"
20
+ SPEC_DOC_INDEX_FILE = "indexed_docs_content.zip"
21
+ BM25_INDEX_FILE = "bm25s.zip"
22
+
23
+ HF_SEARCH_REPO = "OrganizedProgrammers/3GPPDocFinder"
24
+ REPO_DIR = os.path.dirname(os.path.abspath(__file__))
25
+
26
+ def get_docs_stats():
27
+ if os.path.exists(DOC_INDEX_FILE):
28
+ import json
29
+ with open(DOC_INDEX_FILE, 'r', encoding='utf-8') as f:
30
+ data = json.load(f)
31
+ return len(data["docs"])
32
+ return 0
33
+
34
+ def get_specs_stats():
35
+ if os.path.exists(SPEC_INDEX_FILE):
36
+ import json
37
+ with open(SPEC_INDEX_FILE, 'r', encoding='utf-8') as f:
38
+ data = json.load(f)
39
+ return len(data["specs"])
40
+ return 0
41
+
42
+ def get_scopes_stats():
43
+ if os.path.exists(SPEC_INDEX_FILE):
44
+ import json
45
+ with open(SPEC_INDEX_FILE, 'r', encoding="utf-8") as f:
46
+ data = json.load(f)
47
+ return len(data['scopes'])
48
+ return 0
49
+
50
+ def check_permissions(user: str, token: str):
51
+ try:
52
+ req = requests.get("https://huggingface.co/api/whoami-v2", verify=False, headers={"Accept": "application/json", "Authorization": f"Bearer {token}"})
53
+ if req.status_code != 200:
54
+ return False
55
+ reqJson: dict = req.json()
56
+ if not reqJson.get("name") or reqJson['name'] != user:
57
+ return False
58
+ if not reqJson.get("orgs") or len(reqJson['orgs']) == 0:
59
+ return False
60
+ for org in reqJson['orgs']:
61
+ if "645cfa1b5ebf379fd6d8a339" == org['id']:
62
+ return True
63
+ if not reqJson.get('auth') or reqJson['auth'] == {}:
64
+ return False
65
+ if reqJson['auth']['accessToken']['role'] != "fineGrained":
66
+ return False
67
+ for scope in reqJson['auth']['accessToken']['fineGrained']['scoped']:
68
+ if scope['entity']['type'] == "org" and scope['entity']['_id'] == "645cfa1b5ebf379fd6d8a339" and all(perm in scope['permissions'] for perm in ['repo.write', 'repo.content.read']):
69
+ return True
70
+ return False
71
+ except Exception as e:
72
+ traceback.print_exception(e)
73
+ return False
74
+
75
+ def update_logged(user: str, token: str):
76
+ if check_permissions(user, token):
77
+ return gr.update(visible=False), gr.update(visible=True), gr.update(visible=True), gr.update(visible=True)
78
+ else:
79
+ return gr.update(visible=True), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False)
80
+
81
+ def commit_and_push_3gppindexers(user, token, files, message, current_log=""):
82
+ log = current_log + "\n"
83
+ repo = Repo(REPO_DIR)
84
+ origin = repo.remotes.origin
85
+ repo.config_writer().set_value("user", "name", "3GPP Indexer Automatic Git Tool").release()
86
+ repo.config_writer().set_value("user", "email", "[email protected]").release()
87
+ origin.pull()
88
+ log += "Git pull succeed !\n"
89
+ yield log
90
+
91
+ repo.git.add(files)
92
+ repo.index.commit(message)
93
+
94
+ try:
95
+ repo.git.push(f"https://{user}:{token}@huggingface.co/spaces/OrganizedProgrammers/3GPPIndexers")
96
+ log += "Git push succeed !\n"
97
+ yield log
98
+ log += "Wait for Huggingface to restart the Space\n"
99
+ yield log
100
+ except Exception as e:
101
+ log += f"Git push failed: {e}\n"
102
+ yield log
103
+
104
+ def commit_and_push_3gppdocfinder(token, files, message, current_log=""):
105
+ log = current_log + "\n"
106
+ if not token:
107
+ log += "No token provided. Skipping HuggingFace push.\n"
108
+ yield log
109
+ return
110
+
111
+ hf_repo_dir = os.path.join(REPO_DIR, "hf_spaces")
112
+ repo = None
113
+
114
+ if not os.path.exists(hf_repo_dir):
115
+ repo = Repository(
116
+ local_dir=hf_repo_dir,
117
+ repo_type="space",
118
+ clone_from=HF_SEARCH_REPO,
119
+ git_user="3GPP Indexer Automatic Git Tool",
120
+ git_email="[email protected]",
121
+ token=token,
122
+ skip_lfs_files=True
123
+ )
124
+ else:
125
+ repo = Repository(
126
+ local_dir=hf_repo_dir,
127
+ repo_type="space",
128
+ git_user="3GPP Indexer Automatic Git Tool",
129
+ git_email="[email protected]",
130
+ token=token,
131
+ skip_lfs_files=True
132
+ )
133
+
134
+ repo.git_pull()
135
+
136
+ # Copy artifact files to huggingface space
137
+ for f in files:
138
+ import shutil
139
+ shutil.copy2(f, os.path.join(hf_repo_dir, f))
140
+
141
+ repo.git_add(auto_lfs_track=True)
142
+ repo.git_commit(message)
143
+ repo.git_push()
144
+
145
+ log += "Pushed to HuggingFace.\n"
146
+ yield log
147
+
148
+ def refresh_stats():
149
+ return str(get_docs_stats()), str(get_specs_stats()), str(get_scopes_stats())
150
+
151
+ def stream_script_output(script_path, current_log=""):
152
+ accumulated_output = current_log
153
+
154
+ process = subprocess.Popen(
155
+ ["python", script_path],
156
+ stdout=subprocess.PIPE,
157
+ stderr=subprocess.STDOUT,
158
+ bufsize=1,
159
+ universal_newlines=True,
160
+ )
161
+
162
+ for line in process.stdout:
163
+ accumulated_output += line
164
+ yield accumulated_output
165
+
166
+ process.stdout.close()
167
+ process.wait()
168
+
169
+ yield accumulated_output
170
+
171
+ def index_documents(user, token):
172
+ log_output = "⏳ Indexation en cours...\n"
173
+ # Désactiver tous les boutons
174
+ yield gr.update(interactive=False), gr.update(interactive=False), gr.update(interactive=False), log_output
175
+
176
+ # Lancer l'indexation
177
+ if not check_permissions(user, token):
178
+ log_output += "❌ Identifiants invalides\n"
179
+ yield gr.update(interactive=True), gr.update(interactive=True), gr.update(interactive=True), log_output
180
+ return
181
+
182
+ for log in stream_script_output(DOC_INDEXER, log_output):
183
+ yield gr.update(interactive=False), gr.update(interactive=False), gr.update(interactive=False), log
184
+ log_output = log
185
+
186
+ d = datetime.today().strftime("%d/%m/%Y-%H:%M:%S")
187
+
188
+ for log in commit_and_push_3gppdocfinder(token, [DOC_INDEX_FILE], f"Update documents indexer via Indexer: {d}", log_output):
189
+ yield gr.update(interactive=False), gr.update(interactive=False), gr.update(interactive=False), log
190
+ log_output = log
191
+
192
+ for log in commit_and_push_3gppindexers(user, token, [DOC_INDEX_FILE], f"Update documents indexer via Indexer: {d}", log_output):
193
+ yield gr.update(interactive=False), gr.update(interactive=False), gr.update(interactive=False), log
194
+ log_output = log
195
+
196
+ # Réactiver les boutons à la fin
197
+ log_output += "✅ Terminé.\n"
198
+ yield gr.update(interactive=True), gr.update(interactive=True), gr.update(interactive=True), log_output
199
+
200
+ def index_specifications(user, token):
201
+ log_output = "⏳ Indexation en cours...\n"
202
+ # Désactiver tous les boutons
203
+ yield gr.update(interactive=False), gr.update(interactive=False), gr.update(interactive=False), log_output
204
+
205
+ # Lancer l'indexation
206
+ if not check_permissions(user, token):
207
+ log_output += "❌ Identifiants invalides\n"
208
+ yield gr.update(interactive=True), gr.update(interactive=True), gr.update(interactive=True), log_output
209
+ return
210
+
211
+ for log in stream_script_output(SPEC_INDEXER, log_output):
212
+ yield gr.update(interactive=False), gr.update(interactive=False), gr.update(interactive=False), log
213
+ log_output = log
214
+
215
+ for log in stream_script_output(SPEC_DOC_INDEXER, log_output):
216
+ yield gr.update(interactive=False), gr.update(interactive=False), gr.update(interactive=False), log
217
+ log_output = log
218
+
219
+ for log in stream_script_output(BM25_INDEXER, log_output):
220
+ yield gr.update(interactive=False), gr.update(interactive=False), gr.update(interactive=False), log
221
+ log_output = log
222
+
223
+ d = datetime.today().strftime("%d/%m/%Y-%H:%M:%S")
224
+
225
+ for log in commit_and_push_3gppdocfinder(token, [SPEC_DOC_INDEX_FILE, BM25_INDEX_FILE, SPEC_INDEX_FILE], f"Update specifications indexer via Indexer: {d}", log_output):
226
+ yield gr.update(interactive=False), gr.update(interactive=False), gr.update(interactive=False), log
227
+ log_output = log
228
+
229
+ for log in commit_and_push_3gppindexers(user, token, [SPEC_DOC_INDEX_FILE, BM25_INDEX_FILE, SPEC_INDEX_FILE], f"Update specifications indexer via Indexer: {d}", log_output):
230
+ yield gr.update(interactive=False), gr.update(interactive=False), gr.update(interactive=False), log
231
+ log_output = log
232
+
233
+ # Réactiver les boutons à la fin
234
+ log_output += "✅ Terminé.\n"
235
+ yield gr.update(interactive=True), gr.update(interactive=True), gr.update(interactive=True), log_output
236
+
237
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
238
+ gr.Markdown("## 📄 3GPP Indexers")
239
+
240
+ with gr.Row() as r1:
241
+ with gr.Column():
242
+ git_user = gr.Textbox(label="Git user (for push/pull indexes)")
243
+ git_pass = gr.Textbox(label="Git Token", type="password")
244
+ btn_login = gr.Button("Login", variant="primary")
245
+
246
+ with gr.Row(visible=False) as r2:
247
+ with gr.Column():
248
+ doc_count = gr.Textbox(label="Docs Indexed", value=str(get_docs_stats()), interactive=False)
249
+ btn_docs = gr.Button("Re-index Documents", variant="primary")
250
+ with gr.Column():
251
+ spec_count = gr.Textbox(label="Specs Indexed", value=str(get_specs_stats()), interactive=False)
252
+ btn_specs = gr.Button("Re-index Specifications", variant="primary")
253
+ with gr.Column():
254
+ scope_count = gr.Textbox(label="Scopes Indexed", value=str(get_scopes_stats()), interactive=False)
255
+
256
+ out = gr.Textbox(label="Output/Log", lines=13, autoscroll=True, visible=False)
257
+ refresh = gr.Button(value="🔄 Refresh Stats", visible=False)
258
+
259
+ btn_login.click(update_logged, inputs=[git_user, git_pass], outputs=[r1, r2, out, refresh])
260
+ btn_docs.click(index_documents, inputs=[git_user, git_pass], outputs=[btn_docs, btn_specs, refresh, out])
261
+ btn_specs.click(index_specifications, inputs=[git_user, git_pass], outputs=[btn_docs, btn_specs, refresh, out])
262
+ refresh.click(refresh_stats, outputs=[doc_count, spec_count, scope_count])
263
+
264
+ demo.launch()
bm25_maker.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import shutil
2
+ import zipfile
3
+ import json
4
+ import bm25s
5
+
6
+ import nltk
7
+ from nltk.stem import WordNetLemmatizer
8
+
9
+ nltk.download("wordnet")
10
+ lemmatizer = WordNetLemmatizer()
11
+ indexer_id = "3gpp_bm25_docs"
12
+ unique_specs = set()
13
+
14
+ with open("indexed_specifications.json", "r") as f:
15
+ spec_data = json.load(f)["specs"]
16
+ with zipfile.ZipFile(open("indexed_docs_content.zip", "rb")) as zf:
17
+ for file_name in zf.namelist():
18
+ if file_name.endswith(".json"):
19
+ doc_bytes = zf.read(file_name)
20
+ try:
21
+ doc_data = json.loads(doc_bytes.decode("utf-8"))
22
+ print("Documents loaded successfully !")
23
+ except json.JSONDecodeError as e:
24
+ print(f"Error while decoding the JSON file {file_name}: {e}")
25
+
26
+ corpus_json = []
27
+
28
+ for _, specification in spec_data.items():
29
+ full_text = f"{specification['id']} - {specification['title']}\n\n\n"
30
+ if specification['id'] in unique_specs:
31
+ continue
32
+ document = doc_data.get(specification['id'], None)
33
+ if document is None: continue
34
+ if not isinstance(document, str):
35
+ full_text += "\n".join([f"{title}\n\n{document[title]}" for title in document.keys()])
36
+ corpus_json.append({"text": lemmatizer.lemmatize(full_text), "metadata": {
37
+ "id": specification['id'],
38
+ "title": specification['title'],
39
+ "version": specification['version'],
40
+ "release": specification['release'],
41
+ "type": specification['type'],
42
+ "working_group": specification['working_group'],
43
+ "url": specification['url'],
44
+ "scope": specification['scope']
45
+ }})
46
+ unique_specs.add(specification['id'])
47
+ else:
48
+ print(f"Skipping {specification['id']}")
49
+ unique_specs.add(specification['id'])
50
+
51
+ corpus_text = [doc["text"] for doc in corpus_json]
52
+ corpus_tokens = bm25s.tokenize(corpus_text, stopwords="en")
53
+
54
+ retriever = bm25s.BM25(corpus=corpus_json)
55
+ retriever.index(corpus_tokens)
56
+
57
+ retriever.save(indexer_id)
58
+
59
+ shutil.make_archive("bm25s", 'zip', '.', indexer_id)
bm25s.zip ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5dd3204be1335433d0d36b829531cd0919d0753a9e8756518d6f892e4389f1af
3
+ size 123131939
indexed_docs.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ecf8d4a88b0db3166e370fb8c1948615014bae1b305b8b0d9e290be1dff7e15b
3
+ size 69547140
indexed_docs_content.zip ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1d03432cab66c8b3c10fd06c5b22661232d7afd0c4a84b5b9e9d17a81c7f5245
3
+ size 99287891
indexed_specifications.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a6f7f727a937de550fefde356e3a9b79a48f31401bc70fca6ed720884820b3d6
3
+ size 41181773
indexer_multi.py ADDED
@@ -0,0 +1,286 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import datetime
2
+ import requests
3
+ from bs4 import BeautifulSoup
4
+ import json
5
+ import os
6
+ import time
7
+ import warnings
8
+ import re
9
+ import concurrent.futures
10
+ import threading
11
+ from typing import List, Dict, Any
12
+
13
+ warnings.filterwarnings("ignore")
14
+
15
+ class TsgDocIndexer:
16
+ def __init__(self, max_workers=10):
17
+ self.main_ftp_url = "https://www.3gpp.org/ftp"
18
+ self.indexer_file = "indexed_docs.json"
19
+ self.indexer, self.latest_date = self.load_indexer()
20
+ self.valid_doc_pattern = re.compile(r'^(S[1-6P]|C[1-6P])-\d+', flags=re.IGNORECASE)
21
+ self.max_workers = max_workers
22
+
23
+ # Verrous pour les opérations thread-safe
24
+ self.print_lock = threading.Lock()
25
+ self.indexer_lock = threading.Lock()
26
+
27
+ # Compteurs pour le suivi
28
+ self.total_indexed = 0
29
+ self.processed_count = 0
30
+ self.total_count = 0
31
+
32
+ def load_indexer(self):
33
+ """Load existing index if available"""
34
+ if os.path.exists(self.indexer_file):
35
+ with open(self.indexer_file, "r", encoding="utf-8") as f:
36
+ x = json.load(f)
37
+ return x["docs"], x["last_indexed_date"]
38
+ return {}, None
39
+
40
+ def save_indexer(self):
41
+ """Save the updated index"""
42
+ with open(self.indexer_file, "w", encoding="utf-8") as f:
43
+ today = datetime.today()
44
+ self.latest_date = today.strftime("%d/%m/%Y-%H:%M:%S")
45
+ output = {"docs": self.indexer, "last_indexed_date": self.latest_date}
46
+ json.dump(output, f, indent=4, ensure_ascii=False)
47
+
48
+ def get_docs_from_url(self, url):
49
+ """Récupérer la liste des documents/répertoires depuis une URL"""
50
+ try:
51
+ response = requests.get(url, verify=False, timeout=10)
52
+ soup = BeautifulSoup(response.text, "html.parser")
53
+ return [item.get_text() for item in soup.select("tr td a")]
54
+ except Exception as e:
55
+ with self.print_lock:
56
+ print(f"Erreur lors de l'accès à {url}: {e}")
57
+ return []
58
+
59
+ def is_valid_document_pattern(self, filename):
60
+ """Vérifier si le nom de fichier correspond au motif requis"""
61
+ return bool(self.valid_doc_pattern.match(filename))
62
+
63
+ def is_zip_file(self, filename):
64
+ """Vérifier si le fichier est un ZIP"""
65
+ return filename.lower().endswith('.zip')
66
+
67
+ def extract_doc_id(self, filename):
68
+ """Extraire l'identifiant du document à partir du nom de fichier s'il correspond au motif"""
69
+ if self.is_valid_document_pattern(filename):
70
+ match = self.valid_doc_pattern.match(filename)
71
+ if match:
72
+ # Retourner le motif complet (comme S1-12345)
73
+ full_id = filename.split('.')[0] # Enlever l'extension si présente
74
+ return full_id.split('_')[0] # Enlever les suffixes après underscore si présents
75
+ return None
76
+
77
+ def process_zip_files(self, files_list, base_url, workshop=False):
78
+ """Traiter une liste de fichiers pour trouver et indexer les ZIP valides"""
79
+ indexed_count = 0
80
+
81
+ for file in files_list:
82
+ if file in ['./', '../', 'ZIP/', 'zip/']:
83
+ continue
84
+
85
+ # Vérifier si c'est un fichier ZIP et s'il correspond au motif
86
+ if self.is_zip_file(file) and (self.is_valid_document_pattern(file) or workshop):
87
+ file_url = f"{base_url}/{file}"
88
+
89
+ # Extraire l'ID du document
90
+ doc_id = self.extract_doc_id(file)
91
+ if doc_id is None:
92
+ doc_id = file.split('.')[0]
93
+ if doc_id:
94
+ # Vérifier si ce fichier est déjà indexé
95
+ with self.indexer_lock:
96
+ if doc_id in self.indexer and self.indexer[doc_id] == file_url:
97
+ continue
98
+
99
+ # Ajouter ou mettre à jour l'index
100
+ self.indexer[doc_id] = file_url
101
+ indexed_count += 1
102
+ self.total_indexed += 1
103
+
104
+ return indexed_count
105
+
106
+ def process_meeting(self, meeting, wg_url, workshop=False):
107
+ """Traiter une réunion individuelle avec multithreading"""
108
+ try:
109
+ if meeting in ['./', '../']:
110
+ return 0
111
+
112
+ meeting_url = f"{wg_url}/{meeting}"
113
+
114
+ with self.print_lock:
115
+ print(f" Vérification de la réunion: {meeting}")
116
+
117
+ # Vérifier le contenu de la réunion
118
+ meeting_contents = self.get_docs_from_url(meeting_url)
119
+
120
+ key = None
121
+ if "docs" in [x.lower() for x in meeting_contents]:
122
+ key = "docs"
123
+ elif "tdocs" in [x.lower() for x in meeting_contents]:
124
+ key = "tdocs"
125
+
126
+ if key is not None:
127
+ docs_url = f"{meeting_url}/{key}"
128
+
129
+ with self.print_lock:
130
+ print(f" Vérification des documents dans {docs_url}")
131
+
132
+ # Récupérer la liste des fichiers dans le dossier Docs
133
+ docs_files = self.get_docs_from_url(docs_url)
134
+
135
+ # 1. Indexer les fichiers ZIP directement dans le dossier Docs
136
+ docs_indexed_count = self.process_zip_files(docs_files, docs_url, workshop)
137
+
138
+ if docs_indexed_count > 0:
139
+ with self.print_lock:
140
+ print(f" {docs_indexed_count} nouveaux fichiers ZIP indexés dans Docs")
141
+
142
+ # 2. Vérifier le sous-dossier ZIP s'il existe
143
+ if "zip" in [x.lower() for x in docs_files]:
144
+ zip_url = f"{docs_url}/zip"
145
+
146
+ with self.print_lock:
147
+ print(f" Vérification du dossier ZIP: {zip_url}")
148
+
149
+ # Récupérer les fichiers dans le sous-dossier ZIP
150
+ zip_files = self.get_docs_from_url(zip_url)
151
+
152
+ # Indexer les fichiers ZIP dans le sous-dossier ZIP
153
+ zip_indexed_count = self.process_zip_files(zip_files, zip_url, workshop)
154
+
155
+ if zip_indexed_count > 0:
156
+ with self.print_lock:
157
+ print(f" {zip_indexed_count} nouveaux fichiers ZIP indexés dans le dossier ZIP")
158
+
159
+ # Mise à jour du compteur de progression
160
+ with self.indexer_lock:
161
+ self.processed_count += 1
162
+
163
+ # Affichage de la progression
164
+ with self.print_lock:
165
+ progress = (self.processed_count / self.total_count) * 100 if self.total_count > 0 else 0
166
+ print(f"\rProgression: {self.processed_count}/{self.total_count} réunions traitées ({progress:.1f}%)", end="")
167
+
168
+ return 1 # Réunion traitée avec succès
169
+
170
+ except Exception as e:
171
+ with self.print_lock:
172
+ print(f"\nErreur lors du traitement de la réunion {meeting}: {str(e)}")
173
+ return 0
174
+
175
+ def process_workgroup(self, wg, main_url):
176
+ """Traiter un groupe de travail avec multithreading pour ses réunions"""
177
+ if wg in ['./', '../']:
178
+ return
179
+
180
+ wg_url = f"{main_url}/{wg}"
181
+
182
+ with self.print_lock:
183
+ print(f" Vérification du groupe de travail: {wg}")
184
+
185
+ # Récupérer les dossiers de réunion
186
+ meeting_folders = self.get_docs_from_url(wg_url)
187
+
188
+ # Ajouter au compteur total
189
+ self.total_count += len([m for m in meeting_folders if m not in ['./', '../']])
190
+
191
+ # Utiliser ThreadPoolExecutor pour traiter les réunions en parallèle
192
+ with concurrent.futures.ThreadPoolExecutor(max_workers=self.max_workers) as executor:
193
+ futures = [executor.submit(self.process_meeting, meeting, wg_url)
194
+ for meeting in meeting_folders if meeting not in ['./', '../']]
195
+
196
+ # Attendre que toutes les tâches soient terminées
197
+ concurrent.futures.wait(futures)
198
+
199
+ # Sauvegarder après chaque groupe de travail
200
+ with self.indexer_lock:
201
+ self.save_indexer()
202
+
203
+ def index_all_tdocs(self):
204
+ """Indexer tous les documents ZIP dans la structure FTP 3GPP avec multithreading"""
205
+ print("Démarrage de l'indexation des documents ZIP 3GPP (S1-S6, SP, C1-C6, CP)...")
206
+
207
+ start_time = time.time()
208
+ docs_count_before = len(self.indexer)
209
+
210
+ # Principaux groupes TSG
211
+ main_groups = ["tsg_sa", "tsg_ct"] # Ajouter d'autres si nécessaire
212
+
213
+ for main_tsg in main_groups:
214
+ print(f"\nIndexation de {main_tsg.upper()}...")
215
+
216
+ main_url = f"{self.main_ftp_url}/{main_tsg}"
217
+
218
+ # Récupérer les groupes de travail
219
+ workgroups = self.get_docs_from_url(main_url)
220
+
221
+ # Traiter chaque groupe de travail séquentiellement
222
+ # (mais les réunions à l'intérieur seront traitées en parallèle)
223
+ for wg in workgroups:
224
+ self.process_workgroup(wg, main_url)
225
+
226
+ docs_count_after = len(self.indexer)
227
+ new_docs_count = docs_count_after - docs_count_before
228
+
229
+ print(f"\nIndexation terminée en {time.time() - start_time:.2f} secondes")
230
+ print(f"Nouveaux documents ZIP indexés: {new_docs_count}")
231
+ print(f"Total des documents dans l'index: {docs_count_after}")
232
+
233
+ return self.indexer
234
+
235
+ def index_all_workshops(self):
236
+ print("Démarrage de l'indexation des workshops ZIP 3GPP...")
237
+ start_time = time.time()
238
+ docs_count_before = len(self.indexer)
239
+
240
+ print("\nIndexation du dossier 'workshop'")
241
+ main_url = f"{self.main_ftp_url}/workshop"
242
+
243
+ # Récupérer les dossiers de réunion
244
+ meeting_folders = self.get_docs_from_url(main_url)
245
+
246
+ # Ajouter au compteur total
247
+ self.total_count += len([m for m in meeting_folders if m not in ['./', '../']])
248
+
249
+ # Utiliser ThreadPoolExecutor pour traiter les réunions en parallèle
250
+ with concurrent.futures.ThreadPoolExecutor(max_workers=self.max_workers) as executor:
251
+ futures = [executor.submit(self.process_meeting, meeting, main_url, workshop=True)
252
+ for meeting in meeting_folders if meeting not in ['./', '../']]
253
+ concurrent.futures.wait(futures)
254
+
255
+ # Sauvegarder après chaque groupe de travail
256
+ with self.indexer_lock:
257
+ self.save_indexer()
258
+
259
+ docs_count_after = len(self.indexer)
260
+ new_docs_count = docs_count_after - docs_count_before
261
+
262
+ print(f"\nIndexation terminée en {time.time() - start_time:.2f} secondes")
263
+ print(f"Nouveaux documents ZIP indexés: {new_docs_count}")
264
+ print(f"Total des documents dans l'index: {docs_count_after}")
265
+
266
+ return self.indexer
267
+
268
+
269
+
270
+ def main():
271
+ # Nombre de workers pour le multithreading (ajustable selon les ressources disponibles)
272
+ max_workers = 64
273
+
274
+ indexer = TsgDocIndexer(max_workers=max_workers)
275
+
276
+ try:
277
+ indexer.index_all_tdocs()
278
+ indexer.index_all_workshops()
279
+ except Exception as e:
280
+ print(f"Erreur lors de l'indexation: {e}")
281
+ finally:
282
+ indexer.save_indexer()
283
+ print("Index sauvegardé.")
284
+
285
+ if __name__ == "__main__":
286
+ main()
packages.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ libreoffice
2
+ libreoffice-writer
requirements.txt ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ gradio
2
+ requests
3
+ beautifulsoup4
4
+ gitpython
5
+ huggingface_hub
6
+ lxml
7
+ scikit-learn
8
+ bm25s[full]
9
+ nltk
spec_doc_indexer_multi.py ADDED
@@ -0,0 +1,291 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import datetime
2
+ import time
3
+ import sys
4
+ import json
5
+ import traceback
6
+ import requests
7
+ import zipfile
8
+ import uuid
9
+ import os
10
+ import re
11
+ import subprocess
12
+ import concurrent.futures
13
+ import threading
14
+ from io import StringIO, BytesIO
15
+ from typing import List, Dict, Any
16
+
17
+ import pandas as pd
18
+ import numpy as np
19
+ import warnings
20
+
21
+ warnings.filterwarnings("ignore")
22
+
23
+ # Caractères pour le formatage des versions
24
+ chars = "0123456789abcdefghijklmnopqrstuvwxyz"
25
+
26
+ # Verrous pour les opérations thread-safe
27
+ print_lock = threading.Lock()
28
+ dict_lock = threading.Lock()
29
+ scope_lock = threading.Lock()
30
+
31
+ # Dictionnaires globaux
32
+ indexed_specifications = {}
33
+ documents_by_spec_num = {}
34
+ processed_count = 0
35
+ total_count = 0
36
+
37
+ def get_text(specification: str, version: str):
38
+ """Récupère les bytes du PDF à partir d'une spécification et d'une version."""
39
+ doc_id = specification
40
+ series = doc_id.split(".")[0]
41
+
42
+ response = requests.get(
43
+ f"https://www.3gpp.org/ftp/Specs/archive/{series}_series/{doc_id}/{doc_id.replace('.', '')}-{version}.zip",
44
+ verify=False,
45
+ headers={"User-Agent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'}
46
+ )
47
+
48
+ if response.status_code != 200:
49
+ raise Exception(f"Téléchargement du ZIP échoué pour {specification}-{version}")
50
+
51
+ zip_bytes = BytesIO(response.content)
52
+
53
+ with zipfile.ZipFile(zip_bytes) as zf:
54
+ for file_name in zf.namelist():
55
+ if file_name.endswith("zip"):
56
+ print("Another ZIP !")
57
+ zip_bytes = BytesIO(zf.read(file_name))
58
+ zf = zipfile.ZipFile(zip_bytes)
59
+ for file_name2 in zf.namelist():
60
+ if file_name2.endswith("doc") or file_name2.endswith("docx"):
61
+ if "cover" in file_name2.lower():
62
+ print("COVER !")
63
+ continue
64
+ ext = file_name2.split(".")[-1]
65
+ doc_bytes = zf.read(file_name2)
66
+ temp_id = str(uuid.uuid4())
67
+ input_path = f"/tmp/{temp_id}.{ext}"
68
+ output_path = f"/tmp/{temp_id}.txt"
69
+
70
+ with open(input_path, "wb") as f:
71
+ f.write(doc_bytes)
72
+
73
+ subprocess.run([
74
+ "libreoffice",
75
+ "--headless",
76
+ "--convert-to", "txt",
77
+ "--outdir", "/tmp",
78
+ input_path
79
+ ], check=True)
80
+
81
+ with open(output_path, "r") as f:
82
+ txt_data = [line.strip() for line in f if line.strip()]
83
+
84
+ os.remove(input_path)
85
+ os.remove(output_path)
86
+ return txt_data
87
+ elif file_name.endswith("doc") or file_name.endswith("docx"):
88
+ if "cover" in file_name.lower():
89
+ print("COVER !")
90
+ continue
91
+ ext = file_name.split(".")[-1]
92
+ doc_bytes = zf.read(file_name)
93
+ temp_id = str(uuid.uuid4())
94
+ input_path = f"/tmp/{temp_id}.{ext}"
95
+ output_path = f"/tmp/{temp_id}.txt"
96
+
97
+ print("Ecriture")
98
+ with open(input_path, "wb") as f:
99
+ f.write(doc_bytes)
100
+
101
+ print("Convertissement")
102
+ subprocess.run([
103
+ "libreoffice",
104
+ "--headless",
105
+ "--convert-to", "txt",
106
+ "--outdir", "/tmp",
107
+ input_path
108
+ ], check=True)
109
+
110
+ print("Ecriture TXT")
111
+ with open(output_path, "r", encoding="utf-8") as f:
112
+ txt_data = [line.strip() for line in f if line.strip()]
113
+
114
+ os.remove(input_path)
115
+ os.remove(output_path)
116
+ return txt_data
117
+
118
+ raise Exception(f"Aucun fichier .doc/.docx trouvé dans le ZIP pour {specification}-{version}")
119
+
120
+ def get_spec_content(specification: str, version: str):
121
+ text = get_text(specification, version)
122
+ forewords = []
123
+ for x in range(len(text)):
124
+ line = text[x]
125
+ if "Foreword" in line:
126
+ forewords.append(x)
127
+ if len(forewords) >= 2:
128
+ break
129
+
130
+ toc_brut = text[forewords[0]:forewords[1]]
131
+ chapters = []
132
+ for line in toc_brut:
133
+ x = line.split("\t")
134
+ if re.search(r"^\d+\t[\ \S]+", line):
135
+ chapters.append(x[0] if len(x) == 1 else "\t".join(x[:2]))
136
+ if re.search(r"^\d+\.\d+\t[\ \S]+", line):
137
+ chapters.append(x[0] if len(x) == 1 else "\t".join(x[:2]))
138
+ if re.search(r"^\d+\.\d+\.\d+\t[\ \S]+", line):
139
+ chapters.append(x[0] if len(x) == 1 else "\t".join(x[:2]))
140
+ if re.search(r"^\d+\.\d+\.\d+.\d+\t[\ \S]+", line):
141
+ chapters.append(x[0] if len(x) == 1 else "\t".join(x[:2]))
142
+ if re.search(r"^\d+\.\d+\.\d+.\d+.\d+\t[\ \S]+", line):
143
+ chapters.append(x[0] if len(x) == 1 else "\t".join(x[:2]))
144
+
145
+ real_toc_indexes = {}
146
+
147
+ for chapter in chapters:
148
+ try:
149
+ x = text.index(chapter)
150
+ real_toc_indexes[chapter] = x
151
+ except ValueError as e:
152
+ try:
153
+ number = chapter.split("\t")[0] + "\t"
154
+ for line in text[forewords[1]:]:
155
+ if number in line:
156
+ x = text.index(line)
157
+ real_toc_indexes[line] = x
158
+ break
159
+ except:
160
+ real_toc_indexes[chapter] = -float("inf")
161
+
162
+ document = {}
163
+ toc = list(real_toc_indexes.keys())
164
+ index_toc = list(real_toc_indexes.values())
165
+ curr_index = 0
166
+ for x in range(1, len(toc)):
167
+ document[toc[curr_index].replace("\t", " ")] = re.sub(r"[\ \t]+", " ", "\n".join(text[index_toc[curr_index]+1:index_toc[x]]))
168
+ curr_index = x
169
+
170
+ document[toc[curr_index].replace("\t"," ")] = re.sub(r"\s+", " ", " ".join(text[index_toc[curr_index]+1:]))
171
+ return document
172
+
173
+ def process_specification(spec: Dict[str, Any], columns: List[str]) -> None:
174
+ """Traite une spécification individuelle avec multithreading."""
175
+ global processed_count, indexed_specifications, documents_by_spec_num
176
+
177
+ try:
178
+ if spec.get('vers', None) is None:
179
+ return
180
+
181
+ doc_id = str(spec["spec_num"])
182
+ series = doc_id.split(".")[0]
183
+
184
+ a, b, c = str(spec["vers"]).split(".")
185
+
186
+ # Formatage de l'URL selon la version
187
+ if not (int(a) > 35 or int(b) > 35 or int(c) > 35):
188
+ version_code = f"{chars[int(a)]}{chars[int(b)]}{chars[int(c)]}"
189
+ spec_url = f"https://www.3gpp.org/ftp/Specs/archive/{series}_series/{doc_id}/{doc_id.replace('.', '')}-{version_code}.zip"
190
+ else:
191
+ x, y, z = str(a), str(b), str(c)
192
+ while len(x) < 2:
193
+ x = "0" + x
194
+ while len(y) < 2:
195
+ y = "0" + y
196
+ while len(z) < 2:
197
+ z = "0" + z
198
+ version_code = f"{x}{y}{z}"
199
+ spec_url = f"https://www.3gpp.org/ftp/Specs/archive/{series}_series/{doc_id}/{doc_id.replace('.', '')}-{version_code}.zip"
200
+
201
+ string = f"{spec['spec_num']}+-+{spec['title']}+-+{spec['type']}+-+{spec['vers']}+-+{spec['WG']}+-+Rel-{spec['vers'].split('.')[0]}"
202
+
203
+ metadata = {
204
+ "id": str(spec["spec_num"]),
205
+ "title": spec["title"],
206
+ "type": spec["type"],
207
+ "release": str(spec["vers"].split(".")[0]),
208
+ "version": str(spec["vers"]),
209
+ "working_group": spec["WG"],
210
+ "url": spec_url
211
+ }
212
+
213
+ # Mise à jour du dictionnaire global avec verrou
214
+ with dict_lock:
215
+ indexed_specifications[string] = metadata
216
+ processed_count += 1
217
+
218
+ # Affichage de la progression avec verrou
219
+ with print_lock:
220
+ sys.stdout.write(f"\rTraitement: {processed_count}/{total_count} spécifications")
221
+ sys.stdout.flush()
222
+
223
+ except Exception as e:
224
+ with print_lock:
225
+ print(f"\nErreur lors du traitement de {spec.get('spec_num', 'inconnu')}: {str(e)}")
226
+
227
+ def main():
228
+ global total_count
229
+ start_time = time.time()
230
+
231
+ # Récupération des spécifications depuis le site 3GPP
232
+ print("Récupération des spécifications depuis 3GPP...")
233
+ response = requests.get(
234
+ f'https://www.3gpp.org/dynareport?code=status-report.htm',
235
+ headers={"User-Agent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'},
236
+ verify=False
237
+ )
238
+
239
+ # Analyse des tableaux HTML
240
+ dfs = pd.read_html(
241
+ StringIO(response.text),
242
+ storage_options={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'},
243
+ encoding="utf-8"
244
+ )
245
+
246
+ for x in range(len(dfs)):
247
+ dfs[x] = dfs[x].replace({np.nan: None})
248
+
249
+ # Extraction des colonnes nécessaires
250
+ columns_needed = [0, 1, 2, 3, 4]
251
+ extracted_dfs = [df.iloc[:, columns_needed] for df in dfs]
252
+ columns = [x.replace("\xa0", "_") for x in extracted_dfs[0].columns]
253
+
254
+ # Préparation des spécifications
255
+ specifications = []
256
+ for df in extracted_dfs:
257
+ for index, row in df.iterrows():
258
+ doc = row.to_list()
259
+ doc_dict = dict(zip(columns, doc))
260
+ specifications.append(doc_dict)
261
+
262
+ total_count = len(specifications)
263
+ print(f"Traitement de {total_count} spécifications avec multithreading...")
264
+
265
+ try:
266
+ # Vérification si un fichier de documents existe déjà
267
+ if os.path.exists("indexed_docs_content.zip"):
268
+ with zipfile.ZipFile(open("indexed_docs_content.zip", "rb")) as zf:
269
+ for file_name in zf.namelist():
270
+ if file_name.endswith(".json"):
271
+ doc_bytes = zf.read(file_name)
272
+ global documents_by_spec_num
273
+ documents_by_spec_num = json.loads(doc_bytes.decode("utf-8"))
274
+ print(f"Chargement de {len(documents_by_spec_num)} documents depuis le cache.")
275
+
276
+ # Utilisation de ThreadPoolExecutor pour le multithreading
277
+ with concurrent.futures.ThreadPoolExecutor(max_workers=100) as executor:
278
+ futures = [executor.submit(process_specification, spec, columns) for spec in specifications]
279
+ concurrent.futures.wait(futures)
280
+
281
+ finally:
282
+ json_str = json.dumps(documents_by_spec_num, indent=4, ensure_ascii=False)
283
+ json_bytes = json_str.encode("utf-8")
284
+ with zipfile.ZipFile("indexed_docs_content.zip", "w", compression=zipfile.ZIP_DEFLATED) as archive:
285
+ archive.writestr("indexed_documents.json", json_bytes)
286
+ elapsed_time = time.time() - start_time
287
+ print(f"\nTraitement terminé en {elapsed_time:.2f} secondes")
288
+ print(f"Résultats sauvegardés dans l'archive ZIP")
289
+
290
+ if __name__ == "__main__":
291
+ main()
spec_indexer_multi.py ADDED
@@ -0,0 +1,294 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import datetime
2
+ import time
3
+ import sys
4
+ import json
5
+ import traceback
6
+ import requests
7
+ import zipfile
8
+ import uuid
9
+ import os
10
+ import re
11
+ import subprocess
12
+ import concurrent.futures
13
+ import threading
14
+ from io import StringIO, BytesIO
15
+ from typing import List, Dict, Any
16
+
17
+ import pandas as pd
18
+ import numpy as np
19
+ import warnings
20
+
21
+ warnings.filterwarnings("ignore")
22
+
23
+ # Caractères pour le formatage des versions
24
+ chars = "0123456789abcdefghijklmnopqrstuvwxyz"
25
+
26
+ # Verrous pour les opérations thread-safe
27
+ print_lock = threading.Lock()
28
+ dict_lock = threading.Lock()
29
+ scope_lock = threading.Lock()
30
+
31
+ # Dictionnaires globaux
32
+ indexed_specifications = {}
33
+ scopes_by_spec_num = {}
34
+ processed_count = 0
35
+ total_count = 0
36
+
37
+ def get_text(specification: str, version: str):
38
+ """Récupère les bytes du PDF à partir d'une spécification et d'une version."""
39
+ doc_id = specification
40
+ series = doc_id.split(".")[0]
41
+
42
+ response = requests.get(
43
+ f"https://www.3gpp.org/ftp/Specs/archive/{series}_series/{doc_id}/{doc_id.replace('.', '')}-{version}.zip",
44
+ verify=False,
45
+ headers={"User-Agent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'}
46
+ )
47
+
48
+ if response.status_code != 200:
49
+ raise Exception(f"Téléchargement du ZIP échoué pour {specification}-{version}")
50
+
51
+ zip_bytes = BytesIO(response.content)
52
+
53
+ with zipfile.ZipFile(zip_bytes) as zf:
54
+ for file_name in zf.namelist():
55
+ if file_name.endswith("zip"):
56
+ print("Another ZIP !")
57
+ zip_bytes = BytesIO(zf.read(file_name))
58
+ zf = zipfile.ZipFile(zip_bytes)
59
+ for file_name2 in zf.namelist():
60
+ if file_name2.endswith("doc") or file_name2.endswith("docx"):
61
+ if "cover" in file_name2.lower():
62
+ print("COVER !")
63
+ continue
64
+ ext = file_name2.split(".")[-1]
65
+ doc_bytes = zf.read(file_name2)
66
+ temp_id = str(uuid.uuid4())
67
+ input_path = f"/tmp/{temp_id}.{ext}"
68
+ output_path = f"/tmp/{temp_id}.txt"
69
+
70
+ with open(input_path, "wb") as f:
71
+ f.write(doc_bytes)
72
+
73
+ subprocess.run([
74
+ "libreoffice",
75
+ "--headless",
76
+ "--convert-to", "txt",
77
+ "--outdir", "/tmp",
78
+ input_path
79
+ ], check=True)
80
+
81
+ with open(output_path, "r") as f:
82
+ txt_data = [line.strip() for line in f if line.strip()]
83
+
84
+ os.remove(input_path)
85
+ os.remove(output_path)
86
+ return txt_data
87
+ elif file_name.endswith("doc") or file_name.endswith("docx"):
88
+ if "cover" in file_name.lower():
89
+ print("COVER !")
90
+ continue
91
+ ext = file_name.split(".")[-1]
92
+ doc_bytes = zf.read(file_name)
93
+ temp_id = str(uuid.uuid4())
94
+ input_path = f"/tmp/{temp_id}.{ext}"
95
+ output_path = f"/tmp/{temp_id}.txt"
96
+
97
+ print("Ecriture")
98
+ with open(input_path, "wb") as f:
99
+ f.write(doc_bytes)
100
+
101
+ print("Convertissement")
102
+ subprocess.run([
103
+ "libreoffice",
104
+ "--headless",
105
+ "--convert-to", "txt",
106
+ "--outdir", "/tmp",
107
+ input_path
108
+ ], check=True)
109
+
110
+ print("Ecriture TXT")
111
+ with open(output_path, "r", encoding="utf-8") as f:
112
+ txt_data = [line.strip() for line in f if line.strip()]
113
+
114
+ os.remove(input_path)
115
+ os.remove(output_path)
116
+ return txt_data
117
+
118
+ raise Exception(f"Aucun fichier .doc/.docx trouvé dans le ZIP pour {specification}-{version}")
119
+
120
+ def get_scope(specification: str, version: str):
121
+ try:
122
+ spec_text = get_text(specification, version)
123
+ scp_i = 0
124
+ nxt_i = 0
125
+ for x in range(len(spec_text)):
126
+ text = spec_text[x]
127
+ if re.search(r"scope$", text, flags=re.IGNORECASE):
128
+ scp_i = x
129
+ nxt_i = scp_i + 10
130
+ if re.search(r"references$", text, flags=re.IGNORECASE):
131
+ nxt_i = x
132
+
133
+ return re.sub(r"\s+", " ", " ".join(spec_text[scp_i+1:nxt_i])) if len(spec_text[scp_i+1:nxt_i]) < 2 else "Not found"
134
+ except Exception as e:
135
+ traceback.print_exception(e)
136
+ return "Not found (error)"
137
+
138
+ def process_specification(spec: Dict[str, Any], columns: List[str]) -> None:
139
+ """Traite une spécification individuelle avec multithreading."""
140
+ global processed_count, indexed_specifications, scopes_by_spec_num
141
+
142
+ try:
143
+ if spec.get('vers', None) is None:
144
+ return
145
+
146
+ doc_id = str(spec["spec_num"])
147
+ series = doc_id.split(".")[0]
148
+
149
+ a, b, c = str(spec["vers"]).split(".")
150
+
151
+ # Formatage de l'URL selon la version
152
+ if not (int(a) > 35 or int(b) > 35 or int(c) > 35):
153
+ version_code = f"{chars[int(a)]}{chars[int(b)]}{chars[int(c)]}"
154
+ spec_url = f"https://www.3gpp.org/ftp/Specs/archive/{series}_series/{doc_id}/{doc_id.replace('.', '')}-{version_code}.zip"
155
+ else:
156
+ x, y, z = str(a), str(b), str(c)
157
+ while len(x) < 2:
158
+ x = "0" + x
159
+ while len(y) < 2:
160
+ y = "0" + y
161
+ while len(z) < 2:
162
+ z = "0" + z
163
+ version_code = f"{x}{y}{z}"
164
+ spec_url = f"https://www.3gpp.org/ftp/Specs/archive/{series}_series/{doc_id}/{doc_id.replace('.', '')}-{version_code}.zip"
165
+
166
+ string = f"{spec['spec_num']}+-+{spec['title']}+-+{spec['type']}+-+{spec['vers']}+-+{spec['WG']}+-+Rel-{spec['vers'].split('.')[0]}"
167
+
168
+ metadata = {
169
+ "id": str(spec["spec_num"]),
170
+ "title": spec["title"],
171
+ "type": spec["type"],
172
+ "release": str(spec["vers"].split(".")[0]),
173
+ "version": str(spec["vers"]),
174
+ "working_group": spec["WG"],
175
+ "url": spec_url
176
+ }
177
+
178
+ # Vérification si le scope existe déjà pour ce numéro de spécification
179
+ spec_num = str(spec["spec_num"])
180
+
181
+ with scope_lock:
182
+ if spec_num in scopes_by_spec_num:
183
+ # Réutilisation du scope existant
184
+ metadata["scope"] = scopes_by_spec_num[spec_num]
185
+ with print_lock:
186
+ print(f"\nRéutilisation du scope pour {spec_num}")
187
+ else:
188
+ # Extraction du scope seulement si nécessaire
189
+ if not (int(a) > 35 or int(b) > 35 or int(c) > 35):
190
+ version_for_scope = f"{chars[int(a)]}{chars[int(b)]}{chars[int(c)]}"
191
+ else:
192
+ version_for_scope = version_code
193
+
194
+ with print_lock:
195
+ print(f"\nExtraction du scope pour {spec_num} (version {version_for_scope})")
196
+
197
+ try:
198
+ scope = get_scope(metadata["id"], version_for_scope)
199
+ # Stockage du scope pour une utilisation future
200
+ scopes_by_spec_num[spec_num] = scope
201
+ metadata["scope"] = scope
202
+ except Exception as e:
203
+ error_msg = f"Erreur lors de l'extraction du scope: {str(e)}"
204
+ metadata["scope"] = error_msg
205
+ scopes_by_spec_num[spec_num] = error_msg
206
+
207
+ # Mise à jour du dictionnaire global avec verrou
208
+ with dict_lock:
209
+ string += f"+-+{metadata['scope']}" if metadata['scope'] != " " or metadata['scope'] != "" or "not found" not in metadata['scope'].lower() else ""
210
+ indexed_specifications[string] = metadata
211
+ processed_count += 1
212
+
213
+ # Affichage de la progression avec verrou
214
+ with print_lock:
215
+ sys.stdout.write(f"\rTraitement: {processed_count}/{total_count} spécifications")
216
+ sys.stdout.flush()
217
+
218
+ except Exception as e:
219
+ with print_lock:
220
+ print(f"\nErreur lors du traitement de {spec.get('spec_num', 'inconnu')}: {str(e)}")
221
+
222
+ def main():
223
+ global total_count
224
+ old_length = 0
225
+
226
+ start_time = time.time()
227
+
228
+ # Récupération des spécifications depuis le site 3GPP
229
+ print("Récupération des spécifications depuis 3GPP...")
230
+ response = requests.get(
231
+ f'https://www.3gpp.org/dynareport?code=status-report.htm',
232
+ headers={"User-Agent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'},
233
+ verify=False
234
+ )
235
+
236
+ # Analyse des tableaux HTML
237
+ dfs = pd.read_html(
238
+ StringIO(response.text),
239
+ storage_options={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'},
240
+ encoding="utf-8"
241
+ )
242
+
243
+ for x in range(len(dfs)):
244
+ dfs[x] = dfs[x].replace({np.nan: None})
245
+
246
+ # Extraction des colonnes nécessaires
247
+ columns_needed = [0, 1, 2, 3, 4]
248
+ extracted_dfs = [df.iloc[:, columns_needed] for df in dfs]
249
+ columns = [x.replace("\xa0", "_") for x in extracted_dfs[0].columns]
250
+
251
+ # Préparation des spécifications
252
+ specifications = []
253
+ for df in extracted_dfs:
254
+ for index, row in df.iterrows():
255
+ doc = row.to_list()
256
+ doc_dict = dict(zip(columns, doc))
257
+ specifications.append(doc_dict)
258
+
259
+ total_count = len(specifications)
260
+ print(f"Traitement de {total_count} spécifications avec multithreading...")
261
+
262
+ try:
263
+ # Vérification si un fichier de scopes existe déjà
264
+ if os.path.exists("indexed_specifications.json"):
265
+ with open("indexed_specifications.json", "r", encoding="utf-8") as f:
266
+ global scopes_by_spec_num
267
+ f_up = json.load(f)
268
+ scopes_by_spec_num = f_up['scopes']
269
+ before = len(f_up['specs'])
270
+ print(f"Chargement de {len(scopes_by_spec_num)} scopes depuis le cache.")
271
+
272
+ # Utilisation de ThreadPoolExecutor pour le multithreading
273
+ with concurrent.futures.ThreadPoolExecutor(max_workers=100) as executor:
274
+ futures = [executor.submit(process_specification, spec, columns) for spec in specifications]
275
+ concurrent.futures.wait(futures)
276
+
277
+ finally:
278
+ # Sauvegarde des résultats
279
+ result = {
280
+ "specs": indexed_specifications,
281
+ "scopes": scopes_by_spec_num,
282
+ "last_indexed_date": datetime.datetime.today().strftime("%d-%m-%Y")
283
+ }
284
+
285
+ with open("indexed_specifications.json", "w", encoding="utf-8") as f:
286
+ json.dump(result, f, indent=4, ensure_ascii=False)
287
+
288
+ elapsed_time = time.time() - start_time
289
+ print(f"\nTraitement terminé en {elapsed_time:.2f} secondes")
290
+ print(f"Nouveaux specifications : {len(indexed_specifications) - before}")
291
+ print(f"Résultats sauvegardés dans indexed_specifications.json")
292
+
293
+ if __name__ == "__main__":
294
+ main()