rahul7star commited on
Commit
a9194fa
·
verified ·
1 Parent(s): 8087fe3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +19 -56
app.py CHANGED
@@ -1,9 +1,6 @@
1
  import gradio as gr
2
  from google import genai
3
  import os
4
- import sys
5
- import io
6
- import pandas as pd # We will use Pandas to create a DataFrame
7
 
8
  # Load API key from environment variable
9
  GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")
@@ -11,7 +8,7 @@ GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")
11
  # Initialize the Google GenAI client
12
  client = genai.Client(api_key=GEMINI_API_KEY)
13
 
14
- # Function to interact with the Gemini API and generate content or code
15
  def generate_content(prompt):
16
  # Generate content using the Gemini API
17
  response = client.models.generate_content(
@@ -19,71 +16,37 @@ def generate_content(prompt):
19
  contents=[prompt]
20
  )
21
 
22
- result_text = response.text.strip() # Clean response text
23
- return result_text
24
-
25
- # Function to execute the code generated by Gemini
26
- def execute_code(code):
27
- try:
28
- # Redirect stdout to capture print statements from the code
29
- output = io.StringIO()
30
- sys.stdout = output
31
- exec(code) # Execute the Python code
32
- sys.stdout = sys.__stdout__ # Reset stdout
33
- return output.getvalue() # Return captured output
34
- except Exception as e:
35
- return f"Error: {str(e)}" # Return error message if execution fails
36
-
37
- # Function to format result as a table
38
- def format_result_as_table(result):
39
- try:
40
- # Split result into key-value pairs (assuming each line is a pair)
41
- rows = [line.split(':') for line in result.split('\n') if ':' in line]
42
- # Create DataFrame
43
- df = pd.DataFrame(rows, columns=["Key", "Value"])
44
- return df
45
- except Exception as e:
46
- return pd.DataFrame([["Error", str(e)]], columns=["Key", "Value"])
47
 
48
  # Create Gradio interface using Blocks for better control
49
  with gr.Blocks() as interface:
50
  # Title and Description
51
- gr.Markdown("# Gemini AI Content Generator & Code Executor")
52
- gr.Markdown("Provide a prompt to generate content or code. The code will be executed if it's valid Python.")
53
 
54
- # Text input field for prompt and submit button
55
- prompt_input = gr.Textbox(label="Enter your prompt (e.g., Python code):", placeholder="print('Hello, World!')", lines=3)
56
- submit_button = gr.Button("Generate and Execute Code")
57
 
58
- # Output areas for the results
59
- code_section = gr.Markdown(label="Generated Code or Content")
60
- execution_section = gr.DataFrame(headers=["Key", "Value"], datatype=["str", "str"], interactive=False)
61
 
62
- # Loading spinner
63
  loading_spinner = gr.HTML("<p style='color: #4CAF50;'>Loading... Please wait...</p>")
64
  loading_spinner.visible = False # Initially hidden
65
 
66
  # Define button click interaction
67
  def on_submit(prompt):
68
- loading_spinner.visible = True # Show loading message
69
- result = generate_content(prompt) # Get content or code from Gemini
70
-
71
- code_section.value = f"### Generated Code/Content:\n\n{result}" # Display the code/content
72
-
73
- if "```python" in result: # If code is returned, extract Python code and execute it
74
- code = result.split("```python")[1].split("```")[0].strip()
75
- execution_result = execute_code(code)
76
- result = f"**Code Executed Result:**\n\n{execution_result}"
77
- else:
78
- result = f"**Generated Content:**\n\n{result}"
79
-
80
- # Convert the result into a table
81
- table_data = format_result_as_table(result)
82
- loading_spinner.visible = False # Hide loading message
83
- return code_section, table_data, loading_spinner # Return the sections with content and execution result
84
 
85
  # Link the button with the function
86
- submit_button.click(on_submit, inputs=prompt_input, outputs=[code_section, execution_section, loading_spinner])
87
 
88
  # Launch Gradio interface
89
- interface.launch()
 
1
  import gradio as gr
2
  from google import genai
3
  import os
 
 
 
4
 
5
  # Load API key from environment variable
6
  GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")
 
8
  # Initialize the Google GenAI client
9
  client = genai.Client(api_key=GEMINI_API_KEY)
10
 
11
+ # Function to interact with the Gemini API
12
  def generate_content(prompt):
13
  # Generate content using the Gemini API
14
  response = client.models.generate_content(
 
16
  contents=[prompt]
17
  )
18
 
19
+ # Format the result for better readability
20
+ result_text = response.text.strip() # Remove extra spaces and line breaks
21
+ formatted_response = f"**AI Generated Content:**\n\n{result_text}"
22
+ return formatted_response
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
 
24
  # Create Gradio interface using Blocks for better control
25
  with gr.Blocks() as interface:
26
  # Title and Description
27
+ gr.Markdown("# Gemini AI Content Generator")
28
+ gr.Markdown("Provide a prompt and get an explanation from Gemini AI.\n\nThe AI will return a well-formatted response.")
29
 
30
+ # Text input field and submit button
31
+ prompt_input = gr.Textbox(label="Enter your prompt:", placeholder="How does AI work?", lines=2)
32
+ submit_button = gr.Button("Generate Content")
33
 
34
+ # Output area for the result
35
+ output_area = gr.Markdown()
 
36
 
37
+ # Loading spinner (show loading during API call)
38
  loading_spinner = gr.HTML("<p style='color: #4CAF50;'>Loading... Please wait...</p>")
39
  loading_spinner.visible = False # Initially hidden
40
 
41
  # Define button click interaction
42
  def on_submit(prompt):
43
+ loading_spinner.visible = True
44
+ result = generate_content(prompt)
45
+ loading_spinner.visible = False
46
+ return result, loading_spinner
 
 
 
 
 
 
 
 
 
 
 
 
47
 
48
  # Link the button with the function
49
+ submit_button.click(on_submit, inputs=prompt_input, outputs=[output_area, loading_spinner])
50
 
51
  # Launch Gradio interface
52
+ interface.launch()