Spaces:
Sleeping
Sleeping
File size: 12,364 Bytes
4ac6a8a 3ca8aed 4ac6a8a 3ca8aed 4ac6a8a 3ca8aed 4ac6a8a 3ca8aed 4ac6a8a 3ca8aed 4ac6a8a 3ca8aed 4ac6a8a 3ca8aed 4ac6a8a 3ca8aed 4ac6a8a 3ca8aed 4ac6a8a 3ca8aed 4ac6a8a 4da9612 4ac6a8a 3ca8aed 4ac6a8a 3ca8aed 4ac6a8a 3ca8aed 4ac6a8a 3ca8aed 4ac6a8a 4da9612 4ac6a8a |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 |
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)
- 165 (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() |