acecalisto3 commited on
Commit
a9df132
1 Parent(s): b76e9b0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +915 -38
app.py CHANGED
@@ -504,7 +504,6 @@ class TemplateManager:
504
  def classify_image(image):
505
  if image is None:
506
  return {"error": 1.0}
507
- # Add classification logic here
508
  return {"class1": 0.8, "class2": 0.2}
509
 
510
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
@@ -515,7 +514,7 @@ class TemplateManager:
515
  classify_btn = gr.Button("Classify")
516
  with gr.Column():
517
  output_labels = gr.Label()
518
-
519
  classify_btn.click(
520
  fn=classify_image,
521
  inputs=input_image,
@@ -529,61 +528,939 @@ class TemplateManager:
529
  components=["Image", "Button", "Label"],
530
  metadata={"category": "computer_vision"}
531
  ),
532
-
533
- "text_analyzer": Template(
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
534
  code="""
535
  import gradio as gr
536
  import numpy as np
537
 
538
- def analyze_text(text, options):
539
- if not text:
540
- return "Please enter some text"
541
-
542
- results = []
543
- if "word_count" in options:
544
- results.append(f"Word count: {len(text.split())}")
545
- if "char_count" in options:
546
- results.append(f"Character count: {len(text)}")
547
- if "sentiment" in options:
548
- # Add sentiment analysis logic here
549
- results.append("Sentiment: Neutral")
550
-
551
- return "\\n".join(results)
552
 
553
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
554
- gr.Markdown("# Text Analysis Tool")
555
  with gr.Row():
556
  with gr.Column():
557
- input_text = gr.Textbox(
558
- label="Input Text",
559
- placeholder="Enter text to analyze...",
560
- lines=5
561
- )
562
- options = gr.CheckboxGroup(
563
- choices=["word_count", "char_count", "sentiment"],
564
- label="Analysis Options",
565
- value=["word_count"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
566
  )
567
- analyze_btn = gr.Button("Analyze")
568
  with gr.Column():
569
- output_text = gr.Textbox(
570
- label="Analysis Results",
571
- lines=5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
572
  )
573
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
574
  analyze_btn.click(
575
- fn=analyze_text,
576
- inputs=[input_text, options],
577
- outputs=output_text
578
  )
579
 
580
  if __name__ == "__main__":
581
  demo.launch()
582
  """,
583
- description="Text analysis interface with multiple options",
584
- components=["Textbox", "CheckboxGroup", "Button"],
585
  metadata={"category": "nlp"}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
586
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
587
  }
588
 
589
  def save_template(self, name: str, template: Template) -> bool:
 
504
  def classify_image(image):
505
  if image is None:
506
  return {"error": 1.0}
 
507
  return {"class1": 0.8, "class2": 0.2}
508
 
509
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
 
514
  classify_btn = gr.Button("Classify")
515
  with gr.Column():
516
  output_labels = gr.Label()
517
+
518
  classify_btn.click(
519
  fn=classify_image,
520
  inputs=input_image,
 
528
  components=["Image", "Button", "Label"],
529
  metadata={"category": "computer_vision"}
530
  ),
