MultiToolBox / app.py
shukdevdatta123's picture
Create app.py
4ac6a8a verified
raw
history blame
11.1 kB
import gradio as gr
import os
import numpy as np
from PIL import Image
from pytube import YouTube
import demoji
import sounddevice
from scipy.io.wavfile import write
from textblob import TextBlob
from faker import Faker
import pandas as pd
from difflib import SequenceMatcher
# 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
# Function for YouTube to MP3 Download
def download_youtube_mp3(url, destination="."):
if not url:
return "Please enter a valid URL"
try:
yt = YouTube(url)
video = yt.streams.filter(only_audio=True).first()
if not destination:
destination = "."
out_file = video.download(output_path=destination)
# Save the file with .mp3 extension
base, ext = os.path.splitext(out_file)
new_file = base + '.mp3'
os.rename(out_file, new_file)
return f"{yt.title} has been successfully downloaded in .mp3 format at {new_file}"
except Exception as e:
return f"Error: {str(e)}"
# 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 Voice Recording
def record_voice(seconds):
if seconds <= 0:
return "Please enter a positive number of seconds"
try:
fs = 44100 # Sample rate
recording = sounddevice.rec(int(seconds * fs), samplerate=fs, channels=2)
sounddevice.wait()
output_file = "recording.wav"
write(output_file, fs, recording)
return f"Recording completed! Saved as {output_file}", output_file
except Exception as e:
return f"Error recording: {str(e)}", None
# 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):
if count <= 0:
return "Please enter a positive 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")
yt_url = gr.Textbox(label="YouTube URL")
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")
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
""")
# 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 ๐Ÿ“šโค๏ธ๐ŸŒน"
""")
# Voice Recorder Tab
with gr.Tab("Voice Recorder"):
gr.Markdown("### Record Audio")
rec_seconds = gr.Number(label="Recording Duration (seconds)", value=5)
rec_button = gr.Button("Start Recording")
rec_output = gr.Textbox(label="Recording Status")
audio_output = gr.Audio(label="Recorded Audio")
rec_button.click(fn=record_voice, inputs=rec_seconds, outputs=[rec_output, audio_output])
gr.Markdown("""
**How to use:**
1. Enter the desired recording duration in seconds
2. Click "Start Recording"
3. Wait for the recording to complete
4. Play back the recorded audio using the player
**Example:** Enter 5 for a 5-second recording
""")
# 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, min=1, step=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()