om4r932 commited on
Commit
c3ae5eb
·
1 Parent(s): a5a7013

First functional version (still testing)

Browse files
Files changed (3) hide show
  1. app.py +150 -103
  2. indexer_multi.py +286 -0
  3. spec_indexer_multi.py +294 -0
app.py CHANGED
@@ -1,81 +1,21 @@
1
- import gradio as gr
2
- import threading
3
- import sys
4
- import io
5
- import time
6
- from dotenv import load_dotenv
7
  import os
8
- from contextlib import redirect_stdout
 
 
 
 
9
  from git import Repo
10
- from huggingface_hub import Repository, HfApi
11
 
12
- load_dotenv()
13
 
14
- # == PATHS and SETTINGS ==
15
  DOC_INDEXER = "indexer_multi.py"
16
  SPEC_INDEXER = "spec_indexer_multi.py"
17
  DOC_INDEX_FILE = "indexed_docs.json"
18
  SPEC_INDEX_FILE = "indexed_specifications.json"
19
- GIT_REPO_PATH = os.path.abspath(".") # or absolute path to repo
20
- HF_REPO_ID = "OrganizedProgrammers/3GPPDocFinder"
21
- HF_TOKEN = os.environ.get("HF_TOKEN") # set this as env var
22
-
23
- # == Helpers ==
24
- def run_python_module(module_path):
25
- """
26
- Dynamically run a python module, capture and yield stdout in real time.
27
- """
28
- def runner():
29
- local_vars = {}
30
- buffer = io.StringIO()
31
- try:
32
- with redirect_stdout(buffer):
33
- # Import as module, call main()
34
- import runpy
35
- runpy.run_path(module_path, run_name="__main__")
36
- except Exception as e:
37
- print(f"\n❌ Error: {e}")
38
- finally:
39
- yield buffer.getvalue()
40
- buffer.close()
41
- yield from runner()
42
-
43
- def commit_and_push_github(files, message):
44
- repo = Repo(GIT_REPO_PATH)
45
- repo.git.add(files)
46
- repo.index.commit(message)
47
- try:
48
- repo.git.push()
49
- except Exception as e:
50
- print(f"Git push failed: {e}")
51
-
52
- def commit_and_push_hf(files, message):
53
- if not HF_TOKEN:
54
- return "No HF_TOKEN provided. Skipping HuggingFace push."
55
- hf_repo_dir = os.path.join(GIT_REPO_PATH, "hf_spaces")
56
- repo = None
57
- if not os.path.exists(hf_repo_dir):
58
- repo = Repository(
59
- local_dir=hf_repo_dir,
60
- clone_from=HF_REPO_ID,
61
- token=HF_TOKEN,
62
- skip_lfs_files=True
63
- )
64
- else:
65
- repo = Repository(
66
- local_dir=hf_repo_dir,
67
- token=HF_TOKEN,
68
- skip_lfs_files=True
69
- )
70
- repo.git_pull()
71
- # Copy artifact files to huggingface space
72
- for f in files:
73
- import shutil
74
- shutil.copy2(f, os.path.join(hf_repo_dir, f))
75
- repo.git_add(auto_lfs_track=True)
76
- repo.git_commit(message)
77
- repo.git_push()
78
- return "Pushed to HuggingFace."
79
 
80
  def get_docs_stats():
81
  if os.path.exists(DOC_INDEX_FILE):
@@ -101,39 +41,146 @@ def get_scopes_stats():
101
  return len(data['scopes'])
102
  return 0
103
 
104
- # == Gradio Functions ==
105
-
106
- def index_documents(progress=gr.Progress()):
107
- progress(0, desc="Starting document indexing…")
108
- log = ""
109
- for output in run_python_module(DOC_INDEXER):
110
- log = output
111
- progress(0.7, desc="Indexing in progress...")
112
- yield log
113
- commit_and_push_github([DOC_INDEX_FILE], "Update doc index via Gradio")
114
- commit_and_push_hf([DOC_INDEX_FILE], "Update doc index via Gradio")
115
- progress(1, desc="Done!")
116
- yield log + "\n\n✅ Finished! Committed and pushed."
117
-
118
- def index_specifications(progress=gr.Progress()):
119
- progress(0, desc="Starting specifications indexing…")
120
- log = ""
121
- for output in run_python_module(SPEC_INDEXER):
122
- log = output
123
- progress(0.7, desc="Indexing in progress...")
124
- yield log
125
- commit_and_push_github([SPEC_INDEX_FILE], "Update spec index via Gradio")
126
- commit_and_push_hf([SPEC_INDEX_FILE], "Update spec index via Gradio")
127
- progress(1, desc="Done!")
128
- yield log + "\n\n✅ Finished! Committed and pushed."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
129
 
130
  def refresh_stats():
131
  return str(get_docs_stats()), str(get_specs_stats()), str(get_scopes_stats())
132
 
