### Install BERTrend Library Source: https://github.com/rte-france/bertrend/blob/main/getting_started/bertrend_quickstart.ipynb This command uses pip to install the BERTrend library. It's a prerequisite for using any of BERTrend's functionalities. Ensure you have pip installed and configured correctly. ```shell #!pip install bertrend ``` -------------------------------- ### Launch Embedding Server using Python Source: https://github.com/rte-france/bertrend/blob/main/bertrend/services/embedding_server/README.md This snippet shows the command to start the embedding server. It assumes Python is installed and the necessary scripts are available in the project directory. ```shell python start.py ``` -------------------------------- ### Configure BERTrend Data Input Paths (Python) Source: https://github.com/rte-france/bertrend/blob/main/getting_started/bertrend_quickstart.ipynb Sets up the directory and input data file paths for BERTrend analysis. It defines the location of the data feed and a list of data files to be processed sequentially. ```python MY_DATA_DIR = Path("/DSIA/nlp/bertrend/data") / "feeds/feed_sobriete" input_data = [ MY_DATA_DIR / "2024-12-30_feed_sobriete.jsonl", MY_DATA_DIR / "2025-01-06_feed_sobriete.jsonl", MY_DATA_DIR / "2025-01-20_feed_sobriete.jsonl", ] window_size = 7 ``` -------------------------------- ### BERTrend Model Path Configuration (Python) Source: https://github.com/rte-france/bertrend/blob/main/getting_started/bertrend_quickstart.ipynb Defines the directory path where BERTrend models will be stored or restored from. This path is crucial for persisting and loading the state of the topic models between processing runs. ```python BERTREND_MODELS_PATH = MODELS_DIR / "sobriete_models" ``` -------------------------------- ### Access Generated Topic Description Source: https://github.com/rte-france/bertrend/blob/main/getting_started/bertrend_quickstart.ipynb Retrieves the generated title and description for a topic previously processed by `generate_topic_description`. This demonstrates how to access the structured output from the topic description generation function. ```python desc.title ``` ```python desc.description ``` -------------------------------- ### Configure Embedding Service Client (Python) Source: https://github.com/rte-france/bertrend/blob/main/getting_started/bertrend_quickstart.ipynb Initializes the EmbeddingService client configuration. This includes specifying whether to use a local or remote service and providing the URL and client secret for authentication if a remote service is used. ```python embedding_service_cfg = { "local": False, "url": "https://10.132.5.44:6464", "client_secret": client_secret, } embedding_service = EmbeddingService(**embedding_service_cfg) embedding_model_name = embedding_service.embedding_model_name ``` -------------------------------- ### Verify BERTrend Installation Source: https://github.com/rte-france/bertrend/blob/main/README.md This command executes a built-in verification script for BERTrend. Running this script checks for the correct installation of all dependencies and provides feedback on the installation status, guiding users on how to resolve any issues. ```bash python -m bertrend.tests.test_installation ``` -------------------------------- ### Install BERTrend from Source with Core and App Dependencies Source: https://github.com/rte-france/bertrend/blob/main/README.md Illustrates how to install BERTrend from its source directory. It shows commands for a basic installation with core dependencies and an extended installation that includes dependencies for BERTrend applications using pip or poetry. ```bash # Basic installation with core dependencies pip install . # or poetry install # Installation with apps dependencies pip install ".[apps]" # or poetry install --extras apps ``` -------------------------------- ### Import Necessary Libraries for BERTrend Analysis Source: https://github.com/rte-france/bertrend/blob/main/getting_started/bertrend_quickstart.ipynb Imports essential libraries for data manipulation (pandas), path operations (pathlib), display (IPython.display), logging (loguru), operating system interactions (os), and specific BERTrend components for topic modeling, embedding services, and data loading. These are foundational for setting up and running BERTrend analyses. ```python from pathlib import Path import pandas as pd from pandas import Timestamp from IPython.display import display from loguru import logger import os from bertrend import DATA_PATH from bertrend.BERTrend import BERTrend from bertrend import MODELS_DIR from bertrend.utils.data_loading import load_data, split_data, TEXT_COLUMN from bertrend.services.embedding_service import EmbeddingService from bertrend.BERTopicModel import BERTopicModel from bertrend.topic_analysis.topic_description import generate_topic_description from bertrend.trend_analysis.weak_signals import analyze_signal ``` -------------------------------- ### Load IPython Extensions and Auto-Reload Source: https://github.com/rte-france/bertrend/blob/main/getting_started/bertrend_quickstart.ipynb These IPython magic commands are used to load the autoreload extension and set it to reload all modules automatically before executing code. This is useful during development to see changes reflected immediately without restarting the kernel. ```python %load_ext autoreload %autoreload 2 ``` -------------------------------- ### Clone BERTrend Repository and Start Docker Compose Source: https://github.com/rte-france/bertrend/blob/main/docs/docker.md Initializes BERTrend by cloning the repository and then uses Docker Compose to build and start the necessary services in detached mode. This is the recommended quick start method. ```bash git clone https://github.com/rte-france/BERTrend.git cd BERTrend docker-compose up -d ``` -------------------------------- ### Display HTML Content with IPython Source: https://github.com/rte-france/bertrend/blob/main/getting_started/bertrend_quickstart.ipynb This Python snippet utilizes the IPython.display module to render HTML content within an interactive environment. It takes a string of HTML and displays it as rendered HTML. Ensure that the 'formatted_html' variable contains valid HTML. ```python from IPython.display import display, HTML display(HTML(formatted_html)) ``` -------------------------------- ### Set up Python Virtual Environment and Install Dependencies Source: https://github.com/rte-france/bertrend/blob/main/README.md This snippet demonstrates how to create a Python virtual environment, activate it, update pip, and install the BERTrend package along with the python-dotenv library for environment variable loading. It is crucial for managing project dependencies and ensuring a clean installation. ```bash python -m venv .venv source .venv/bin/activate # Windows: .venv\\Scripts\\activate pip install -U pip pip install . pip install python-dotenv ``` -------------------------------- ### HTML Dashboard Structure and Styling Source: https://github.com/rte-france/bertrend/blob/main/getting_started/bertrend_quickstart.ipynb This HTML code defines the structure and styling for a dashboard analyzing the evolution of a topic, likely related to political or economic leadership. It includes sections for topic evolution and scenario analysis, with CSS for layout and visual presentation. This is a static representation of data. ```html A New Era of American Leadership Analysis Dashboard