531
+ "chatbot": Template(
532
+ code="""
533
+ import gradio as gr
534
+
535
+ def respond(message, history):
536
+ return f"You said: {message}"
537
+
538
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
539
+ gr.Markdown("# AI Chatbot")
540
+ chatbot = gr.Chatbot()
541
+ msg = gr.Textbox(label="Message")
542
+ clear = gr.Button("Clear")
543
+
544
+ msg.submit(respond, [msg, chatbot], [chatbot])
545
+ clear.click(lambda: None, None, chatbot, queue=False)
546
+
547
+ if __name__ == "__main__":
548
+ demo.launch()
549
+ """,
550
+ description="Interactive chatbot interface",
551
+ components=["Chatbot", "Textbox", "Button"],
552
+ metadata={"category": "nlp"}
553
+ ),
554
+ "audio_processor": Template(
555
  code="""
556
  import gradio as gr
557
  import numpy as np
558
 
559
+ def process_audio(audio, volume_factor=1.0):
560
+ if audio is None:
561
+ return None
562
+ sr, data = audio
563
+ return (sr, data * volume_factor)
 
 
 
 
 
 
 
 
 
564
 
565
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
566
+ gr.Markdown("# Audio Processor")
567
  with gr.Row():
568
  with gr.Column():
569
+ input_audio = gr.Audio(source="microphone", type="numpy")
570
+ volume = gr.Slider(minimum=0, maximum=2, value=1, label="Volume")
571
+ process_btn = gr.Button("Process")
572
+ with gr.Column():
573
+ output_audio = gr.Audio(type="numpy")
574
+
575
+ process_btn.click(
576
+ fn=process_audio,
577
+ inputs=[input_audio, volume],
578
+ outputs=output_audio
579
+ )
580
+
581
+ if __name__ == "__main__":
582
+ demo.launch()
583
+ """,
584
+ description="Audio processing interface",
585
+ components=["Audio", "Slider", "Button"],
586
+ metadata={"category": "audio"}
587
+ ),
588
+ "file_processor": Template(
589
+ code="""
590
+ import gradio as gr
591
+
592
+ def process_file(file):
593
+ if file is None:
594
+ return "No file uploaded"
595
+ return f"Processed file: {file.name}"
596
+
597
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
598
+ gr.Markdown("# File Processor")
599
+ with gr.Row():
600
+ with gr.Column():
601
+ file_input = gr.File(label="Upload File")
602
+ process_btn = gr.Button("Process")
603
+ with gr.Column():
604
+ output = gr.Textbox(label="Results")
605
+ json_output = gr.JSON(label="Detailed Results")
606
+
607
+ process_btn.click(
608
+ fn=process_file,
609
+ inputs=file_input,
610
+ outputs=[output, json_output]
611
+ )
612
+
613
+ if __name__ == "__main__":
614
+ demo.launch()
615
+ """,
616
+ description="File processing interface",
617
+ components=["File", "Button", "Textbox", "JSON"],
618
+ metadata={"category": "utility"}
619
+ ),
620
+ "data_visualization": Template(
621
+ code="""
622
+ import gradio as gr
623
+ import pandas as pd
624
+ import plotly.express as px
625
+
626
+ def visualize_data(data, plot_type):
627
+ if data is None:
628
+ return None
629
+
630
+ df = pd.read_csv(data.name)
631
+ if plot_type == "scatter":
632
+ fig = px.scatter(df, x=df.columns[0], y=df.columns[1])
633
+ elif plot_type == "line":
634
+ fig = px.line(df, x=df.columns[0], y=df.columns[1])
635
+ else:
636
+ fig = px.bar(df, x=df.columns[0], y=df.columns[1])
637
+
638
+ return fig
639
+
640
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
641
+ gr.Markdown("# Data Visualizer")
642
+ with gr.Row():
643
+ with gr.Column():
644
+ file_input = gr.File(label="Upload CSV")
645
+ plot_type = gr.Radio(
646
+ choices=["scatter", "line", "bar"],
647
+ label="Plot Type",
648
+ value="scatter"
649
  )
650
+ visualize_btn = gr.Button("Visualize")
651
  with gr.Column():
652
+ plot_output = gr.Plot(label="Visualization")
653
+
654
+ visualize_btn.click(
655
+ fn=visualize_data,
656
+ inputs=[file_input, plot_type],
657
+ outputs=plot_output
658
+ )
659
+
660
+ if __name__ == "__main__":
661
+ demo.launch()
662
+ """,
663
+ description="Data visualization interface",
664
+ components=["File", "Radio", "Button", "Plot"],
665
+ metadata={"category": "data_science"}
666
+ ),
667
+ "form_builder": Template(
668
+ code="""
669
+ import gradio as gr
670
+ import json
671
+
672
+ def submit_form(name, email, age, interests, subscribe):
673
+ return json.dumps({
674
+ "name": name,
675
+ "email": email,
676
+ "age": age,
677
+ "interests": interests,
678
+ "subscribe": subscribe
679
+ }, indent=2)
680
+
681
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
682
+ gr.Markdown("# Form Builder")
683
+ with gr.Row():
684
+ with gr.Column():
685
+ name = gr.Textbox(label="Name")
686
+ email = gr.Textbox(label="Email")
687
+ age = gr.Number(label="Age")
688
+ interests = gr.CheckboxGroup(
689
+ choices=["Sports", "Music", "Art", "Technology"],
690
+ label="Interests"
691
  )
692
+ subscribe = gr.Checkbox(label="Subscribe to newsletter")
693
+ submit_btn = gr.Button("Submit")
694
+ with gr.Column():
695
+ output = gr.JSON(label="Form Data")
696
+
697
+ submit_btn.click(
698
+ fn=submit_form,
699
+ inputs=[name, email, age, interests, subscribe],
700
+ outputs=output
701
+ )
702
+
703
+ if __name__ == "__main__":
704
+ demo.launch()
705
+ """,
706
+ description="Form builder interface",
707
+ components=["Textbox", "Number", "CheckboxGroup", "Checkbox", "Button", "JSON"],
708
+ metadata={"category": "utility"}
709
+ )
710
+ }
711
+
712
+ self.component_index = self._build_component_index()
713
+ self.category_index = self._build_category_index()
714
+
715
+ def _build_component_index(self) -> Dict[str, List[str]]:
716
+ """Build index of templates by component"""
717
+ index = {}
718
+ for name, template in self.templates.items():
719
+ for component in template.components:
720
+ if component not in index:
721
+ index[component] = []
722
+ index[component].append(name)
723
+ return index
724
+
725
+ def _build_category_index(self) -> Dict[str, List[str]]:
726
+ """Build index of templates by category"""
727
+ index = {}
728
+ for name, template in self.templates.items():
729
+ category = template.metadata.get("category", "other")
730
+ if category not in index:
731
+ index[category] = []
732
+ index[category].append(name)
733
+ return index
734
+
735
+ def search(self, query: str, limit: int = 5) -> List[Dict]:
736
+ """Search templates by description or metadata"""
737
+ try:
738
+ results = []
739
+ for name, template in self.templates.items():
740
+ desc_score = difflib.SequenceMatcher(
741
+ None,
742
+ query.lower(),
743
+ template.description.lower()
744
+ ).ratio()
745
+
746
+ category_score = difflib.SequenceMatcher(
747
+ None,
748
+ query.lower(),
749
+ template.metadata.get("category", "").lower()
750
+ ).ratio()
751
+
752
+ comp_score = sum(0.2 for component in template.components if component.lower() in query.lower())
753
+
754
+ final_score = max(desc_score, category_score) + comp_score
755
+
756
+ results.append({
757
+ "name": name,
758
+ "template": template,
759
+ "score": final_score
760
+ })
761
+
762
+ results.sort(key=lambda x: x["score"], reverse=True)
763
+ return results[:limit]
764
+
765
+ except Exception as e:
766
+ logger.error(f"Error searching templates: {str(e)}")
767
+ return []
768
+
769
+ def search_by_components(self, components: List[str], limit: int = 5) -> List[Dict]:
770
+ """Search templates by required components"""
771
+ try:
772
+ results = []
773
+ for name, template in self.templates.items():
774
+ matches = sum(1 for c in components if c in template.components)
775
+ if matches > 0:
776
+ score = matches / len(components)
777
+ results.append({
778
+ "name": name,
779
+ "template": template,
780
+ "score": score
781
+ })
782
+
783
+ results.sort(key=lambda x: x["score"], reverse=True)
784
+ return results[:limit]
785
+
786
+ except Exception as e:
787
+ logger.error(f"Error searching by components: {str(e)}")
788
+ return []
789
+
790
+ def search_by_category(self, category: str) -> List[Dict]:
791
+ """Get all templates in a category"""
792
+ try:
793
+ return [
794
+ {
795
+ "name": name,
796
+ "template": self.templates[name]
797
+ }
798
+ for name in self.category_index.get(category, [])
799
+ ]
800
+ except Exception as e:
801
+ logger.error(f"Error searching by category: {str(e)}")
802
+ return []
803
+
804
+ def get_template(self, name: str) -> Optional[Template]:
805
+ """Get specific template by name"""
806
+ return self.templates.get(name)
807
+
808
+ def get_categories(self) -> List[str]:
809
+ """Get list of all categories"""
810
+ return list(self.category_index.keys())
811
+
812
+ def get_components(self) -> List[str]:
813
+ """Get list of all components"""
814
+ return list(self.component_index.keys())
815
+
816
+ def export_templates(self, path: str):
817
+ """Export templates to JSON file"""
818
+ try:
819
+ data = {
820
+ name: {
821
+ "description": template.description,
822
+ "components": template.components,
823
+ "metadata": template.metadata,
824
+ "example": template.example
825
+ }
826
+ for name, template in self.templates.items()
827
+ }
828
+
829
+ with open(path, 'w') as f:
830
+ json.dump(data, f, indent=2)
831
+
832
+ logger.info(f"Templates exported to {path}")
833
+
834
+ except Exception as e:
835
+ logger.error(f"Error exporting templates: {str(e)}")
836
+ raise
837
+
838
+ def import_templates(self, path: str):
839
+ """Import templates from JSON file"""
840
+ try:
841
+ with open(path, 'r') as f:
842
+ data = json.load(f)
843
+
844
+ for name, template_data in data.items():
845
+ self.templates[name] = Template(
846
+ code="", # Code should be loaded separately
847
+ description=template_data["description"],
848
+ components=template_data["components"],
849
+ metadata=template_data["metadata"],
850
+ example=template_data.get("example")
851
+ )
852
+
853
+ # Rebuild indexes
854
+ self.component_index = self._build_component_index()
855
+ self.category_index = self._build_category_index()
856
+
857
+ logger.info(f"Templates imported from {path}")
858
+
859
+ except Exception as e:
860
+ logger.error(f"Error importing templates: {str(e)}")
861
+ raise
862
+
863
+
864
+ # Usage example:
865
+ if __name__ == "__main__":
866
+ # Initialize template manager
867
+ manager = TemplateManager()
868
+
869
+ # Search examples
870
+ print("\nSearching for 'machine learning':")
871
+ results = manager.search("machine learning")
872
+ for result in results:
873
+ print(f"{result['name']}: {result['score']:.2f}")
874
+
875
+ print("\nSearching for components ['Image', 'Slider']:")
876
+ results = manager.search_by_components(['Image', 'Slider'])
877
+ for result in results:
878
+ print(f"{result['name']}: {result['score']:.2f}")
879
+
880
+ print("\nCategories available:")
881
+ print(manager.get_categories())
882
+
883
+ print("\nComponents available:")
884
+ print(manager.get_components())
885
+
886
+ "text_summarizer": Template(
887
+ code="""
888
+ import gradio as gr
889
+ from transformers import pipeline
890
+
891
+ summarizer = pipeline("summarization")
892
+
893
+ def summarize_text(text):
894
+ summary = summarizer(text, max_length=150, min_length=40, do_sample=False)
895
+ return summary[0]['summary_text']
896
+
897
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
898
+ gr.Markdown("# Text Summarizer")
899
+ with gr.Row():
900
+ with gr.Column():
901
+ input_text = gr.Textbox(label="Input Text", lines=10, placeholder="Enter text to summarize...")
902
+ summarize_btn = gr.Button("Summarize")
903
+ with gr.Column():
904
+ summary_output = gr.Textbox(label="Summary", lines=5)
905
+
906
+ summarize_btn.click(
907
+ fn=summarize_text,
908
+ inputs=input_text,
909
+ outputs=summary_output
910
+ )
911
+
912
+ if __name__ == "__main__":
913
+ demo.launch()
914
+ """,
915
+ description="Text summarization interface using a transformer model",
916
+ components=["Textbox", "Button"],
917
+ metadata={"category": "nlp"}
918
+ ),
919
+
920
+ "image_captioner": Template(
921
+ code="""
922
+ import gradio as gr
923
+ from transformers import BlipProcessor, BlipForConditionalGeneration
924
+ from PIL import Image
925
+
926
+ processor = BlipProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
927
+ model = BlipForConditionalGeneration.from_pretrained("Salesforce/blip-image-captioning-base")
928
+
929
+ def generate_caption(image):
930
+ inputs = processor(image, return_tensors="pt")
931
+ out = model.generate(**inputs)
932
+ caption = processor.decode(out[0], skip_special_tokens=True)
933
+ return caption
934
+
935
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
936
+ gr.Markdown("# Image Caption Generator")
937
+ with gr.Row():
938
+ with gr.Column():
939
+ input_image = gr.Image(type="pil", label="Upload Image")
940
+ caption_btn = gr.Button("Generate Caption")
941
+ with gr.Column():
942
+ caption_output = gr.Textbox(label="Generated Caption")
943
+
944
+ caption_btn.click(
945
+ fn=generate_caption,
946
+ inputs=input_image,
947
+ outputs=caption_output
948
+ )
949
+
950
+ if __name__ == "__main__":
951
+ demo.launch()
952
+ """,
953
+ description="Image captioning interface using a transformer model",
954
+ components=["Image", "Button", "Textbox"],
955
+ metadata={"category": "computer_vision"}
956
+ ),
957
+
958
+ "style_transfer": Template(
959
+ code="""
960
+ import gradio as gr
961
+ import tensorflow as tf
962
+ import tensorflow_hub as hub
963
+
964
+ hub_model = hub.load('https://tfhub.dev/google/magenta/arbitrary-image-stylization-v1-256/2')
965
+
966
+ def apply_style(content_image, style_image):
967
+ content_image = tf.image.convert_image_dtype(content_image, tf.float32)[tf.newaxis, ...]
968
+ style_image = tf.image.convert_image_dtype(style_image, tf.float32)[tf.newaxis, ...]
969
+ stylized_image = hub_model(content_image, style_image)[0]
970
+ return tf.squeeze(stylized_image).numpy()
971
+
972
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
973
+ gr.Markdown("# Neural Style Transfer")
974
+ with gr.Row():
975
+ with gr.Column():
976
+ content_image = gr.Image(label="Content Image")
977
+ style_image = gr.Image(label="Style Image")
978
+ transfer_btn = gr.Button("Transfer Style")
979
+ with gr.Column():
980
+ output_image = gr.Image(label="Stylized Image")
981
+
982
+ transfer_btn.click(
983
+ fn=apply_style,
984
+ inputs=[content_image, style_image],
985
+ outputs=output_image
986
+ )
987
+
988
+ if __name__ == "__main__":
989
+ demo.launch()
990
+ """,
991
+ description="Neural style transfer between two images",
992
+ components=["Image", "Button"],
993
+ metadata={"category": "computer_vision"}
994
+ ),
995
+
996
+ "sentiment_analysis": Template(
997
+ code="""
998
+ import gradio as gr
999
+ from transformers import pipeline
1000
+
1001
+ sentiment_pipeline = pipeline("sentiment-analysis")
1002
+
1003
+ def analyze_sentiment(text):
1004
+ result = sentiment_pipeline(text)[0]
1005
+ return f"{result['label']} ({result['score']:.2f})"
1006
+
1007
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
1008
+ gr.Markdown("# Sentiment Analysis")
1009
+ with gr.Row():
1010
+ with gr.Column():
1011
+ input_text = gr.Textbox(label="Input Text", lines=5, placeholder="Enter text to analyze sentiment...")
1012
+ analyze_btn = gr.Button("Analyze Sentiment")
1013
+ with gr.Column():
1014
+ sentiment_output = gr.Textbox(label="Sentiment Result")
1015
+
1016
  analyze_btn.click(
1017
+ fn=analyze_sentiment,
1018
+ inputs=input_text,
1019
+ outputs=sentiment_output
1020
  )
1021
 
1022
  if __name__ == "__main__":
1023
  demo.launch()
1024
  """,
1025
+ description="Sentiment analysis using transformer model",
1026
+ components=["Textbox", "Button"],
1027
  metadata={"category": "nlp"}
1028
+ ),
1029
+
1030
+ "pdf_to_text": Template(
1031
+ code="""
1032
+ import gradio as gr
1033
+ import PyPDF2
1034
+
1035
+ def extract_text_from_pdf(pdf):
1036
+ reader = PyPDF2.PdfFileReader(pdf)
1037
+ text = ''
1038
+ for page_num in range(reader.numPages):
1039
+ page = reader.getPage(page_num)
1040
+ text += page.extract_text()
1041
+ return text
1042
+
1043
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
1044
+ gr.Markdown("# PDF to Text Extractor")
1045
+ with gr.Row():
1046
+ with gr.Column():
1047
+ pdf_file = gr.File(label="Upload PDF")
1048
+ extract_btn = gr.Button("Extract Text")
1049
+ with gr.Column():
1050
+ output_text = gr.Textbox(label="Extracted Text", lines=10)
1051
+
1052
+ extract_btn.click(
1053
+ fn=extract_text_from_pdf,
1054
+ inputs=pdf_file,
1055
+ outputs=output_text
1056
+ )
1057
+
1058
+ if __name__ == "__main__":
1059
+ demo.launch()
1060
+ """,
1061
+ description="Extract text from PDF files",
1062
+ components=["File", "Button", "Textbox"],
1063
+ metadata={"category": "utility"}
1064
+ )
1065
+
1066
+ "website_monitor": Template(
1067
+ code="""
1068
+ import gradio as gr
1069
+ import requests
1070
+ from datetime import datetime
1071
+
1072
+ def monitor_website(url):
1073
+ try:
1074
+ response = requests.get(url)
1075
+ status_code = response.status_code
1076
+ status = "Up" if status_code == 200 else "Down"
1077
+ return {
1078
+ "url": url,
1079
+ "status": status,
1080
+ "response_time": response.elapsed.total_seconds(),
1081
+ "last_checked": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
1082
+ }
1083
+ except Exception as e:
1084
+ return {"error": str(e)}
1085
+
1086
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
1087
+ gr.Markdown("# Website Uptime Monitor")
1088
+ with gr.Row():
1089
+ with gr.Column():
1090
+ url_input = gr.Textbox(label="Website URL", placeholder="https://example.com")
1091
+ check_btn = gr.Button("Check Website")
1092
+ with gr.Column():
1093
+ result_output = gr.JSON(label="Monitoring Result")
1094
+
1095
+ check_btn.click(
1096
+ fn=monitor_website,
1097
+ inputs=url_input,
1098
+ outputs=result_output
1099
+ )
1100
+
1101
+ if __name__ == "__main__":
1102
+ demo.launch()
1103
+ """,
1104
+ description="Monitor the uptime and response time of a website",
1105
+ components=["Textbox", "Button", "JSON"],
1106
+ metadata={"category": "web_monitoring"}
1107
+ ),
1108
+
1109
+ "rss_feed_fetcher": Template(
1110
+ code="""
1111
+ import gradio as gr
1112
+ import feedparser
1113
+
1114
+ def fetch_rss_feed(url):
1115
+ feed = feedparser.parse(url)
1116
+ if feed.bozo:
1117
+ return {"error": "Invalid RSS feed URL"}
1118
+
1119
+ return [{"title": entry.title, "link": entry.link} for entry in feed.entries[:5]]
1120
+
1121
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
1122
+ gr.Markdown("# RSS Feed Fetcher")
1123
+ with gr.Row():
1124
+ with gr.Column():
1125
+ feed_url = gr.Textbox(label="RSS Feed URL", placeholder="https://example.com/feed")
1126
+ fetch_btn = gr.Button("Fetch Latest Posts")
1127
+ with gr.Column():
1128
+ feed_output = gr.JSON(label="Latest Feed Entries")
1129
+
1130
+ fetch_btn.click(
1131
+ fn=fetch_rss_feed,
1132
+ inputs=feed_url,
1133
+ outputs=feed_output
1134
+ )
1135
+
1136
+ if __name__ == "__main__":
1137
+ demo.launch()
1138
+ """,
1139
+ description="Fetch the latest entries from an RSS feed",
1140
+ components=["Textbox", "Button", "JSON"],
1141
+ metadata={"category": "web_scraping"}
1142
+ ),
1143
+
1144
+ "web_scraper": Template(
1145
+ code="""
1146
+ import gradio as gr
1147
+ from bs4 import BeautifulSoup
1148
+ import requests
1149
+
1150
+ def scrape_website(url, tag):
1151
+ try:
1152
+ response = requests.get(url)
1153
+ soup = BeautifulSoup(response.text, "html.parser")
1154
+ elements = soup.find_all(tag)
1155
+ return [element.get_text() for element in elements][:5] # Limit to 5 elements
1156
+ except Exception as e:
1157
+ return f"Error: {str(e)}"
1158
+
1159
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
1160
+ gr.Markdown("# Web Scraper")
1161
+ with gr.Row():
1162
+ with gr.Column():
1163
+ url_input = gr.Textbox(label="Website URL", placeholder="https://example.com")
1164
+ tag_input = gr.Textbox(label="HTML Tag to Scrape", placeholder="h1, p, div, etc.")
1165
+ scrape_btn = gr.Button("Scrape Website")
1166
+ with gr.Column():
1167
+ result_output = gr.JSON(label="Scraped Results")
1168
+
1169
+ scrape_btn.click(
1170
+ fn=scrape_website,
1171
+ inputs=[url_input, tag_input],
1172
+ outputs=result_output
1173
+ )
1174
+
1175
+ if __name__ == "__main__":
1176
+ demo.launch()
1177
+ """,
1178
+ description="Scrape text from a website based on the specified HTML tag",
1179
+ components=["Textbox", "Button", "JSON"],
1180
+ metadata={"category": "web_scraping"}
1181
+ ),
1182
+
1183
+ "api_tester": Template(
1184
+ code="""
1185
+ import gradio as gr
1186
+ import requests
1187
+
1188
+ def test_api(endpoint, method, payload):
1189
+ try:
1190
+ if method == "GET":
1191
+ response = requests.get(endpoint)
1192
+ elif method == "POST":
1193
+ response = requests.post(endpoint, json=payload)
1194
+ else:
1195
+ return "Unsupported method"
1196
+
1197
+ return {
1198
+ "status_code": response.status_code,
1199
+ "response_body": response.json() if response.headers.get("Content-Type") == "application/json" else response.text
1200
+ }
1201
+ except Exception as e:
1202
+ return {"error": str(e)}
1203
+
1204
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
1205
+ gr.Markdown("# API Tester")
1206
+ with gr.Row():
1207
+ with gr.Column():
1208
+ endpoint = gr.Textbox(label="API Endpoint", placeholder="https://api.example.com/endpoint")
1209
+ method = gr.Radio(choices=["GET", "POST"], label="HTTP Method", value="GET")
1210
+ payload = gr.JSON(label="Payload (for POST)", value={})
1211
+ test_btn = gr.Button("Test API")
1212
+ with gr.Column():
1213
+ result_output = gr.JSON(label="API Response")
1214
+
1215
+ test_btn.click(
1216
+ fn=test_api,
1217
+ inputs=[endpoint, method, payload],
1218
+ outputs=result_output
1219
+ )
1220
+
1221
+ if __name__ == "__main__":
1222
+ demo.launch()
1223
+ """,
1224
+ description="Test API endpoints with GET and POST requests",
1225
+ components=["Textbox", "Radio", "JSON", "Button"],
1226
+ metadata={"category": "api_testing"}
1227
+ ),
1228
+
1229
+ "email_scheduler": Template(
1230
+ code="""
1231
+ import gradio as gr
1232
+ import smtplib
1233
+ from email.mime.text import MIMEText
1234
+ from email.mime.multipart import MIMEMultipart
1235
+ from apscheduler.schedulers.background import BackgroundScheduler
1236
+
1237
+ scheduler = BackgroundScheduler()
1238
+ scheduler.start()
1239
+
1240
+ def send_email(to_email, subject, body):
1241
+ try:
1242
+ sender_email = "your_email@example.com"
1243
+ password = "your_password"
1244
+
1245
+ msg = MIMEMultipart()
1246
+ msg['From'] = sender_email
1247
+ msg['To'] = to_email
1248
+ msg['Subject'] = subject
1249
+
1250
+ msg.attach(MIMEText(body, 'plain'))
1251
+
1252
+ server = smtplib.SMTP('smtp.example.com', 587)
1253
+ server.starttls()
1254
+ server.login(sender_email, password)
1255
+ text = msg.as_string()
1256
+ server.sendmail(sender_email, to_email, text)
1257
+ server.quit()
1258
+
1259
+ return "Email sent successfully"
1260
+ except Exception as e:
1261
+ return f"Error: {str(e)}"
1262
+
1263
+ def schedule_email(to_email, subject, body, delay):
1264
+ scheduler.add_job(send_email, 'interval', seconds=delay, args=[to_email, subject, body])
1265
+ return f"Email scheduled to be sent in {delay} seconds"
1266
+
1267
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
1268
+ gr.Markdown("# Email Scheduler")
1269
+ with gr.Row():
1270
+ with gr.Column():
1271
+ to_email = gr.Textbox(label="Recipient Email")
1272
+ subject = gr.Textbox(label="Subject")
1273
+ body = gr.Textbox(label="Email Body", lines=5)
1274
+ delay = gr.Slider(label="Delay (seconds)", minimum=10, maximum=300, step=10, value=60)
1275
+ schedule_btn = gr.Button("Schedule Email")
1276
+ with gr.Column():
1277
+ result_output = gr.Textbox(label="Result")
1278
+
1279
+ schedule_btn.click(
1280
+ fn=schedule_email,
1281
+ inputs=[to_email, subject, body, delay],
1282
+ outputs=result_output
1283
+ )
1284
+
1285
+ if __name__ == "__main__":
1286
+ demo.launch()
1287
+ """,
1288
+ description="Schedule emails to be sent after a delay",
1289
+ components=["Textbox", "Slider", "Button"],
1290
+ metadata={"category": "task_automation"}
1291
  )