133
- # == UI ==
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
134
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
135
  gr.Markdown("## 📄 3GPP Indexers")
136
- with gr.Row():
 
 
 
 
 
137
  with gr.Column():
138
  doc_count = gr.Textbox(label="Docs Indexed", value=str(get_docs_stats()), interactive=False)
139
  btn_docs = gr.Button("Re-index Documents", variant="primary")
@@ -142,11 +189,11 @@ with gr.Blocks(theme=gr.themes.Soft()) as demo:
142
  btn_specs = gr.Button("Re-index Specifications", variant="primary")
143
  with gr.Column():
144
  scope_count = gr.Textbox(label="Scopes Indexed", value=str(get_scopes_stats()), interactive=False)
145
- out = gr.Textbox(label="Output/Log", lines=13)
146
- refresh = gr.Button("🔄 Refresh Stats")
147
- btn_docs.click(index_documents, outputs=out)
148
- btn_specs.click(index_specifications, outputs=out)
 
149
  refresh.click(refresh_stats, outputs=[doc_count, spec_count, scope_count])
150
 
151
- if __name__ == "__main__":
152
- demo.launch()
 
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
  DOC_INDEX_FILE = "indexed_docs.json"
16
  SPEC_INDEX_FILE = "indexed_specifications.json"
17
+ HF_SEARCH_REPO = "OrganizedProgrammers/3GPPDocFinder"
18
+ REPO_DIR = os.path.dirname(os.path.abspath(__file__))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
 
20
  def get_docs_stats():
21
  if os.path.exists(DOC_INDEX_FILE):
 
41
  return len(data['scopes'])
42
  return 0
43
 
44
+ def check_permissions(user: str, token: str):
45
+ try:
46
+ req = requests.get("https://huggingface.co/api/whoami-v2", verify=False, headers={"Accept": "application/json", "Authorization": f"Bearer {token}"})
47
+ if req.status_code != 200:
48
+ return False
49
+ reqJson: dict = req.json()
50
+ if not reqJson.get("name") or reqJson['name'] != user:
51
+ return False
52
+ if not reqJson.get("orgs") or len(reqJson['orgs']) == 0:
53
+ return False
54
+ for org in reqJson['orgs']:
55
+ if "645cfa1b5ebf379fd6d8a339" == org['id']:
56
+ return True
57
+ if not reqJson.get('auth') or reqJson['auth'] == {}:
58
+ return False
59
+ if reqJson['auth']['accessToken']['role'] != "fineGrained":
60
+ return False
61
+ for scope in reqJson['auth']['accessToken']['fineGrained']['scoped']:
62
+ if scope['entity']['type'] == "org" and scope['entity']['_id'] == "645cfa1b5ebf379fd6d8a339" and all(perm in scope['permissions'] for perm in ['repo.write', 'repo.content.read']):
63
+ return True
64
+ return False
65
+ except Exception as e:
66
+ traceback.print_exception(e)
67
+ return False
68
+
69
+ def update_logged(user: str, token: str):
70
+ if check_permissions(user, token):
71
+ return gr.update(visible=False), gr.update(visible=True), gr.update(visible=True), gr.update(visible=True)
72
+ else:
73
+ return gr.update(visible=True), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False)
74
+
75
+ def commit_and_push_3gppindexers(user, token, files, message):
76
+ repo = Repo(REPO_DIR)
77
+ origin = repo.remotes.origin
78
+ origin.pull()
79
+ yield "Git pull succeed !"
80
+ repo.git.add(files)
81
+ repo.index.commit(message)
82
+ try:
83
+ repo.git.push(f"https://{user}:{token}@huggingface.co/spaces/OrganizedProgrammers/3GPPIndexers")
84
+ yield "Git push succeed !"
85
+ yield "Wait for Huggingface to restart the Space"
86
+ except Exception as e:
87
+ yield f"Git push failed: {e}"
88
+
89
+ def commit_and_push_3gppdocfinder(token, files, message):
90
+ if not token:
91
+ yield "No token provided. Skipping HuggingFace push."
92
+ hf_repo_dir = os.path.join(REPO_DIR, "hf_spaces")
93
+ repo = None
94
+ if not os.path.exists(hf_repo_dir):
95
+ repo = Repository(
96
+ local_dir=hf_repo_dir,
97
+ repo_type="space",
98
+ clone_from=HF_SEARCH_REPO,
99
+ token=token,
100
+ skip_lfs_files=False
101
+ )
102
+ else:
103
+ repo = Repository(
104
+ local_dir=hf_repo_dir,
105
+ repo_type="space",
106
+ token=token,
107
+ skip_lfs_files=False
108
+ )
109
+ repo.git_pull()
110
+ # Copy artifact files to huggingface space
111
+ for f in files:
112
+ import shutil
113
+ shutil.copy2(f, os.path.join(hf_repo_dir, f))
114
+ repo.git_add(auto_lfs_track=True)
115
+ repo.git_commit(message)
116
+ repo.git_push()
117
+ yield "Pushed to HuggingFace."
118
 
