import gradio as gr import multiprocessing import threading import time import os from math import isqrt # Path to save the primes PRIME_SAVE_PATH = "primes.txt" lock = threading.Lock() # Thread lock to control file access # Function to check if a number is prime def is_prime(n): if n < 2: return False if n in (2, 3): return True if n % 2 == 0 or n % 3 == 0: return False for i in range(5, isqrt(n) + 1, 6): if n % i == 0 or n % (i + 2) == 0: return False return True # Function to find primes in a given range def find_primes_in_range(start, end, queue): primes = [str(num) for num in range(start, end) if is_prime(num)] queue.put(primes) # Function to load previously saved primes def load_saved_primes(): if os.path.exists(PRIME_SAVE_PATH): with open(PRIME_SAVE_PATH, "r") as file: return file.read().splitlines() return [] # Function to save new primes to file def save_primes_to_file(prime_list): with lock: # Ensure only one process writes to the file at a time with open(PRIME_SAVE_PATH, "a") as file: file.write("\n".join(prime_list) + "\n") file.flush() # Ensure data is written to disk os.fsync(file.fileno()) # Force file system to sync # Background prime number generator function def prime_generator(): num = 2 batch_size = 1000 num_processes = multiprocessing.cpu_count() prime_list = load_saved_primes() # Load previously generated primes while True: processes = [] queue = multiprocessing.Queue() # Start multiple processes to find primes in parallel for i in range(num_processes): start = num + i * batch_size end = start + batch_size process = multiprocessing.Process(target=find_primes_in_range, args=(start, end, queue)) process.start() processes.append(process) # Collect primes from all processes all_new_primes = [] for process in processes: process.join() primes = queue.get() all_new_primes.extend(primes) prime_list.extend(all_new_primes) # Save the newly found primes to the file save_primes_to_file(all_new_primes) num += num_processes * batch_size time.sleep(0.1) # Adjust this to control responsiveness and resource usage def start_background_thread(): thread = threading.Thread(target=prime_generator, daemon=True) thread.start() # Function to display the primes in Gradio def display_primes(): prime_list = load_saved_primes() while True: yield "\n".join(prime_list) time.sleep(1) # Refresh interval # Start the background prime number generation start_background_thread() # Gradio Interface interface = gr.Interface( fn=display_primes, # Display function inputs=None, # No inputs required outputs="text", # Output is a text field live=True # Enable live updates ) # Launch the interface interface.launch()