my code {import json import os from tqdm import tqdm from sklearn.featureextraction.text…
- User
my code {import json import os from tqdm import tqdm from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.metrics.pairwise import cosine_similarity from sklearn.feature_extraction import text
Path to the folder containing JSON files
input_folder_path = "/home/user/app/output/" output_folder_path = "/home/user/app/output/final/"
Ensure the output directory exists
os.makedirs(output_folder_path, exist_ok=True)
Function to read a JSON file
def read_json_file(file_path): with open(file_path, 'r') as file: return json.load(file)
Function to remove duplicates using cosine similarity
def remove_duplicates(texts, threshold=0.8): # Filter out empty strings and stop words stop_words = text.ENGLISH_STOP_WORDS texts = [t for t in texts if t.strip() and not all(word in stop_words for word in t.split())]
code# Check if the list is still not empty after filtering if not texts: return [] vectorizer = TfidfVectorizer() vectors = vectorizer.fit_transform(texts).toarray() cosine_sim_matrix = cosine_similarity(vectors) unique_texts = [] duplicate_indices = set() for i in range(len(texts)): if i not in duplicate_indices: for j in range(i+1, len(texts)): if cosine_sim_matrix[i][j] > threshold: duplicate_indices.add(j) unique_texts.append(texts[i]) return unique_textsProcess each JSON file in the input folder
for filename in tqdm(os.listdir(input_folder_path), desc="Processing JSON files"): if filename.endswith(".json"): input_file_path = os.path.join(input_folder_path, filename) output_file_path = os.path.join(output_folder_path, filename)
code Assistant