1292
+
1293
+ "log_file_analyzer": Template(
1294
+ code="""
1295
+ import gradio as gr
1296
+ import re
1297
+
1298
+ def analyze_logs(log_file, filter_text):
1299
+ try:
1300
+ logs = log_file.read().decode("utf-8")
1301
+ if filter_text:
1302
+ filtered_logs = "\n".join([line for line in logs.splitlines() if re.search(filter_text, line)])
1303
+ else:
1304
+ filtered_logs = logs
1305
+ return filtered_logs
1306
+ except Exception as e:
1307
+ return f"Error: {str(e)}"
1308
+
1309
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
1310
+ gr.Markdown("# Log File Analyzer")
1311
+ with gr.Row():
1312
+ with gr.Column():
1313
+ log_input = gr.File(label="Upload Log File")
1314
+ filter_input = gr.Textbox(label="Filter (Regex)", placeholder="Error|Warning")
1315
+ analyze_btn = gr.Button("Analyze Logs")
1316
+ with gr.Column():
1317
+ output_logs = gr.Textbox(label="Filtered Logs", lines=20)
1318
+
1319
+ analyze_btn.click(
1320
+ fn=analyze_logs,
1321
+ inputs=[log_input, filter_input],
1322
+ outputs=output_logs
1323
+ )
1324
+
1325
+ if __name__ == "__main__":
1326
+ demo.launch()
1327
+ """,
1328
+ description="Analyze and filter log files using regex",
1329
+ components=["File", "Textbox", "Button"],
1330
+ metadata={"category": "log_analysis"}
1331
+ ),
1332
+
1333
+ "file_encryption_tool": Template(
1334
+ code="""
1335
+ import gradio as gr
1336
+ from cryptography.fernet import Fernet
1337
+
1338
+ def encrypt_file(file, password):
1339
+ try:
1340
+ key = password.ljust(32, '0').encode()[:32] # Basic password -> key mapping
1341
+ cipher = Fernet(Fernet.generate_key())
1342
+ file_data = file.read()
1343
+ encrypted_data = cipher.encrypt(file_data)
1344
+ return encrypted_data.decode("utf-8")
1345
+ except Exception as e:
1346
+ return f"Error: {str(e)}"
1347
+
1348
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
1349
+ gr.Markdown("# File Encryption Tool")
1350
+ with gr.Row():
1351
+ with gr.Column():
1352
+ file_input = gr.File(label="Upload File")
1353
+ password_input = gr.Textbox(label="Password", type="password")
1354
+ encrypt_btn = gr.Button("Encrypt File")
1355
+ with gr.Column():
1356
+ encrypted_output = gr.Textbox(label="Encrypted Data", lines=20)
1357
+
1358
+ encrypt_btn.click(
1359
+ fn=encrypt_file,
1360
+ inputs=[file_input, password_input],
1361
+ outputs=encrypted_output
1362
+ )
1363
+
1364
+ if __name__ == "__main__":
1365
+ demo.launch()
1366
+ """,
1367
+ description="Encrypt a file using a password-based key",
1368
+ components=["File", "Textbox", "Button"],
1369
+ metadata={"category": "security"}
1370
+ ),
1371
+
1372
+ "task_scheduler": Template(
1373
+ code="""
1374
+ import gradio as gr
1375
+ from apscheduler.schedulers.background import BackgroundScheduler
1376
+ from datetime import datetime
1377
+
1378
+ scheduler = BackgroundScheduler()
1379
+ scheduler.start()
1380
+
1381
+ def schedule_task(task_name, interval):
1382
+ scheduler.add_job(lambda: print(f"Running task: {task_name} at {datetime.now()}"), 'interval', seconds=interval)
1383
+ return f"Task '{task_name}' scheduled to run every {interval} seconds."
1384
+
1385
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
1386
+ gr.Markdown("# Task Scheduler")
1387
+ with gr.Row():
1388
+ with gr.Column():
1389
+ task_input = gr.Textbox(label="Task Name", placeholder="Example Task")
1390
+ interval_input = gr.Slider(minimum=1, maximum=60, label="Interval (Seconds)", value=10)
1391
+ schedule_btn = gr.Button("Schedule Task")
1392
+ with gr.Column():
1393
+ result_output = gr.Textbox(label="Result")
1394
+
1395
+ schedule_btn.click(
1396
+ fn=schedule_task,
1397
+ inputs=[task_input, interval_input],
1398
+ outputs=result_output
1399
+ )
1400
+
1401
+ if __name__ == "__main__":
1402
+ demo.launch()
1403
+ """,
1404
+ description="Schedule tasks to run at regular intervals",
1405
+ components=["Textbox", "Slider", "Button"],
1406
+ metadata={"category": "task_automation"}
1407
+ ),
1408
+
1409
+ "code_comparator": Template(
1410
+ code="""
1411
+ import gradio as gr
1412
+ import difflib
1413
+
1414
+ def compare_code(code1, code2):
1415
+ diff = difflib.unified_diff(code1.splitlines(), code2.splitlines(), lineterm='', fromfile='code1', tofile='code2')
1416
+ return '\n'.join(diff)
1417
+
1418
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
1419
+ gr.Markdown("# Code Comparator")
1420
+ with gr.Row():
1421
+ with gr.Column():
1422
+ code1_input = gr.Textbox(label="Code 1", lines=15, placeholder="Paste the first code snippet here...")
1423
+ code2_input = gr.Textbox(label="Code 2", lines=15, placeholder="Paste the second code snippet here...")
1424
+ compare_btn = gr.Button("Compare Codes")
1425
+ with gr.Column():
1426
+ diff_output = gr.Textbox(label="Difference", lines=20)
1427
+
1428
+ compare_btn.click(
1429
+ fn=compare_code,
1430
+ inputs=[code1_input, code2_input],
1431
+ outputs=diff_output
1432
+ )
1433
+
1434
+ if __name__ == "__main__":
1435
+ demo.launch()
1436
+ """,
1437
+ description="Compare two code snippets and show the differences",
1438
+ components=["Textbox", "Button"],
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
  }
1465
 
1466
  def save_template(self, name: str, template: Template) -> bool: