acecalisto3 commited on
Commit
00184de
·
verified ·
1 Parent(s): b2abdcf

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +107 -243
app.py CHANGED
@@ -10,194 +10,34 @@ from selenium.webdriver.chrome.service import Service
10
  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
- import random
15
- import yaml
16
-
17
- # Check for Hugging Face API key
18
- api_key = os.getenv('access')
19
- if not api_key:
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
-
124
- VERBOSE = True
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):
@@ -218,80 +58,104 @@ def monitor_urls(storage_location, url1, url2, scrape_interval, content_type):
218
  options.add_argument("--no-sandbox")
219
  options.add_argument("--disable-dev-shm-usage")
220
 
221
- try:
222
- with webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=options) as driver:
223
- try:
224
- while True:
225
- for i, url in enumerate(urls):
226
- try:
227
- driver.get(url)
228
- time.sleep(2) # Wait for the page to load
229
- if content_type == "text":
230
- current_content = driver.page_source
231
- elif content_type == "media":
232
- current_content = driver.find_elements_by_tag_name("img")
233
- else:
234
- current_content = driver.page_source
235
-
236
- current_hash = hashlib.md5(str(current_content).encode('utf-8')).hexdigest()
237
-
238
- if current_hash != previous_hashes[i]:
239
- previous_hashes[i] = current_hash
240
- date_time_str = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
241
- history.append(f"Change detected at {url} on {date_time_str}")
242
- csv_toolkit.writerow({"date": date_time_str.split()[0], "time": date_time_str.split()[1], "url": url, "change": "Content changed"})
243
- logging.info(f"Change detected at {url} on {date_time_str}")
244
- except Exception as e:
245
- logging.error(f"Error accessing {url}: {e}")
246
-
247
- time.sleep(scrape_interval * 60) # Check every scrape_interval minutes
248
- except KeyboardInterrupt:
249
- logging.info("Monitoring stopped by user.")
250
- except WebDriverException as e:
251
- logging.error(f"WebDriverException: {e}")
252
- raise
253
 
254
  # Define main function to handle user input
255
- def handle_input(task, storage_location, url1, url2, scrape_interval, content_type):
256
  global current_task, history
257
 
258
- if task == "Monitor URLs for Changes":
259
- current_task = f"Monitoring URLs: {url1}, {url2}"
260
- history.append(f"Task started: {current_task}")
261
- monitor_urls(storage_location, url1, url2, scrape_interval, content_type)
262
- return TASK_PROMPT.format(task=current_task, history="\n".join(history))
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()
 
10
  from selenium.webdriver.chrome.options import Options
11
  from webdriver_manager.chrome import ChromeDriverManager
12
  from huggingface_hub import InferenceClient
 
 
 
 
 
 
 
 
13
 
14
  # Configure logging
15
+ logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
 
 
 
 
 
 
 
 
 
16
 
17
+ # Define constants
18
+ PREFIX = "Task started at {date_time_str}. Purpose: {purpose}"
19
+ TASK_PROMPT = "Current task: {task}. History:\n{history}"
20
 
21
+ # Define current date/time
22
+ date_time_str = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
 
 
 
 
 
 
 
 
 
 
 
 
23
 
24
+ # Define purpose
25
+ purpose = """
26
+ You go to Culvers sites, you continuously seek changes on them since your last observation.
27
+ Anything new that gets logged and dumped into csv, stored in your log folder at user/app/scraped_data.
 
 
 
 
 
 
 
 
 
 
 
 
28
  """
29
 
30
+ # Define history
31
+ history = []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32
 
33
+ # Define current task
34
+ current_task = None
 
 
 
 
 
35
 
36
+ # Default file path
37
+ default_file_path = "user/app/scraped_data/culver/culvers_changes.csv"
38
 