Topic Evolution

January 20, 2017: A New Era of American Leadership

Donald Trump’s inauguration marked a shift in power dynamics, emphasizing a government "for the people." The slogan "America First" was introduced, focusing on job creation, border control, and economic revitalization. A commitment to "Buy American & Hire American" was established as a core principle of the administration.

What's New: This foundational rhetoric set the stage for a series of policies aimed at reshaping the American economy and its global standing.

January 22, 2017: Building Momentum for Change

Trump engaged with industry leaders, reinforcing his commitment to job creation and economic growth. The administration began to address controversial topics such as sanctuary cities and healthcare reform. Public sentiment reflected optimism regarding economic prospects, with the stock market showing positive trends.

What's New: This period introduced a more hands-on approach from the administration, with direct engagement with industry leaders and a focus on immediate policy discussions.

February 19, 2017: Reinforcing the "America First" Agenda

Continued emphasis on "America First" with a focus on job creation and economic revitalization. The administration highlighted its commitment to border control and national security. Public demonstrations and protests were acknowledged as part of the democratic process.

What's New: This period saw a stronger emphasis on national security and the acknowledgment of public dissent.

Evolution Scenarios

Optimistic Scenario

The focus on domestic job creation leads to a revitalized manufacturing sector, resulting in significant economic growth and reduced unemployme ``` -------------------------------- ### Initialize BERTrend Object with a Topic Model Source: https://github.com/rte-france/bertrend/blob/main/getting_started/bertrend_quickstart.ipynb Creates an instance of the BERTrend class, passing a pre-configured BERTopicModel object. BERTrend relies on these topic models to perform its trend analysis, especially for retrospective tasks where multiple models are trained on different time slices of data. ```python # Basic creation of the object and parametrization # BERTrend uses several topic models; therefore, it is necessary to pass a topic_model object as a reference bertrend = BERTrend(topic_model=topic_model) ``` -------------------------------- ### Install BERTrend Package from PyPI Source: https://github.com/rte-france/bertrend/blob/main/README.md Provides the command to install the BERTrend package directly from the Python Package Index (PyPI). This is the simplest method for users who want to use the pre-built distribution of the package. ```bash pip install bertrend ``` -------------------------------- ### Retrieve Embedding Model Name Source: https://github.com/rte-france/bertrend/blob/main/getting_started/bertrend_quickstart.ipynb Retrieves the name of the embedding model currently being used by the initialized EmbeddingService. This can be useful for logging or verifying the model configuration. ```python embedding_model_name = embedding_service.embedding_model_name ``` -------------------------------- ### Iterate Through Input Data for BERTrend Analysis (Python) Source: https://github.com/rte-france/bertrend/blob/main/getting_started/bertrend_quickstart.ipynb This script iterates through a list of input data files, extracts a timestamp from each filename, and calls the `process_new_data` function to perform prospective trend analysis for each data slice. ```python for data_file in input_data: timestamp = pd.Timestamp(data_file.name.split("_")[0]) display(process_new_data(data_file, timestamp)) ``` -------------------------------- ### Initialize and Use EmbeddingService Source: https://github.com/rte-france/bertrend/blob/main/getting_started/bertrend_quickstart.ipynb Configures and initializes an EmbeddingService for generating text embeddings. It specifies the service URL and client secret, then uses the service to embed the 'text' column of a DataFrame. This process involves sending texts to a remote embedding service. ```python df = df.head(1000) client_secret = "bd76aa472dd91aed4a56bf1935dbb802583c119824380d8567086579c0ef3324" # embedding_service_cfg = {"local": False, "url":"https://localhost:6464"} embedding_service_cfg = { "local": False, "url": "https://10.132.5.44:6464", "client_secret": client_secret, } embedding_service = EmbeddingService(**embedding_service_cfg) embeddings, token_strings, token_embeddings = embedding_service.embed( texts=df["text"], ) ``` -------------------------------- ### Generate Topic Description using BERTopic Source: https://github.com/rte-france/bertrend/blob/main/getting_started/bertrend_quickstart.ipynb Generates a textual description for a specific topic within a BERTopic model. This function takes the topic model, topic number, filtered documents, and a language code as input. It leverages LLM utilities to create a coherent description. ```python desc = generate_topic_description( topic_model=selected_topic_model, topic_number=5, filtered_docs=df, language_code="en", ) ``` -------------------------------- ### Example Configuration File (TOML) Source: https://github.com/rte-france/bertrend/blob/main/bertrend_apps/prospective_demo/docs/automated_report_generation.md A complete example of a TOML configuration file for a Bertrend model, including settings for model, analysis, and reporting. ```toml [model_config] granularity = 7 window_size = 7 language = "en" split_by_paragraph = true [analysis_config] topic_evolution = true evolution_scenarios = true multifactorial_analysis = true [report_config] auto_send = true email_recipients = [ "team-lead@company.com", "analyst@company.com" ] report_title = "Weekly AI & Technology Trends Report" max_emerging_topics = 3 max_strong_topics = 5 ``` -------------------------------- ### Run Topic Analysis Demo (Bash) Source: https://github.com/rte-france/bertrend/blob/main/docs/demos.md Navigates to the Topic Analysis Demo directory and runs the Streamlit application. Requires Streamlit to be installed. ```bash cd bertrend/demos/topic_analysis streamlit run app.py ``` -------------------------------- ### Python OpenAI Client API Call for Content Generation Source: https://github.com/rte-france/bertrend/blob/main/getting_started/bertrend_quickstart.ipynb This Python code snippet demonstrates a call to the OpenAI API using the `openai_client` library to generate content based on a historical conversation. It logs the API response, including the generated content and metadata like chat completion ID and choices. This function is part of a larger LLM utility. ```python API returned: ChatCompletion(id='chatcmpl-BH8i9vBvO8xD7z4Fcx7mZocOJMFIN', choices=[Choice(finish_reason='stop', index=0, logprobs=None, message=ChatCompletionMessage(content='```html A New Era of American Leadership Analysis Dashboard

