Spaces:
Paused
Paused
Update app.py
Browse files12345620 unmodified lines27282930313233343536373839404142434445464748495051525354555657585960616263645 unmodified lines7071727374753 unmodified lines79808182838485import gradio as grfrom gradio_client import Clientimport osimport loggingimport time # Import time module for adding delays20 unmodified lineslogger.error(f"API call failed: {e}")raise gr.Error(f"API call failed: {str(e)}")# Function to segment the text file into chunks of 1500 wordsdef segment_text(file_path):try:logger.info(f"Reading file: {file_path}")# Try reading with UTF-8 encoding firstwith open(file_path, "r", encoding="utf-8") as f:text = f.read()logger.info("File read successfully with UTF-8 encoding.")except UnicodeDecodeError:logger.warning("UTF-8 encoding failed. Trying latin-1 encoding.")# Fallback to latin-1 encoding if UTF-8 failswith open(file_path, "r", encoding="latin-1") as f:text = f.read()logger.info("File read successfully with latin-1 encoding.")except Exception as e:logger.error(f"Failed to read file: {e}")raise gr.Error(f"Failed to read file: {str(e)}")# Split the text into chunks of 1500 wordswords = text.split()chunks = [" ".join(words[i:i + 1500]) for i in range(0, len(words), 1250)]logger.info(f"Segmented text into {len(chunks)} chunks.")return chunks# Function to process the text file and make API calls with rate limitingdef process_text(file, prompt):try:logger.info("Starting text processing...")# Segment the text file into chunksfile_path = file.name if hasattr(file, "name") else filechunks = segment_text(file_path)# Process each chunk with a 15-second delay between API callsresults = []5 unmodified linesresults.append(result)logger.info(f"Chunk {idx + 1} processed successfully.")# Wait 15 seconds before the next API callif idx < len(chunks) - 1: # No need to wait after the last chunklogger.info("Waiting 15 seconds before the next API call...")3 unmodified lineslogger.error(f"Failed to process chunk {idx + 1}: {e}")raise gr.Error(f"Failed to process chunk {idx + 1}: {str(e)}")return "All chunks processed successfully."except Exception as e:logger.error(f"An error occurred during processing: {e}")12345620 unmodified lines27282930313233343536373839404142434445464748495051525354555657585 unmodified lines64656667686970717273747576777879808182833 unmodified lines87888990919293import gradio as grfrom gradio_client import Clientfrom huggingface_hub import HfApiimport loggingimport time # Import time module for adding delays20 unmodified lineslogger.error(f"API call failed: {e}")raise gr.Error(f"API call failed: {str(e)}")# Function to segment the text into chunks of 1500 wordsdef segment_text(text):# Split the text into chunks of 1500 wordswords = text.split()chunks = [" ".join(words[i:i + 1500]) for i in range(0, len(words), 1250)]logger.info(f"Segmented text into {len(chunks)} chunks.")return chunks# Function to process the text and make API calls with rate limitingdef process_text(file, prompt):try:logger.info("Starting text processing...")# Read the text directly from the uploaded filetext = file.decode('utf-8') # Assuming the file is encoded in UTF-8# Segment the text into chunkschunks = segment_text(text)# Initialize Hugging Face APIhf_api = HfApi(token=os.environ.get("HUGGINGFACE_TOKEN"))if not hf_api.token:raise ValueError("Hugging Face token not found in environment variables.")# Repository name on Hugging Face Hubrepo_name = "TeacherPuffy/book2"# Process each chunk with a 15-second delay between API callsresults = []5 unmodified linesresults.append(result)logger.info(f"Chunk {idx + 1} processed successfully.")# Upload the chunk directly to Hugging Facetry:logger.info(f"Uploading chunk {idx + 1} to Hugging Face...")hf_api.upload_file(path_or_fileobj=result.encode('utf-8'), # Convert result to bytespath_in_repo=f"output_{idx}.txt", # File name in the repositoryrepo_id=repo_name,repo_type="dataset",)logger.info(f"Chunk {idx + 1} uploaded to Hugging Face successfully.")except Exception as e:logger.error(f"Failed to upload chunk {idx + 1} to Hugging Face: {e}")raise gr.Error(f"Failed to upload chunk {idx + 1} to Hugging Face: {str(e)}")# Wait 15 seconds before the next API callif idx < len(chunks) - 1: # No need to wait after the last chunklogger.info("Waiting 15 seconds before the next API call...")3 unmodified lineslogger.error(f"Failed to process chunk {idx + 1}: {e}")raise gr.Error(f"Failed to process chunk {idx + 1}: {str(e)}")return "All chunks processed and uploaded to Hugging Face."except Exception as e:logger.error(f"An error occurred during processing: {e}")
app.py+32-24