Update app.py
Browse files
app.py
CHANGED
@@ -2,6 +2,63 @@ import tensorflow
|
|
2 |
import torch
|
3 |
import gradio as gr
|
4 |
from transformers import pipeline, AutoModelForCausalLM, AutoTokenizer
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
5 |
|
6 |
# --- Load the NLP pipeline for text classification ---
|
7 |
classifier = pipeline("text-classification")
|
@@ -62,6 +119,71 @@ with gr.Blocks() as demo_text:
|
|
62 |
output_text = gr.Textbox(label="Generated Text")
|
63 |
input_text.submit(generate_text, inputs=input_text, outputs=output_text)
|
64 |
|
65 |
-
|
66 |
-
|
67 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
2 |
import torch
|
3 |
import gradio as gr
|
4 |
from transformers import pipeline, AutoModelForCausalLM, AutoTokenizer
|
5 |
+
import gradio as gr
|
6 |
+
import importlib
|
7 |
+
import subprocess
|
8 |
+
import sys
|
9 |
+
import io
|
10 |
+
import threading
|
11 |
+
import time
|
12 |
+
from flask import Flask
|
13 |
+
|
14 |
+
def install_and_import(package_name):
|
15 |
+
"""Installs a package using pip and imports it."""
|
16 |
+
subprocess.check_call(["pip", "install", package_name])
|
17 |
+
return importlib.import_module(package_name)
|
18 |
+
|
19 |
+
def extract_package_name(input_str):
|
20 |
+
"""Extracts the package name from a PyPI URL or pip command."""
|
21 |
+
if input_str.startswith("https://pypi.org/project/"):
|
22 |
+
return input_str.split("/")[-2]
|
23 |
+
elif input_str.startswith("pip install "):
|
24 |
+
return input_str.split(" ")[2]
|
25 |
+
else:
|
26 |
+
return input_str
|
27 |
+
|
28 |
+
def create_interface_from_input(input_str):
|
29 |
+
"""
|
30 |
+
Creates a Gradio interface with buttons for functions from a package.
|
31 |
+
"""
|
32 |
+
try:
|
33 |
+
package_name = extract_package_name(input_str)
|
34 |
+
module = install_and_import(package_name)
|
35 |
+
|
36 |
+
# Handle Flask application context if needed
|
37 |
+
if 'flask' in sys.modules or 'flask_restful' in sys.modules:
|
38 |
+
app = Flask(__name__)
|
39 |
+
with app.app_context():
|
40 |
+
functions = [getattr(module, name) for name in dir(module) if callable(getattr(module, name))]
|
41 |
+
else:
|
42 |
+
functions = [getattr(module, name) for name in dir(module) if callable(getattr(module, name))]
|
43 |
+
|
44 |
+
function_list = [(func.__name__, func) for func in functions if not func.__name__.startswith("_")]
|
45 |
+
return function_list, f"Interface for `{package_name}`"
|
46 |
+
|
47 |
+
except Exception as e:
|
48 |
+
return [], str(e)
|
49 |
+
|
50 |
+
def execute_pip_command(command, add_message):
|
51 |
+
"""Executes a pip command and streams the output."""
|
52 |
+
process = subprocess.Popen(command.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
|
53 |
+
while True:
|
54 |
+
output = process.stdout.readline()
|
55 |
+
if output == '' and process.poll() is not None:
|
56 |
+
break
|
57 |
+
if output:
|
58 |
+
add_message("System", f"```\n{output.strip()}\n```")
|
59 |
+
time.sleep(0.1) # Simulate delay for more realistic streaming
|
60 |
+
rc = process.poll()
|
61 |
+
return rc
|
62 |
|
63 |
# --- Load the NLP pipeline for text classification ---
|
64 |
classifier = pipeline("text-classification")
|
|
|
119 |
output_text = gr.Textbox(label="Generated Text")
|
120 |
input_text.submit(generate_text, inputs=input_text, outputs=output_text)
|
121 |
|
122 |
+
def handle_chat(input_text, history):
|
123 |
+
"""Handles the chat input and updates the chat history."""
|
124 |
+
def add_message(sender, message):
|
125 |
+
history.append((sender, message))
|
126 |
+
|
127 |
+
add_message("User", input_text)
|
128 |
+
|
129 |
+
if input_text.startswith("pip install ") or input_text.startswith("https://pypi.org/project/"):
|
130 |
+
package_name = extract_package_name(input_text)
|
131 |
+
add_message("System", f"Installing `{package_name}`...")
|
132 |
+
|
133 |
+
execute_pip_command(input_text, add_message)
|
134 |
+
|
135 |
+
function_list, message = create_interface_from_input(input_text)
|
136 |
+
add_message("System", message)
|
137 |
+
|
138 |
+
if function_list:
|
139 |
+
functions_str = "\n".join([f" - {name}()" for name, _ in function_list])
|
140 |
+
add_message("System", f"Available functions:\n{functions_str}")
|
141 |
+
|
142 |
+
return history, function_list
|
143 |
+
else:
|
144 |
+
# Check if the input is to call a function
|
145 |
+
if '(' in input_text and ')' in input_text:
|
146 |
+
func_name = input_text.split('(')[0].strip()
|
147 |
+
func_args = input_text.split('(')[1].split(')')[0].strip()
|
148 |
+
|
149 |
+
if func_args:
|
150 |
+
func_args = [arg.strip() for arg in func_args.split(',')]
|
151 |
+
|
152 |
+
# Find the function in the current dynamic interface
|
153 |
+
for name, func in dynamic_functions:
|
154 |
+
if func_name == name:
|
155 |
+
try:
|
156 |
+
result = func(*func_args)
|
157 |
+
add_message("System", f"Result of {func_name}({', '.join(func_args)}): {result}")
|
158 |
+
except Exception as e:
|
159 |
+
add_message("System", f"Error: {str(e)}")
|
160 |
+
break
|
161 |
+
else:
|
162 |
+
add_message("System", f"Function '{func_name}' not found.")
|
163 |
+
else:
|
164 |
+
add_message("System", "Invalid function call. Please use the format 'function_name(arg1, arg2, ...)'")
|
165 |
+
|
166 |
+
return history, dynamic_functions
|
167 |
+
|
168 |
+
# Initialize dynamic functions list to store available functions
|
169 |
+
dynamic_functions = []
|
170 |
+
|
171 |
+
# Gradio app
|
172 |
+
with gr.Blocks() as demo:
|
173 |
+
with gr.Row():
|
174 |
+
chat_interface = gr.Chatbot()
|
175 |
+
|
176 |
+
with gr.Row():
|
177 |
+
chat_input = gr.Textbox(placeholder="Enter pip command or package URL", show_label=False)
|
178 |
+
submit_button = gr.Button("Submit")
|
179 |
+
|
180 |
+
def chat_handler(input_text, history):
|
181 |
+
global dynamic_functions
|
182 |
+
history, new_functions = handle_chat(input_text, history)
|
183 |
+
dynamic_functions = new_functions
|
184 |
+
return history
|
185 |
+
|
186 |
+
submit_button.click(fn=chat_handler, inputs=[chat_input, chat_interface], outputs=[chat_interface])
|
187 |
+
chat_input.submit(fn=chat_handler, inputs=[chat_input, chat_interface], outputs=[chat_interface])
|
188 |
+
|
189 |
+
demo.launch()
|