Topic Evolution

January 20, 2017: A New Era of American Leadership

Donald Trump’s inauguration marked a shift in power dynamics, emphasizing a government "for the people." The slogan "America First" was introduced, focusing on job creation, border control, and economic revitalization. A commitment to "Buy American & Hire American" was established as a core principle of the administration.

What's New: This foundational rhetoric set the stage for a series of policies aimed at reshaping the American economy and its global standing.

January 22, 2017: Building Momentum for Change

Trump engaged with industry leaders, reinforcing his commitment to job creation and economic growth. The administration began to address controversial topics such as sanctuary cities and healthcare reform. Public sentiment reflected optimism regarding economic prospects, with the stock market showing positive trends.

What's New: This period introduced a more hands-on approach from the administration, with direct engagement with industry leaders and a focus on immediate policy discussions.

February 19, 2017: Reinforcing the "America First" Agenda

Continued emphasis on "America First" with a focus on job creation and economic revitalization. The administration highlighted its commitment to border control and national security. Public demonstrations and protests were acknowledged as part of the democratic process.

What's New: This period saw a stronger emphasis on national security and the acknowledgment of public dissent.

Evolution Scenarios

Optimistic Scenario

The focus on domestic job creation leads to a revitalized manufacturing sector, resulting in significant economic growth and reduced unemployme ``` -------------------------------- ### Calculate Signal Popularity in BERTrend Source: https://github.com/rte-france/bertrend/blob/main/getting_started/bertrend_quickstart.ipynb Calculates the signal popularity within the BERTrend model. This function often requires a `window_size` parameter to define the period over which popularity is assessed. The output typically includes information about the saved model location. ```python bertrend.calculate_signal_popularity() window_size = 30 ``` -------------------------------- ### Run Weak Signals Demo (Bash) Source: https://github.com/rte-france/bertrend/blob/main/docs/demos.md Navigates to the Weak Signals Demo directory and runs the Streamlit application. Requires Streamlit to be installed. ```bash cd bertrend/demos/weak_signals streamlit run app.py ``` -------------------------------- ### Process New Data with BERTrend (Python) Source: https://github.com/rte-france/bertrend/blob/main/getting_started/bertrend_quickstart.ipynb Processes a new slice of data for trend analysis. It attempts to restore existing BERTrend models, loads and prepares the new data, generates embeddings, trains new topic models, and merges them with existing ones. It then calculates signal popularity and classifies weak and strong signals based on a specified window size. ```python def process_new_data(data_slice_path: Path, timestamp: pd.Timestamp): logger.debug(f"Processing new data: {data_slice_path}") # Restore previous models try: bertrend = BERTrend.restore_model(BERTREND_MODELS_PATH) except: logger.warning("Cannot restore previous models, creating new one") bertrend = BERTrend(topic_model=BERTopicModel()) # Read data df = load_data(data_slice_path, language="French") df = split_data(df) text = df[TEXT_COLUMN] # Embed new data embeddings, token_strings, token_embeddings = embedding_service.embed( texts=text, ) # Create topic model for new data bertrend.train_topic_models( {timestamp: df}, embeddings=embeddings, embedding_model=embedding_model_name ) logger.info(f"BERTrend processed {len(bertrend.doc_groups)} time periods") # Save models bertrend.save_model(models_path=BERTREND_MODELS_PATH) if len(bertrend.doc_groups) < 2: return None # Compute popularities bertrend.calculate_signal_popularity() # classify last signals noise_topics_df, weak_signal_topics_df, strong_signal_topics_df = ( bertrend.classify_signals(window_size, timestamp) ) # TODO: save dfs if weak_signal_topics_df.empty: return None wt = weak_signal_topics_df["Topic"] logger.info(f"Weak topics: {wt}") wt_list = [] for topic in wt: topic_model = bertrend.restore_topic_model(timestamp) desc = generate_topic_description( topic_model=topic_model, topic_number=topic, filtered_docs=df, language_code="fr", ) wt_list.append({ "timestamp": timestamp, "topic": topic, "title": desc.title, "description": desc.description, }) return pd.DataFrame(wt_list) ``` -------------------------------- ### Download and Load Historical Tweet Data Source: https://github.com/rte-france/bertrend/blob/main/getting_started/bertrend_quickstart.ipynb Downloads a CSV file containing Donald Trump's tweets from a specified GitHub URL using a shell command. It then loads this data into a pandas DataFrame, specifying the separator, quote character, and skipping initial spaces. This step is crucial for preparing the dataset for trend analysis. ```python # Here some Trump tweets from: https://github.com/MarkHershey/CompleteTrumpTweetsArchive/blob/master/data/realDonaldTrump_in_office.csv #!wget "https://raw.githubusercontent.com/MarkHershey/CompleteTrumpTweetsArchive/refs/heads/master/data/realDonaldTrump_in_office.csv" df = pd.read_csv( "realDonaldTrump_in_office.csv", sep=",", quotechar='"', skipinitialspace=True ) ``` -------------------------------- ### Run Main BERTrend Application Container Source: https://github.com/rte-france/bertrend/blob/main/docs/docker.md Starts the main BERTrend application container, exposing demo ports and mounting a volume for persistent data. It configures API keys, embedding service URLs, and user IDs, with GPU support enabled via `--gpus all`. ```bash docker run --gpus all \ -p 8501:8501 -p 8502:8502 -p 8503:8503 \ -v /path/to/bertrend/data:/bertrend \ -e OPENAI_API_KEY=your_key \ -e OPENAI_BASE_URL=your_endpoint \ -e EMBEDDING_SERVICE_URL=https://your-embedding-server:6464 \ -e HOST_UID=$(id -u) -e HOST_GID=$(id -g) \ bertrend:latest ``` -------------------------------- ### BERTrend Main Application Volume Mount Example Source: https://github.com/rte-france/bertrend/blob/main/docs/docker.md Illustrates how to mount a local directory to the `/bertrend` path inside the main BERTrend Docker container. This ensures that data generated or used by BERTrend is persisted on the host system. ```bash -v /path/on/host:/bertrend ``` -------------------------------- ### Running BERTrend Streamlit Demos Source: https://context7.com/rte-france/bertrend/llms.txt This section describes how to launch and utilize the interactive Streamlit demos for BERTrend, specifically for Topic Analysis and Weak Signals. It provides command-line instructions for launching the demos and outlines the key features of each application. It also includes an example of programmatic usage for data loading and embedding components. ```bash # Launching the Topic Analysis Demo cd bertrend/demos/topic_analysis CUDA_VISIBLE_DEVICES=0 streamlit run app.py # Launching the Weak Signals Demo cd bertrend/demos/weak_signals CUDA_VISIBLE_DEVICES=0 streamlit run app.py ``` ```python from bertrend.demos.demos_utils.data_loading_component import ( display_data_loading_component ) from bertrend.demos.demos_utils.embed_documents_component import ( embed_documents_component ) import streamlit as st # Example of programmatic usage within a Streamlit app: # st.title("BERTrend Demo Components") # # st.header("Data Loading") # display_data_loading_component() # # st.header("Document Embedding") # # Assuming 'documents' is a list of strings and 'model_name' is specified # # documents, model_name = embed_documents_component(...) # st.write("Run embed_documents_component to get embeddings.") ``` -------------------------------- ### Generate Topic Summary from LLM API Response Source: https://github.com/rte-france/bertrend/blob/main/getting_started/bertrend_quickstart.ipynb This snippet demonstrates how to extract and parse a JSON response from an LLM API call, specifically for generating a title and description for a given topic. It handles the JSON parsing and ensures the data is structured correctly for further use. This function is part of the LLM utilities within the BERTrend project. ```python from bertrend.llm_utils.openai_client import generate_from_history import json # Assuming 'history' is a pre-defined list of messages for the API call # The actual content of 'history' would depend on the specific conversation context history = [ {"role": "system", "content": "You are a helpful assistant that summarizes topics."}, {"role": "user", "content": "Summarize the following topic: ..."} ] # Call the API to generate the response api_response = generate_from_history(history) # Extract the content from the API response content = api_response.choices[0].message.content # Parse the JSON content to get the title and description topic_data = json.loads(content) title = topic_data.get("title") description = topic_data.get("description") print(f"Topic Title: {title}") print(f"Topic Description: {description}") ``` -------------------------------- ### Train Topic Models with BERTrend (Python) Source: https://github.com/rte-france/bertrend/blob/main/getting_started/bertrend_quickstart.ipynb Trains topic models using the `bertrend.train_topic_models` function. This function requires grouped data, the name of the embedding model, and the corresponding embeddings. It handles the iterative training process and fitting the underlying BERTopic model, including steps like dimensionality reduction and clustering. ```python bertrend.train_topic_models( grouped_data=grouped_data, embedding_model=embedding_model_name, embeddings=embeddings, ) ``` -------------------------------- ### Configure BERTopic Model with Custom Parameters Source: https://github.com/rte-france/bertrend/blob/main/getting_started/bertrend_quickstart.ipynb Defines a configuration string in TOML format to customize the BERTopic model. It allows overriding default settings for global parameters, BERTopic itself, UMAP, HDBSCAN, CountVectorizer, ClassTfidfTransformer, and MaximalMarginalRelevance. This enables fine-tuning topic modeling for specific use cases, such as setting the language to English and adjusting representation models. ```python # Topic model with default parameters - each parameter of BERTopic can be modified from the constructor or can be read from a configuration file # overrides the default config to use English config = """ # Default configuration file to be used for topic model # Global parameters [global] language = "English" # BERTopic parameters: https://maartengr.github.io/BERTopic/api/bertopic.html#bertopic._bertopic.BERTopic.__init__ [bertopic_model] top_n_words = 10 verbose = true representation_model = ["MaximalMarginalRelevance"] # KeyBERTInspired, OpenAI zeroshot_topic_list = [] zeroshot_min_similarity = 0 # UMAP parameters: https://umap-learn.readthedocs.io/en/latest/api.html [umap_model] n_neighbors = 5 n_components = 5 min_dist = 0.0 metric = "cosine" random_state = 42 # HDBSCAN parameters: https://hdbscan.readthedocs.io/en/latest/api.html [hdbscan_model] min_cluster_size = 5 min_samples = 5 metric = "euclidean" cluster_selection_method = "eom" prediction_data = true # CountVectorizer: https://scikit-learn.org/1.5/modules/generated/sklearn.feature_extraction.text.CountVectorizer.html [vectorizer_model] ngram_range = [1, 1] stop_words = true # If true, will check `language` parameter and load associated stopwords file min_df = 2 # ClassTfidfTransformer: https://maartengr.github.io/BERTopic/api/ctfidf.html [ctfidf_model] bm25_weighting = false reduce_frequent_words = true # MaximalMarginalRelevance: https://maartengr.github.io/BERTopic/api/representation/mmr.html [mmr_model] diversity = 0.3 # Reduce outliers: https://maartengr.github.io/BERTopic/api/bertopic.html#bertopic._bertopic.BERTopic.reduce_outliers [reduce_outliers] strategy = "c-tf-idf" " topic_model = BERTopicModel(config) ``` -------------------------------- ### Embedding Server Volume Mount Example Source: https://github.com/rte-france/bertrend/blob/main/docs/docker.md Demonstrates mounting a local directory to the Hugging Face cache path within the embedding server container. This strategy prevents redundant model downloads across container instances, optimizing storage and startup time. ```bash -v /path/to/huggingface/cache:/root/.cache/huggingface ``` -------------------------------- ### Run Integration Tests with Pytest Source: https://github.com/rte-france/bertrend/blob/main/bertrend/tests/README_integration_tests.md This command executes all tests marked with the 'integration' marker in the specified file, providing verbose output. Ensure BERTrend is installed with its dependencies. ```bash pytest -m integration bertrend/tests/test_integration.py -v ``` -------------------------------- ### Test Email Sending Configuration (Python) Source: https://github.com/rte-france/bertrend/blob/main/docs/mail_configuration.md This script demonstrates how to test the configured email sending functionality. It imports necessary functions from 'bertrend_apps.common.mail_utils' and sends a test email. It shows how to obtain credentials for Gmail OAuth and format the email content. ```python from bertrend_apps.common.mail_utils import get_credentials, send_email # For Gmail OAuth credentials = get_credentials() send_email( credentials=credentials, subject="BERTrend Test Email", recipients=["your-test-email@example.com"], content="