119
  def refresh_stats():
120
  return str(get_docs_stats()), str(get_specs_stats()), str(get_scopes_stats())
121
 
122
+ def stream_script_output(script_path):
123
+ process = subprocess.Popen(
124
+ ["python", script_path],
125
+ stdout=subprocess.PIPE,
126
+ stderr=subprocess.STDOUT,
127
+ bufsize=1,
128
+ universal_newlines=True,
129
+ )
130
+ output = ""
131
+ for line in process.stdout:
132
+ output += line
133
+ yield output
134
+ process.stdout.close()
135
+ process.wait()
136
+ yield output
137
+
138
+ def index_documents(user, token):
139
+ # Désactiver tous les boutons
140
+ yield gr.update(interactive=False), gr.update(interactive=False), gr.update(interactive=False), "⏳ Indexation en cours..."
141
+
142
+ # Lancer l'indexation
143
+ if not check_permissions(user, token):
144
+ yield gr.update(interactive=True), gr.update(interactive=True), gr.update(interactive=True), "❌ Identifiants invalides"
145
+ return
146
+
147
+ for log in stream_script_output(DOC_INDEXER):
148
+ yield gr.update(None), gr.update(None), gr.update(None), log
149
+
150
+ d = datetime.today().strftime("%d/%m/%Y-%H:%M:%S")
151
+ yield gr.update(None), gr.update(None), gr.update(None), commit_and_push_3gppdocfinder(token, ["indexed_docs.json"], f"Update documents indexer via Indexer: {d}")
152
+ yield gr.update(None), gr.update(None), gr.update(None), commit_and_push_3gppindexers(user, token, ["indexed_docs.json"], f"Update documents indexer via Indexer: {d}")
153
+
154
+ # Réactiver les boutons à la fin
155
+ yield gr.update(None), gr.update(None), gr.update(None), "✅ Terminé."
156
+
157
+ def index_specifications(user, token):
158
+ # Désactiver tous les boutons
159
+ yield gr.update(interactive=False), gr.update(interactive=False), gr.update(interactive=False), "⏳ Indexation en cours..."
160
+
161
+ # Lancer l'indexation
162
+ if not check_permissions(user, token):
163
+ yield gr.update(interactive=True), gr.update(interactive=True), gr.update(interactive=True), "❌ Identifiants invalides"
164
+ return
165
+
166
+ for log in stream_script_output(DOC_INDEXER):
167
+ yield gr.update(None), gr.update(None), gr.update(None), log
168
+
169
+ d = datetime.today().strftime("%d/%m/%Y-%H:%M:%S")
170
+ yield gr.update(None), gr.update(None), gr.update(None), commit_and_push_3gppdocfinder(token, ["indexed_specifications.json"], f"Update specifications indexer via Indexer: {d}")
171
+ yield gr.update(None), gr.update(None), gr.update(None), commit_and_push_3gppindexers(user, token, ["indexed_specifications.json"], f"Update specifications indexer via Indexer: {d}")
172
+
173
+ # Réactiver les boutons à la fin
174
+ yield gr.update(None), gr.update(None), gr.update(None), "✅ Terminé."
175
+
176
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
177
  gr.Markdown("## 📄 3GPP Indexers")
178
+ with gr.Row() as r1:
179
+ with gr.Column():
180
+ git_user = gr.Textbox(label="Git user (for push/pull indexes)")
181
+ git_pass = gr.Textbox(label="Git Token", type="password")
182
+ btn_login = gr.Button("Login", variant="primary")
183
+ with gr.Row(visible=False) as r2:
184
  with gr.Column():
185
  doc_count = gr.Textbox(label="Docs Indexed", value=str(get_docs_stats()), interactive=False)
186
  btn_docs = gr.Button("Re-index Documents", variant="primary")
 
189
  btn_specs = gr.Button("Re-index Specifications", variant="primary")
190
  with gr.Column():
191
  scope_count = gr.Textbox(label="Scopes Indexed", value=str(get_scopes_stats()), interactive=False)
192
+ out = gr.Textbox(label="Output/Log", lines=13, autoscroll=True, visible=False)
193
+ refresh = gr.Button(value="🔄 Refresh Stats", visible=False)
194
+ btn_login.click(update_logged, inputs=[git_user, git_pass], outputs=[r1, r2, out, refresh])
195
+ btn_docs.click(index_documents, inputs=[git_user, git_pass], outputs=[btn_docs, btn_specs, refresh, out])
196
+ btn_specs.click(index_specifications, inputs=[git_user, git_pass], outputs=[btn_docs, btn_specs, refresh, out])
197
  refresh.click(refresh_stats, outputs=[doc_count, spec_count, scope_count])
198
 
199
+ demo.launch()
 
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()
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()