acecalisto3 commited on
Commit
b2abdcf
·
verified ·
1 Parent(s): 9028cd0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +197 -88
app.py CHANGED
@@ -11,6 +11,8 @@ from selenium.webdriver.chrome.options import Options
11
  from webdriver_manager.chrome import ChromeDriverManager
12
  from huggingface_hub import InferenceClient
13
  from selenium.common.exceptions import WebDriverException
 
 
14
 
15
  # Check for Hugging Face API key
16
  api_key = os.getenv('access')
@@ -18,7 +20,104 @@ if not api_key:
18
  raise EnvironmentError("Error: Hugging Face API key not found. Please set the 'access' environment variable.")
19
 
20
  # Configure logging
21
- logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
 
23
  client = InferenceClient("mistralai/Mixtral-8x7B-Instruct-v0.1")
24
 
@@ -26,33 +125,79 @@ VERBOSE = True
26
  MAX_HISTORY = 125
27
 
28
  def format_prompt(message, history):
29
- messages = []
30
  for user_prompt, bot_response in history:
31
- messages.append({"role": "user", "content": user_prompt})
32
- messages.append({"role": "assistant", "content": bot_response})
33
- messages.append({"role": "user", "content": message})
34
- return messages
35
-
36
- # Define current date/time
37
- date_time_str = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
38
-
39
- # Define purpose
40
- purpose = """
41
- You go to Culvers sites, you continuously seek changes on them since your last observation.
42
- Anything new that gets logged and dumped into csv, stored in your log folder at user/app/scraped_data.
43
- """
 
44
 
45
- # Define history
46
- history = []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47
 
48
- # Define current task
49
- current_task = None
50
 
51
- # Default file path
52
- default_file_path = "user/app/scraped_data/culver/culvers_changes.csv"
 
 
 
 
 
 
 
 
 
53
 
