Spaces:
Paused
Paused
Update app.py
Browse files4 unmodified lines56789101143 unmodified lines555657585960612 unmodified lines6465666768697071727374757677787980818283848586878889909192939495969798991001011021035 unmodified lines1091101111121131141151 unmodified line1171181191201211221234 unmodified linesfrom datasets import Datasetfrom huggingface_hub import HfApiimport loggingfrom datetime import datetime# Set up logginglogging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")43 unmodified lineslogger.info(f"Segmented text into {len(chunks)} chunks.")return chunks# Function to process the text file and make API callsdef process_text(file, prompt):try:logger.info("Starting text processing...")2 unmodified linesfile_path = file.name if hasattr(file, "name") else filechunks = segment_text(file_path)# Perform API calls for each chunkresults = []for idx, chunk in enumerate(chunks):logger.info(f"Processing chunk {idx + 1}/{len(chunks)}")try:result = call_api(f"{prompt}\n\n{chunk}")results.append(result)logger.info(f"Chunk {idx + 1} processed successfully.")except Exception as e:logger.error(f"Failed to process chunk {idx + 1}: {e}")raise gr.Error(f"Failed to process chunk {idx + 1}: {str(e)}")# Save results as individual text filesos.makedirs("outputs", exist_ok=True)for idx, result in enumerate(results):output_file = f"outputs/output_{idx}.txt"with open(output_file, "w", encoding="utf-8") as f:f.write(result)logger.info(f"Saved result to {output_file}")# Upload to Hugging Face datasettry:logger.info("Uploading results to Hugging Face dataset...")hf_api = HfApi(token=os.environ.get("HUGGINGFACE_TOKEN"))if not hf_api.token:raise ValueError("Hugging Face token not found in environment variables.")dataset = Dataset.from_dict({"text": results})dataset.push_to_hub("TeacherPuffy/book") # Updated dataset namelogger.info("Results uploaded to Hugging Face dataset successfully.")except Exception as e:logger.error(f"Failed to upload to Hugging Face: {e}")raise gr.Error(f"Failed to upload to Hugging Face: {str(e)}")# Create a ZIP filetry:logger.info("Creating ZIP file...")with zipfile.ZipFile("outputs.zip", "w") as zipf:5 unmodified lineslogger.error(f"Failed to create ZIP file: {e}")raise gr.Error(f"Failed to create ZIP file: {str(e)}")return "outputs.zip", "Results uploaded to Hugging Face dataset and ZIP file created."except Exception as e:logger.error(f"An error occurred during processing: {e}")1 unmodified line# Gradio interfacewith gr.Blocks() as demo:gr.Markdown("## Text File Processor with API Calls")with gr.Row():file_input = gr.File(label="Upload Text File")prompt_input = gr.Textbox(label="Enter Prompt")4 unmodified lines56789101143 unmodified lines555657585960612 unmodified lines6465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101115 unmodified lines1171181191201211221231 unmodified line1251261271281291301314 unmodified linesfrom datasets import Datasetfrom huggingface_hub import HfApiimport loggingimport time # Import time module for adding delays# Set up logginglogging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")43 unmodified lineslogger.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...")2 unmodified linesfile_path = file.name if hasattr(file, "name") else filechunks = segment_text(file_path)# 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.")# Process each chunk with a 20-second delay between API callsresults = []for idx, chunk in enumerate(chunks):logger.info(f"Processing chunk {idx + 1}/{len(chunks)}")try:# Call the APIresult = call_api(f"{prompt}\n\n{chunk}")results.append(result)logger.info(f"Chunk {idx + 1} processed successfully.")# Save the result to a fileos.makedirs("outputs", exist_ok=True)output_file = f"outputs/output_{idx}.txt"with open(output_file, "w", encoding="utf-8") as f:f.write(result)logger.info(f"Saved result to {output_file}")# Upload the chunk to Hugging Facetry:logger.info(f"Uploading chunk {idx + 1} to Hugging Face...")dataset = Dataset.from_dict({"text": [result]})dataset.push_to_hub("TeacherPuffy/book") # Updated dataset namelogger.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 20 seconds before the next API callif idx < len(chunks) - 1: # No need to wait after the last chunklogger.info("Waiting 20 seconds before the next API call...")time.sleep(20)except Exception as e:logger.error(f"Failed to process chunk {idx + 1}: {e}")raise gr.Error(f"Failed to process chunk {idx + 1}: {str(e)}")# Create a ZIP file of all outputstry:logger.info("Creating ZIP file...")with zipfile.ZipFile("outputs.zip", "w") as zipf:5 unmodified lineslogger.error(f"Failed to create ZIP file: {e}")raise gr.Error(f"Failed to create ZIP file: {str(e)}")return "outputs.zip", "All chunks processed and uploaded to Hugging Face. ZIP file created."except Exception as e:logger.error(f"An error occurred during processing: {e}")1 unmodified line# Gradio interfacewith gr.Blocks() as demo:gr.Markdown("## Text File Processor with Rate-Limited API Calls")with gr.Row():file_input = gr.File(label="Upload Text File")prompt_input = gr.Textbox(label="Enter Prompt")
app.py+35-27