MultiToolBox / app.py
shukdevdatta123's picture
Update app.py
f1e83c4 verified
raw
history blame
12.4 kB
import gradio as gr
import os
import numpy as np
from PIL import Image
import re
import demoji
from textblob import TextBlob
from faker import Faker
import pandas as pd
from difflib import SequenceMatcher
# Try importing pytube with better error handling
try:
from pytube import YouTube
from pytube.exceptions import RegexMatchError, VideoUnavailable
PYTUBE_AVAILABLE = True
except ImportError:
PYTUBE_AVAILABLE = False
# Function for Image Mirroring
def mirror_image(input_img):
if input_img is None:
return None
mirrored_img = Image.fromarray(input_img).transpose(Image.FLIP_LEFT_RIGHT)
return mirrored_img
# Improved YouTube URL validation
def is_valid_youtube_url(url):
if not url:
return False
# Common YouTube URL patterns
youtube_regex = (
r'(https?://)?(www\.)?'
r'(youtube|youtu|youtube-nocookie)\.(com|be)/'
r'(watch\?v=|embed/|v/|.+\?v=)?([^&=%\?]{11})')
match = re.match(youtube_regex, url)
return match is not None
# Function for YouTube to MP3 Download with improved error handling
def download_youtube_mp3(url, destination="."):
if not PYTUBE_AVAILABLE:
return "Error: pytube library is not available. Please install it with 'pip install pytube'."
if not url:
return "Please enter a valid URL"
if not is_valid_youtube_url(url):
return "Error: The URL does not appear to be a valid YouTube URL"
try:
yt = YouTube(url)
# Check if video is available
title = yt.title # This will raise an exception if the video is unavailable
# Get the highest quality audio stream
audio_stream = yt.streams.filter(only_audio=True).order_by('abr').desc().first()
if not audio_stream:
return "Error: No audio stream found for this video"
if not destination:
destination = "."
# Ensure destination directory exists
if not os.path.exists(destination):
try:
os.makedirs(destination)
except Exception as e:
return f"Error creating destination directory: {str(e)}"
# Download the file
out_file = audio_stream.download(output_path=destination)
# Save the file with .mp3 extension
base, ext = os.path.splitext(out_file)
new_file = base + '.mp3'
# Handle file already exists
if os.path.exists(new_file):
os.remove(new_file)
os.rename(out_file, new_file)
return f"Success! '{yt.title}' has been downloaded in MP3 format to: {new_file}"
except VideoUnavailable:
return "Error: This video is unavailable or private"
except RegexMatchError:
return "Error: The YouTube URL is not valid"
except Exception as e:
error_message = str(e)
if "429" in error_message:
return "Error: Too many requests. YouTube is rate-limiting downloads. Please try again later."
elif "403" in error_message:
return "Error: Access forbidden. YouTube may have restricted this content."
else:
return f"Error: {error_message}. If this is a recurring issue, YouTube may have updated their site. Try updating pytube with 'pip install --upgrade pytube'."
# Function for Emoji Detection
def detect_emojis(text):
if not text:
return "Please enter text containing emojis"
emoji_dict = demoji.findall(text)
if emoji_dict:
result = "Emojis found:\n"
for emoji, desc in emoji_dict.items():
result += f"{emoji}: {desc}\n"
return result
else:
return "No emojis found in the text"
# Function for Spell Correction
def correct_spelling(text):
if not text:
return "Please enter text to correct"
words = text.split()
corrected_words = []
for word in words:
corrected_words.append(str(TextBlob(word).correct()))
return f"Original: {text}\nCorrected: {' '.join(corrected_words)}"
# Function to Check for Disarium Number
def check_disarium(number):
try:
number = int(number)
if number <= 0:
return "Please enter a positive integer"
length = len(str(number))
temp = number
sum_val = 0
while temp > 0:
rem = temp % 10
sum_val += rem ** length
temp = temp // 10
length -= 1
if sum_val == number:
return f"{number} is a Disarium Number"
else:
return f"{number} is NOT a Disarium Number"
except ValueError:
return "Please enter a valid integer"
# Function to Generate Fake Data
def generate_fake_data(count=1, include_profile=False):
try:
count = int(count)
if count <= 0:
return "Please enter a positive number"
except (ValueError, TypeError):
return "Please enter a valid number"
fake = Faker()
if include_profile:
data = [fake.profile() for _ in range(count)]
df = pd.DataFrame(data)
return df.to_string()
else:
result = ""
for _ in range(count):
result += f"Name: {fake.name()}\n"
result += f"Address: {fake.address()}\n"
result += f"Text: {fake.text()}\n\n"
return result
# Function to Compare Text Similarity
def compare_texts(text1, text2):
if not text1 or not text2:
return "Please enter both texts to compare"
similarity = SequenceMatcher(None, text1, text2).ratio()
return f"The texts are {similarity * 100:.2f}% similar"
# Create the Gradio interface with tabs
with gr.Blocks(title="MultiToolBox") as app:
gr.Markdown("# MultiToolBox")
gr.Markdown("A versatile utility toolkit with multiple functions")
with gr.Tabs():
# Image Mirroring Tab
with gr.Tab("Image Mirror"):
gr.Markdown("### Mirror an Image Horizontally")
with gr.Row():
with gr.Column():
img_input = gr.Image(label="Upload Image")
mirror_btn = gr.Button("Mirror Image")
with gr.Column():
img_output = gr.Image(label="Mirrored Image")
mirror_btn.click(fn=mirror_image, inputs=img_input, outputs=img_output)
gr.Markdown("""
**How to use:**
1. Upload an image using the upload button
2. Click "Mirror Image" to flip it horizontally
3. The result will appear in the right panel
""")
# YouTube to MP3 Tab
with gr.Tab("YouTube to MP3"):
gr.Markdown("### Download YouTube Videos as MP3")
if not PYTUBE_AVAILABLE:
gr.Markdown("โš ๏ธ **Warning:** pytube library is not installed. This feature will not work properly.")
yt_url = gr.Textbox(label="YouTube URL", placeholder="https://www.youtube.com/watch?v=dQw4w9WgXcQ")
yt_destination = gr.Textbox(label="Destination Folder (leave empty for current directory)", placeholder=".")
yt_download_btn = gr.Button("Download")
yt_output = gr.Textbox(label="Result", lines=3)
yt_download_btn.click(fn=download_youtube_mp3, inputs=[yt_url, yt_destination], outputs=yt_output)
gr.Markdown("""
**How to use:**
1. Enter a valid YouTube URL (e.g., https://www.youtube.com/watch?v=dQw4w9WgXcQ)
2. Optionally specify a destination folder
3. Click "Download" to convert and save as MP3
**Example:** https://www.youtube.com/watch?v=dQw4w9WgXcQ
**Note:** If you encounter errors, try running `pip install --upgrade pytube` to update the YouTube library
""")
# Emoji Detection Tab
with gr.Tab("Emoji Detector"):
gr.Markdown("### Detect Emojis in Text")
emoji_input = gr.Textbox(label="Enter text with emojis")
emoji_detect_btn = gr.Button("Detect Emojis")
emoji_output = gr.Textbox(label="Results")
emoji_detect_btn.click(fn=detect_emojis, inputs=emoji_input, outputs=emoji_output)
gr.Markdown("""
**How to use:**
1. Enter text containing emojis
2. Click "Detect Emojis" to identify and describe them
**Example:** "I love reading books ๐Ÿ“šโค๏ธ๐ŸŒน"
""")
# Spell Correction Tab
with gr.Tab("Spell Checker"):
gr.Markdown("### Correct Spelling Errors")
spell_input = gr.Textbox(label="Enter text with spelling errors")
spell_btn = gr.Button("Correct Spelling")
spell_output = gr.Textbox(label="Corrected Text")
spell_btn.click(fn=correct_spelling, inputs=spell_input, outputs=spell_output)
gr.Markdown("""
**How to use:**
1. Enter text with spelling mistakes
2. Click "Correct Spelling" to fix errors
**Example:** "I havv a problm with speling"
""")
# Disarium Number Tab
with gr.Tab("Disarium Checker"):
gr.Markdown("### Check if a Number is a Disarium Number")
gr.Markdown("""
A Disarium number is a number where the sum of its digits raised to their respective positions equals the number itself.
Example: 135 is a Disarium number because 1^1 + 3^2 + 5^3 = 1 + 9 + 125 = 135
""")
disarium_input = gr.Textbox(label="Enter a number")
disarium_btn = gr.Button("Check")
disarium_output = gr.Textbox(label="Result")
disarium_btn.click(fn=check_disarium, inputs=disarium_input, outputs=disarium_output)
gr.Markdown("""
**How to use:**
1. Enter a positive integer
2. Click "Check" to determine if it's a Disarium number
**Examples:**
- 135 (Disarium number)
- 89 (Disarium number: 8^1 + 9^2 = 8 + 81 = 89)
- 175 (Not a Disarium number)
""")
# Fake Data Generator Tab
with gr.Tab("Fake Data Generator"):
gr.Markdown("### Generate Fake Data")
with gr.Row():
fake_count = gr.Number(label="Number of entries", value=1)
fake_profile = gr.Checkbox(label="Generate detailed profiles")
fake_btn = gr.Button("Generate")
fake_output = gr.Textbox(label="Generated Data", lines=10)
fake_btn.click(fn=generate_fake_data, inputs=[fake_count, fake_profile], outputs=fake_output)
gr.Markdown("""
**How to use:**
1. Enter the number of fake data entries to generate
2. Choose whether to generate detailed profiles
3. Click "Generate" to create fake data
**Example:** Generate 5 entries with detailed profiles
""")
# Text Similarity Tab
with gr.Tab("Text Similarity"):
gr.Markdown("### Compare Text Similarity")
text1_input = gr.Textbox(label="First Text")
text2_input = gr.Textbox(label="Second Text")
compare_btn = gr.Button("Compare")
similarity_output = gr.Textbox(label="Similarity Result")
compare_btn.click(fn=compare_texts, inputs=[text1_input, text2_input], outputs=similarity_output)
gr.Markdown("""
**How to use:**
1. Enter the first text for comparison
2. Enter the second text for comparison
3. Click "Compare" to calculate similarity percentage
**Example:**
- Text 1: "Hello, how are you today?"
- Text 2: "Hello, how are you doing today?"
""")
if __name__ == "__main__":
app.launch()