acecalisto3 commited on
Commit
fbf9669
1 Parent(s): 4004481

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +130 -169
app.py CHANGED
@@ -1,189 +1,150 @@
1
- import tensorflow
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")
65
-
66
- # --- Define the function to generate mini-apps based on user input ---
67
- def generate_mini_apps(theme):
68
- # Use the NLP pipeline to classify the input theme
69
- classification = classifier(theme)
70
 
71
- # Generate a set of mini-apps based on the classification
72
- if classification[0]['label'] == 'Productivity':
73
- mini_apps = [
74
- 'Idea-to-Codebase Generator',
75
- 'Automated GitHub Repo Guardian Angel',
76
- 'AI-Powered IDE'
77
- ]
78
- elif classification[0]['label'] == 'Creativity':
79
- mini_apps = [
80
- 'Brainstorming Assistant',
81
- 'Mood Board Generator',
82
- 'Writing Assistant'
83
- ]
84
- elif classification[0]['label'] == 'Well-being':
85
- mini_apps = [
86
- 'Meditation Guide',
87
- 'Mood Tracker',
88
- 'Sleep Tracker'
89
- ]
90
- else:
91
- mini_apps = ["No matching mini-apps found. Try a different theme."]
92
-
93
- # Return the generated mini-apps
94
- return mini_apps
95
-
96
- # --- Load the model and tokenizer from the provided files ---
97
- model = AutoModelForCausalLM.from_pretrained("./", trust_remote_code=True) # Load from the current directory
98
- tokenizer = AutoTokenizer.from_pretrained("./")
99
 
100
- # --- Define a function to generate text using the model ---
101
- def generate_text(input_text):
102
- inputs = tokenizer(input_text, return_tensors="pt")
103
- output = model.generate(**inputs, max_length=50, num_return_sequences=1)
104
- return tokenizer.decode(output[0], skip_special_tokens=True)
 
 
 
 
 
 
 
 
 
 
 
105
 
106
- # --- Create the Gradio interface ---
107
  demo = gr.Interface(
108
- fn=generate_mini_apps,
109
- inputs=gr.Textbox(label="Enter a theme for your life"),
110
- outputs=gr.Textbox(label="Generated Mini-Apps"),
111
- title="AI4ME: Personalized AI Tools",
112
- description="Enter your hobby/interest/job and we'll generate a set of AI-powered mini-apps tailored to your specific needs."
113
  )
114
 
115
- # --- Add a text generation tab ---
116
- with gr.Blocks() as demo_text:
117
- gr.Markdown("## Text Generation")
118
- input_text = gr.Textbox(label="Enter your text")
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()
 
 
 
 
1
  import gradio as gr
2
+ import os
3
+ import json
4
+ from pathlib import Path
5
+ from transformers import AutoModelForSequenceClassification, AutoTokenizer
6
+ import logging
7
+ import hashlib
8
+
9
+ # Set up logging
10
+ logging.basicConfig(filename='remokode.log', level=logging.INFO)
11
+
12
+ # Load the Hugging Face model and tokenizer
13
+ model_name = "distilbert-base-uncased"
14
+ model = AutoModelForSequenceClassification.from_pretrained(model_name)
15
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
16
+
17
+ # Define the chatbot function
18
+ def chatbot(message):
19
+ """
20
+ Handles user input and responds with a relevant message
21
+ """
22
+ try:
23
+ inputs = tokenizer(message, return_tensors="pt")
24
+ outputs = model(**inputs)
25
+ response = tokenizer.decode(outputs.logits.argmax(-1), skip_special_tokens=True)
26
+ return response
27
+ except Exception as e:
28
+ logging.error(f"Error in chatbot: {e}")
29
+ return "Error: unable to process input"
30
 
31
+ # Define the terminal function
32
+ def terminal(command):
33
+ """
34
+ Executes a terminal command and returns the output
35
+ """
36
+ try:
37
+ # Validate input command
38
+ if not command.strip():
39
+ return "Error: invalid command"
40
+ # Execute command and return output
41
+ output = os.popen(command).read()
42
+ return output
43
+ except Exception as e:
44
+ logging.error(f"Error in terminal: {e}")
45
+ return "Error: unable to execute command"
46
 