Test successful!

", content_type="html" ) ``` -------------------------------- ### BERTrend Environment Configuration Source: https://context7.com/rte-france/bertrend/llms.txt This code snippet explains how to configure BERTrend using a `.env` file and environment variables. It shows how to load variables using `dotenv`, print key configuration settings, and provides an example `.env` file structure. It also demonstrates accessing BERTrend's internal path variables. Dependencies include `os`, `pathlib`, `dotenv`, and BERTrend's configuration constants. ```python import os from pathlib import Path from dotenv import load_dotenv # BERTrend auto-loads .env on import, but you can reload if needed # load_dotenv(override=True) # Access and print key environment variables relevant to BERTrend print("Configuration from environment:") print(f" Base directory: {os.getenv('BERTREND_BASE_DIR')}") print(f" OpenAI API key: {'set' if os.getenv('OPENAI_API_KEY') else 'not set'}") print(f" OpenAI model: {os.getenv('OPENAI_DEFAULT_MODEL')}") print(f" OpenAI base URL: {os.getenv('OPENAI_BASE_URL', 'default')}") print(f" CUDA devices: {os.getenv('CUDA_VISIBLE_DEVICES', 'all')}") # Example .env file structure content env_template = """ # Base directory for BERTrend data/models/logs BERTREND_BASE_DIR=/path/to/bertrend/data # OpenAI/LLM Configuration OPENAI_API_KEY=sk-your-api-key OPENAI_BASE_URL=https://api.openai.com/v1 OPENAI_DEFAULT_MODEL=gpt-4 # External API Keys (optional) SEMANTIC_SCHOLAR_API_KEY=your_key NEWSCATCHER_API_KEY=your_key # Embedding Service Security (optional) BERTREND_SECRET_KEY=your_secret_key DEFAULT_RATE_LIMIT=100 DEFAULT_RATE_WINDOW=3600 # GPU Configuration CUDA_VISIBLE_DEVICES=0,1 """ # Write the template to a .env file if it doesn't exist env_file = Path(".env") if not env_file.exists(): env_file.write_text(env_template) print("\n.env template created") # Access configuration constants provided by BERTrend from bertrend import BERTREND_BASE_DIR, BASE_PATH, DATA_PATH, CACHE_PATH print(f"\nBERTrend paths:") print(f" Base: {BASE_PATH}") print(f" Data: {DATA_PATH}") print(f" Cache: {CACHE_PATH}") ``` -------------------------------- ### Environment-Based Email Configuration (Python) Source: https://github.com/rte-france/bertrend/blob/main/docs/mail_configuration.md This function sends emails by dynamically selecting the email backend based on the BERTREND_EMAIL_BACKEND environment variable. Supported backends include 'gmail', 'smtp', and 'sendgrid'. It requires corresponding functions for each backend to be defined elsewhere. ```python import os EMAIL_BACKEND = os.getenv("BERTREND_EMAIL_BACKEND", "gmail") # gmail, smtp, sendgrid def send_email(credentials, subject: str, recipients: list[str], content, **kwargs): """Send email using configured backend""" if EMAIL_BACKEND == "gmail": return send_email_gmail(credentials, subject, recipients, content, **kwargs) elif EMAIL_BACKEND == "smtp": return send_email_smtp(subject, recipients, content, **kwargs) elif EMAIL_BACKEND == "sendgrid": return send_email_sendgrid(subject, recipients, content, **kwargs) else: raise ValueError(f"Unsupported email backend: {EMAIL_BACKEND}") ``` -------------------------------- ### Basic Article Assessment with Default Weights (Python) Source: https://github.com/rte-france/bertrend/blob/main/docs/article_scoring.md Performs a basic assessment of an article using default weighting configurations. This example initializes the `ArticleScore` with provided criteria scores and prints the resulting quality level and final score. ```python # Simple assessment with default weights scores = CriteriaScores( depth_of_reporting=0.7, originality_and_exclusivity=0.6, # ... other criteria ) article_score = ArticleScore(scores=scores) print(f"Quality: {article_score.quality_level}") print(f"Score: {article_score.final_score}") ``` -------------------------------- ### SMTP Email Sending Implementation (Python) Source: https://github.com/rte-france/bertrend/blob/main/docs/mail_configuration.md Python code snippet demonstrating how to send emails using the SMTP protocol. This implementation can be adapted for various email providers like Outlook or corporate email servers by configuring the SMTP server details, port, username, and password. It supports sending content as HTML or plain text and includes basic error handling. ```python import smtplib from email.message import EmailMessage from email.utils import COMMASPACE import mimetypes from pathlib import Path # SMTP Configuration SMTP_SERVER = "smtp.your-provider.com" # e.g., "smtp.office365.com" for Outlook SMTP_PORT = 587 SMTP_USERNAME = "your-email@domain.com" SMTP_PASSWORD = "your-password" # Consider using environment variables def send_email_smtp( subject: str, recipients: list[str], content: str | Path, content_type: str = "html", file_name: str = None, ) -> None: """Send email using SMTP""" try: msg = EmailMessage() msg["Subject"] = subject msg["From"] = SMTP_USERNAME msg["To"] = COMMASPACE.join(recipients) # Handle file attachment or content if isinstance(content, Path) and content.is_file(): # File attachment logic (similar to original) # ... (adapt the file attachment code from original) else: # Content as body subtype = "plain" if content_type.lower() in {"md", "text", "txt"} else content_type msg.set_content(content, subtype=subtype) # Send via SMTP with smtplib.SMTP(SMTP_SERVER, SMTP_PORT) as server: server.starttls() server.login(SMTP_USERNAME, SMTP_PASSWORD) server.send_message(msg) logger.debug("Email successfully sent via SMTP.") except Exception as err: logger.exception("SMTP error: ", err) ``` -------------------------------- ### Interact with Embedding Server API using Python Client Source: https://github.com/rte-france/bertrend/blob/main/bertrend/services/embedding_server/README.md Demonstrates how to use the EmbeddingAPIClient to connect to the embedding server, get the model name, and generate embeddings for a given text. Requires the 'bertrend' library and a running embedding server. ```python from bertrend.services.embedding_client import EmbeddingAPIClient embedding_service_endpoint = "https://yourservice:1234" # Initialize the API api = EmbeddingAPIClient(embedding_service_endpoint) # Get embedding model name print(api.get_api_model_name()) # Transform text to embedding text = "Hello, world!" embedding = api.embed_query(text) print(embedding) ``` -------------------------------- ### Launch Topic Analysis Demonstrator Source: https://github.com/rte-france/bertrend/blob/main/README.md Command to launch the topic analysis demonstrator using Streamlit. It requires navigating to the correct directory and setting a GPU device. ```bash cd bertrend/demos/topic_analysis CUDA_VISIBLE_DEVICES= streamlit run app.py ``` -------------------------------- ### Newsletter Configuration (TOML) Source: https://github.com/rte-france/bertrend/blob/main/docs/mail_configuration.md Example TOML configuration for BERTrend's newsletter feature. This specifies the recipients and title for the automated newsletters. Other newsletter-related settings can also be defined here. ```toml [newsletter] recipients = "['recipient1@example.com', 'recipient2@example.com']" title = "Your Newsletter Title" # ... other newsletter settings ``` -------------------------------- ### Launch Weak Signal Analysis Demonstrator Source: https://github.com/rte-france/bertrend/blob/main/README.md Command to launch the weak signal analysis demonstrator. Similar to the topic analysis demonstrator, it involves changing directory and specifying a GPU. ```bash cd bertrend/demos/weak_signals CUDA_VISIBLE_DEVICES= streamlit run app.py ``` -------------------------------- ### Restore BERTopic Model from Timestamp Source: https://github.com/rte-france/bertrend/blob/main/getting_started/bertrend_quickstart.ipynb Restores a BERTopic model for a specific timestamp. This operation requires a Timestamp object and the bertrend library. It loads the model state corresponding to the given time. ```python selected_timestamp = Timestamp("2017-04-20 00:00:00") selected_topic_model = bertrend.restore_topic_model(selected_timestamp) ``` -------------------------------- ### Split Data into Time Slices (Python) Source: https://github.com/rte-france/bertrend/blob/main/getting_started/bertrend_quickstart.ipynb Splits a Pandas DataFrame into smaller DataFrames based on a specified daily granularity. This is useful for time-series analysis or processing data in manageable chunks. It uses the `group_by_days` utility function from `bertrend.utils.data_loading`. ```python from bertrend.utils.data_loading import group_by_days, load_data day_granularity = 30 grouped_data = group_by_days(df=df, day_granularity=day_granularity) ``` -------------------------------- ### Run Prospective Demo with GPU (Bash) Source: https://github.com/rte-france/bertrend/blob/main/docs/demos.md Navigates to the Prospective Demo directory, sets the CUDA_VISIBLE_DEVICES environment variable, and runs the Streamlit application. Requires Streamlit and a CUDA-enabled GPU. ```bash cd bertrend_apps/prospective_demo CUDA_VISIBLE_DEVICES= streamlit run app.py ``` -------------------------------- ### Format DataFrame for BERTrend Source: https://github.com/rte-france/bertrend/blob/main/getting_started/bertrend_quickstart.ipynb Renames columns in a Pandas DataFrame to match BERTrend's expected format ('timestamp', 'url', 'text'). It also adds 'source' and 'document_id' columns and resets the index. This prepares the data for subsequent processing. ```python df = df.rename(columns={"Time": "timestamp", "Tweet URL": "url", "Tweet Text": "text"}) df["source"] = df["ID"] df["document_id"] = df.index df.reset_index(inplace=True, drop=True) df.head(5) ``` -------------------------------- ### Analyze Signal with BERTopic Source: https://github.com/rte-france/bertrend/blob/main/getting_started/bertrend_quickstart.ipynb Analyzes a signal within the BERTopic context, likely related to trend detection or anomaly identification. This function returns a summary, analysis details, and formatted HTML output, indicating a comprehensive signal examination process. ```python summary, analysis, formatted_html = analyze_signal(bertrend, 1, selected_timestamp) ``` -------------------------------- ### Save Trained BERTrend Model Source: https://github.com/rte-france/bertrend/blob/main/getting_started/bertrend_quickstart.ipynb Saves the trained BERTrend model to a specified location. It's important to note that if an embedding model (like sentence-transformers or HuggingFace models) was used, it should ideally be saved explicitly using a pointer for better reproducibility. ```python bertrend.save_model() ``` -------------------------------- ### Fit BERTopic Model in BERTrend Source: https://github.com/rte-france/bertrend/blob/main/getting_started/bertrend_quickstart.ipynb Fits a BERTopic model for trend analysis. This process involves training topic models for different periods and potentially merging them. Warnings may arise if custom topic assignments are used before reduction, or if embedding models are not explicitly defined during saving. ```python bertrend.BERTopicModel().fit() ``` -------------------------------- ### Generate Query File Command Parameters (Bash) Source: https://github.com/rte-france/bertrend/blob/main/docs/data_provider.md Detailed parameters for the `generate-query-file` command in bash. Includes required keywords, optional date ranges (`--after`, `--before`), the output file path (`--save-path`), and an interval for request splitting (`--interval`). ```bash python -m data_provider generate-query-file [OPTIONS] [KEYWORDS] Generates a query file to be used with the auto-scrape command. This is useful for queries generating many results. This will split the broad query into many ones, each one covering an 'interval' (range) in days covered by each atomic request. If you want to cover several keywords, run the command several times with the same output file. Parameters ---------- keywords: str query described as keywords after: str "from" date, formatted as YYYY-MM-DD before: str "to" date, formatted as YYYY-MM-DD save_path: str Path to the output file (jsonl format) Returns ------- ╭─ Arguments ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮ │ keywords [KEYWORDS] keywords for news search engine. [default: None] │ ╰────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯ ╭─ Options ──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮ │ --after TEXT date after which to consider news [format YYYY-MM-DD] [default: None] │ │ --before TEXT date before which to consider news [format YYYY-MM-DD] [default: None] │ │ --save-path TEXT Path for writing results. File is in jsonl format. [default: None] │ │ --interval INTEGER Range of days of atomic requests [default: 30] │ │ --help Show this message and exit. │ ╰────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯ ``` -------------------------------- ### Iterate and Classify Signals with BertTrend Source: https://github.com/rte-france/bertrend/blob/main/getting_started/bertrend_quickstart.ipynb This Python code iterates through document groups (likely time periods) in the BertTrend object. For each time series, it classifies weak and strong signals using a specified window size. It then prints the timestamp and displays the top 5 topics and their representations for any detected weak or strong signals. ```python for ts in bertrend.doc_groups.keys(): print(ts) noise_topics_df, weak_signal_topics_df, strong_signal_topics_df = ( bertrend.classify_signals(window_size, ts) ) if not weak_signal_topics_df.empty: print("Weak signals") display(weak_signal_topics_df[["Topic", "Representation"]].head(5)) if not strong_signal_topics_df.empty: print("Strong signals") display(strong_signal_topics_df[["Topic", "Representation"]].head(5)) print() ``` -------------------------------- ### Generate Query File CLI (Bash) Source: https://github.com/rte-france/bertrend/blob/main/docs/data_provider.md Command-line interface for generating a query file using the `bertrend_apps.data_provider` module. This command takes keywords, date ranges, and an output path to create a JSONL file suitable for batch scraping. It allows for specifying an interval in days for splitting requests. ```bash python -m bertrend_apps.data_provider generate-query-file --help ``` -------------------------------- ### Run BERTrend Embedding Server Container Source: https://github.com/rte-france/bertrend/blob/main/docs/docker.md Launches the BERTrend embedding server as a standalone Docker container. It maps ports, mounts volumes for Hugging Face cache, and configures user IDs for host file permissions, enabling GPU acceleration with `--gpus all`. ```bash docker run --gpus all -p 6464:6464 \ -v /path/to/huggingface/cache:/root/.cache/huggingface \ -e HOST_UID=$(id -u) -e HOST_GID=$(id -g) \ -e HF_HOME=/root/.cache/huggingface \ bertrend-embedding-server:latest ```