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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from dataclasses import dataclass
|
| 2 |
+
from typing import Dict, List, Optional
|
| 3 |
+
import difflib
|
| 4 |
+
import json
|
| 5 |
+
import logging
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
|
| 8 |
+
# Configure logging
|
| 9 |
+
logging.basicConfig(
|
| 10 |
+
level=logging.INFO,
|
| 11 |
+
format='%(asctime)s - %(levelname)s - %(message)s'
|
| 12 |
+
)
|
| 13 |
+
logger = logging.getLogger(__name__)
|
| 14 |
+
|
| 15 |
+
@dataclass
|
| 16 |
+
class Template:
|
| 17 |
+
"""Template data structure"""
|
| 18 |
+
code: str
|
| 19 |
+
description: str
|
| 20 |
+
components: List[str]
|
| 21 |
+
metadata: Dict[str, str]
|
| 22 |
+
example: Optional[str] = None
|
| 23 |
+
|
| 24 |
+
class TemplateManager:
|
| 25 |
+
"""Manages and searches through templates"""
|
| 26 |
+
|
| 27 |
+
def __init__(self):
|
| 28 |
+
self.templates = {
|
| 29 |
+
"image_classifier": Template(
|
| 30 |
+
code="""
|
| 31 |
+
import gradio as gr
|
| 32 |
+
import numpy as np
|
| 33 |
+
from PIL import Image
|
| 34 |
+
|
| 35 |
+
def classify_image(image):
|
| 36 |
+
if image is None:
|
| 37 |
+
return {"error": 1.0}
|
| 38 |
+
return {"class1": 0.8, "class2": 0.2}
|
| 39 |
+
|
| 40 |
+
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 41 |
+
gr.Markdown("# Image Classifier")
|
| 42 |
+
with gr.Row():
|
| 43 |
+
with gr.Column():
|
| 44 |
+
input_image = gr.Image(type="pil")
|
| 45 |
+
classify_btn = gr.Button("Classify")
|
| 46 |
+
with gr.Column():
|
| 47 |
+
output_labels = gr.Label()
|
| 48 |
+
|
| 49 |
+
classify_btn.click(
|
| 50 |
+
fn=classify_image,
|
| 51 |
+
inputs=input_image,
|
| 52 |
+
outputs=output_labels
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
if __name__ == "__main__":
|
| 56 |
+
demo.launch()
|
| 57 |
+
""",
|
| 58 |
+
description="Basic image classification interface",
|
| 59 |
+
components=["Image", "Button", "Label"],
|
| 60 |
+
metadata={"category": "computer_vision"}
|
| 61 |
+
),
|
| 62 |
+
"chatbot": Template(
|
| 63 |
+
code="""
|
| 64 |
+
import gradio as gr
|
| 65 |
+
|
| 66 |
+
def respond(message, history):
|
| 67 |
+
return f"You said: {message}"
|
| 68 |
+
|
| 69 |
+
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 70 |
+
gr.Markdown("# AI Chatbot")
|
| 71 |
+
chatbot = gr.Chatbot()
|
| 72 |
+
msg = gr.Textbox(label="Message")
|
| 73 |
+
clear = gr.Button("Clear")
|
| 74 |
+
|
| 75 |
+
msg.submit(respond, [msg, chatbot], [chatbot])
|
| 76 |
+
clear.click(lambda: None, None, chatbot, queue=False)
|
| 77 |
+
|
| 78 |
+
if __name__ == "__main__":
|
| 79 |
+
demo.launch()
|
| 80 |
+
""",
|
| 81 |
+
description="Interactive chatbot interface",
|
| 82 |
+
components=["Chatbot", "Textbox", "Button"],
|
| 83 |
+
metadata={"category": "nlp"}
|
| 84 |
+
),
|
| 85 |
+
"audio_processor": Template(
|
| 86 |
+
code="""
|
| 87 |
+
import gradio as gr
|
| 88 |
+
import numpy as np
|
| 89 |
+
|
| 90 |
+
def process_audio(audio, volume_factor=1.0):
|
| 91 |
+
if audio is None:
|
| 92 |
+
return None
|
| 93 |
+
sr, data = audio
|
| 94 |
+
return (sr, data * volume_factor)
|
| 95 |
+
|
| 96 |
+
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 97 |
+
gr.Markdown("# Audio Processor")
|
| 98 |
+
with gr.Row():
|
| 99 |
+
with gr.Column():
|
| 100 |
+
input_audio = gr.Audio(source="microphone", type="numpy")
|
| 101 |
+
volume = gr.Slider(minimum=0, maximum=2, value=1, label="Volume")
|
| 102 |
+
process_btn = gr.Button("Process")
|
| 103 |
+
with gr.Column():
|
| 104 |
+
output_audio = gr.Audio(type="numpy")
|
| 105 |
+
|
| 106 |
+
process_btn.click(
|
| 107 |
+
fn=process_audio,
|
| 108 |
+
inputs=[input_audio, volume],
|
| 109 |
+
outputs=output_audio
|
| 110 |
+
)
|
| 111 |
+
|
| 112 |
+
if __name__ == "__main__":
|
| 113 |
+
demo.launch()
|
| 114 |
+
""",
|
| 115 |
+
description="Audio processing interface",
|
| 116 |
+
components=["Audio", "Slider", "Button"],
|
| 117 |
+
metadata={"category": "audio"}
|
| 118 |
+
),
|
| 119 |
+
"file_processor": Template(
|
| 120 |
+
code="""
|
| 121 |
+
import gradio as gr
|
| 122 |
+
|
| 123 |
+
def process_file(file):
|
| 124 |
+
if file is None:
|
| 125 |
+
return "No file uploaded"
|
| 126 |
+
return f"Processed file: {file.name}"
|
| 127 |
+
|
| 128 |
+
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 129 |
+
gr.Markdown("# File Processor")
|
| 130 |
+
with gr.Row():
|
| 131 |
+
with gr.Column():
|
| 132 |
+
file_input = gr.File(label="Upload File")
|
| 133 |
+
process_btn = gr.Button("Process")
|
| 134 |
+
with gr.Column():
|
| 135 |
+
output = gr.Textbox(label="Results")
|
| 136 |
+
json_output = gr.JSON(label="Detailed Results")
|
| 137 |
+
|
| 138 |
+
process_btn.click(
|
| 139 |
+
fn=process_file,
|
| 140 |
+
inputs=file_input,
|
| 141 |
+
outputs=[output, json_output]
|
| 142 |
+
)
|
| 143 |
+
|
| 144 |
+
if __name__ == "__main__":
|
| 145 |
+
demo.launch()
|
| 146 |
+
""",
|
| 147 |
+
description="File processing interface",
|
| 148 |
+
components=["File", "Button", "Textbox", "JSON"],
|
| 149 |
+
metadata={"category": "utility"}
|
| 150 |
+
),
|
| 151 |
+
"data_visualization": Template(
|
| 152 |
+
code="" """
|
| 153 |
+
import gradio as gr
|
| 154 |
+
import pandas as pd
|
| 155 |
+
import plotly.express as px
|
| 156 |
+
|
| 157 |
+
def visualize_data(data, plot_type):
|
| 158 |
+
if data is None:
|
| 159 |
+
return None
|
| 160 |
+
|
| 161 |
+
df = pd.read_csv(data.name)
|
| 162 |
+
if plot_type == "scatter":
|
| 163 |
+
fig = px.scatter(df, x=df.columns[0], y=df.columns[1])
|
| 164 |
+
elif plot_type == "line":
|
| 165 |
+
fig = px.line(df, x=df.columns[0], y=df.columns[1])
|
| 166 |
+
else:
|
| 167 |
+
fig = px.bar(df, x=df.columns[0], y=df.columns[1])
|
| 168 |
+
|
| 169 |
+
return fig
|
| 170 |
+
|
| 171 |
+
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 172 |
+
gr.Markdown("# Data Visualizer")
|
| 173 |
+
with gr.Row():
|
| 174 |
+
with gr.Column():
|
| 175 |
+
file_input = gr.File(label="Upload CSV")
|
| 176 |
+
plot_type = gr.Radio(
|
| 177 |
+
choices=["scatter", "line", "bar"],
|
| 178 |
+
label="Plot Type",
|
| 179 |
+
value="scatter"
|
| 180 |
+
)
|
| 181 |
+
visualize_btn = gr.Button("Visualize")
|
| 182 |
+
with gr.Column():
|
| 183 |
+
plot_output = gr.Plot(label="Visualization")
|
| 184 |
+
|
| 185 |
+
visualize_btn.click(
|
| 186 |
+
fn=visualize_data,
|
| 187 |
+
inputs=[file_input, plot_type],
|
| 188 |
+
outputs=plot_output
|
| 189 |
+
)
|
| 190 |
+
|
| 191 |
+
if __name__ == "__main__":
|
| 192 |
+
demo.launch()
|
| 193 |
+
""",
|
| 194 |
+
description="Data visualization interface",
|
| 195 |
+
components=["File", "Radio", "Button", "Plot"],
|
| 196 |
+
metadata={"category": "data_science"}
|
| 197 |
+
),
|
| 198 |
+
"form_builder": Template(
|
| 199 |
+
code="""
|
| 200 |
+
import gradio as gr
|
| 201 |
+
import json
|
| 202 |
+
|
| 203 |
+
def submit_form(name, email, age, interests, subscribe):
|
| 204 |
+
return json.dumps({
|
| 205 |
+
"name": name,
|
| 206 |
+
"email": email,
|
| 207 |
+
"age": age,
|
| 208 |
+
"interests": interests,
|
| 209 |
+
"subscribe": subscribe
|
| 210 |
+
}, indent=2)
|
| 211 |
+
|
| 212 |
+
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 213 |
+
gr.Markdown("# Form Builder")
|
| 214 |
+
with gr.Row():
|
| 215 |
+
with gr.Column():
|
| 216 |
+
name = gr.Textbox(label="Name")
|
| 217 |
+
email = gr.Textbox(label="Email")
|
| 218 |
+
age = gr.Number(label="Age")
|
| 219 |
+
interests = gr.CheckboxGroup(
|
| 220 |
+
choices=["Sports", "Music", "Art", "Technology"],
|
| 221 |
+
label="Interests"
|
| 222 |
+
)
|
| 223 |
+
subscribe = gr.Checkbox(label="Subscribe to newsletter")
|
| 224 |
+
submit_btn = gr.Button("Submit")
|
| 225 |
+
with gr.Column():
|
| 226 |
+
output = gr.JSON(label="Form Data")
|
| 227 |
+
|
| 228 |
+
submit_btn.click(
|
| 229 |
+
fn=submit_form,
|
| 230 |
+
inputs=[name, email, age, interests, subscribe],
|
| 231 |
+
outputs=output
|
| 232 |
+
)
|
| 233 |
+
|
| 234 |
+
if __name__ == "__main__":
|
| 235 |
+
demo.launch()
|
| 236 |
+
""",
|
| 237 |
+
description="Form builder interface",
|
| 238 |
+
components=["Textbox", "Number", "CheckboxGroup", "Checkbox", "Button", "JSON"],
|
| 239 |
+
metadata={"category": "utility"}
|
| 240 |
+
),
|
| 241 |
+
"text_summarizer": Template(
|
| 242 |
+
code="""
|
| 243 |
+
import gradio as gr
|
| 244 |
+
from transformers import pipeline
|
| 245 |
+
|
| 246 |
+
summarizer = pipeline("summarization")
|
| 247 |
+
|
| 248 |
+
def summarize_text(text):
|
| 249 |
+
summary = summarizer(text, max_length=150, min_length=40, do_sample=False)
|
| 250 |
+
return summary[0]['summary_text']
|
| 251 |
+
|
| 252 |
+
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 253 |
+
gr.Markdown("# Text Summarizer")
|
| 254 |
+
with gr.Row():
|
| 255 |
+
with gr.Column():
|
| 256 |
+
input_text = gr.Textbox(label="Input Text", lines=10, placeholder="Enter text to summarize...")
|
| 257 |
+
summarize_btn = gr.Button("Summarize")
|
| 258 |
+
with gr.Column():
|
| 259 |
+
summary_output = gr.Textbox(label="Summary", lines=5)
|
| 260 |
+
|
| 261 |
+
summarize_btn.click(
|
| 262 |
+
fn=summarize_text,
|
| 263 |
+
inputs=input_text,
|
| 264 |
+
outputs=summary_output
|
| 265 |
+
)
|
| 266 |
+
|
| 267 |
+
if __name__ == "__main__":
|
| 268 |
+
demo.launch()
|
| 269 |
+
""",
|
| 270 |
+
description="Text summarization interface using a transformer model",
|
| 271 |
+
components=["Textbox", "Button"],
|
| 272 |
+
metadata={"category": "nlp"}
|
| 273 |
+
),
|
| 274 |
+
"image_captioner": Template(
|
| 275 |
+
code="""
|
| 276 |
+
import gradio as gr
|
| 277 |
+
from transformers import BlipProcessor, BlipForConditionalGeneration
|
| 278 |
+
from PIL import Image
|
| 279 |
+
|
| 280 |
+
processor = BlipProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
|
| 281 |
+
model = BlipForConditionalGeneration.from_pretrained("Salesforce/blip-image-captioning-base")
|
| 282 |
+
|
| 283 |
+
def generate_caption(image):
|
| 284 |
+
inputs = processor(image, return_tensors="pt")
|
| 285 |
+
out = model.generate(**inputs)
|
| 286 |
+
caption = processor.decode(out[0], skip_special_tokens=True)
|
| 287 |
+
return caption
|
| 288 |
+
|
| 289 |
+
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 290 |
+
gr.Markdown("# Image Caption Generator")
|
| 291 |
+
with gr.Row():
|
| 292 |
+
with gr.Column():
|
| 293 |
+
input_image = gr.Image(type="pil", label="Upload Image")
|
| 294 |
+
caption_btn = gr.Button("Generate Caption")
|
| 295 |
+
with gr.Column():
|
| 296 |
+
caption_output = gr.Textbox(label="Generated Caption")
|
| 297 |
+
|
| 298 |
+
caption_btn.click(
|
| 299 |
+
fn=generate_caption,
|
| 300 |
+
inputs=input_image,
|
| 301 |
+
outputs=caption_output
|
| 302 |
+
)
|
| 303 |
+
|
| 304 |
+
if __name__ == "__main__":
|
| 305 |
+
demo.launch()
|
| 306 |
+
""",
|
| 307 |
+
description="Image captioning interface using a transformer model",
|
| 308 |
+
components=["Image", "Button", "Textbox"],
|
| 309 |
+
metadata={"category": "computer_vision"}
|
| 310 |
+
),
|
| 311 |
+
"style_transfer": Template(
|
| 312 |
+
code="""
|
| 313 |
+
import gradio as gr
|
| 314 |
+
import tensorflow as tf
|
| 315 |
+
import tensorflow_hub as hub
|
| 316 |
+
|
| 317 |
+
hub_model = hub.load('https://tfhub.dev/google/magenta/arbitrary-image-stylization-v1-256/2')
|
| 318 |
+
|
| 319 |
+
def apply_style(content_image, style_image):
|
| 320 |
+
content_image = tf.image.convert_image_dtype(content_image, tf.float32)[tf.newaxis, ...]
|
| 321 |
+
style_image = tf.image.convert_image_dtype(style_image, tf.float32)[tf.newaxis, ...]
|
| 322 |
+
stylized_image = hub_model(content_image, style_image)[0]
|
| 323 |
+
return tf.squeeze(stylized_image).numpy()
|
| 324 |
+
|
| 325 |
+
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 326 |
+
gr.Markdown("# Neural Style Transfer")
|
| 327 |
+
with gr.Row():
|
| 328 |
+
with gr.Column():
|
| 329 |
+
content_image = gr.Image(label="Content Image")
|
| 330 |
+
style_image = gr.Image(label="Style Image")
|
| 331 |
+
transfer_btn = gr.Button("Transfer Style")
|
| 332 |
+
with gr.Column():
|
| 333 |
+
output_image = gr.Image(label="Stylized Image")
|
| 334 |
+
|
| 335 |
+
transfer_btn.click(
|
| 336 |
+
fn=apply_style,
|
| 337 |
+
inputs=[content_image, style_image],
|
| 338 |
+
outputs=output_image
|
| 339 |
+
)
|
| 340 |
+
|
| 341 |
+
if __name__ == "__main__":
|
| 342 |
+
demo.launch()
|
| 343 |
+
""",
|
| 344 |
+
description="Neural style transfer between two images",
|
| 345 |
+
components=["Image", "Button"],
|
| 346 |
+
metadata={"category": "computer_vision"}
|
| 347 |
+
),
|
| 348 |
+
"sentiment_analysis": Template(
|
| 349 |
+
code="""
|
| 350 |
+
import gradio as gr
|
| 351 |
+
from transformers import pipeline
|
| 352 |
+
|
| 353 |
+
sentiment_pipeline = pipeline("sentiment-analysis")
|
| 354 |
+
|
| 355 |
+
def analyze_sentiment(text):
|
| 356 |
+
result = sentiment_pipeline(text)[0]
|
| 357 |
+
return f"{result['label']} ({result['score']:.2f})"
|
| 358 |
+
|
| 359 |
+
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 360 |
+
gr.Markdown("# Sentiment Analysis")
|
| 361 |
+
with gr.Row():
|
| 362 |
+
with gr.Column():
|
| 363 |
+
input_text = gr.Textbox(label="Input Text", lines=5, placeholder="Enter text to analyze sentiment...")
|
| 364 |
+
analyze_btn = gr.Button("Analyze Sentiment")
|
| 365 |
+
with gr.Column():
|
| 366 |
+
sentiment_output = gr.Textbox(label="Sentiment Result")
|
| 367 |
+
|
| 368 |
+
analyze_btn.click(
|
| 369 |
+
fn=analyze_sentiment,
|
| 370 |
+
inputs=input_text,
|
| 371 |
+
outputs=sentiment_output
|
| 372 |
+
)
|
| 373 |
+
|
| 374 |
+
if __name__ == "__main__":
|
| 375 |
+
demo.launch()
|
| 376 |
+
""",
|
| 377 |
+
description="Sentiment analysis using transformer model",
|
| 378 |
+
components=["Textbox", "Button"],
|
| 379 |
+
metadata={"category": "nlp"}
|
| 380 |
+
),
|
| 381 |
+
"pdf_to_text": Template(
|
| 382 |
+
code="""
|
| 383 |
+
import gradio as gr
|
| 384 |
+
import PyPDF2
|
| 385 |
+
|
| 386 |
+
def extract_text_from_pdf(pdf):
|
| 387 |
+
reader = PyPDF2.PdfFileReader(pdf)
|
| 388 |
+
text = ''
|
| 389 |
+
for page_num in range(reader.numPages):
|
| 390 |
+
page = reader.getPage(page_num)
|
| 391 |
+
text += page.extract_text()
|
| 392 |
+
return text
|
| 393 |
+
|
| 394 |
+
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 395 |
+
gr.Markdown("# PDF to Text Extractor")
|
| 396 |
+
with gr.Row():
|
| 397 |
+
with gr.Column():
|
| 398 |
+
pdf_file = gr.File(label="Upload PDF")
|
| 399 |
+
extract_btn = gr.Button("Extract Text")
|
| 400 |
+
with gr.Column():
|
| 401 |
+
output_text = gr.Textbox(label="Extracted Text", lines=10)
|
| 402 |
+
|
| 403 |
+
extract_btn.click(
|
| 404 |
+
fn=extract_text_from_pdf,
|
| 405 |
+
inputs=pdf_file,
|
| 406 |
+
outputs=output_text
|
| 407 |
+
)
|
| 408 |
+
|
| 409 |
+
if __name__ == "__main__":
|
| 410 |
+
demo.launch()
|
| 411 |
+
""",
|
| 412 |
+
description="Extract text from PDF files",
|
| 413 |
+
components=["File", "Button", "Textbox"],
|
| 414 |
+
metadata={"category": "utility"}
|
| 415 |
+
),
|
| 416 |
+
"website_monitor": Template(
|
| 417 |
+
code="""
|
| 418 |
+
import gradio as gr
|
| 419 |
+
import requests
|
| 420 |
+
from datetime import datetime
|
| 421 |
+
|
| 422 |
+
def monitor_website(url):
|
| 423 |
+
try:
|
| 424 |
+
response = requests.get(url)
|
| 425 |
+
status_code = response.status_code
|
| 426 |
+
status = "Up" if status_code == 200 else "Down"
|
| 427 |
+
return {
|
| 428 |
+
"url": url,
|
| 429 |
+
"status": status,
|
| 430 |
+
"response_time": response.elapsed.total_seconds(),
|
| 431 |
+
"last_checked": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
| 432 |
+
}
|
| 433 |
+
except Exception as e:
|
| 434 |
+
return {"error": str(e)}
|
| 435 |
+
|
| 436 |
+
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 437 |
+
gr.Markdown("# Website Uptime Monitor")
|
| 438 |
+
with gr.Row():
|
| 439 |
+
with gr.Column():
|
| 440 |
+
url_input = gr.Textbox(label="Website URL", placeholder="https://example.com")
|
| 441 |
+
check_btn = gr.Button("Check Website")
|
| 442 |
+
with gr.Column():
|
| 443 |
+
result_output = gr.JSON(label="Monitoring Result")
|
| 444 |
+
|
| 445 |
+
check_btn.click(
|
| 446 |
+
fn=monitor_website,
|
| 447 |
+
inputs=url_input,
|
| 448 |
+
outputs=result_output
|
| 449 |
+
)
|
| 450 |
+
|
| 451 |
+
if __name__ == "__main__":
|
| 452 |
+
demo.launch()
|
| 453 |
+
""",
|
| 454 |
+
description="Monitor the uptime and response time of a website",
|
| 455 |
+
components=["Textbox", "Button", "JSON"],
|
| 456 |
+
metadata={"category": "web_monitoring"}
|
| 457 |
+
),
|
| 458 |
+
"rss_feed_fetcher": Template(
|
| 459 |
+
code="""
|
| 460 |
+
import gradio as gr
|
| 461 |
+
import feedparser
|
| 462 |
+
|
| 463 |
+
def fetch_rss_feed(url):
|
| 464 |
+
feed = feedparser.parse(url)
|
| 465 |
+
if feed.bozo:
|
| 466 |
+
return {"error": "Invalid RSS feed URL"}
|
| 467 |
+
|
| 468 |
+
return [{"title": entry.title, "link": entry.link} for entry in feed.entries[:5]]
|
| 469 |
+
|
| 470 |
+
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 471 |
+
gr.Markdown("# RSS Feed Fetcher")
|
| 472 |
+
with gr.Row():
|
| 473 |
+
with gr.Column():
|
| 474 |
+
feed_url = gr.Textbox(label="RSS Feed URL", placeholder="https://example.com/feed")
|
| 475 |
+
fetch_btn = gr.Button("Fetch Latest Posts")
|
| 476 |
+
with gr.Column():
|
| 477 |
+
feed_output = gr.JSON(label="Latest Feed Entries")
|
| 478 |
+
|
| 479 |
+
fetch_btn.click(
|
| 480 |
+
fn=fetch_rss_feed,
|
| 481 |
+
inputs=feed_url,
|
| 482 |
+
outputs=feed_output
|
| 483 |
+
)
|
| 484 |
+
|
| 485 |
+
if __name__ == "__main__":
|
| 486 |
+
demo.launch()
|
| 487 |
+
""",
|
| 488 |
+
description="Fetch the latest entries from an RSS feed",
|
| 489 |
+
components=["Textbox", "Button", "JSON"],
|
| 490 |
+
metadata={"category": "web_scraping"}
|
| 491 |
+
),
|
| 492 |
+
"web_scraper": Template(
|
| 493 |
+
code="""
|
| 494 |
+
import gradio as gr
|
| 495 |
+
from bs4 import BeautifulSoup
|
| 496 |
+
import requests
|
| 497 |
+
|
| 498 |
+
def scrape_website(url, tag):
|
| 499 |
+
try:
|
| 500 |
+
response = requests.get(url)
|
| 501 |
+
soup = BeautifulSoup(response.text, "html.parser")
|
| 502 |
+
elements = soup.find_all(tag)
|
| 503 |
+
return [element.get_text() for element in elements][:5] # Limit to 5 elements
|
| 504 |
+
except Exception as e:
|
| 505 |
+
return f"Error: {str(e)}"
|
| 506 |
+
|
| 507 |
+
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 508 |
+
gr.Markdown("# Web Scraper")
|
| 509 |
+
with gr.Row():
|
| 510 |
+
with gr.Column():
|
| 511 |
+
url_input = gr.Textbox(label="Website URL", placeholder="https://example.com")
|
| 512 |
+
tag_input = gr.Textbox(label="HTML Tag to Scrape", placeholder="h1, p, div, etc.")
|
| 513 |
+
scrape_btn = gr.Button("Scrape Website")
|
| 514 |
+
with gr.Column():
|
| 515 |
+
result_output = gr.JSON(label="Scraped Results")
|
| 516 |
+
|
| 517 |
+
scrape_btn.click(
|
| 518 |
+
fn=scrape_website,
|
| 519 |
+
inputs=[url_input, tag_input],
|
| 520 |
+
outputs=result_output
|
| 521 |
+
)
|
| 522 |
+
|
| 523 |
+
if __name__ == "__main__":
|
| 524 |
+
demo.launch()
|
| 525 |
+
""",
|
| 526 |
+
description="Scrape text from a website based on the specified HTML tag",
|
| 527 |
+
components=["Textbox", "Button", "JSON"],
|
| 528 |
+
metadata={"category": "web_scraping"}
|
| 529 |
+
),
|
| 530 |
+
"api_tester": Template(
|
| 531 |
+
code="""
|
| 532 |
+
import gradio as gr
|
| 533 |
+
import requests
|
| 534 |
+
|
| 535 |
+
def test_api(endpoint, method, payload):
|
| 536 |
+
try:
|
| 537 |
+
if method == "GET":
|
| 538 |
+
response = requests.get(endpoint)
|
| 539 |
+
elif method == "POST":
|
| 540 |
+
response = requests.post(endpoint, json=payload)
|
| 541 |
+
else:
|
| 542 |
+
return "Unsupported method"
|
| 543 |
+
|
| 544 |
+
return {
|
| 545 |
+
"status_code": response.status_code,
|
| 546 |
+
"response_body": response.json() if response.headers.get("Content-Type") == "application/json" else response.text
|
| 547 |
+
}
|
| 548 |
+
except Exception as e:
|
| 549 |
+
return {"error": str(e)}
|
| 550 |
+
|
| 551 |
+
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 552 |
+
gr.Markdown("# API Tester")
|
| 553 |
+
with gr.Row():
|
| 554 |
+
with gr.Column():
|
| 555 |
+
endpoint = gr.Textbox(label="API Endpoint", placeholder="https://api.example.com/endpoint")
|
| 556 |
+
method = gr.Radio(choices=["GET", "POST"], label="HTTP Method", value="GET")
|
| 557 |
+
payload = gr.JSON(label="Payload (for POST)", value={})
|
| 558 |
+
test_btn = gr.Button("Test API")
|
| 559 |
+
with gr.Column():
|
| 560 |
+
result_output = gr.JSON(label="API Response")
|
| 561 |
+
|
| 562 |
+
test_btn.click(
|
| 563 |
+
fn=test_api,
|
| 564 |
+
inputs=[endpoint, method, payload],
|
| 565 |
+
outputs=result_output
|
| 566 |
+
)
|
| 567 |
+
|
| 568 |
+
if __name__ == "__main__":
|
| 569 |
+
demo.launch()
|
| 570 |
+
""",
|
| 571 |
+
description="Test API endpoints with GET and POST requests",
|
| 572 |
+
components=["Textbox", "Radio", "JSON", "Button"],
|
| 573 |
+
metadata={"category": "api_testing"}
|
| 574 |
+
),
|
| 575 |
+
"email_scheduler": Template(
|
| 576 |
+
code="""
|
| 577 |
+
import gradio as gr
|
| 578 |
+
import smtplib
|
| 579 |
+
from email.mime.text import MIMEText
|
| 580 |
+
from email.mime.multipart import MIMEMultipart
|
| 581 |
+
from apscheduler.schedulers.background import BackgroundScheduler
|
| 582 |
+
|
| 583 |
+
scheduler = BackgroundScheduler()
|
| 584 |
+
scheduler.start()
|
| 585 |
+
|
| 586 |
+
def send_email(to_email, subject, body):
|
| 587 |
+
try:
|
| 588 |
+
sender_email = "your_email@example.com"
|
| 589 |
+
password = "your_password"
|
| 590 |
+
|
| 591 |
+
msg = MIMEMultipart()
|
| 592 |
+
msg['From'] = sender_email
|
| 593 |
+
msg['To'] = to_email
|
| 594 |
+
msg['Subject'] = subject
|
| 595 |
+
|
| 596 |
+
msg.attach(MIMEText(body, 'plain'))
|
| 597 |
+
|
| 598 |
+
server = smtplib.SMTP('smtp.example.com', 587)
|
| 599 |
+
server.starttls()
|
| 600 |
+
server.login(sender_email, password)
|
| 601 |
+
text = msg.as_string()
|
| 602 |
+
server.sendmail(sender_email, to_email, text)
|
| 603 |
+
server.quit()
|
| 604 |
+
|
| 605 |
+
return "Email sent successfully"
|
| 606 |
+
except Exception as e:
|
| 607 |
+
return f"Error: {str(e)}"
|
| 608 |
+
|
| 609 |
+
def schedule_email(to_email, subject, body, delay):
|
| 610 |
+
scheduler.add_job(send_email, 'interval', seconds=delay, args=[to_email, subject, body])
|
| 611 |
+
return f"Email scheduled to be sent in {delay} seconds"
|
| 612 |
+
|
| 613 |
+
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 614 |
+
gr.Markdown("# Email Scheduler")
|
| 615 |
+
with gr.Row():
|
| 616 |
+
with gr.Column():
|
| 617 |
+
to_email = gr.Textbox(label="Recipient Email")
|
| 618 |
+
subject = gr.Textbox(label="Subject")
|
| 619 |
+
body = gr.Textbox(label="Email Body", lines=5)
|
| 620 |
+
delay = gr.Slider(label="Delay (seconds)", minimum=10, maximum=300, step=10, value=60)
|
| 621 |
+
schedule_btn = gr.Button("Schedule Email")
|
| 622 |
+
with gr.Column():
|
| 623 |
+
result_output = gr.Textbox(label="Result")
|
| 624 |
+
|
| 625 |
+
schedule_btn.click(
|
| 626 |
+
fn=schedule_email,
|
| 627 |
+
inputs=[to_email, subject, body, delay],
|
| 628 |
+
outputs=result_output
|
| 629 |
+
)
|
| 630 |
+
|
| 631 |
+
if __name__ == "__main__":
|
| 632 |
+
demo.launch()
|
| 633 |
+
""",
|
| 634 |
+
description="Schedule emails to be sent after a delay",
|
| 635 |
+
components=["Textbox", "Slider", "Button"],
|
| 636 |
+
metadata={"category": "task_automation"}
|
| 637 |
+
),
|
| 638 |
+
"log_file_analyzer": Template(
|
| 639 |
+
code="""
|
| 640 |
+
import gradio as gr
|
| 641 |
+
import re
|
| 642 |
+
|
| 643 |
+
def analyze_logs(log_file, filter_text):
|
| 644 |
+
try:
|
| 645 |
+
logs = log_file.read().decode("utf-8")
|
| 646 |
+
if filter_text:
|
| 647 |
+
filtered_logs = "\n".join([line for line in logs.splitlines() if re.search(filter_text, line)])
|
| 648 |
+
else:
|
| 649 |
+
filtered_logs = logs
|
| 650 |
+
return filtered_logs
|
| 651 |
+
except Exception as e:
|
| 652 |
+
return f"Error: {str(e)}"
|
| 653 |
+
|
| 654 |
+
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 655 |
+
gr.Markdown("# Log File Analyzer")
|
| 656 |
+
with gr.Row():
|
| 657 |
+
with gr.Column():
|
| 658 |
+
log_input = gr.File(label="Upload Log File")
|
| 659 |
+
filter_input = gr.Textbox(label="Filter (Regex)", placeholder="Error|Warning")
|
| 660 |
+
analyze_btn = gr.Button("Analyze Logs")
|
| 661 |
+
with gr.Column():
|
| 662 |
+
output_logs = gr.Textbox(label="Filtered Logs", lines=20)
|
| 663 |
+
|
| 664 |
+
analyze_btn.click(
|
| 665 |
+
fn=analyze_logs,
|
| 666 |
+
inputs=[log_input, filter_input],
|
| 667 |
+
outputs=output_logs
|
| 668 |
+
)
|
| 669 |
+
|
| 670 |
+
if __name__ == "__main__":
|
| 671 |
+
demo.launch()
|
| 672 |
+
""",
|
| 673 |
+
description="Analyze and filter log files using regex",
|
| 674 |
+
components=["File", "Textbox", "Button"],
|
| 675 |
+
metadata={"category": "log_analysis"}
|
| 676 |
+
),
|
| 677 |
+
"file_encryption_tool": Template(
|
| 678 |
+
code="""
|
| 679 |
+
import gradio as gr
|
| 680 |
+
from cryptography.fernet import Fernet
|
| 681 |
+
|
| 682 |
+
def encrypt_file(file, password):
|
| 683 |
+
try:
|
| 684 |
+
key = password.ljust(32, '0').encode()[:32] # Basic password -> key mapping
|
| 685 |
+
cipher = Fernet(Fernet.generate_key())
|
| 686 |
+
file_data = file.read()
|
| 687 |
+
encrypted_data = cipher.encrypt(file_data)
|
| 688 |
+
return encrypted_data.decode("utf-8")
|
| 689 |
+
except Exception as e:
|
| 690 |
+
return f"Error: {str(e)}"
|
| 691 |
+
|
| 692 |
+
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 693 |
+
gr.Markdown("# File Encryption Tool")
|
| 694 |
+
with gr.Row():
|
| 695 |
+
with gr.Column():
|
| 696 |
+
file_input = gr.File(label="Upload File")
|
| 697 |
+
password_input = gr.Textbox(label="Password", type="password")
|
| 698 |
+
encrypt_btn = gr.Button("Encrypt File")
|
| 699 |
+
with gr.Column():
|
| 700 |
+
encrypted_output = gr.Textbox(label = "Encrypted Data", lines=20)
|
| 701 |
+
|
| 702 |
+
encrypt_btn.click(
|
| 703 |
+
fn=encrypt_file,
|
| 704 |
+
inputs=[file_input, password_input],
|
| 705 |
+
outputs=encrypted_output
|
| 706 |
+
)
|
| 707 |
+
|
| 708 |
+
if __name__ == "__main__":
|
| 709 |
+
demo.launch()
|
| 710 |
+
""",
|
| 711 |
+
description="Encrypt a file using a password-based key",
|
| 712 |
+
components=["File", "Textbox", "Button"],
|
| 713 |
+
metadata={"category": "security"}
|
| 714 |
+
),
|
| 715 |
+
"task_scheduler": Template(
|
| 716 |
+
code="""
|
| 717 |
+
import gradio as gr
|
| 718 |
+
from apscheduler.schedulers.background import BackgroundScheduler
|
| 719 |
+
from datetime import datetime
|
| 720 |
+
|
| 721 |
+
scheduler = BackgroundScheduler()
|
| 722 |
+
scheduler.start()
|
| 723 |
+
|
| 724 |
+
def schedule_task(task_name, interval):
|
| 725 |
+
scheduler.add_job(lambda: print(f"Running task: {task_name} at {datetime.now()}"), 'interval', seconds=interval)
|
| 726 |
+
return f"Task '{task_name}' scheduled to run every {interval} seconds."
|
| 727 |
+
|
| 728 |
+
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 729 |
+
gr.Markdown("# Task Scheduler")
|
| 730 |
+
with gr.Row():
|
| 731 |
+
with gr.Column():
|
| 732 |
+
task_input = gr.Textbox(label="Task Name", placeholder="Example Task")
|
| 733 |
+
interval_input = gr.Slider(minimum=1, maximum=60, label="Interval (Seconds)", value=10)
|
| 734 |
+
schedule_btn = gr.Button("Schedule Task")
|
| 735 |
+
with gr.Column():
|
| 736 |
+
result_output = gr.Textbox(label="Result")
|
| 737 |
+
|
| 738 |
+
schedule_btn.click(
|
| 739 |
+
fn=schedule_task,
|
| 740 |
+
inputs=[task_input, interval_input],
|
| 741 |
+
outputs=result_output
|
| 742 |
+
)
|
| 743 |
+
|
| 744 |
+
if __name__ == "__main__":
|
| 745 |
+
demo.launch()
|
| 746 |
+
""",
|
| 747 |
+
description="Schedule tasks to run at regular intervals",
|
| 748 |
+
components=["Textbox", "Slider", "Button"],
|
| 749 |
+
metadata={"category": "task_automation"}
|
| 750 |
+
),
|
| 751 |
+
"code_comparator": Template(
|
| 752 |
+
code="""
|
| 753 |
+
import gradio as gr
|
| 754 |
+
import difflib
|
| 755 |
+
|
| 756 |
+
def compare_code(code1, code2):
|
| 757 |
+
diff = difflib.unified_diff(code1.splitlines(), code2.splitlines(), lineterm='', fromfile='code1', tofile='code2')
|
| 758 |
+
return '\n'.join(diff)
|
| 759 |
+
|
| 760 |
+
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 761 |
+
gr.Markdown("# Code Comparator")
|
| 762 |
+
with gr.Row():
|
| 763 |
+
with gr.Column():
|
| 764 |
+
code1_input = gr.Textbox(label="Code 1", lines=15, placeholder="Paste the first code snippet here...")
|
| 765 |
+
code2_input = gr.Textbox(label="Code 2", lines=15, placeholder="Paste the second code snippet here...")
|
| 766 |
+
compare_btn = gr.Button("Compare Codes")
|
| 767 |
+
with gr.Column():
|
| 768 |
+
diff_output = gr.Textbox(label="Difference", lines=20)
|
| 769 |
+
|
| 770 |
+
compare_btn.click(
|
| 771 |
+
fn=compare_code,
|
| 772 |
+
inputs=[code1_input, code2_input],
|
| 773 |
+
outputs=diff_output
|
| 774 |
+
)
|
| 775 |
+
|
| 776 |
+
if __name__ == "__main__":
|
| 777 |
+
demo.launch()
|
| 778 |
+
""",
|
| 779 |
+
description="Compare two code snippets and show the differences",
|
| 780 |
+
components=["Textbox", "Button"],
|
| 781 |
+
metadata={"category": "development"}
|
| 782 |
+
),
|
| 783 |
+
"database_query_tool": Template(
|
| 784 |
+
code="""
|
| 785 |
+
import gradio as gr
|
| 786 |
+
import sqlite3
|
| 787 |
+
|
| 788 |
+
def query_database(db_file, query):
|
| 789 |
+
try:
|
| 790 |
+
conn = sqlite3.connect(db_file.name)
|
| 791 |
+
cursor = conn.cursor()
|
| 792 |
+
cursor.execute(query)
|
| 793 |
+
results = cursor.fetchall()
|
| 794 |
+
conn.close()
|
| 795 |
+
return results
|
| 796 |
+
except Exception as e:
|
| 797 |
+
return f"Error: {str(e)}"
|
| 798 |
+
|
| 799 |
+
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 800 |
+
gr.Markdown("# Database Query Tool")
|
| 801 |
+
with gr.Row():
|
| 802 |
+
with gr.Column():
|
| 803 |
+
db_input = gr.File(label="Upload SQLite DB File")
|
| 804 |
+
query_input = gr.Textbox(label="SQL Query", placeholder="SELECT * FROM table_name;")
|
| 805 |
+
query_btn = gr.Button("Run Query")
|
| 806 |
+
with gr.Column():
|
| 807 |
+
query_output = gr.JSON(label="Query Results")
|
| 808 |
+
|
| 809 |
+
query_btn.click(
|
| 810 |
+
fn=query_database,
|
| 811 |
+
inputs=[db_input, query_input],
|
| 812 |
+
outputs=query_output
|
| 813 |
+
)
|
| 814 |
+
|
| 815 |
+
if __name__ == "__main__":
|
| 816 |
+
demo.launch()
|
| 817 |
+
""",
|
| 818 |
+
description="Run SQL queries on a SQLite database",
|
| 819 |
+
components=["File", "Textbox", "Button", "JSON"],
|
| 820 |
+
metadata={"category": "database"}
|
| 821 |
+
),
|
| 822 |
+
"code_generator": Template(
|
| 823 |
+
code="""
|
| 824 |
+
import gradio as gr
|
| 825 |
+
from transformers import pipeline
|
| 826 |
+
|
| 827 |
+
code_generator = pipeline("text-generation", model="Salesforce/codegen-2B-multi")
|
| 828 |
+
|
| 829 |
+
def generate_code(prompt):
|
| 830 |
+
response = code_generator(prompt, max_length=150, num_return_sequences=1)
|
| 831 |
+
return response[0]['generated_text']
|
| 832 |
+
|
| 833 |
+
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 834 |
+
gr.Markdown("# Code Generator ")
|
| 835 |
+
with gr.Row():
|
| 836 |
+
with gr.Column():
|
| 837 |
+
prompt_input = gr.Textbox(label="Enter Code Prompt", placeholder="Write a Python function to reverse a string")
|
| 838 |
+
generate_btn = gr.Button("Generate Code")
|
| 839 |
+
with gr.Column():
|
| 840 |
+
generated_code = gr.Textbox(label="Generated Code", lines=10)
|
| 841 |
+
|
| 842 |
+
generate_btn.click(
|
| 843 |
+
fn=generate_code,
|
| 844 |
+
inputs=prompt_input,
|
| 845 |
+
outputs=generated_code
|
| 846 |
+
)
|
| 847 |
+
|
| 848 |
+
if __name__ == "__main__":
|
| 849 |
+
demo.launch()
|
| 850 |
+
""",
|
| 851 |
+
description="Generate code snippets based on natural language prompts",
|
| 852 |
+
components=["Textbox", "Button"],
|
| 853 |
+
metadata={"category": "development"}
|
| 854 |
+
),
|
| 855 |
+
"code_debugger": Template(
|
| 856 |
+
code="""
|
| 857 |
+
import gradio as gr
|
| 858 |
+
import subprocess
|
| 859 |
+
|
| 860 |
+
def debug_code(code):
|
| 861 |
+
try:
|
| 862 |
+
with open("temp_code.py", "w") as f:
|
| 863 |
+
f.write(code)
|
| 864 |
+
result = subprocess.run(["python3", "temp_code.py"], capture_output=True, text=True)
|
| 865 |
+
return {"stdout": result.stdout, "stderr": result.stderr}
|
| 866 |
+
except Exception as e:
|
| 867 |
+
return {"error": str(e)}
|
| 868 |
+
|
| 869 |
+
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 870 |
+
gr.Markdown("# Code Debugger")
|
| 871 |
+
with gr.Row():
|
| 872 |
+
with gr.Column():
|
| 873 |
+
code_input = gr.Textbox(label="Code to Debug", lines=10, placeholder="Paste your Python code here...")
|
| 874 |
+
debug_btn = gr.Button("Run Debug")
|
| 875 |
+
with gr.Column():
|
| 876 |
+
debug_output = gr.JSON(label="Debug Output")
|
| 877 |
+
|
| 878 |
+
debug_btn.click(
|
| 879 |
+
fn=debug_code,
|
| 880 |
+
inputs=code_input,
|
| 881 |
+
outputs=debug_output
|
| 882 |
+
)
|
| 883 |
+
|
| 884 |
+
if __name__ == "__main__":
|
| 885 |
+
demo.launch()
|
| 886 |
+
""",
|
| 887 |
+
description="Run and debug Python code by capturing stdout and stderr",
|
| 888 |
+
components=["Textbox", "Button", "JSON"],
|
| 889 |
+
metadata={"category": "development"}
|
| 890 |
+
),
|
| 891 |
+
"multi_agent_task_manager": Template(
|
| 892 |
+
code="""
|
| 893 |
+
import gradio as gr
|
| 894 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 895 |
+
import time
|
| 896 |
+
|
| 897 |
+
agent_pool = ThreadPoolExecutor(max_workers=5)
|
| 898 |
+
agent_status = {}
|
| 899 |
+
|
| 900 |
+
def agent_task(agent_name, task):
|
| 901 |
+
agent_status[agent_name] = "Running"
|
| 902 |
+
time.sleep(5) # Simulate task duration
|
| 903 |
+
agent_status[agent_name] = "Completed"
|
| 904 |
+
return f"Agent {agent_name} has completed the task: {task}"
|
| 905 |
+
|
| 906 |
+
def trigger_agents(agents, task):
|
| 907 |
+
results = []
|
| 908 |
+
for agent in agents:
|
| 909 |
+
future = agent_pool.submit(agent_task, agent, task)
|
| 910 |
+
results.append(f"Agent {agent} triggered")
|
| 911 |
+
return results
|
| 912 |
+
|
| 913 |
+
def get_agent_status():
|
| 914 |
+
return agent_status
|
| 915 |
+
|
| 916 |
+
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 917 |
+
gr.Markdown("# Multi-Agent Task Manager")
|
| 918 |
+
with gr.Row():
|
| 919 |
+
with gr.Column():
|
| 920 |
+
agents = gr.CheckboxGroup(choices=["Agent1", "Agent2", "Agent3", "Agent4", "Agent5"], label="Select Agents")
|
| 921 |
+
task_input = gr.Textbox(label="Task to Perform", placeholder="Describe the task...")
|
| 922 |
+
trigger_btn = gr.Button("Trigger Agents")
|
| 923 |
+
with gr.Column():
|
| 924 |
+
task_output = gr.JSON(label="Agent Responses")
|
| 925 |
+
|
| 926 |
+
with gr.Row():
|
| 927 |
+
status_btn = gr.Button("Get Agent Status")
|
| 928 |
+
status_output = gr.JSON(label="Current Agent Status")
|
| 929 |
+
|
| 930 |
+
trigger_btn.click(
|
| 931 |
+
fn=trigger_agents,
|
| 932 |
+
inputs=[agents, task_input],
|
| 933 |
+
outputs=task_output
|
| 934 |
+
)
|
| 935 |
+
|
| 936 |
+
status_btn.click(
|
| 937 |
+
fn=get_agent_status,
|
| 938 |
+
inputs=[],
|
| 939 |
+
outputs=status_output
|
| 940 |
+
)
|
| 941 |
+
|
| 942 |
+
if __name__ == "__main__":
|
| 943 |
+
demo.launch()
|
| 944 |
+
""",
|
| 945 |
+
description="Manage and trigger tasks for multiple autonomous agents",
|
| 946 |
+
components=["CheckboxGroup", "Textbox", "Button", "JSON"],
|
| 947 |
+
metadata={"category": "task_automation"}
|
| 948 |
+
),
|
| 949 |
+
"auto_code_refactor": Template(
|
| 950 |
+
code="""
|
| 951 |
+
import gradio as gr
|
| 952 |
+
from transformers import pipeline
|
| 953 |
+
|
| 954 |
+
code_refactor = pipeline("text2text-generation", model="facebook/bart-large-cnn")
|
| 955 |
+
|
| 956 |
+
def refactor_code(code):
|
| 957 |
+
result = code_refactor(f"Refactor the following Python code: {code}", max_length=150)
|
| 958 |
+
return result[0]['generated_text']
|
| 959 |
+
|
| 960 |
+
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 961 |
+
gr.Markdown("# Auto Code Refactor")
|
| 962 |
+
with gr.Row():
|
| 963 |
+
with gr.Column():
|
| 964 |
+
code_input = gr.Textbox(label="Code to Refactor", lines=10, placeholder="Paste your Python code here...")
|
| 965 |
+
refactor_btn = gr.Button("Refactor Code")
|
| 966 |
+
with gr.Column():
|
| 967 |
+
refactored_code = gr.Textbox(label="Refactored Code", lines =10)
|
| 968 |
+
|
| 969 |
+
refactor_btn.click(
|
| 970 |
+
fn=refactor_code,
|
| 971 |
+
inputs=code_input,
|
| 972 |
+
outputs=refactored_code
|
| 973 |
+
)
|
| 974 |
+
|
| 975 |
+
if __name__ == "__main__":
|
| 976 |
+
demo.launch()
|
| 977 |
+
""",
|
| 978 |
+
description="Automatically refactor Python code for better efficiency or readability",
|
| 979 |
+
components=["Textbox", "Button"],
|
| 980 |
+
metadata={"category": "development"}
|
| 981 |
+
),
|
| 982 |
+
"agent_cluster_deployer": Template(
|
| 983 |
+
code="""
|
| 984 |
+
import gradio as gr
|
| 985 |
+
import random
|
| 986 |
+
|
| 987 |
+
cluster_status = {}
|
| 988 |
+
|
| 989 |
+
def deploy_agent_cluster(agent_count, task):
|
| 990 |
+
cluster_id = random.randint(1000, 9999)
|
| 991 |
+
cluster_status[cluster_id] = {
|
| 992 |
+
"status": "Deploying",
|
| 993 |
+
"agents": agent_count,
|
| 994 |
+
"task": task
|
| 995 |
+
}
|
| 996 |
+
return f"Cluster {cluster_id} is deploying with {agent_count} agents for task: {task}"
|
| 997 |
+
|
| 998 |
+
def get_cluster_status():
|
| 999 |
+
return cluster_status
|
| 1000 |
+
|
| 1001 |
+
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 1002 |
+
gr.Markdown("# Agent Cluster Deployer")
|
| 1003 |
+
with gr.Row():
|
| 1004 |
+
with gr.Column():
|
| 1005 |
+
agent_count = gr.Slider(label="Number of Agents", minimum=1, maximum=10, step=1, value=3)
|
| 1006 |
+
task_input = gr.Textbox(label="Cluster Task", placeholder="Describe the task for the cluster...")
|
| 1007 |
+
deploy_btn = gr.Button("Deploy Cluster")
|
| 1008 |
+
with gr.Column():
|
| 1009 |
+
deploy_output = gr.Textbox(label="Cluster Deployment Status")
|
| 1010 |
+
|
| 1011 |
+
with gr.Row():
|
| 1012 |
+
status_btn = gr.Button("Get Cluster Status")
|
| 1013 |
+
status_output = gr.JSON(label="Current Cluster Status")
|
| 1014 |
+
|
| 1015 |
+
deploy_btn.click(
|
| 1016 |
+
fn=deploy_agent_cluster,
|
| 1017 |
+
inputs=[agent_count, task_input],
|
| 1018 |
+
outputs=deploy_output
|
| 1019 |
+
)
|
| 1020 |
+
|
| 1021 |
+
status_btn.click(
|
| 1022 |
+
fn=get_cluster_status,
|
| 1023 |
+
inputs=[],
|
| 1024 |
+
outputs=status_output
|
| 1025 |
+
)
|
| 1026 |
+
|
| 1027 |
+
if __name__ == "__main__":
|
| 1028 |
+
demo.launch()
|
| 1029 |
+
""",
|
| 1030 |
+
description="Deploy an autonomous agent cluster for task execution",
|
| 1031 |
+
components=["Slider", "Textbox", "Button", "JSON"],
|
| 1032 |
+
metadata={"category": "task_automation"}
|
| 1033 |
+
)
|
| 1034 |
+
}
|
| 1035 |
+
|
| 1036 |
+
self.component_index = self._build_component_index()
|
| 1037 |
+
self.category_index = self._build_category_index()
|
| 1038 |
+
|
| 1039 |
+
def _build_component_index(self) -> Dict[str, List[str]]:
|
| 1040 |
+
"""Build index of templates by component"""
|
| 1041 |
+
index = {}
|
| 1042 |
+
for name, template in self.templates.items():
|
| 1043 |
+
for component in template.components:
|
| 1044 |
+
if component not in index:
|
| 1045 |
+
index[component] = []
|
| 1046 |
+
index[component].append(name)
|
| 1047 |
+
return index
|
| 1048 |
+
|
| 1049 |
+
def _build_category_index(self) -> Dict[str, List[str]]:
|
| 1050 |
+
"""Build index of templates by category"""
|
| 1051 |
+
index = {}
|
| 1052 |
+
for name, template in self.templates.items():
|
| 1053 |
+
category = template.metadata.get("category", "other")
|
| 1054 |
+
if category not in index:
|
| 1055 |
+
index[category] = []
|
| 1056 |
+
index[category].append(name)
|
| 1057 |
+
return index
|
| 1058 |
+
|
| 1059 |
+
def search(self, query: str, limit: int = 5) -> List[Dict]:
|
| 1060 |
+
"""Search templates by description or metadata"""
|
| 1061 |
+
try:
|
| 1062 |
+
results = []
|
| 1063 |
+
for name, template in self.templates.items():
|
| 1064 |
+
desc_score = difflib.SequenceMatcher(
|
| 1065 |
+
None,
|
| 1066 |
+
query.lower(),
|
| 1067 |
+
template.description.lower()
|
| 1068 |
+
).ratio()
|
| 1069 |
+
|
| 1070 |
+
category_score = difflib.SequenceMatcher(
|
| 1071 |
+
None,
|
| 1072 |
+
query.lower(),
|
| 1073 |
+
template.metadata.get("category", "").lower()
|
| 1074 |
+
).ratio()
|
| 1075 |
+
|
| 1076 |
+
comp_score = sum(0.2 for component in template.components if component.lower() in query.lower())
|
| 1077 |
+
|
| 1078 |
+
final_score = max(desc_score, category_score) + comp_score
|
| 1079 |
+
|
| 1080 |
+
results.append({
|
| 1081 |
+
"name": name,
|
| 1082 |
+
"template": template,
|
| 1083 |
+
"score": final_score
|
| 1084 |
+
})
|
| 1085 |
+
|
| 1086 |
+
results.sort(key=lambda x: x["score"], reverse=True)
|
| 1087 |
+
return results[:limit]
|
| 1088 |
+
|
| 1089 |
+
except Exception as e:
|
| 1090 |
+
logger.error(f"Error searching templates: {str(e)}")
|
| 1091 |
+
return []
|
| 1092 |
+
|
| 1093 |
+
def search_by_components(self, components: List[str], limit: int = 5) -> List[Dict]:
|
| 1094 |
+
"""Search templates by required components"""
|
| 1095 |
+
try:
|
| 1096 |
+
results = []
|
| 1097 |
+
for name, template in self.templates.items():
|
| 1098 |
+
matches = sum(1 for c in components if c in template.components)
|
| 1099 |
+
if matches > 0:
|
| 1100 |
+
score = matches / len(components)
|
| 1101 |
+
results.append({
|
| 1102 |
+
"name": name,
|
| 1103 |
+
"template": template,
|
| 1104 |
+
"score": score
|
| 1105 |
+
})
|
| 1106 |
+
|
| 1107 |
+
results.sort(key=lambda x: x["score"], reverse=True)
|
| 1108 |
+
return results[:limit]
|
| 1109 |
+
|
| 1110 |
+
except Exception as e:
|
| 1111 |
+
logger.error(f"Error searching by components: {str(e)}")
|
| 1112 |
+
return []
|
| 1113 |
+
|
| 1114 |
+
def search_by_category(self, category: str) -> List[Dict]:
|
| 1115 |
+
"""Get all templates in a category"""
|
| 1116 |
+
try:
|
| 1117 |
+
return [
|
| 1118 |
+
{
|
| 1119 |
+
"name": name,
|
| 1120 |
+
"template": self.templates[name]
|
| 1121 |
+
}
|
| 1122 |
+
for name in self.category_index.get(category, [])
|
| 1123 |
+
]
|
| 1124 |
+
except Exception as e:
|
| 1125 |
+
logger.error(f"Error searching by category: {str(e)}")
|
| 1126 |
+
return []
|
| 1127 |
+
|
| 1128 |
+
def get_template(self, name: str) -> Optional[Template]:
|
| 1129 |
+
"""Get specific template by name"""
|
| 1130 |
+
return self.templates.get(name)
|
| 1131 |
+
|
| 1132 |
+
def get_categories(self) -> List[str]:
|
| 1133 |
+
"""Get list of all categories"""
|
| 1134 |
+
return list(self.category_index.keys())
|
| 1135 |
+
|
| 1136 |
+
def get_components(self) -> List[str]:
|
| 1137 |
+
"""Get list of all components"""
|
| 1138 |
+
return list(self.component_index.keys())
|
| 1139 |
+
|
| 1140 |
+
def export_templates(self, path: str):
|
| 1141 |
+
"""Export templates to JSON file"""
|
| 1142 |
+
try:
|
| 1143 |
+
data = {
|
| 1144 |
+
name: {
|
| 1145 |
+
"description": template.description,
|
| 1146 |
+
"components": template.components,
|
| 1147 |
+
"metadata": template.metadata,
|
| 1148 |
+
"example": template.example
|
| 1149 |
+
}
|
| 1150 |
+
for name, template in self.templates.items()
|
| 1151 |
+
}
|
| 1152 |
+
|
| 1153 |
+
with open(path, 'w') as f:
|
| 1154 |
+
json.dump(data, f, indent=2)
|
| 1155 |
+
|
| 1156 |
+
logger.info(f"Templates exported to {path}")
|
| 1157 |
+
|
| 1158 |
+
except Exception as e:
|
| 1159 |
+
logger.error(f"Error exporting templates: {str(e)}")
|
| 1160 |
+
raise
|
| 1161 |
+
|
| 1162 |
+
def import_templates(self, path: str):
|
| 1163 |
+
"""Import templates from JSON file"""
|
| 1164 |
+
try:
|
| 1165 |
+
with open(path, 'r') as f:
|
| 1166 |
+
data = json.load(f)
|
| 1167 |
+
|
| 1168 |
+
for name, template_data in data.items():
|
| 1169 |
+
self.templates[name] = Template(
|
| 1170 |
+
code="", # Code should be loaded separately
|
| 1171 |
+
description=template_data["description"],
|
| 1172 |
+
components=template_data["components"],
|
| 1173 |
+
metadata=template_data["metadata"],
|
| 1174 |
+
example=template_data.get("example")
|
| 1175 |
+
)
|
| 1176 |
+
|
| 1177 |
+
# Rebuild indexes
|
| 1178 |
+
self.component_index = self._build_component_index()
|
| 1179 |
+
self.category_index = self._build_category_index()
|
| 1180 |
+
|
| 1181 |
+
logger.info(f"Templates imported from {path}")
|
| 1182 |
+
|
| 1183 |
+
except Exception as e:
|
| 1184 |
+
logger.error(f"Error importing templates: {str(e)}")
|
| 1185 |
+
raise
|
| 1186 |
+
|
| 1187 |
+
# Usage example:
|
| 1188 |
+
if __name__ == "__main__":
|
| 1189 |
+
# Initialize template manager
|
| 1190 |
+
manager = TemplateManager()
|
| 1191 |
+
|
| 1192 |
+
# Search examples
|
| 1193 |
+
print("\nSearching for 'machine learning':")
|
| 1194 |
+
results = manager.search("machine learning")
|
| 1195 |
+
for result in results:
|
| 1196 |
+
print(f"{result['name']}: {result['score']:.2f}")
|
| 1197 |
+
|
| 1198 |
+
print("\nSearching for components ['Image', 'Slider']:")
|
| 1199 |
+
results = manager.search_by_components(['Image', 'Slider'])
|
| 1200 |
+
for result in results:
|
| 1201 |
+
print(f"{result['name']}: {result['score']:.2f}")
|
| 1202 |
+
|
| 1203 |
+
print("\nCategories available:")
|
| 1204 |
+
print(manager.get_categories())
|
| 1205 |
+
|
| 1206 |
+
print("\nComponents available:")
|
| 1207 |
+
print(manager.get_components())
|