acecalisto3 commited on
Commit
442c5e9
·
verified ·
1 Parent(s): c2ef245

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +988 -0
app.py CHANGED
@@ -1439,6 +1439,994 @@ if __name__ == "__main__":
1439
  metadata={"category": "development"}
1440
  ),
1441
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1442
  "database_query_tool": Template(
1443
  code="""
1444
  import gradio as gr
 
1439
  metadata={"category": "development"}
1440
  ),
1441
 
1442
+ "database_query_tool": Template(
1443
+ code="""
1444
+ import gradio as gr
1445
+ import sqlite3
1446
+
1447
+ def query_database(db_file, query):
1448
+ try:
1449
+ conn = sqlite3.connect(db_file.name)
1450
+ cursor = conn.cursor()
1451
+ cursor.execute(query)
1452
+ results = cursor.fetchall()
1453
+ conn.close()
1454
+ return results
1455
+ except Exception as e:
1456
+ return f"Error: {str(e)}"
1457
+
1458
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
1459
+ gr.Markdown("# Database Query Tool")
1460
+ with gr.Row():
1461
+ with gr.Column():
1462
+ db_input = gr.File(label="Upload SQLite DB File")
1463
+ query_input = gr.Textbox(label="SQL Query", placeholder="SELECT * FROM table_name;")
1464
+ query_btn = gr.Button("Run Query")
1465
+ with gr.Column():
1466
+ query_output = gr.JSON(label="Query Results")
1467
+
1468
+ query_btn.click(
1469
+ fn=query_database,
1470
+ inputs=[db_input, query_input],
1471
+ outputs=query_output
1472
+ )
1473
+
1474
+ if __name__ == "__main__":
1475
+ demo.launch()
1476
+ """,
1477
+ description="Run SQL queries on a SQLite database",
1478
+ components=["File", "Textbox", "Button", "JSON"],
1479
+ metadata={"category": "database"}
1480
+ )
1481
+
1482
+ "code_generator": Template(
1483
+ code="""
1484
+ import gradio as gr
1485
+ from transformers import pipeline
1486
+
1487
+ code_generator = pipeline("text-generation", model="Salesforce/codegen-2B-multi")
1488
+
1489
+ def generate_code(prompt):
1490
+ response = code_generator(prompt, max_length=150, num_return_sequences=1)
1491
+ return response[0]['generated_text']
1492
+
1493
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
1494
+ gr.Markdown("# Code Generator")
1495
+ with gr.Row():
1496
+ with gr.Column():
1497
+ prompt_input = gr.Textbox(label="Enter Code Prompt", placeholder="Write a Python function to reverse a string")
1498
+ generate_btn = gr.Button("Generate Code")
1499
+ with gr.Column():
1500
+ generated_code = gr.Textbox(label="Generated Code", lines=10)
1501
+
1502
+ generate_btn.click(
1503
+ fn=generate_code,
1504
+ inputs=prompt_input,
1505
+ outputs=generated_code
1506
+ )
1507
+
1508
+ if __name__ == "__main__":
1509
+ demo.launch()
1510
+ """,
1511
+ description="Generate code snippets based on natural language prompts",
1512
+ components=["Textbox", "Button"],
1513
+ metadata={"category": "development"}
1514
+ ),
1515
+
1516
+ "code_debugger": Template(
1517
+ code="""
1518
+ import gradio as gr
1519
+ import subprocess
1520
+
1521
+ def debug_code(code):
1522
+ try:
1523
+ with open("temp_code.py", "w") as f:
1524
+ f.write(code)
1525
+ result = subprocess.run(["python3", "temp_code.py"], capture_output=True, text=True)
1526
+ return {"stdout": result.stdout, "stderr": result.stderr}
1527
+ except Exception as e:
1528
+ return {"error": str(e)}
1529
+
1530
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
1531
+ gr.Markdown("# Code Debugger")
1532
+ with gr.Row():
1533
+ with gr.Column():
1534
+ code_input = gr.Textbox(label="Code to Debug", lines=10, placeholder="Paste your Python code here...")
1535
+ debug_btn = gr.Button("Run Debug")
1536
+ with gr.Column():
1537
+ debug_output = gr.JSON(label="Debug Output")
1538
+
1539
+ debug_btn.click(
1540
+ fn=debug_code,
1541
+ inputs=code_input,
1542
+ outputs=debug_output
1543
+ )
1544
+
1545
+ if __name__ == "__main__":
1546
+ demo.launch()
1547
+ """,
1548
+ description="Run and debug Python code by capturing stdout and stderr",
1549
+ components=["Textbox", "Button", "JSON"],
1550
+ metadata={"category": "development"}
1551
+ ),
1552
+
1553
+ "multi_agent_task_manager": Template(
1554
+ code="""
1555
+ import gradio as gr
1556
+ from concurrent.futures import ThreadPoolExecutor
1557
+ import time
1558
+
1559
+ agent_pool = ThreadPoolExecutor(max_workers=5)
1560
+ agent_status = {}
1561
+
1562
+ def agent_task(agent_name, task):
1563
+ agent_status[agent_name] = "Running"
1564
+ time.sleep(5) # Simulate task duration
1565
+ agent_status[agent_name] = "Completed"
1566
+ return f"Agent {agent_name} has completed the task: {task}"
1567
+
1568
+ def trigger_agents(agents, task):
1569
+ results = []
1570
+ for agent in agents:
1571
+ future = agent_pool.submit(agent_task, agent, task)
1572
+ results.append(f"Agent {agent} triggered")
1573
+ return results
1574
+
1575
+ def get_agent_status():
1576
+ return agent_status
1577
+
1578
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
1579
+ gr.Markdown("# Multi-Agent Task Manager")
1580
+ with gr.Row():
1581
+ with gr.Column():
1582
+ agents = gr.CheckboxGroup(choices=["Agent1", "Agent2", "Agent3", "Agent4", "Agent5"], label="Select Agents")
1583
+ task_input = gr.Textbox(label="Task to Perform", placeholder="Describe the task...")
1584
+ trigger_btn = gr.Button("Trigger Agents")
1585
+ with gr.Column():
1586
+ task_output = gr.JSON(label="Agent Responses")
1587
+
1588
+ with gr.Row():
1589
+ status_btn = gr.Button("Get Agent Status")
1590
+ status_output = gr.JSON(label="Current Agent Status")
1591
+
1592
+ trigger_btn.click(
1593
+ fn=trigger_agents,
1594
+ inputs=[agents, task_input],
1595
+ outputs=task_output
1596
+ )
1597
+
1598
+ status_btn.click(
1599
+ fn=get_agent_status,
1600
+ inputs=[],
1601
+ outputs=status_output
1602
+ )
1603
+
1604
+ if __name__ == "__main__":
1605
+ demo.launch()
1606
+ """,
1607
+ description="Manage and trigger tasks for multiple autonomous agents",
1608
+ components=["CheckboxGroup", "Textbox", "Button", "JSON"],
1609
+ metadata={"category": "task_automation"}
1610
+ ),
1611
+
1612
+ "auto_code_refactor": Template(
1613
+ code="""
1614
+ import gradio as gr
1615
+ from transformers import pipeline
1616
+
1617
+ code_refactor = pipeline("text2text-generation", model="facebook/bart-large-cnn")
1618
+
1619
+ def refactor_code(code):
1620
+ result = code_refactor(f"Refactor the following Python code: {code}", max_length=150)
1621
+ return result[0]['generated_text']
1622
+
1623
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
1624
+ gr.Markdown("# Auto Code Refactor")
1625
+ with gr.Row():
1626
+ with gr.Column():
1627
+ code_input = gr.Textbox(label="Code to Refactor", lines=10, placeholder="Paste your Python code here...")
1628
+ refactor_btn = gr.Button("Refactor Code")
1629
+ with gr.Column():
1630
+ refactored_code = gr.Textbox(label="Refactored Code", lines=10)
1631
+
1632
+ refactor_btn.click(
1633
+ fn=refactor_code,
1634
+ inputs=code_input,
1635
+ outputs=refactored_code
1636
+ )
1637
+
1638
+ if __name__ == "__main__":
1639
+ demo.launch()
1640
+ """,
1641
+ description="Automatically refactor Python code for better efficiency or readability",
1642
+ components=["Textbox", "Button"],
1643
+ metadata={"category": "development"}
1644
+ ),
1645
+
1646
+ "agent_cluster_deployer": Template(
1647
+ code="""
1648
+ import gradio as gr
1649
+ import random
1650
+
1651
+ cluster_status = {}
1652
+
1653
+ def deploy_agent_cluster(agent_count, task):
1654
+ cluster_id = random.randint(1000, 9999)
1655
+ cluster_status[cluster_id] = {
1656
+ "status": "Deploying",
1657
+ "agents": agent_count,
1658
+ "task": task
1659
+ }
1660
+ return f"Cluster {cluster_id} is deploying with {agent_count} agents for task: {task}"
1661
+
1662
+ def get_cluster_status():
1663
+ return cluster_status
1664
+
1665
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
1666
+ gr.Markdown("# Agent Cluster Deployer")
1667
+ with gr.Row():
1668
+ with gr.Column():
1669
+ agent_count = gr.Slider(label="Number of Agents", minimum=1, maximum=10, step=1, value=3)
1670
+ task_input = gr.Textbox(label="Cluster Task", placeholder="Describe the task for the cluster...")
1671
+ deploy_btn = gr.Button("Deploy Cluster")
1672
+ with gr.Column():
1673
+ deploy_output = gr.Textbox(label="Cluster Deployment Status")
1674
+
1675
+ with gr.Row():
1676
+ status_btn = gr.Button("Get Cluster Status")
1677
+ status_output = gr.JSON(label="Current Cluster Status")
1678
+
1679
+ deploy_btn.click(
1680
+ fn=deploy_agent_cluster,
1681
+ inputs=[agent_count, task_input],
1682
+ outputs=deploy_output
1683
+ )
1684
+
1685
+ status_btn.click(
1686
+ fn=get_cluster_status,
1687
+ inputs=[],
1688
+ outputs=status_output
1689
+ )
1690
+
1691
+ if __name__ == "__main__":
1692
+ demo.launch()
1693
+ """,
1694
+ description="Deploy an autonomous agent cluster for task execution",
1695
+ components=["Slider", "Textbox", "Button", "JSON"],
1696
+ metadata={"category": "task_automation"}
1697
+ )
1698
+ }
1699
+
1700
+ self.component_index = self._build_component_index()
1701
+ self.category_index = self._build_category_index()
1702
+
1703
+ def _build_component_index(self) -> Dict[str, List[str]]:
1704
+ """Build index of templates by component"""
1705
+ index = {}
1706
+ for name, template in self.templates.items():
1707
+ for component in template.components:
1708
+ if component not in index:
1709
+ index[component] = []
1710
+ index[component].append(name)
1711
+ return index
1712
+
1713
+ def _build_category_index(self) -> Dict[str, List[str]]:
1714
+ """Build index of templates by category"""
1715
+ index = {}
1716
+ for name, template in self.templates.items():
1717
+ category = template.metadata.get("category", "other")
1718
+ if category not in index:
1719
+ index[category] = []
1720
+ index[category].append(name)
1721
+ return index
1722
+
1723
+ def search(self, query: str, limit: int = 5) -> List[Dict]:
1724
+ """Search templates by description or metadata"""
1725
+ try:
1726
+ results = []
1727
+ for name, template in self.templates.items():
1728
+ desc_score = difflib.SequenceMatcher(
1729
+ None,
1730
+ query.lower(),
1731
+ template.description.lower()
1732
+ ).ratio()
1733
+
1734
+ category_score = difflib.SequenceMatcher(
1735
+ None,
1736
+ query.lower(),
1737
+ template.metadata.get("category", "").lower()
1738
+ ).ratio()
1739
+
1740
+ comp_score = sum(0.2 for component in template.components if component.lower() in query.lower())
1741
+
1742
+ final_score = max(desc_score, category_score) + comp_score
1743
+
1744
+ results.append({
1745
+ "name": name,
1746
+ "template": template,
1747
+ "score": final_score
1748
+ })
1749
+
1750
+ results.sort(key=lambda x: x["score"], reverse=True)
1751
+ return results[:limit]
1752
+
1753
+ except Exception as e:
1754
+ logger.error(f"Error searching templates: {str(e)}")
1755
+ return []
1756
+
1757
+ def search_by_components(self, components: List[str], limit: int = 5) -> List[Dict]:
1758
+ """Search templates by required components"""
1759
+ try:
1760
+ results = []
1761
+ for name, template in self.templates.items():
1762
+ matches = sum(1 for c in components if c in template.components)
1763
+ if matches > 0:
1764
+ score = matches / len(components)
1765
+ results.append({
1766
+ "name": name,
1767
+ "template": template,
1768
+ "score": score
1769
+ })
1770
+
1771
+ results.sort(key=lambda x: x["score"], reverse=True)
1772
+ return results[:limit]
1773
+
1774
+ except Exception as e:
1775
+ logger.error(f"Error searching by components: {str(e)}")
1776
+ return []
1777
+
1778
+ def search_by_category(self, category: str) -> List[Dict]:
1779
+ """Get all templates in a category"""
1780
+ try:
1781
+ return [
1782
+ {
1783
+ "name": name,
1784
+ "template": self.templates[name]
1785
+ }
1786
+ for name in self.category_index.get(category, [])
1787
+ ]
1788
+ except Exception as e:
1789
+ logger.error(f"Error searching by category: {str(e)}")
1790
+ return []
1791
+
1792
+ def get_template(self, name: str) -> Optional[Template]:
1793
+ """Get specific template by name"""
1794
+ return self.templates.get(name)
1795
+
1796
+ def get_categories(self) -> List[str]:
1797
+ """Get list of all categories"""
1798
+ return list(self.category_index.keys())
1799
+
1800
+ def get_components(self) -> List[str]:
1801
+ """Get list of all components"""
1802
+ return list(self.component_index.keys())
1803
+
1804
+ def export_templates(self, path: str):
1805
+ """Export templates to JSON file"""
1806
+ try:
1807
+ data = {
1808
+ name: {
1809
+ "description": template.description,
1810
+ "components": template.components,
1811
+ "metadata": template.metadata,
1812
+ "example": template.example
1813
+ }
1814
+ for name, template in self.templates.items()
1815
+ }
1816
+
1817
+ with open(path, 'w') as f:
1818
+ json.dump(data, f, indent=2)
1819
+
1820
+ logger.info(f"Templates exported to {path}")
1821
+
1822
+ except Exception as e:
1823
+ logger.error(f"Error exporting templates: {str(e)}")
1824
+ raise
1825
+
1826
+ def import_templates(self, path: str):
1827
+ """Import templates from JSON file"""
1828
+ try:
1829
+ with open(path, 'r') as f:
1830
+ data = json.load(f)
1831
+
1832
+ for name, template_data in data.items():
1833
+ self.templates[name] = Template(
1834
+ code="", # Code should be loaded separately
1835
+ description=template_data["description"],
1836
+ components=template_data["components"],
1837
+ metadata=template_data["metadata"],
1838
+ example=template_data.get("example")
1839
+ )
1840
+
1841
+ # Rebuild indexes
1842
+ self.component_index = self._build_component_index()
1843
+ self.category_index = self._build_category_index()
1844
+
1845
+ logger.info(f"Templates imported from {path}")
1846
+
1847
+ except Exception as e:
1848
+ logger.error(f"Error importing templates: {str(e)}")
1849
+ raise
1850
+
1851
+
1852
+ # Usage example:
1853
+ if __name__ == "__main__":
1854
+ # Initialize template manager
1855
+ manager = TemplateManager()
1856
+
1857
+ # Search examples
1858
+ print("\nSearching for 'machine learning':")
1859
+ results = manager.search("machine learning")
1860
+ for result in results:
1861
+ print(f"{result['name']}: {result['score']:.2f}")
1862
+
1863
+ print("\nSearching for components ['Image', 'Slider']:")
1864
+ results = manager.search_by_components(['Image', 'Slider'])
1865
+ for result in results:
1866
+ print(f"{result['name']}: {result['score']:.2f}")
1867
+
1868
+ print("\nCategories available:")
1869
+ print(manager.get_categories())
1870
+
1871
+ print("\nComponents available:")
1872
+ print(manager.get_components())
1873
+
1874
+ "text_summarizer": Template(
1875
+ code="""
1876
+ import gradio as gr
1877
+ from transformers import pipeline
1878
+
1879
+ summarizer = pipeline("summarization")
1880
+
1881
+ def summarize_text(text):
1882
+ summary = summarizer(text, max_length=150, min_length=40, do_sample=False)
1883
+ return summary[0]['summary_text']
1884
+
1885
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
1886
+ gr.Markdown("# Text Summarizer")
1887
+ with gr.Row():
1888
+ with gr.Column():
1889
+ input_text = gr.Textbox(label="Input Text", lines=10, placeholder="Enter text to summarize...")
1890
+ summarize_btn = gr.Button("Summarize")
1891
+ with gr.Column():
1892
+ summary_output = gr.Textbox(label="Summary", lines=5)
1893
+
1894
+ summarize_btn.click(
1895
+ fn=summarize_text,
1896
+ inputs=input_text,
1897
+ outputs=summary_output
1898
+ )
1899
+
1900
+ if __name__ == "__main__":
1901
+ demo.launch()
1902
+ """,
1903
+ description="Text summarization interface using a transformer model",
1904
+ components=["Textbox", "Button"],
1905
+ metadata={"category": "nlp"}
1906
+ ),
1907
+
1908
+ "image_captioner": Template(
1909
+ code="""
1910
+ import gradio as gr
1911
+ from transformers import BlipProcessor, BlipForConditionalGeneration
1912
+ from PIL import Image
1913
+
1914
+ processor = BlipProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
1915
+ model = BlipForConditionalGeneration.from_pretrained("Salesforce/blip-image-captioning-base")
1916
+
1917
+ def generate_caption(image):
1918
+ inputs = processor(image, return_tensors="pt")
1919
+ out = model.generate(**inputs)
1920
+ caption = processor.decode(out[0], skip_special_tokens=True)
1921
+ return caption
1922
+
1923
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
1924
+ gr.Markdown("# Image Caption Generator")
1925
+ with gr.Row():
1926
+ with gr.Column():
1927
+ input_image = gr.Image(type="pil", label="Upload Image")
1928
+ caption_btn = gr.Button("Generate Caption")
1929
+ with gr.Column():
1930
+ caption_output = gr.Textbox(label="Generated Caption")
1931
+
1932
+ caption_btn.click(
1933
+ fn=generate_caption,
1934
+ inputs=input_image,
1935
+ outputs=caption_output
1936
+ )
1937
+
1938
+ if __name__ == "__main__":
1939
+ demo.launch()
1940
+ """,
1941
+ description="Image captioning interface using a transformer model",
1942
+ components=["Image", "Button", "Textbox"],
1943
+ metadata={"category": "computer_vision"}
1944
+ ),
1945
+
1946
+ "style_transfer": Template(
1947
+ code="""
1948
+ import gradio as gr
1949
+ import tensorflow as tf
1950
+ import tensorflow_hub as hub
1951
+
1952
+ hub_model = hub.load('https://tfhub.dev/google/magenta/arbitrary-image-stylization-v1-256/2')
1953
+
1954
+ def apply_style(content_image, style_image):
1955
+ content_image = tf.image.convert_image_dtype(content_image, tf.float32)[tf.newaxis, ...]
1956
+ style_image = tf.image.convert_image_dtype(style_image, tf.float32)[tf.newaxis, ...]
1957
+ stylized_image = hub_model(content_image, style_image)[0]
1958
+ return tf.squeeze(stylized_image).numpy()
1959
+
1960
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
1961
+ gr.Markdown("# Neural Style Transfer")
1962
+ with gr.Row():
1963
+ with gr.Column():
1964
+ content_image = gr.Image(label="Content Image")
1965
+ style_image = gr.Image(label="Style Image")
1966
+ transfer_btn = gr.Button("Transfer Style")
1967
+ with gr.Column():
1968
+ output_image = gr.Image(label="Stylized Image")
1969
+
1970
+ transfer_btn.click(
1971
+ fn=apply_style,
1972
+ inputs=[content_image, style_image],
1973
+ outputs=output_image
1974
+ )
1975
+
1976
+ if __name__ == "__main__":
1977
+ demo.launch()
1978
+ """,
1979
+ description="Neural style transfer between two images",
1980
+ components=["Image", "Button"],
1981
+ metadata={"category": "computer_vision"}
1982
+ ),
1983
+
1984
+ "sentiment_analysis": Template(
1985
+ code="""
1986
+ import gradio as gr
1987
+ from transformers import pipeline
1988
+
1989
+ sentiment_pipeline = pipeline("sentiment-analysis")
1990
+
1991
+ def analyze_sentiment(text):
1992
+ result = sentiment_pipeline(text)[0]
1993
+ return f"{result['label']} ({result['score']:.2f})"
1994
+
1995
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
1996
+ gr.Markdown("# Sentiment Analysis")
1997
+ with gr.Row():
1998
+ with gr.Column():
1999
+ input_text = gr.Textbox(label="Input Text", lines=5, placeholder="Enter text to analyze sentiment...")
2000
+ analyze_btn = gr.Button("Analyze Sentiment")
2001
+ with gr.Column():
2002
+ sentiment_output = gr.Textbox(label="Sentiment Result")
2003
+
2004
+ analyze_btn.click(
2005
+ fn=analyze_sentiment,
2006
+ inputs=input_text,
2007
+ outputs=sentiment_output
2008
+ )
2009
+
2010
+ if __name__ == "__main__":
2011
+ demo.launch()
2012
+ """,
2013
+ description="Sentiment analysis using transformer model",
2014
+ components=["Textbox", "Button"],
2015
+ metadata={"category": "nlp"}
2016
+ ),
2017
+
2018
+ "pdf_to_text": Template(
2019
+ code="""
2020
+ import gradio as gr
2021
+ import PyPDF2
2022
+
2023
+ def extract_text_from_pdf(pdf):
2024
+ reader = PyPDF2.PdfFileReader(pdf)
2025
+ text = ''
2026
+ for page_num in range(reader.numPages):
2027
+ page = reader.getPage(page_num)
2028
+ text += page.extract_text()
2029
+ return text
2030
+
2031
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
2032
+ gr.Markdown("# PDF to Text Extractor")
2033
+ with gr.Row():
2034
+ with gr.Column():
2035
+ pdf_file = gr.File(label="Upload PDF")
2036
+ extract_btn = gr.Button("Extract Text")
2037
+ with gr.Column():
2038
+ output_text = gr.Textbox(label="Extracted Text", lines=10)
2039
+
2040
+ extract_btn.click(
2041
+ fn=extract_text_from_pdf,
2042
+ inputs=pdf_file,
2043
+ outputs=output_text
2044
+ )
2045
+
2046
+ if __name__ == "__main__":
2047
+ demo.launch()
2048
+ """,
2049
+ description="Extract text from PDF files",
2050
+ components=["File", "Button", "Textbox"],
2051
+ metadata={"category": "utility"}
2052
+ )
2053
+
2054
+ "website_monitor": Template(
2055
+ code="""
2056
+ import gradio as gr
2057
+ import requests
2058
+ from datetime import datetime
2059
+
2060
+ def monitor_website(url):
2061
+ try:
2062
+ response = requests.get(url)
2063
+ status_code = response.status_code
2064
+ status = "Up" if status_code == 200 else "Down"
2065
+ return {
2066
+ "url": url,
2067
+ "status": status,
2068
+ "response_time": response.elapsed.total_seconds(),
2069
+ "last_checked": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
2070
+ }
2071
+ except Exception as e:
2072
+ return {"error": str(e)}
2073
+
2074
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
2075
+ gr.Markdown("# Website Uptime Monitor")
2076
+ with gr.Row():
2077
+ with gr.Column():
2078
+ url_input = gr.Textbox(label="Website URL", placeholder="https://example.com")
2079
+ check_btn = gr.Button("Check Website")
2080
+ with gr.Column():
2081
+ result_output = gr.JSON(label="Monitoring Result")
2082
+
2083
+ check_btn.click(
2084
+ fn=monitor_website,
2085
+ inputs=url_input,
2086
+ outputs=result_output
2087
+ )
2088
+
2089
+ if __name__ == "__main__":
2090
+ demo.launch()
2091
+ """,
2092
+ description="Monitor the uptime and response time of a website",
2093
+ components=["Textbox", "Button", "JSON"],
2094
+ metadata={"category": "web_monitoring"}
2095
+ ),
2096
+
2097
+ "rss_feed_fetcher": Template(
2098
+ code="""
2099
+ import gradio as gr
2100
+ import feedparser
2101
+
2102
+ def fetch_rss_feed(url):
2103
+ feed = feedparser.parse(url)
2104
+ if feed.bozo:
2105
+ return {"error": "Invalid RSS feed URL"}
2106
+
2107
+ return [{"title": entry.title, "link": entry.link} for entry in feed.entries[:5]]
2108
+
2109
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
2110
+ gr.Markdown("# RSS Feed Fetcher")
2111
+ with gr.Row():
2112
+ with gr.Column():
2113
+ feed_url = gr.Textbox(label="RSS Feed URL", placeholder="https://example.com/feed")
2114
+ fetch_btn = gr.Button("Fetch Latest Posts")
2115
+ with gr.Column():
2116
+ feed_output = gr.JSON(label="Latest Feed Entries")
2117
+
2118
+ fetch_btn.click(
2119
+ fn=fetch_rss_feed,
2120
+ inputs=feed_url,
2121
+ outputs=feed_output
2122
+ )
2123
+
2124
+ if __name__ == "__main__":
2125
+ demo.launch()
2126
+ """,
2127
+ description="Fetch the latest entries from an RSS feed",
2128
+ components=["Textbox", "Button", "JSON"],
2129
+ metadata={"category": "web_scraping"}
2130
+ ),
2131
+
2132
+ "web_scraper": Template(
2133
+ code="""
2134
+ import gradio as gr
2135
+ from bs4 import BeautifulSoup
2136
+ import requests
2137
+
2138
+ def scrape_website(url, tag):
2139
+ try:
2140
+ response = requests.get(url)
2141
+ soup = BeautifulSoup(response.text, "html.parser")
2142
+ elements = soup.find_all(tag)
2143
+ return [element.get_text() for element in elements][:5] # Limit to 5 elements
2144
+ except Exception as e:
2145
+ return f"Error: {str(e)}"
2146
+
2147
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
2148
+ gr.Markdown("# Web Scraper")
2149
+ with gr.Row():
2150
+ with gr.Column():
2151
+ url_input = gr.Textbox(label="Website URL", placeholder="https://example.com")
2152
+ tag_input = gr.Textbox(label="HTML Tag to Scrape", placeholder="h1, p, div, etc.")
2153
+ scrape_btn = gr.Button("Scrape Website")
2154
+ with gr.Column():
2155
+ result_output = gr.JSON(label="Scraped Results")
2156
+
2157
+ scrape_btn.click(
2158
+ fn=scrape_website,
2159
+ inputs=[url_input, tag_input],
2160
+ outputs=result_output
2161
+ )
2162
+
2163
+ if __name__ == "__main__":
2164
+ demo.launch()
2165
+ """,
2166
+ description="Scrape text from a website based on the specified HTML tag",
2167
+ components=["Textbox", "Button", "JSON"],
2168
+ metadata={"category": "web_scraping"}
2169
+ ),
2170
+
2171
+ "api_tester": Template(
2172
+ code="""
2173
+ import gradio as gr
2174
+ import requests
2175
+
2176
+ def test_api(endpoint, method, payload):
2177
+ try:
2178
+ if method == "GET":
2179
+ response = requests.get(endpoint)
2180
+ elif method == "POST":
2181
+ response = requests.post(endpoint, json=payload)
2182
+ else:
2183
+ return "Unsupported method"
2184
+
2185
+ return {
2186
+ "status_code": response.status_code,
2187
+ "response_body": response.json() if response.headers.get("Content-Type") == "application/json" else response.text
2188
+ }
2189
+ except Exception as e:
2190
+ return {"error": str(e)}
2191
+
2192
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
2193
+ gr.Markdown("# API Tester")
2194
+ with gr.Row():
2195
+ with gr.Column():
2196
+ endpoint = gr.Textbox(label="API Endpoint", placeholder="https://api.example.com/endpoint")
2197
+ method = gr.Radio(choices=["GET", "POST"], label="HTTP Method", value="GET")
2198
+ payload = gr.JSON(label="Payload (for POST)", value={})
2199
+ test_btn = gr.Button("Test API")
2200
+ with gr.Column():
2201
+ result_output = gr.JSON(label="API Response")
2202
+
2203
+ test_btn.click(
2204
+ fn=test_api,
2205
+ inputs=[endpoint, method, payload],
2206
+ outputs=result_output
2207
+ )
2208
+
2209
+ if __name__ == "__main__":
2210
+ demo.launch()
2211
+ """,
2212
+ description="Test API endpoints with GET and POST requests",
2213
+ components=["Textbox", "Radio", "JSON", "Button"],
2214
+ metadata={"category": "api_testing"}
2215
+ ),
2216
+
2217
+ "email_scheduler": Template(
2218
+ code="""
2219
+ import gradio as gr
2220
+ import smtplib
2221
+ from email.mime.text import MIMEText
2222
+ from email.mime.multipart import MIMEMultipart
2223
+ from apscheduler.schedulers.background import BackgroundScheduler
2224
+
2225
+ scheduler = BackgroundScheduler()
2226
+ scheduler.start()
2227
+
2228
+ def send_email(to_email, subject, body):
2229
+ try:
2230
+ sender_email = "[email protected]"
2231
+ password = "your_password"
2232
+
2233
+ msg = MIMEMultipart()
2234
+ msg['From'] = sender_email
2235
+ msg['To'] = to_email
2236
+ msg['Subject'] = subject
2237
+
2238
+ msg.attach(MIMEText(body, 'plain'))
2239
+
2240
+ server = smtplib.SMTP('smtp.example.com', 587)
2241
+ server.starttls()
2242
+ server.login(sender_email, password)
2243
+ text = msg.as_string()
2244
+ server.sendmail(sender_email, to_email, text)
2245
+ server.quit()
2246
+
2247
+ return "Email sent successfully"
2248
+ except Exception as e:
2249
+ return f"Error: {str(e)}"
2250
+
2251
+ def schedule_email(to_email, subject, body, delay):
2252
+ scheduler.add_job(send_email, 'interval', seconds=delay, args=[to_email, subject, body])
2253
+ return f"Email scheduled to be sent in {delay} seconds"
2254
+
2255
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
2256
+ gr.Markdown("# Email Scheduler")
2257
+ with gr.Row():
2258
+ with gr.Column():
2259
+ to_email = gr.Textbox(label="Recipient Email")
2260
+ subject = gr.Textbox(label="Subject")
2261
+ body = gr.Textbox(label="Email Body", lines=5)
2262
+ delay = gr.Slider(label="Delay (seconds)", minimum=10, maximum=300, step=10, value=60)
2263
+ schedule_btn = gr.Button("Schedule Email")
2264
+ with gr.Column():
2265
+ result_output = gr.Textbox(label="Result")
2266
+
2267
+ schedule_btn.click(
2268
+ fn=schedule_email,
2269
+ inputs=[to_email, subject, body, delay],
2270
+ outputs=result_output
2271
+ )
2272
+
2273
+ if __name__ == "__main__":
2274
+ demo.launch()
2275
+ """,
2276
+ description="Schedule emails to be sent after a delay",
2277
+ components=["Textbox", "Slider", "Button"],
2278
+ metadata={"category": "task_automation"}
2279
+ )
2280
+
2281
+ "log_file_analyzer": Template(
2282
+ code="""
2283
+ import gradio as gr
2284
+ import re
2285
+
2286
+ def analyze_logs(log_file, filter_text):
2287
+ try:
2288
+ logs = log_file.read().decode("utf-8")
2289
+ if filter_text:
2290
+ filtered_logs = "\n".join([line for line in logs.splitlines() if re.search(filter_text, line)])
2291
+ else:
2292
+ filtered_logs = logs
2293
+ return filtered_logs
2294
+ except Exception as e:
2295
+ return f"Error: {str(e)}"
2296
+
2297
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
2298
+ gr.Markdown("# Log File Analyzer")
2299
+ with gr.Row():
2300
+ with gr.Column():
2301
+ log_input = gr.File(label="Upload Log File")
2302
+ filter_input = gr.Textbox(label="Filter (Regex)", placeholder="Error|Warning")
2303
+ analyze_btn = gr.Button("Analyze Logs")
2304
+ with gr.Column():
2305
+ output_logs = gr.Textbox(label="Filtered Logs", lines=20)
2306
+
2307
+ analyze_btn.click(
2308
+ fn=analyze_logs,
2309
+ inputs=[log_input, filter_input],
2310
+ outputs=output_logs
2311
+ )
2312
+
2313
+ if __name__ == "__main__":
2314
+ demo.launch()
2315
+ """,
2316
+ description="Analyze and filter log files using regex",
2317
+ components=["File", "Textbox", "Button"],
2318
+ metadata={"category": "log_analysis"}
2319
+ ),
2320
+
2321
+ "file_encryption_tool": Template(
2322
+ code="""
2323
+ import gradio as gr
2324
+ from cryptography.fernet import Fernet
2325
+
2326
+ def encrypt_file(file, password):
2327
+ try:
2328
+ key = password.ljust(32, '0').encode()[:32] # Basic password -> key mapping
2329
+ cipher = Fernet(Fernet.generate_key())
2330
+ file_data = file.read()
2331
+ encrypted_data = cipher.encrypt(file_data)
2332
+ return encrypted_data.decode("utf-8")
2333
+ except Exception as e:
2334
+ return f"Error: {str(e)}"
2335
+
2336
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
2337
+ gr.Markdown("# File Encryption Tool")
2338
+ with gr.Row():
2339
+ with gr.Column():
2340
+ file_input = gr.File(label="Upload File")
2341
+ password_input = gr.Textbox(label="Password", type="password")
2342
+ encrypt_btn = gr.Button("Encrypt File")
2343
+ with gr.Column():
2344
+ encrypted_output = gr.Textbox(label="Encrypted Data", lines=20)
2345
+
2346
+ encrypt_btn.click(
2347
+ fn=encrypt_file,
2348
+ inputs=[file_input, password_input],
2349
+ outputs=encrypted_output
2350
+ )
2351
+
2352
+ if __name__ == "__main__":
2353
+ demo.launch()
2354
+ """,
2355
+ description="Encrypt a file using a password-based key",
2356
+ components=["File", "Textbox", "Button"],
2357
+ metadata={"category": "security"}
2358
+ ),
2359
+
2360
+ "task_scheduler": Template(
2361
+ code="""
2362
+ import gradio as gr
2363
+ from apscheduler.schedulers.background import BackgroundScheduler
2364
+ from datetime import datetime
2365
+
2366
+ scheduler = BackgroundScheduler()
2367
+ scheduler.start()
2368
+
2369
+ def schedule_task(task_name, interval):
2370
+ scheduler.add_job(lambda: print(f"Running task: {task_name} at {datetime.now()}"), 'interval', seconds=interval)
2371
+ return f"Task '{task_name}' scheduled to run every {interval} seconds."
2372
+
2373
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
2374
+ gr.Markdown("# Task Scheduler")
2375
+ with gr.Row():
2376
+ with gr.Column():
2377
+ task_input = gr.Textbox(label="Task Name", placeholder="Example Task")
2378
+ interval_input = gr.Slider(minimum=1, maximum=60, label="Interval (Seconds)", value=10)
2379
+ schedule_btn = gr.Button("Schedule Task")
2380
+ with gr.Column():
2381
+ result_output = gr.Textbox(label="Result")
2382
+
2383
+ schedule_btn.click(
2384
+ fn=schedule_task,
2385
+ inputs=[task_input, interval_input],
2386
+ outputs=result_output
2387
+ )
2388
+
2389
+ if __name__ == "__main__":
2390
+ demo.launch()
2391
+ """,
2392
+ description="Schedule tasks to run at regular intervals",
2393
+ components=["Textbox", "Slider", "Button"],
2394
+ metadata={"category": "task_automation"}
2395
+ ),
2396
+
2397
+ "code_comparator": Template(
2398
+ code="""
2399
+ import gradio as gr
2400
+ import difflib
2401
+
2402
+ def compare_code(code1, code2):
2403
+ diff = difflib.unified_diff(code1.splitlines(), code2.splitlines(), lineterm='', fromfile='code1', tofile='code2')
2404
+ return '\n'.join(diff)
2405
+
2406
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
2407
+ gr.Markdown("# Code Comparator")
2408
+ with gr.Row():
2409
+ with gr.Column():
2410
+ code1_input = gr.Textbox(label="Code 1", lines=15, placeholder="Paste the first code snippet here...")
2411
+ code2_input = gr.Textbox(label="Code 2", lines=15, placeholder="Paste the second code snippet here...")
2412
+ compare_btn = gr.Button("Compare Codes")
2413
+ with gr.Column():
2414
+ diff_output = gr.Textbox(label="Difference", lines=20)
2415
+
2416
+ compare_btn.click(
2417
+ fn=compare_code,
2418
+ inputs=[code1_input, code2_input],
2419
+ outputs=diff_output
2420
+ )
2421
+
2422
+ if __name__ == "__main__":
2423
+ demo.launch()
2424
+ """,
2425
+ description="Compare two code snippets and show the differences",
2426
+ components=["Textbox", "Button"],
2427
+ metadata={"category": "development"}
2428
+ ),
2429
+
2430
  "database_query_tool": Template(
2431
  code="""
2432
  import gradio as gr