39
+ # Ensure the directory exists
40
+ os.makedirs(os.path.dirname(default_file_path), exist_ok=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41
 
42
  # Function to monitor URLs for changes
43
  def monitor_urls(storage_location, url1, url2, scrape_interval, content_type):
 
58
  options.add_argument("--no-sandbox")
59
  options.add_argument("--disable-dev-shm-usage")
60
 
61
+ with webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=options) as driver:
62
+ try:
63
+ while True:
64
+ for i, url in enumerate(urls):
65
+ try:
66
+ driver.get(url)
67
+ time.sleep(2) # Wait for the page to load
68
+ if content_type == "text":
69
+ current_content = driver.page_source
70
+ elif content_type == "media":
71
+ current_content = driver.find_elements_by_tag_name("img")
72
+ else:
73
+ current_content = driver.page_source
74
+
75
+ current_hash = hashlib.md5(str(current_content).encode('utf-8')).hexdigest()
76
+
77
+ if current_hash != previous_hashes[i]:
78
+ previous_hashes[i] = current_hash
79
+ date_time_str = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
80
+ history.append(f"Change detected at {url} on {date_time_str}")
81
+ csv_toolkit.writerow({"date": date_time_str.split()[0], "time": date_time_str.split()[1], "url": url, "change": "Content changed"})
82
+ logging.info(f"Change detected at {url} on {date_time_str}")
83
+ except Exception as e:
84
+ logging.error(f"Error accessing {url}: {e}")
85
+
86
+ time.sleep(scrape_interval * 60) # Check every scrape_interval minutes
87
+ except KeyboardInterrupt:
88
+ logging.info("Monitoring stopped by user.")
89
+ finally:
90
+ driver.quit()
 
 
91
 
92
  # Define main function to handle user input
93
+ def handle_input(storage_location, url1, url2, scrape_interval, content_type):
94
  global current_task, history
95
 
96
+ current_task = f"Monitoring URLs: {url1}, {url2}"
97
+ history.append(f"Task started: {current_task}")
98
+ monitor_urls(storage_location, url1, url2, scrape_interval, content_type)
99
+ return TASK_PROMPT.format(task=current_task, history="\n".join(history))
100
+
101
+ # Define the chat response function
102
+ client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
103
+
104
+ def respond(
105
+ message,
106
+ history: list[tuple[str, str]],
107
+ system_message,
108
+ max_tokens,
109
+ temperature,
110
+ top_p,
111
+ ):
112
+ messages = [{"role": "system", "content": system_message}]
113
 
114
+ for val in history:
115
+ if val[0]:
116
+ messages.append({"role": "user", "content": val[0]})
117
+ if val[1]:
118
+ messages.append({"role": "assistant", "content": val[1]})
 
119
 
120
+ messages.append({"role": "user", "content": message})
121
 
122
+ response = ""
 
 
 
123
 
124
+ for message in client.chat_completion(
125
+ messages,
126
+ max_tokens=max_tokens,
127
+ stream=True,
128
+ temperature=temperature,
129
+ top_p=top_p,
130
+ ):
131
+ token = message.choices[0].delta.content
132
 
133
+ response += token
134
+ yield response
135
 
136
+ # Create Gradio interface
137
+ demo = gr.ChatInterface(
138
+ respond,
139
+ additional_inputs=[
140
+ gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
141
+ gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
142
+ gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
143
+ gr.Slider(
144
+ minimum=0.1,
145
+ maximum=1.0,
146
+ value=0.95,
147
+ step=0.05,
148
+ label="Top-p (nucleus sampling)",
149
+ ),
150
+ gr.Textbox(value=default_file_path, label="Storage Location"),
151
+ gr.Textbox(value="https://www.culver.k12.in.us/", label="URL 1"),
152
+ gr.Textbox(value="https://www.facebook.com/CulverCommunitySchools", label="URL 2"),
153
+ gr.Slider(minimum=1, maximum=60, value=5, step=1, label="Scrape Interval (minutes)"),
154
+ gr.Radio(choices=["text", "media", "both"], value="text", label="Content Type"),
155
+ ],
156
+ title="Culvers Site Monitor and Chatbot",
157
+ description="Monitor changes on Culvers' websites and log them into a CSV file. Also, chat with a friendly chatbot."
158
+ )
159
 
160
  if __name__ == "__main__":
161
+ demo.launch()