Code Tactics
الذهاب إلى القناة على Telegram
ur portal to the freshest tech stuff! ⚡️ What I drop here’s shit I need, love, think about... not just for u 😁
إظهار المزيد513
المشتركون
لا توجد بيانات24 ساعات
-37 أيام
-330 أيام
أرشيف المشاركات
513
t (including any necessary intermediate directories).
* Read Source File: Uses
with open(...) to read the .md file content using UTF-8 encoding.
* Skip Empty Files: If the file content is empty, skip it.
* Call Translation Function: Passes the file content to the translate_text_ollama function for translation.
* Write Target File: If translation was successful (returned non-None), writes the translated result to the corresponding target path file using UTF-8 encoding.
* Handle Failure: If translation failed, prints an error message and skips the file.
* Apply Delay: Calls time.sleep(REQUEST_DELAY) to wait for the specified number of seconds.
* If not an .md file or directory: Prints a skipping message.
5.
Main Execution Block (if __name__ == "__main__":):
* This is the script's entry point.
* Prints startup information, showing the configuration parameters.
* Check Source Directory: Ensures SOURCE_DIR exists; exits with an error if not.
* Create Target Directory: Creates TARGET_DIR if it doesn't exist.
* Start Processing: Calls the process_directory function, starting from the top-level SOURCE_DIR and TARGET_DIR.
* Completion & Error Catching: Uses a try...except block to catch potential errors during the entire process and prints a completion message or error information at the end. Part 4: Running the Script and Considerations How to Run the Script: 1. Open Terminal.
2.
Navigate to the Project Directory: Use the cd command to enter the servbay_translator folder you created. cd /path/to/your/servbay_translator # Example if using ServBay's default www location: # cd /Applications/ServBay/www/servbay_translator 3.
Ensure ServBay and Ollama Service are Running: Go back to the ServBay interface and confirm that the AI -> Ollama service is active.
4.
Run the Python Script: python translate_script.py # Or use python3 if 'python' points to Python 2 on your system # python3 translate_script.py 5.
Observe the Output: The script will start running and print progress information in the terminal, including which directory and file it's processing, the status of requests being sent, and brief info about the translation results or errors.
6.
Check the Results: After the script finishes, check the translated_docs folder. You should see a directory structure identical to the docs folder, containing the translated .md files. Open a few files to check the translation quality and the preservation of Markdown formatting. Considerations and Potential Optimizations: 1.
Model Choice and Translation Quality:
* Translation quality highly depends on the LLM you choose (MODEL_NAME). Different models may perform differently on various language pairs and text types.
* Experiment with different models (e.g., various versions of llama3, mistral, qwen, gemma3, etc.) and parameter sizes to find what works best for your needs.
* For specific language pairs, there might be specially fine-tuned models that perform better; check the Ollama community or platforms like Hugging Face.
2.
Prompt Engineering:
* The prompt in the translate_text_ollama function significantly impacts the translation result. You can try adjusting the instructions, for example:
* Explicitly specifying the source language (if the LLM needs it).
* Making more specific requests about format preservation.
* Trying different tones (formal, informal).
* If the translation results are unsatisfactory, refining the prompt is often the first step.
3.
Markdown Format Preservation:
* Although the prompt requests format preservation, LLMs might sometimes still miss or mishandle complex Markdown syntax (like nested lists,[...]21 أبريل 2025, 04:17
21 أبريل 2025, ~04:47
513
here).
*
time: For adding delays between requests (time.sleep).
2.
Configuration Constants:
* OLLAMA_API_URL: The endpoint for the Ollama generation API. Ensure this matches the IP and port in your ServBay configuration.
* MODEL_NAME: Crucial! Must exactly match the name (including the tag) of the model you downloaded in ServBay and wish to use. Modify this according to your chosen model.
* SOURCE_DIR: The name of the folder containing the original .md files.
* TARGET_DIR: The name of the folder where the translated .md files will be saved.
* TARGET_LANGUAGE: The name of the language you want to translate into. Use clear language names like "Simplified Chinese", "French", "German", "English". LLMs usually understand these natural language instructions.
* REQUEST_DELAY: How many seconds to wait after processing one file before starting the next. This helps prevent overloading the Ollama service or exhausting local machine resources, especially when processing many files or using resource-intensive models.
3. translate_text_ollama Function:
* Takes the original text, model name, and target language as input.
* Build Prompt: This is key to communicating with the LLM. We construct a clear instruction telling the model:
* The task is to "Translate the following Markdown text into [Target Language]".
* Emphasize "Preserve the original Markdown formatting". This is vital for document translation.
* Request "Only output the translated text" to avoid extra explanatory phrases from the model (like "Here is the translation:").
* Use --- separators to clearly mark the original text.
* Prepare API Request: Set the request headers (Content-Type: application/json) and the request body (data).
* model: Specifies the model to use.
* prompt: Our carefully crafted instruction.
* stream: False: We want the complete translation result at once, not streamed fragments.
* options (commented out optional part): You can pass additional Ollama parameters like temperature (controls randomness/creativity; for translation, lower values like 0.2-0.5 are often better).
* Send Request: Use requests.post to send the request to the Ollama API. A longer timeout (300 seconds) is set to handle potentially large files or slower model responses.
* Error Handling:
* response.raise_for_status(): Checks for HTTP-level errors (like 404 Not Found, 500 Internal Server Error).
* try...except block catches network request errors (requests.exceptions.RequestException), JSON parsing errors (json.JSONDecodeError), and other unexpected errors.
* Parse Response: If the request is successful, extract the response field from the returned JSON data, which usually contains the complete text generated by the LLM (i.e., the translation). .strip() removes any leading/trailing whitespace.
* Return Result: Returns the translated text, or None if an error occurred.
4. process_directory Function:
* This is a recursive function designed to handle the directory structure.
* Takes the current source directory path (source_base) and the corresponding target directory path (target_base).
* Uses os.listdir to get all files and subdirectories in the current directory.
* Iterates:
* If it's a subdirectory: Prints info and recursively calls process_directory for that subdirectory, passing the updated source and target paths.
* If it's a file ending with .md:
* Prints info.
* Create Target Directory: Uses os.path.dirname to get the expected parent directory of the target file. If this directory doesn't exist, os.makedirs creates i[...]21 أبريل 2025, 04:17
21 أبريل 2025, ~04:47
513
in response_data: translated_text = response_data['response'].strip() print(f" Translation received (length: {len(translated_text)} chars).") return translated_text else: print(f" Error: 'response' key not found in Ollama output: {response_data}") return None except requests.exceptions.RequestException as e: print(f" Error calling Ollama API: {e}") return None except json.JSONDecodeError: print(f" Error decoding JSON response from Ollama: {response.text}") return None except Exception as e: print(f" An unexpected error occurred during translation: {e}") return None # --- Main Processing Logic --- def process_directory(source_base, target_base): """
Recursively traverses the source directory, translates .md files,
and saves them to the target directory, preserving structure. """ print(f"\nProcessing directory: {source_base}") for item in os.listdir(source_base): source_path = os.path.join(source_base, item) target_path = os.path.join(target_base, item) if os.path.isdir(source_path): # If it's a subdirectory, process it recursively print(f"- Found subdirectory: {item}") process_directory(source_path, target_path) elif os.path.isfile(source_path) and item.lower().endswith(".md"): # If it's a Markdown file, translate it print(f"- Found Markdown file: {item}") # Ensure the target file's parent directory exists target_file_dir = os.path.dirname(target_path) if not os.path.exists(target_file_dir): print(f" Creating target directory: {target_file_dir}") os.makedirs(target_file_dir) # Optional: Check if target file already exists and skip # if os.path.exists(target_path): # print(f" Skipping, target file already exists: {target_path}") # continue try: # Read the source file content print(f" Reading source file: {source_path}") with open(source_path, 'r', encoding='utf-8') as f_in: original_content = f_in.read() if not original_content.strip(): print(" Skipping empty file.") continue # Call Ollama for translation translated_content = translate_text_ollama(original_content, MODEL_NAME, TARGET_LANGUAGE) if translated_content: # Write the translated content to the target file print(f" Writing translated file: {target_path}") with open(target_path, 'w', encoding='utf-8') as f_out: f_out.write(translated_content) print(" Translation complete for this file.") else: print(f" Failed to translate file: {source_path}. Skipping.") # Add delay between API requests if REQUEST_DELAY > 0: print(f" Waiting for {REQUEST_DELAY} second(s)...") time.sleep(REQUEST_DELAY) except Exception as e: print(f" Error processing file {source_path}: {e}") else: print(f"- Skipping non-Markdown file or other item: {item}") # --- Script Entry Point --- if __name__ == "__main__": print("Starting Markdown Bulk Translation Process...") print(f"Source Directory: {SOURCE_DIR}") print(f"Target Directory: {TARGET_DIR}") print(f"Target Language: {TARGET_LANGUAGE}") print(f"Using Ollama Model: {MODEL_NAME} at {OLLAMA_API_URL}") print("-" * 30) # Check if source directory exists if not os.path.isdir(SOURCE_DIR): print(f"Error: Source directory '{SOURCE_DIR}' not found.") print("Please create the 'docs' directory and place your Markdown files inside.") exit(1) # Check/Create target directory if not os.path.exists(TARGET_DIR): print(f"Creating target directory: {TARGET_DIR}") os.makedirs(TARGET_DIR) # Start processing try: process_directory(SOURCE_DIR, TARGET_DIR) print("\n" + "=" * 30) print("Batch translation process finished!") print(f"Translated files are saved in the '{TARGET_DIR}' directory.") except Exception as e: print(f"\nAn error occurred during the process: {e}") Code Explanation: 1.
Import Libraries (import os, requests, json, time):
* os: For file and directory operations (walking directories, checking paths, creating directories, etc.).
* requests: For sending HTTP POST requests to the Ollama API.
* json: For handling JSON data in API requests/responses (though requests handles much of this internally [...]
21 أبريل 2025, 04:17
21 أبريل 2025, ~04:47
513
ronment: Ensure Python is installed on your system. You can check by running python --version or python3 --version in your terminal. ServBay comes with Python 3. If not installed, install it from ServBay's Packages -> Python. https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fartg92kykxpqfn13a9q0.png 1. requests Library: We need the requests library to send HTTP requests to the Ollama API. If not already installed, run this in your terminal: pip install requests # or
pip3 install requests 2.
Create Project Structure: - Create a project folder, for example, `servbay_translator`.
- Inside the `servbay_translator` folder, create a subfolder named `docs`. Place the Markdown files (`.md`) you need to translate into the `docs` folder and its subfolders. For example: ```
servbay_translator/
├── docs/
│ ├── introduction.md
│ ├── chapter1/
│ │ └── setup.md
│ └── chapter2/
│ └── usage.md
└── translate_script.py (We will create this file)
``` - The script will automatically create a `translated_docs` folder to store the translated files, maintaining the original directory structure. Python Script (translate_script.py) import os import requests import json import time # --- Configuration Constants --- # Ollama API address and port (consistent with ServBay config) OLLAMA_API_URL = "http://127.0.0.1:11434/api/generate" # The model name you downloaded in ServBay and want to use for translation
# Ensure it exactly matches the model name in Ollama
# Examples: "llama3:8b", "mistral:7b", "deepseek-llm:7b-chat" etc. MODEL_NAME = "llama3:8b" # <---# Directory containing the source Markdown files SOURCE_DIR = "docs" # Directory to store the translated files (script will create it) TARGET_DIR = "translated_docs" # The target language you want to translate the documents into TARGET_LANGUAGE = "English" # Examples: "Simplified Chinese", "French", "German", "Japanese", "Spanish" # Optional: Add a delay (in seconds) between requests to avoid overloading or give the system time to respond REQUEST_DELAY = 1 # 1 second delay, adjust as needed # --- Ollama API Call Function --- def translate_text_ollama(text_to_translate, model_name, target_language): """
Translates the given text using the Ollama API.
Args:
text_to_translate (str): The original text to be translated.
model_name (str): The name of the Ollama model to use.
target_language (str): The target language for translation.
Returns:
str: The translated text, or None if an error occurred. """ # Construct a clear translation instruction prompt prompt = f"""Translate the following Markdown text into {target_language}.
Preserve the original Markdown formatting (like headings, lists, bold text, code blocks, etc.).
Only output the translated text, without any introductory phrases like "Here is the translation:".
Original Text:
--- {text_to_translate}
---
Translated Text ({target_language}):""" headers = {'Content-Type': 'application/json'} data = { "model": model_name, "prompt": prompt, "stream": False, # Set to False to get the full response at once, not streaming # Optional parameters, adjust as needed, e.g., temperature controls creativity (lower is more conservative) # "options": { # "temperature": 0.3 # } } try: print(f" Sending request to Ollama (model: {model_name})...") # Increase timeout to 300 seconds for potentially long translations response = requests.post(OLLAMA_API_URL, headers=headers, json=data, timeout=300) response.raise_for_status() # Check for HTTP errors (e.g., 404, 500) response_data = response.json() # Extract the translated text from the response # Ollama's /api/generate response structure usually contains the full output in the 'response' field if 'response'[...]
21 أبريل 2025, 04:17
21 أبريل 2025, ~04:47
513
This lists models available for download and those already installed locally. Step 4: Search for and Download a Translation Model Now we need to select and download an LLM suitable for translation tasks. An LLM's translation capability is often related to its general instruction-following ability and multilingual training data. Some good choices might include (as of writing):
* Llama 3 series (e.g.,
llama3:8b): Meta AI's latest open-source model, with strong general capabilities and good instruction following, usually handles translation tasks well. The 8B version has relatively moderate hardware requirements.
* Mistral series (e.g., mistral:7b): Another very popular high-performance open-source model known for its efficiency.
* DeepSeek Coder/LLM series (e.g., deepseek-llm:7b-chat): Although DeepSeek is known for its coding abilities, its general chat models usually also possess translation capabilities. The deepseek-r1 in the screenshot might be one of its variants or a specific version.
* Specialized Translation Models (if available in the Ollama library): Sometimes there are models specifically optimized for translation, but strong general instruction-following models often perform very well too. Performing Search and Download: 1. In the search box at the top of the model management interface, enter the name of the model you want to find, e.g., llama3 or mistral.
2. The interface will dynamically display a list of matching models, including different parameter sizes (like 7b, 8b, 70b, etc.) and tags (like latest, instruct, chat).
3. Considerations when selecting a model:
* Parameters: Such as 7b (7 billion), 8b (8 billion), 70b (70 billion). Larger parameter counts usually mean stronger capabilities but also higher requirements for memory (RAM) and video memory (VRAM), and slower inference speed. For batch translation, a 7b or 8b model is often a good starting point, balancing performance and resource consumption.
* Tags: Models tagged instruct or chat are usually better at following instructions (like "Please translate the following text into...").
* File Size: Note that model files can be large (from several GB to tens of GB). Ensure you have sufficient disk space.
4. Find the model version you want to download (e.g., llama3:8b) and click the download icon next to it (usually a downward arrow).
5. ServBay will start downloading the model. You can see the download progress. The download time depends on your network speed and the model size. Step 5: Verify Model Installation Once the model download is complete, it should appear in the list of installed models on the left side of the Ollama Config interface. Also, in the Models (Ollama) interface, the action button for that model might change to a delete icon (🗑️). Step 6: Confirm Ollama Service is Running Ensure the status indicator at the top of the Ollama Config interface shows green or a running state. ServBay usually starts the Ollama service automatically when you launch the application or enable the AI features. If the service is not running, look for a start button and activate it.
At this point, your ServBay environment has the Ollama service configured, and you have downloaded a local LLM ready for translation. Next, we will write the Python script to call this local AI service. Part 3: Writing the Python Script for Batch Translation Now that we have an LLM running locally and accessible via an API (http://127.0.0.1:11434), let's write a Python script to automate the translation process: iterate through all Markdown files in the specified docs folder, send their content to Ollama for translation, and save the results to new files. Prerequisites 1. Python Envi[...]21 أبريل 2025, 04:17
21 أبريل 2025, ~04:47
513
Role.For Session Manager to work, the instance needs an IAM role with SSM permissions. Create a role with the following managed policy attached:
AmazonSSMManagedInstanceCore
* Under Trusted entity type, choose AWS service.
* Under Use case, select** EC2** and click Next.
* Attach the policy:
AmazonSSMManagedInstanceCore.
* Click Next, name the role (e.g., SSM_EC2_Access), and create the role.
1.
Attach the IAM Role to Your EC2 Instance
If you are launching a new instance:
* In the EC2 launch wizard, under Advanced Details, locate IAM
Instance Profile.
* Select the IAM role (SSM_EC2_Access) created earlier.
* If the instance is already running:
* Navigate to EC2 Console > Instances.
* Select your instance and go to Actions > Security > Modify
IAM Role.
* Select the SSM_EC2_Access role and save changes.
2.
Ensure SSM Agent is Installed
Amazon Linux and Ubuntu AMIs come with SSM Agent pre-installed. If using another OS, install the agent manually: sudo yum install -y amazon-ssm-agent # Amazon Linux
sudo snap install amazon-ssm-agent # Ubuntu For Windows: Start-Service AmazonSSMAgent 1. Connect to the Instance Using Session Manager
Once the instance is properly configured:
* AWS Console → EC2 → Select Instance → Click on "Connect"
Select Session Manager → Click "Start session" Or
* Navigate to AWS Systems Manager > Session Manager.
* Click Start session.
* Select the instance and click Start session.
* You now have shell access to the EC2 instance.
Alternatively, use the AWS CLI:aws ssm start-session --target <instance-id
Troubleshooting
If you cannot connect using Session Manager, check the following:
* Ensure IAM role is attached to the instance.
* Confirm AmazonSSMManagedInstanceCore policy is included.
* Verify SSM Agent is installed and running. ( Ensure the EC2 Instance Has SSM Agent Installed
Most Amazon Machine Images (AMIs), including Amazon Linux 2 and Ubuntu, come with the SSM Agent pre-installed. To verify, run:sudo systemctl status amazon-ssm-agent
* Make sure the instance has internet access or a VPC endpoint for SSM.
Conclusion
Among the different methods of connecting to an EC2 instance, Session Manager stands out as the most secure and managed approach. Unlike PuTTY, where you must handle key configurations and security yourself, AWS manages the entire access process for you. No inbound ports need to be opened, and access is controlled centrally via IAM. If you're looking for a robust and secure way to manage your EC2 instances, Session Manager is the way to go.
This is part of my hands-on cloud learning journey, and I hope it helps anyone navigating the different ways to connect to an EC2 instance. Let me know if you have any questions or if there's anything you'd like me to explore further!21 أبريل 2025, 04:17
21 أبريل 2025, ~04:47
513
ource-name export RG_NAME=<your-resource-group-name Get the resource ID of the Azure OpenAI resource and assign the Cognitive Services OpenAI Contributor role to the service principal: export AZURE_OPENAI_ID=$(az cognitiveservices account show --name $AZURE_OPENAI_RESOURCE_NAME --resource-group $RG_NAME --query "id" -o tsv)
az role assignment create --assignee $PRINCIPAL_ID --role "Cognitive Services OpenAI Contributor" --scope $AZURE_OPENAI_ID Assign Azure Cosmos DB role export COSMOSDB_ACCOUNT=<your-cosmosdb-account-name export COSMOSDB_RG_NAME=<your-resource-group-name Get the resource ID of the Azure Cosmos DB account and assign the Cosmos DB Built-in Data Contributor role to the service principal: export COSMOSDB_ACC_ID=$(az cosmosdb show --name $COSMOSDB_ACCOUNT --resource-group $COSMOSDB_RG_NAME --query "id" -o tsv)
az cosmosdb sql role assignment create -n "Cosmos DB Built-in Data Contributor" -g $COSMOSDB_RG_NAME -a $COSMOSDB_ACCOUNT -p $PRINCIPAL_ID --scope $COSMOSDB_ACC_ID Run the web application Make sure you have Go installed on your machine. You can download it from here.
Clone the GitHub repository: git clone https://github.com/abhirockzz/cosmosdb_openai_vector_embedding_webapp_golang cd cosmosdb_openai_vector_embedding_webapp_golang
go mod tidy Set the service principal credentials as environment variables, and run the application: export AZURE_TENANT_ID="<tenant" export AZURE_CLIENT_ID="<value" export AZURE_CLIENT_SECRET="<value"
go run main.go You will be asked to configure the app - enter values for Azure Cosmos DB endpoint, Azure OpenAI endpoint, and more. https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Frvecz80wkfxoeuv6dqdi.png Once that's done, go ahead and enter a URL for a file, or choose any text file(s) from your local machine: https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F96zm3lsn6yq5yilvpsdi.png As part of the processing, the vector embeddings will be generated and stored in Azure Cosmos DB. The application will show you the progress as well.
Once the processing finishes, verify the same in Azure Cosmsos DB. For example, if you chose to process the following markdown file URL, run this query to see the results: SELECT c.id FROM c WHERE CONTAINS(c.metadata.source, "vector-search.md") Now you can execute vector queries using the Azure Cosmos DB SDKs. For example, refer to the Vector/Similarity search section in this blog. Troubleshooting If you see an error similar to Error: HTTP error! status: 500, message: Failed to process, the issue could be related to:
* RBAC - make sure the service principal has the right permissions for Azure Cosmos DB and Azure OpenAI
* You entered an incorrect database, container, or Azure OpenAI model name
* Either of Cosmos DB or Azure OpenAI endpoints are incorrect
21 أبريل 2025, 04:17
21 أبريل 2025, ~04:47
513
eters, and even perform fine-tuning (although ServBay itself doesn't directly provide fine-tuning features, the localized Ollama environment lays the foundation for it).
* Low Latency: Requests are sent directly to the locally running service, typically resulting in lower latency and faster responses compared to calling remote APIs over the internet.
In summary, by integrating Ollama, ServBay significantly lowers the barrier for users to utilize local large language models, seamlessly incorporating their powerful AI capabilities into a familiar development environment, providing a solid foundation for implementing advanced automation tasks like batch document translation. https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fh09tb9zzptzqe26laerd.png Part 2: Installing and Configuring Ollama and Models in ServBay Now, let's walk through setting up the Ollama service in ServBay step-by-step and download a model suitable for translation tasks. Step 1: Navigate to ServBay's AI Configuration 1. Launch the ServBay application.
2. In the left-hand navigation bar of the ServBay main interface, find and click AI.
3. In the AI sub-menu, click Ollama. You should see an interface similar to the
Ollama Config shown in the first screenshot. Step 2: Check and (Optionally) Adjust Ollama Configuration ServBay usually provides a reasonable set of default configurations, often sufficient for initial use or basic tasks. However, understanding these options helps with future optimization:
* Ollama Service Status: There is usually a toggle switch or status indicator at the top of the interface (a green dot in the screenshot). Ensure the Ollama service is enabled. If ServBay provides Start/Stop buttons, make sure it's running.
* Bind IP and Bind Port: The defaults 127.0.0.1 and 11434 are standard configurations, meaning the Ollama service listens only for requests from the local machine on port 11434. This is the address our Python script will need to connect to later. Usually, no changes are needed.
* Models folder: This is the path where downloaded LLM models are stored. The screenshot shows /Applications/ServBay/db/ollama/models. You can change this to another location with sufficient disk space if needed, but ensure the path exists and ServBay has write permissions. Note this path; although the script doesn't use it directly, knowing where the models are is helpful.
* Model Download Threads: The number of concurrent threads used when downloading models. If you have a good network connection, you can increase this slightly to speed up downloads. The default is 10.
* Other Options (e.g., GPU Overhead, Max loaded models, etc.): These are more advanced performance tuning options. If you have a compatible GPU (NVIDIA or Apple Silicon), Ollama usually detects and uses it automatically. Max loaded models limits the number of models loaded into memory/VRAM simultaneously, depending on your RAM/VRAM size. For batch translation tasks, usually only one model is loaded at a time, so the default value is generally sufficient.
* Origins: This is the CORS (Cross-Origin Resource Sharing) setting, controlling which web pages (origins) can access the Ollama API. The default includes various variations of http://localhost and http://127.0.0.1, which is usually sufficient for local scripts or local web applications.
Important Note: If you modify any configuration, be sure to click the Save button in the lower right corner of the interface to apply the changes. If you encounter problems, you can try clicking Reset to restore the default settings. Step 3: Navigate to the Model Management Interface 1. In the left-hand navigation bar of ServBay, under the AI category, click Models (Ollama).
2. You will see a model management interface similar to the second screenshot. [...]21 أبريل 2025, 04:17
21 أبريل 2025, ~04:47
513
hromedriver beautifulsoup4
Step 3: Writing the Python Script
Here’s a basic script to get you started with scraping Google Search results. import time from selenium.webdriver.common.keys import Keys import undetected_chromedriver as uc from bs4 import BeautifulSoup # Setup driver = uc.Chrome() driver.get("https://www.google.com") # Search for a query search_box = driver.find_element("name", "q") search_box.send_keys("web scraping python") search_box.send_keys(Keys.RETURN) # Wait for the results to load time.sleep(5) # Parse the page soup = BeautifulSoup(driver.page_source, 'lxml') listings = soup.select('#rso > div') # Extract information for listing in listings: container = listing.find('div', class_="N54PNb BToiNc") if container: url = container.find('a')['href'] title = container.find('h3').text description = container.find_all('span')[-1].text print(url, title, description, '\n') Step 4: Handle Data and Save to CSV
Most of the time, you’ll want to store the results in a structured format like CSV. Here’s how you can modify the script to save the results to a file: import csv with open('google_search_results.csv', 'w', newline='', encoding='utf-8') as csvfile: writer = csv.writer(csvfile) writer.writerow(['URL', 'Title', 'Description']) # Header row for listing in listings: container = listing.find('div', class_="N54PNb BToiNc") if container: url = container.find('a')['href'] title = container.find('h3').text description = container.find_all('span')[-1].text writer.writerow([url, title, description]) driver.quit() print("Data saved to google_search_results.csv") Handling IP Blocking and CAPTCHA Google is vigilant about blocking scrapers, so it's important to take steps to avoid getting blocked. Here are a few tips:
Rotate IPs: Use residential proxies that rotate your IP address with every request.
Set Request Delays: Always introduce a small delay between requests to avoid hitting the server too hard.
Use a CAPTCHA Solving Service: If you encounter CAPTCHAs, services like 2Captcha or CapSolver can help you bypass them.
Change User-Agent Strings: Rotating user-agent strings will help disguise your scraper as a regular user. Conclusion Scraping Google Search results may sound daunting at first, but with the right tools and strategies, it’s entirely doable. Whether you choose to use Python libraries like Selenium or opt for a more hands-off approach with a scraper API, the key is to start small and scale up.
21 أبريل 2025, 04:17
21 أبريل 2025, ~04:47
513
nage Ollama. Users don't need to manually download Ollama, configure environment variables, or manage complex dependencies. Simply enable and configure it briefly in ServBay's AI panel, and you have a ready-to-use local LLM service.
* Visual Configuration Management: ServBay offers rich configuration options, such as
Model Download Threads, Bind IP, Bind Port (defaults to 127.0.0.1:11434, the standard Ollama configuration), debug switches (Debug, Flash Attention, No History, No Prune, Schedule Spread, Multi-user Cache), cache type (K/V Cache Type), GPU optimization (GPU Overhead), connection persistence (Keepalive), load timeout (Load Timeout), maximum loaded models (Max loaded models), maximum queue (Max Queue), parallel processing number (Parallel Num.), LLM library path (LLM Library), model storage path (Models folder), and access origin control (origins). This allows users to fine-tune Ollama's runtime parameters based on their hardware and needs without memorizing command-line arguments.
* Unified Ecosystem: Integrating Ollama into ServBay means your web development environment and AI inference environment can work together under the same management platform. This provides great convenience for developing web applications that require AI functions (such as intelligent customer service, content generation, local data analysis, etc.). Convenient Model Management Just having a running framework isn't enough; selecting and managing appropriate AI models is equally important. ServBay excels in this area as well:
* Model Listing and Search: ServBay provides a model list interface where users can directly search for available models in the official Ollama model library (e.g., the screenshot shows searching for deeps displaying different versions of deepseek-r1).
* One-Click Download and Deletion: For searched models, the interface clearly displays the model name (including tags like latest, 1.5b, 7b, etc.), base model, number of parameters (Parameters), file size (File Size), and action buttons (download + or delete). Users simply click a button, and ServBay automatically handles the download and storage of the model (the storage path can be specified in the Ollama configuration, defaulting to /Applications/ServBay/db/ollama/models).
* Local Model Overview: In the Ollama Config interface (first screenshot), the left-side list shows the models currently downloaded locally (e.g., alfred, all-minilm, codellama, etc.). This gives users a clear overview of the local AI "brains" they possess. Core Value of Local AI Why use local AI (via Ollama in ServBay) for translation instead of continuing with online services?
* Data Privacy and Security: This is the most crucial advantage. All data processing is done on your own computer; your document content doesn't need to be sent to any third-party servers. This is essential for documents containing sensitive information or trade secrets.
* Cost-Effectiveness: Running LLMs locally incurs no API call fees. While there might be an initial hardware investment (especially if GPU acceleration is needed), the long-term cost for large or frequent tasks is far lower than pay-as-you-go cloud services.
* Offline Availability: Once a model is downloaded locally, you can perform translation or other AI tasks without an internet connection, which is very useful in environments with unstable networks or scenarios requiring complete offline operation.
* Customization and Control: You have the freedom to choose the model best suited for your task and hardware, experiment with different model versions and param[...]21 أبريل 2025, 04:17
21 أبريل 2025, ~04:47
513
solution.
For developers eager to explore more, we recommend consulting Warp's official documentation and delving into community-led forums and discussions for emergent best practices and shared experiences.
By understanding both the potential and pitfalls present in Warp, developers can anticipate a refined workflow—one that balances powerful functionality with an intuitive user experience that transcends traditional command-line environments.
21 أبريل 2025, 04:17
21 أبريل 2025, ~04:47
513
* Use bullet points and images
* End with a call to action or question Conclusion Choosing the right blog post format can make a big difference in how your readers engage with your content. Whether you're writing a simple listicle or a detailed guide, the key is to give value, keep it simple, and make it easy to read. Try mixing these formats on your blog and see what your audience likes the most.
If you found this post helpful, feel free to share it or leave a comment below. And if you’re looking for more blogging tips, stay tuned to my blog!
21 أبريل 2025, 04:17
21 أبريل 2025, ~04:47
513
The DEV Community
[Boost]
https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F3063066%2F0683a163-f3ae-49a4-8fa5-7d709215280d.png
What is the difference between Laravel and Node.js in web development?
PIXAWARE TECHNOLOGY SOLUTIONS PVT LTD ・ Apr 21
21 أبريل 2025, 04:17
21 أبريل 2025, ~04:47
513
The DEV Community Step-by-Step Guide to Scraping Google Search
Ever wondered what hidden gems lie in the data that Google Search provides? With the right tools and know-how, you can unlock valuable insights that can supercharge your digital strategy. Whether you’re optimizing for SEO, analyzing competitors, or discovering new keywords, Google Search results hold a wealth of information that can make a difference.
In this guide, we’ll show you how to scrape Google Search results with Python and break down exactly what you need to know to do it effectively. By the end, you’ll have the knowledge to pull data from the world’s most popular search engine with ease. The Need to Scrape Google Search Google Search is a goldmine for data. The information available in its Search Engine Results Pages (SERPs) can reveal trends, user behavior, and competitive insights. Here's how scraping can help:
SEO Insights: Discover keyword variations, related terms, and opportunities for content optimization.
Competitor Research: Analyze competitors' rankings and strategies.
Brand Monitoring: Track your brand's visibility and media mentions.
Customer Behavior: Uncover trends and preferences based on actual search data.
Every time you dive into Google Search data, you're essentially gaining insights into search behavior, market trends, and user intent. This is valuable intelligence. What You Can Find in Google’s SERPs Google’s SERPs are a dynamic blend of results that can include:
Featured Snippets: These concise answers sit at the top of the search results. Grabbing a spot here can drive significant traffic.
Video Carousels: Videos often surface in searches with high informational intent, offering a window into user engagement.
People Also Ask: These questions, often appearing below organic results, reveal user intent and are a goldmine for content ideas.
Local Pack: For location-based searches, this feature lists businesses that match local queries, giving valuable data for local SEO.
Related Searches: At the bottom of the page, related searches provide alternate keywords, helping you refine your SEO strategy.
By scraping these different elements, you can build a comprehensive picture of what users are searching for and how to optimize your own presence on Google. Different Ways to Scrape Google Search Results There are a few main ways to scrape Google, depending on your level of expertise and what you’re trying to achieve. Here’s a breakdown:
1. Google’s Custom Search JSON API
Google offers a reliable (albeit limited) way to pull search results using its official API. This API is designed to return data in JSON format and avoids blocking issues or CAPTCHA challenges.
2. Building a Custom Scraper
If you're up for a challenge, you can build a scraper from scratch. This gives you total control over the process but requires more technical know-how.
3. Using a Scraper API
Scraper APIs handle much of the heavy lifting for you. These APIs are designed specifically to bypass Google’s defenses and return structured SERP data in JSON or HTML. Scrape Google Search Like a Pro Using Python If you decide to go the DIY route, here’s how to get started. We’ll use Selenium, undetected_chromedriver, and BeautifulSoup to scrape the search results.
Step 1: Inspecting the Results HTML
Start by inspecting the Google Search result page. Right-click and choose Inspect. From there, look for the HTML structure of the organic listings. These are typically wrapped in a div with the id="rso".
Step 2: Setting Up Your Development Environment
Before we jump into the code, let’s ensure your environment is ready. You’ll need:
Python 3.6 or higher
Selenium: Automates the browser interaction.
undetected_chromedriver: Helps bypass CAPTCHA.
BeautifulSoup: For parsing HTML content.
Run this command to install the necessary packages: pip install selenium undetected-c[...]
21 أبريل 2025, 04:17
21 أبريل 2025, ~04:47
513
The DEV Community
Connecting to an EC2 Instance: A Deep Dive into Session Manager
Introduction
When working with Amazon EC2 instances, one of the first things you'll need to do is connect to your instance to manage and configure it. There are several different ways to establish a connection. AWS provides multiple ways to achieve this, each with its own advantages and considerations. One commonly used method is Secure Shell (SSH), which requires key pairs. While many are familiar with SSH via PuTTY or the browser-based EC2 Instance Connect, a more secure and centralized option exists: AWS Systems Manager Session Manager.
In this article, I'll break down the different ways to connect to an EC2 instance, why Session Manager is a game-changer, and how to use it effectively. This is based on my hands-on learning, and I'll make sure to explain the reasoning behind each choice so that both beginners and those interested in cloud deployment can see the depth of understanding involved.
Different Ways to Connect to an EC2 Instance
AWS provides multiple methods to connect to an EC2 instance, and choosing the right one depends on security, ease of use, and the level of management you want. Here are the three primary ways:
1.
EC2 Instance Connect (Browser-Based Access)
* This is the easiest and most direct method.
* Simply click Connect from the AWS Console, and a browser-
based terminal opens.
* No need for SSH keys or additional configurations.
* However, it's only available for Amazon Linux and Ubuntu
instances.
2.
SSH via PuTTY (User-Managed Access)
* Requires downloading PuTTY and configuring it with a
.ppk
private key.
* The key file is generated from the.pem key provided when
launching the instance.
* Requires opening inbound SSH (port 22) in the security
group, which can expose the instance to attacks if not
managed properly.
* AWS does not manage PuTTY access—you handle the
configurations and security yourself.
3.
AWS Systems Manager Session Manager (AWS-Managed Access)
* A fully AWS-managed solution.
* No need to open inbound SSH ports, making it more secure.
* Centralized access control using IAM policies.
* Does not require you to manage key pairs.
* Works with instances that have the SSM Agent installed and
an IAM role with necessary permissions.
What is AWS Session Manager?
AWS Session Manager is a feature of AWS Systems Manager (SSM) that enables secure shell access to EC2 instances without requiring an SSH key or opening ports. It leverages IAM roles to grant access and manage permissions.
Why Choose Session Manager?
Unlike PuTTY, where AWS does not manage the access or security settings, Session Manager offers a hassle-free and secure way to connect to EC2 instances:
* No need for inbound ports: Eliminates the risk of unauthorized access through SSH.
* IAM-based access control: You can define who has permission to access which instances.
-** Centralized logging**: Session logs can be sent to Amazon S3 or CloudWatch for auditing.
* Bastion host replacement: Traditionally, to access private EC2 instances, you’d need a Bastion Host (a publicly accessible instance acting as a gateway). Session Manager removes this requirement.
* Access from anywhere: You don’t need to install additional software like PuTTY—just use the AWS Console or AWS CLI.
What is a Bastion Host?
A Bastion Host is an EC2 instance used as a secure gateway to access other private instances inside a VPC. While effective, it requires proper security configurations and maintenance, unlike Session Manager, which eliminates the need for it entirely.
Steps to Set Up Session Manager for EC2
1. Create an IAM Role for EC2
Since Session Manager relies on IAM roles, we must create a role that grants EC2 the necessary permissions.
* Navigate to AWS IAM Console.
* Select Roles > Create[...]21 أبريل 2025, 04:17
21 أبريل 2025, ~04:47
513
The DEV Community Vector embeddings made easy with Go, Azure Cosmos DB, and OpenAI
When working on applications that need vector/semantic/similarity search, it's often useful to have a quick and easy way to create vector embeddings of data and save them in a vector database for further querying. This blog will walk you through a simple web application using which you can quickly generate vector embeddings for various document types and store them directly into Azure Cosmos DB. Once stored, this data can be leveraged by other applications for tasks like vector search, part of a Retrieval-Augmented Generation (RAG) workflow, and more. https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fidoswlq6dym40jtefr4p.png The application is built using Go using the SDKs for Azure Cosmos DB (azcosmos) and Azure OpenAI (azopenai). It also utilizes the langchaingo library for document loading and text splitting. The frontend is a simple HTML, CSS, and JavaScript embedded directly in the Go application.
* Supports any text content, including file types such as .txt, .pdf, .md, .html, and .csv.
* You can directly reference a file using URLs (example) or use multiple local files at once.
* Easily configure Azure Cosmos DB (endpoint, database, container) and Azure OpenAI (endpoint and embedding model) details.
* No need to use service keys since the application supports service principals via DefaultAzureCredential.
* Also stores source file name in the metadata attribute
Although the application itself can be useful for quick prototyping, it can be built using any language (Python, JS/TS, etc.). Go is heavily used for web applications, especially backend/API components. For those interested in Go, I think this will also serve as a useful learning excercise on how to use Go for building applications using Azure Cosmos DB and Azure OpenAI. Prerequisites Complete these steps before running the application. Setup Azure Cosmos DB Create an Azure Cosmos DB for NoSQL account. Enable the vector indexing and search feature - this is a one-time operation.
Create a database and collection (use partition key /id for this application). Also, configure a vector policy for the container with the right path, distance function, etc. https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fz9yntpvhhe0i2nx7xk41.png Azure OpenAI Create an Azure OpenAI Service resource. Azure OpenAI Service provides access to OpenAI's models including the GPT-4o, GPT-4o mini (and more), as well as embedding models. Deploy an embedding model of your choice using the Azure AI Foundry portal (for example, I used the text-embedding-3-small model). RBAC setup Using RBAC is a good practice as it allows us to use eliminate hardcoding API keys and secrets in the code.
I will show you how to run the app locally. The service principal that you use for the app needs to have the right permissions for Azure Cosmos DB and Azure OpenAI. Create service principal Execute the following command to create a service principal: az ad sp create-for-rbac You should see an output similar to this. Note down the system-assigned password as you can't retrieve it again { "appId": "<the", "displayName": "<the", "password": "<the", "tenant": "<tenant" } Get the principal ID using the following command: export PRINCIPAL_ID=$(az ad sp show --id <entercommand output> --query "id" -o tsv) Assign Azure OpenAI role export AZURE_OPENAI_RESOURCE_NAME=<your-openai-res[...]
21 أبريل 2025, 04:17
21 أبريل 2025, ~04:47
513
The DEV Community
Leveraging ServBay's Local AI Capabilities: Effortlessly Batch Translate Markdown Documents
Introduction In today's increasingly globalized world, the demand for multilingual content is exploding. Whether it's technical documentation, blog posts, research reports, or personal notes, translating them into different languages can significantly expand their audience and impact. However, traditional translation methods, such as manual translation, are costly and time-consuming. Using online translation services (like Google Translate, DeepL, etc.) might involve concerns about data privacy, API call fees, and network connectivity limitations.
For developers, content creators, and tech enthusiasts seeking efficiency, data privacy, and cost-effectiveness, is there a way to perform high-quality batch translation locally, offline, and at a low cost? The answer is yes! With the maturation and popularization of local Large Language Model (LLM) technology, we can now run powerful AI models on our own computers to accomplish various tasks, including text translation.
And for ServBay users, this becomes even simpler and more integrated. ServBay, as a powerful integrated Web development environment, not only provides convenient management of web servers, databases, and language environments but its latest version also keeps pace with technological trends by incorporating built-in support for AI/LLM, specifically integrating the popular Ollama framework. This means you can easily deploy and manage local AI models within the ServBay environment without complex configurations and leverage their powerful capabilities.
This tutorial, based on ServBay, will guide you in detail on how to:
1. Understand ServBay's latest AI/LLM support, particularly its integrated Ollama features.
2. Easily install and configure the Ollama service within ServBay.
3. Search, download, and manage Ollama models suitable for translation tasks through ServBay's graphical interface.
4. Write a Python script that utilizes the Ollama API endpoint provided by ServBay to automate the batch translation of all Markdown (
.md) files within a specified folder (e.g., docs).
Through this tutorial, you will master a powerful, private, and efficient local document translation solution, fully unleashing the potential of ServBay and local AI. Let's embark on this exciting local AI journey! https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F1f40ck5ptnccbulgh4vd.png Part 1: ServBay's AI / LLM New Era: Embracing Local Intelligence ServBay has always been committed to providing developers with a one-stop, efficient, and convenient local development environment. From managing multiple versions of PHP, Python, Java, .Net, Node.js, switching between Nginx/Apache/Caddy, to supporting MySQL/PostgreSQL/MongoDB databases, ServBay greatly simplifies the setup and maintenance of development environments. Now, ServBay is once again at the forefront, integrating powerful AI/LLM capabilities into its core features, opening a new chapter of local intelligence for its users. Integrating Ollama: The Swiss Army Knife for Local LLMs The core of ServBay's AI functionality is the integration of Ollama. Ollama is an open-source project designed to enable users to easily run large language models like Llama 3, Mistral, Phi-3, Gemma3, etc., locally. It significantly simplifies the process of setting up, running, and managing models, providing a standard API interface that allows developers to interact with local models as conveniently as calling cloud services.
ServBay's integration of Ollama brings numerous advantages:
* One-Click Installation and Configuration: ServBay provides a dedicated graphical interface to ma[...]21 أبريل 2025, 04:17
21 أبريل 2025, ~04:47
513
animations: Lottie or Rive.
* For advanced effects and UI graphics: Skia or Framer Motion.
Each library has its strengths, so the best choice depends on your app’s needs.
Thank you for reading! Feel free to connect with me on LinkedIn or GitHub.
21 أبريل 2025, 04:17
21 أبريل 2025, ~04:47
513
de>2.3 Intelligent Command Execution and Suggestions Warp employs machine learning algorithms to analyze previous commands used, learning to suggest commands based on context, thus optimizing repetitive workflows.
// Pseudocode for suggesting commands based on context function suggestCommand(inputContext) { const suggestions = fetchCommandSuggestionsFromAPI(inputContext); displaySuggestions(suggestions); } // Example input context derived from previous commands: const inputContext = 'git commit'; suggestCommand(inputContext); 3. Real-World Use Cases 3.1 Collaborative Coding Environments In a modern development landscape, pair programming and team collaborations are commonplace. Warp allows developers to work side-by-side within the terminal by sharing terminal blocks, enabling real-time collaboration, which can be especially valuable for junior developers and onboarding processes. 3.2 Streamlined DevOps Interactions Through its re-executability feature, Warp simplifies tedious deployment and build tasks. Engineers can encapsulate complex commands or sequences that are often repeated during CI/CD processes into a single block, saving time and reducing human error. # Example: Encapsulating a Docker build command in a Warp block BLOCK_NAME="DockerBuild"
warp runCommand EOF
docker build -t myapp:latest . EOF 4. Performance Considerations and Optimization Strategies 4.1 Performance Metrics When considering performance metrics for terminal tools, several key components come into play:
* Startup Time: Required to boot the terminal and load configurations.
* Latency: Time taken to process commands and return results.
* Memory Usage: Resource allocation, particularly when handling large outputs or continuous monitoring.
Tools like htop or perf can be used to analyze terminal performance, benchmarking against traditional terminal solutions. 4.2 Optimization Techniques * Reduce Context Switching: Frequent toggling between GUI applications and terminals can hinder focus. Effectively leveraging Warp's blocks and integrated features minimizes this.
* Resource Management: Utilizing features such as lazy-loading plugins or deferring non-essential commands can lead to quicker startup and operational speeds.
* WebAssembly: Deploying critical command execution tasks in WebAssembly can lead to marked performance improvements. 5. Edge Cases and Advanced Debugging Techniques 5.1 Pitfalls of Intelligent Features 1.
Misinterpretation of Context: As Warp learns from user commands, there exists the risk of misinterpreting commands, which can lead to improper suggestions.
* Solution: Toggle user-provided, context-driven suggestions off for infrequent tasks.
2.
Overhead from Integrated Services: While fetching real-time command suggestions benefits productivity, it may create latency under poor network conditions.
* Solution: Temporarily revert to a static context during network failures. 5.2 Advanced Debugging Tools Warp includes built-in race condition detection workflows, which identify cases where non-deterministic output can result from concurrent command execution. Using these workflows can significantly streamline the debugging process. # Enabling race condition detection
warp enableRaceDetection 6. Conclusion and Future Directions Warp Terminal introduces an array of intelligent features designed to foster developer productivity and collaboration, significantly outperforming traditional terminals in usability and efficiency. Its innovative architecture and modern UI facilitate a commanding experience for both novice and experienced developers.
Going forward, we can anticipate:
* Enhanced AI/ML capabilities for contextual command suggestions.
* Increased support for plugins and integrations with third-party development tools.
* Advanced debugging utilities to further streamline developer engagement with terminal-based error re[...]21 أبريل 2025, 04:17
21 أبريل 2025, ~04:47
513
The DEV Community
Best Blog Post Formats That Keep Readers Hooked (With Examples)
If you're a blogger like me, then you already know that writing content is just one part of the job. The real challenge is keeping your readers engaged from the first line to the last. One way to do that is by using the right blog post format. In this guide, I’ll show you the best blog post formats that not only make your content look good but also make readers want to stay longer and read more. 1. List Posts (Listicles) This is one of my favorite formats, and it works really well. A list post breaks down information into easy-to-read points. Readers love lists because they know what to expect, and they can skim through quickly.
Example:"10 Easy SEO Tips for Beginners" or "7 Reasons Your Blog Isn’t Growing"
Why it works:
* Scannable and quick to read
* Easy to share on social media
* Each point gives value 2. How-To Guides This format is perfect for tutorials and step-by-step instructions. It helps readers solve a problem or learn something new. I often use this when writing Termux tutorials or anything that needs a walkthrough.
Example:"How to Install Metasploit in Termux (Step-by-Step)"
Why it works:
* Teaches something useful
* Builds trust and authority
* Keeps readers on your page longer 3. Case Studies Case studies show real results from something you’ve done. This could be how you got traffic to your blog, how you made money online, or even how a tool helped you improve your SEO. It adds proof and real-life examples to your blog.
Example:"How I Got 1,000 Visitors in One Week with Simple SEO Tweaks"
Why it works:
* Shows real data and results
* Makes your blog more trustworthy
* Readers can relate to your journey 4. Comparison Posts These posts compare two or more tools, products, or ideas. They help readers make a decision. This is great for affiliate marketing too, as you can include links to the tools you recommend.
Example:"WordPress vs Blogger: Which is Better for New Bloggers?"
Why it works:
* Helps users choose the best option
* Can target high-converting keywords
* Encourages more engagement and comments 5. Opinion Posts Sometimes, people want to hear what you really think. Opinion posts give you a chance to share your views on a trending topic or something important in your niche. It builds your voice and personality.
Example:"Why I Think Free Tools Are Better Than Paid Ones for Beginners"
Why it works:
* Creates connection with your readers
* Shows your personality and values
* Can start discussions and debates 6. Ultimate Guides This is a deep, long-form format that covers everything about a topic. It's like a mini eBook but in a blog post. If you want to rank on Google and get backlinks, this is one of the best formats to use.
Example:"The Ultimate Guide to Starting a Blog in 2025"
Why it works:
* High SEO potential
* Provides full value in one place
* Great for sharing and saving 7. Interview Posts Interviewing experts or influencers in your niche is a great way to bring new voices to your blog. It also gives you authority and opens doors for networking.
Example:"Interview with a Cybersecurity Expert: How to Stay Safe Online"
Why it works:
* Adds variety to your content
* Brings in new audiences
* Builds credibility and trust 8. Frequently Asked Questions (FAQ) This format targets questions your readers are already searching for. Answering FAQs helps you appear in search engine results and gives quick value to your audience.
Example:"FAQ: How to Use Termux for Ethical Hacking"
Why it works:
* Answers real user questions
* Improves SEO with question-based keywords
* Great for featured snippets Tips to Keep Readers Engaged in Any Format * Use short paragraphs and simple sentences
* Add subheadings to break content
[...]
21 أبريل 2025, 04:16
21 أبريل 2025, ~04:47