47
+ # Define the in-app-explorer function
48
+ def explorer(path):
49
  """
50
+ Returns a list of files and directories in the given path
51
  """
52
  try:
53
+ # Validate input path
54
+ if not path.strip():
55
+ return "Error: invalid path"
56
+ # Return list of files and directories
57
+ files = []
58
+ for file in Path(path).iterdir():
59
+ files.append(file.name)
60
+ return json.dumps(files)
61
+ except Exception as e:
62
+ logging.error(f"Error in explorer: {e}")
63
+ return "Error: unable to access path"
64
 
65
+ # Define the package manager function
66
+ def package_manager(command):
67
+ """
68
+ Manages packages and abilities for the chat app
69
+ """
70
+ try:
71
+ # Validate input command
72
+ if not command.strip():
73
+ return "Error: invalid command"
74
+ # Execute package manager command
75
+ if command == "list":
76
+ return "List of packages: [...]"
77
+ elif command == "install":
78
+ return "Package installed successfully"
79
  else:
80
+ return "Error: invalid package manager command"
 
 
 
 
81
  except Exception as e:
82
+ logging.error(f"Error in package manager: {e}")
83
+ return "Error: unable to execute package manager command"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84
 
85
+ # Define the user authentication function
86
+ def authenticate(username, password):
87
+ """
88
+ Authenticates the user and returns a session token
89
+ """
90
+ try:
91
+ # Validate input username and password
92
+ if not username.strip() or not password.strip():
93
+ return "Error: invalid username or password"
94
+ # Authenticate user and return session token
95
+ # (this is a placeholder, you should implement a secure authentication mechanism)
96
+ session_token = hashlib.sha256(f"{username}:{password}".encode()).hexdigest()
97
+ return session_token
98
+ except Exception as e:
99
+ logging.error(f"Error in authentication: {e}")
100
+ return "Error: unable to authenticate user"
 
 
 
 
 
 
 
 
 
 
 
 
101
 
102
+ # Define the session management function
103
+ def manage_session(session_token):
104
+ """
105
+ Manages the user session and returns the session state
106
+ """
107
+ try:
108
+ # Validate input session token
109
+ if not session_token.strip():
110
+ return "Error: invalid session token"
111
+ # Manage session and return session state
112
+ # (this is a placeholder, you should implement a secure session management mechanism)
113
+ session_state = {"username": "user", "packages": ["package1", "package2"]}
114
+ return session_state
115
+ except Exception as e:
116
+ logging.error(f"Error in session management: {e}")
117
+ return "Error: unable to manage session"
118
 
119
+ # Create the Gradio interface
120
  demo = gr.Interface(
121
+ fn=chatbot,
122
+ inputs="textbox",
123
+ outputs="textbox",
124
+ title="Remokode Chat App",
125
+ description="A dev space chat app with terminal and in-app-explorer"
126
  )
127
 
128
+ # Add a terminal component to the interface
129
+ terminal_component = gr.components.Textbox(label="Terminal")
130
+ demo.add_component(terminal_component, inputs="textbox", outputs="textbox", fn=terminal)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
131
 
132
+ # Add an in-app-explorer component to the interface
133
+ explorer_component = gr.components.FileBrowser(label="In-App Explorer")
134
+ demo.add_component(explorer_component, inputs=None, outputs="json", fn=explorer)
135
 
136
+ # Add a package manager component to the interface
137
+ package_manager_component = gr.components.Textbox(label="Package Manager")
138
+ demo.add_component(package_manager_component, inputs="textbox", outputs="textbox", fn=package_manager)
 
 
 
 
 
139
 
140
+ # Add a user authentication component to the interface
141
+ authentication_component = gr.components.Textbox(label="Username")
142
+ password_component = gr.components.Textbox(label="Password", type="password")
143
+ demo.add_component(authentication_component, inputs=[authentication_component, password_component], outputs="textbox", fn=authenticate)
 
144
 
145
+ # Add a session management component to the interface
146
+ session_component = gr.components.Textbox(label="Session Token")
147
+ demo.add_component(session_component, inputs=[session_component], outputs="textbox", fn=manage_session)
148
 
149
+ # Launch the demo
150
+ demo.launch(share=True)