54
- # Ensure the directory exists
55
- os.makedirs(os.path.dirname(default_file_path), exist_ok=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56
 
57
  # Function to monitor URLs for changes
58
  def monitor_urls(storage_location, url1, url2, scrape_interval, content_type):
@@ -118,71 +263,35 @@ def handle_input(task, storage_location, url1, url2, scrape_interval, content_ty
118
  elif task == "Chat with a Friendly Chatbot":
119
  return "You can chat with the friendly chatbot below."
120
 
121
- # Define the chat response function
122
- def respond(
123
- message,
124
- history,
125
- system_message,
126
- max_tokens,
127
- temperature,
128
- top_p,
129
- task,
130
- storage_location,
131
- url1,
132
- url2,
133
- scrape_interval,
134
- content_type
135
- ):
136
- global client
137
-
138
- # Format the prompt
139
- messages = format_prompt(message, history)
140
-
141
- # Generate response using the InferenceClient
142
- response = ""
143
- try:
144
- for message in client.chat_completion(
145
- messages=messages,
146
- max_tokens=max_tokens,
147
- temperature=temperature,
148
- top_p=top_p,
149
- ):
150
- print("DEBUG: message:", message) # Debugging statement
151
- response += message # Assuming message is a string
152
- yield response
153
- except Exception as e:
154
- print("Error during chat completion:", e)
155
-
156
- # Append the response to history
157
- history.append((message, response))
158
-
159
- # Handle the selected task
160
- handle_input(task, storage_location, url1, url2, scrape_interval, content_type)
161
-
162
  # Create Gradio interface
163
- demo = gr.ChatInterface(
164
- respond,
165
- additional_inputs=[
166
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
167
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
168
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
169
- gr.Slider(
170
- minimum=0.1,
171
- maximum=1.0,
172
- value=0.95,
173
- step=0.05,
174
- label="Top-p (nucleus sampling)",
175
- ),
176
- gr.Dropdown(choices=["Monitor URLs for Changes", "Chat with a Friendly Chatbot"], label="Select Task"),
177
- gr.Textbox(value=default_file_path, label="Storage Location"),
178
- gr.Textbox(value="https://www.culver.k12.in.us/", label="URL 1"),
179
- gr.Textbox(value="https://www.facebook.com/CulverCommunitySchools", label="URL 2"),
180
- gr.Slider(minimum=1, maximum=60, value=5, step=1, label="Scrape Interval (minutes)"),
181
- gr.Radio(choices=["text", "media", "both"], value="text", label="Content Type"),
182
- ],
183
- title="Culvers Site Monitor and Chatbot",
184
- description="Monitor changes on Culvers' websites and log them into a CSV file. Also, chat with a friendly chatbot."
185
- )
 
 
 
 
 
186
 
187
  if __name__ == "__main__":
188
- demo.launch()
 
11
  from webdriver_manager.chrome import ChromeDriverManager
12
  from huggingface_hub import InferenceClient
13
  from selenium.common.exceptions import WebDriverException
14
+ import random
15
+ import yaml
16
 
17
  # Check for Hugging Face API key
18
  api_key = os.getenv('access')
 
20
  raise EnvironmentError("Error: Hugging Face API key not found. Please set the 'access' environment variable.")
21
 
22
  # Configure logging
23
+ log_dir = "logs"
24
+ if not os.path.exists(log_dir):
25
+ os.makedirs(log_dir)
26
+
27
+ logging.basicConfig(
28
+ filename=os.path.join(log_dir, "gradio_log.txt"),
29
+ level=logging.INFO,
30
+ format="%(asctime)s [%(levelname)s] %(message)s",
31
+ filemode="a+",
32
+ )
33
+
34
+ logger = logging.getLogger(__name__)
35
+
36
+ # Load custom prompts
37
+ try:
38
+ with open('custom_prompts.yaml', 'r') as fp:
39
+ custom_prompts = yaml.safe_load(fp)
40
+ except FileNotFoundError:
41
+ custom_prompts = {
42
+ "WEB_DEV": "",
43
+ "AI_SYSTEM_PROMPT": "",
44
+ "PYTHON_CODE_DEV": "",
45
+ "CODE_GENERATION": "",
46
+ "CODE_INTERPRETATION": "",
47
+ "CODE_TRANSLATION": "",
48
+ "CODE_IMPLEMENTATION": ""
49
+ }
50
+
51
+ for key, val in custom_prompts.items():
52
+ globals()[key] = val
53
+
54
+ # Define advanced prompts
55
+ CODE_GENERATION = """
56
+ You are an expert AI code generation assistant. Your task is to generate high-quality, production-ready code based on the given requirements. You should be able to generate code in various programming languages, including Python, JavaScript, Java, C++, and more.
57
+ When generating code, follow these guidelines:
58
+ 1. Understand the requirements thoroughly and ask clarifying questions if needed.
59
+ 2. Write clean, modular, and maintainable code following best practices and industry standards.
60
+ 3. Implement proper error handling, input validation, and edge case handling.
61
+ 4. Optimize the code for performance and scalability when necessary.
62
+ 5. Provide clear and concise comments to explain the code's functionality and logic.
63
+ 6. If applicable, suggest and implement testing strategies (unit tests, integration tests, etc.).
64
+ 7. Ensure the generated code is compatible with the target environment (e.g., web, mobile, desktop).
65
+ 8. Provide examples or usage instructions if required.
66
+ Remember to always prioritize code quality, maintainability, and security. Your generated code should be ready for production use or further development.
67
+ """
68
+
69
+ CODE_INTERPRETATION = """
70
+ You are an expert AI code interpretation assistant. Your task is to analyze and explain existing code in various programming languages, including Python, JavaScript, Java, C++, and more.
71
+ When interpreting code, follow these guidelines:
72
+ 1. Read and understand the code thoroughly, including its functionality, logic, and structure.
73
+ 2. Identify and explain the purpose of each code block, function, or module.
74
+ 3. Highlight any potential issues, inefficiencies, or areas for improvement.
75
+ 4. Suggest refactoring or optimization techniques if applicable.
76
+ 5. Explain the code's input and output, as well as any dependencies or external libraries used.
77
+ 6. Provide clear and concise explanations, using code comments or separate documentation.
78
+ 7. If applicable, explain the testing strategies or methodologies used in the code.
79
+ 8. Ensure your interpretations are accurate, unbiased, and tailored to the target audience's skill level.
80
+ Remember to prioritize clarity, accuracy, and completeness in your code interpretations. Your explanations should help developers understand the code's functionality and potential areas for improvement.
81
+ """
82
+
83
+ CODE_TRANSLATION = """
84
+ You are an expert AI code translation assistant. Your task is to translate code from one programming language to another, ensuring the translated code maintains the original functionality and follows best practices in the target language.
85
+ When translating code, follow these guidelines:
86
+ 1. Understand the original code's functionality, logic, and structure thoroughly.
87
+ 2. Identify and translate all code elements, including variables, functions, classes, and data structures.
88
+ 3. Ensure the translated code adheres to the coding conventions and best practices of the target language.
89
+ 4. Optimize the translated code for performance and readability in the target language.
90
+ 5. Preserve comments and documentation, translating them to the target language if necessary.
91
+ 6. Handle any language-specific features or constructs appropriately during the translation process.
92
+ 7. Implement error handling, input validation, and edge case handling in the translated code.
93
+ 8. Provide clear and concise comments or documentation to explain any necessary changes or deviations from the original code.
94
+ Remember to prioritize accuracy, maintainability, and idiomatic usage in the target language. Your translated code should be functionally equivalent to the original code while adhering to the best practices of the target language.
95
+ """
96
+
97
+ CODE_IMPLEMENTATION = """
98
+ You are an expert AI code implementation assistant. Your task is to take existing code or requirements and implement them in a production-ready environment, ensuring proper integration, deployment, and maintenance.
99
+ When implementing code, follow these guidelines:
100
+ 1. Understand the code's functionality, dependencies, and requirements thoroughly.
101
+ 2. Set up the appropriate development environment, including installing necessary tools, libraries, and frameworks.
102
+ 3. Integrate the code with existing systems, APIs, or databases, if applicable.
103
+ 4. Implement proper configuration management, version control, and continuous integration/deployment processes.
104
+ 5. Ensure the code is properly tested, including unit tests, integration tests, and end-to-end tests.
105
+ 6. Optimize the code for performance, scalability, and security in the production environment.
106
+ 7. Implement monitoring, logging, and error handling mechanisms for the deployed code.
107
+ 8. Document the implementation process, including any specific configurations, deployment steps, or maintenance procedures.
108
+ Remember to prioritize reliability, maintainability, and scalability in your code implementations. Your implementations should be production-ready, well-documented, and aligned with industry best practices for software development and deployment.
109
+ """
110
+
111
+ # Update the custom_prompts dictionary with the new prompts
112
+ custom_prompts.update({
113
+ "CODE_GENERATION": CODE_GENERATION,
114
+ "CODE_INTERPRETATION": CODE_INTERPRETATION,
115
+ "CODE_TRANSLATION": CODE_TRANSLATION,
116
+ "CODE_IMPLEMENTATION": CODE_IMPLEMENTATION
117
+ })
118
+
119
+ now = datetime.now()
120
+ date_time_str = now.strftime("%Y-%m-%d %H:%M:%S")
121
 
122
  client = InferenceClient("mistralai/Mixtral-8x7B-Instruct-v0.1")
123
 
 
125
  MAX_HISTORY = 125
126
 
127
  def format_prompt(message, history):
128
+ prompt = "<s>"
129
  for user_prompt, bot_response in history:
130
+ prompt += f"[INST] {user_prompt} [/INST]"
131
+ prompt += f" {bot_response}</s> "
132
+ prompt += f"[INST] {message} [/INST]"
133
+ return prompt
134
+
135
+ agents = [
136
+ "WEB_DEV",
137
+ "AI_SYSTEM_PROMPT",
138
+ "PYTHON_CODE_DEV",
139
+ "CODE_GENERATION",
140
+ "CODE_INTERPRETATION",
141
+ "CODE_TRANSLATION",
142
+ "CODE_IMPLEMENTATION"
143
+ ]
144
 
145
+ def generate(
146
+ prompt, history, agent_name=agents[0], sys_prompt="", temperature=0.9, max_new_tokens=256, top_p=0.95, repetition_penalty=1.7,
147
+ ):
148
+ seed = random.randint(1, 1111111111111111)
149
+ agent = custom_prompts[agent_name]
150
+
151
+ system_prompt = agent if sys_prompt == "" else sys_prompt
152
+ temperature = max(float(temperature), 1e-2)
153
+ top_p = float(top_p)
154
+
155
+ generate_kwargs = dict(
156
+ temperature=temperature,
157
+ max_new_tokens=max_new_tokens,
158
+ top_p=top_p,
159
+ repetition_penalty=repetition_penalty,
160
+ do_sample=True,
161
+ seed=seed,
162
+ )
163
+
164
+ formatted_prompt = format_prompt(f"{system_prompt}\n\n{prompt}", history)
165
+ output = client.text_generation(formatted_prompt, **generate_kwargs, stream=False, return_full_text=False)
166
+
167
+ return output
168
 
169
+ def update_sys_prompt(agent):
170
+ return custom_prompts[agent]
171
 
172
+ def get_helpful_tip(agent):
173
+ tips = {
174
+ 'WEB_DEV': "Provide information related to Web Development tasks.",
175
+ 'AI_SYSTEM_PROMPT': "Update the system instructions for the assistant here.",
176
+ 'PYTHON_CODE_DEV': "Describe what you want me to help you with regarding Python coding tasks.",
177
+ 'CODE_GENERATION': "Provide requirements for the code you want me to generate.",
178
+ 'CODE_INTERPRETATION': "Share the code you want me to analyze and explain.",
179
+ 'CODE_TRANSLATION': "Specify the source and target programming languages, and provide the code you want me to translate.",
180
+ 'CODE_IMPLEMENTATION': "Provide the code or requirements you want me to implement in a production-ready environment."
181
+ }
182
+ return tips.get(agent, "Select an agent to get started.")
183
 
184
+ def chat_interface(prompt, history, agent_name, sys_prompt, temperature, max_new_tokens, top_p, repetition_penalty):
185
+ generated_text = generate(prompt, history, agent_name, sys_prompt, temperature, max_new_tokens, top_p, repetition_penalty)
186
+ history.append((prompt, generated_text))
187
+ return history, ""
188
+
189
+ def log_messages(*args):
190
+ logger.info(f'Input: {args}')
191
+
192
+ examples = [
193
+ ["Based on previous interactions, generate an interactive preview of the user's requested application.", "WEB_DEV", "", 0.9, 1024, 0.95, 1.2],
194
+ ["Utilize the relevant code snippets and components from previous interactions.", "PYTHON_CODE_DEV", "", 0.9, 1024, 0.95, 1.2],
195
+ ["Assemble a working demo that showcases the core functionality of the application.", "CODE_IMPLEMENTATION", "", 0.9, 1024, 0.95, 1.2],
196
+ ["Present the demo in an interactive environment within the Gradio interface.", "WEB_DEV", "", 0.9, 1024, 0.95, 1.2],
197
+ ["Allow the user to explore and interact with the demo to test its features.", "CODE_GENERATION", "", 0.9, 1024, 0.95, 1.2],
198
+ ["Gather feedback from the user about the demo and potential improvements.", "AI_SYSTEM_PROMPT", "", 0.9, 1024, 0.95, 1.2],
199
+ ["If the user approves of the app's running state, provide a bash script that will automate all aspects of a local run and a docker image for ease-of-launch in addition to the huggingface-ready app.py with all functions and GUI, and the requirements.txt file comprised of all required libraries and packages the application is dependent on, avoiding OpenAI API at all points since we only use Hugging Face transformers, models, agents, libraries, and API.", "CODE_IMPLEMENTATION", "", 0.9, 2048, 0.95, 1.2],
200
+ ]
201
 
202
  # Function to monitor URLs for changes
203
  def monitor_urls(storage_location, url1, url2, scrape_interval, content_type):
 
263
  elif task == "Chat with a Friendly Chatbot":
264
  return "You can chat with the friendly chatbot below."
265
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
266
  # Create Gradio interface
267
+ with gr.Blocks() as iface:
268
+ gr.Markdown("# School Site Monitor and Chatbot")
269
+
270
+ chatbot = gr.Chatbot()
271
+ msg = gr.Textbox()
272
+ clear = gr.Button("Clear")
273
+
274
+ agent_dropdown = gr.Dropdown(label="Agents", choices=agents, value=agents[0])
275
+ sys_prompt = gr.Textbox(label="System Prompt", max_lines=1)
276
+ temperature = gr.Slider(label="Temperature", value=0.65, minimum=0.0, maximum=2.0, step=0.01)
277
+ max_new_tokens = gr.Slider(label="Max new tokens", value=8000, minimum=0, maximum=8000, step=64)
278
+ top_p = gr.Slider(label="Top-p (nucleus sampling)", value=0.90, minimum=0.0, maximum=1, step=0.05)
279
+ repetition_penalty = gr.Slider(label="Repetition penalty", value=1.2, minimum=1.0, maximum=2.0, step=0.05)
280
+
281
+ helpful_tip = gr.Markdown()
282
+
283
+ msg.submit(chat_interface,
284
+ [msg, chatbot, agent_dropdown, sys_prompt, temperature, max_new_tokens, top_p, repetition_penalty],
285
+ [chatbot, msg])
286
+ clear.click(lambda: None, None, chatbot, queue=False)
287
+
288
+ gr.Examples(examples, [msg, agent_dropdown, sys_prompt, temperature, max_new_tokens, top_p, repetition_penalty])
289
+
290
+ agent_dropdown.change(fn=get_helpful_tip, inputs=agent_dropdown, outputs=helpful_tip)
291
+ agent_dropdown.change(fn=update_sys_prompt, inputs=agent_dropdown, outputs=sys_prompt)
292
+
293
+ for component in [msg, agent_dropdown, sys_prompt, temperature, max_new_tokens, top_p, repetition_penalty]:
294
+ component.change(fn=log_messages, inputs=[component])
295
 
296
  if __name__ == "__main__":
297
+ iface.launch()