Forrest99 commited on
Commit
e54550e
·
verified ·
1 Parent(s): f6942d6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +332 -23
app.py CHANGED
@@ -13,29 +13,338 @@ app.logger = logging.getLogger("CodeSearchAPI")
13
 
14
  # 预定义代码片段
15
  CODE_SNIPPETS = [
16
- "def sort_list(x): return sorted(x)",
17
- """def count_above_threshold(elements, threshold=0):
18
- return sum(1 for e in elements if e > threshold)""",
19
- """def find_min_max(elements):
20
- return min(elements), max(elements)"""
21
- """def count_evens(nums):
22
- return len([n for n in nums if n % 2 == 0])""",
23
- """def reverse_string(s):
24
- return s[::-1]""",
25
- """def is_prime(n):
26
- if n < 2:
27
- return False
28
- for i in range(2, int(n**0.5)+1):
29
- if n % i == 0:
30
- return False
31
- return True""",
32
- """def factorial(n):
33
- result = 1
34
- for i in range(1, n+1):
35
- result *= i
36
- return result""",
37
- """def sum_of_squares(nums):
38
- return sum(map(lambda x: x**2, nums))"""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
  ]
40
 
41
  # 全局服务状态
 
13
 
14
  # 预定义代码片段
15
  CODE_SNIPPETS = [
16
+ "print('Hello, World!')",
17
+ "def add(a, b): return a + b",
18
+ "import random; def generate_random(): return random.randint(1, 100)",
19
+ "def is_even(n): return n % 2 == 0",
20
+ "def string_length(s): return len(s)",
21
+ "from datetime import date; def get_current_date(): return date.today()",
22
+ "import os; def file_exists(path): return os.path.exists(path)",
23
+ "def read_file(path): return open(path, 'r').read()",
24
+ "def write_file(path, content): open(path, 'w').write(content)",
25
+ "from datetime import datetime; def get_current_time(): return datetime.now()",
26
+ "def to_upper(s): return s.upper()",
27
+ "def to_lower(s): return s.lower()",
28
+ "def reverse_string(s): return s[::-1]",
29
+ "def list_length(lst): return len(lst)",
30
+ "def list_max(lst): return max(lst)",
31
+ "def list_min(lst): return min(lst)",
32
+ "def sort_list(lst): return sorted(lst)",
33
+ "def merge_lists(lst1, lst2): return lst1 + lst2",
34
+ "def remove_element(lst, element): lst.remove(element)",
35
+ "def is_list_empty(lst): return len(lst) == 0",
36
+ "def count_char(s, char): return s.count(char)",
37
+ "def contains_substring(s, sub): return sub in s",
38
+ "def int_to_str(n): return str(n)",
39
+ "def str_to_int(s): return int(s)",
40
+ "def is_numeric(s): return s.isdigit()",
41
+ "def get_index(lst, element): return lst.index(element)",
42
+ "def clear_list(lst): lst.clear()",
43
+ "def reverse_list(lst): lst.reverse()",
44
+ "def remove_duplicates(lst): return list(set(lst))",
45
+ "def is_in_list(lst, value): return value in lst",
46
+ "def create_dict(): return {}",
47
+ "def add_to_dict(d, key, value): d[key] = value",
48
+ "def delete_key(d, key): del d[key]",
49
+ "def get_keys(d): return list(d.keys())",
50
+ "def get_values(d): return list(d.values())",
51
+ "def merge_dicts(d1, d2): return {**d1, **d2}",
52
+ "def is_dict_empty(d): return len(d) == 0",
53
+ "def get_value(d, key): return d[key]",
54
+ "def key_exists(d, key): return key in d",
55
+ "def clear_dict(d): d.clear()",
56
+ "def count_lines(path): return len(open(path).readlines())",
57
+ "def write_list_to_file(path, lst): open(path, 'w').write('\\n'.join(map(str, lst)))",
58
+ "def read_list_from_file(path): return open(path, 'r').read().splitlines()",
59
+ "def count_words(path): return len(open(path, 'r').read().split())",
60
+ "def is_leap_year(year): return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)",
61
+ "from datetime import datetime; def format_time(dt): return dt.strftime('%Y-%m-%d %H:%M:%S')",
62
+ "from datetime import date; def days_between(d1, d2): return (d2 - d1).days",
63
+ "import os; def get_current_dir(): return os.getcwd()",
64
+ "import os; def list_files(path): return os.listdir(path)",
65
+ "import os; def create_dir(path): os.mkdir(path)"
66
+ "import os; def remove_dir(path): os.rmdir(path)",
67
+ "import os; def is_file(path): return os.path.isfile(path)",
68
+ "import os; def is_dir(path): return os.path.isdir(path)",
69
+ "import os; def get_file_size(path): return os.path.getsize(path)",
70
+ "import os; def rename_file(src, dst): os.rename(src, dst)",
71
+ "import shutil; def copy_file(src, dst): shutil.copy(src, dst)",
72
+ "import shutil; def move_file(src, dst): shutil.move(src, dst)",
73
+ "import os; def delete_file(path): os.remove(path)",
74
+ "import os; def get_env_var(key): return os.getenv(key)",
75
+ "import os; def set_env_var(key, value): os.environ[key] = value",
76
+ "import webbrowser; def open_url(url): webbrowser.open(url)",
77
+ "import requests; def send_get_request(url): return requests.get(url).text",
78
+ "import json; def parse_json(data): return json.loads(data)",
79
+ "import json; def write_json(data, path): open(path, 'w').write(json.dumps(data))",
80
+ "import json; def read_json(path): return json.loads(open(path, 'r').read())",
81
+ "def list_to_string(lst): return ''.join(lst)",
82
+ "def string_to_list(s): return list(s)",
83
+ "def join_with_comma(lst): return ','.join(lst)",
84
+ "def join_with_newline(lst): return '\\n'.join(lst)",
85
+ "def split_by_space(s): return s.split()",
86
+ "def split_by_char(s, char): return s.split(char)",
87
+ "def split_to_chars(s): return list(s)",
88
+ "def replace_string(s, old, new): return s.replace(old, new)",
89
+ "def remove_spaces(s): return s.replace(' ', '')",
90
+ "import string; def remove_punctuation(s): return s.translate(str.maketrans('', '', string.punctuation))",
91
+ "def is_string_empty(s): return len(s) == 0",
92
+ "def is_palindrome(s): return s == s[::-1]",
93
+ "import csv; def write_csv(data, path): open(path, 'w', newline='').write('\\n'.join([','.join(map(str, row)) for row in data]))",
94
+ "import csv; def read_csv(path): return [row for row in csv.reader(open(path, 'r'))]",
95
+ "def count_csv_lines(path): return len(open(path).readlines())",
96
+ "import random; def shuffle_list(lst): random.shuffle(lst)",
97
+ "import random; def random_choice(lst): return random.choice(lst)",
98
+ "import random; def random_sample(lst, k): return random.sample(lst, k)",
99
+ "import random; def roll_dice(): return random.randint(1, 6)",
100
+ "import random; def flip_coin(): return random.choice(['Heads', 'Tails'])",
101
+ "import random; import string; def generate_password(length=8): return ''.join(random.choices(string.ascii_letters + string.digits, k=length))",
102
+ "import random; def generate_color(): return '#%06x' % random.randint(0, 0xFFFFFF)",
103
+ "import uuid; def generate_uuid(): return str(uuid.uuid4())",
104
+ "class MyClass: pass",
105
+ "def create_instance(): return MyClass()",
106
+ "class MyClass: def my_method(self): pass",
107
+ "class MyClass: def __init__(self): self.my_attr = None",
108
+ "class ChildClass(MyClass): pass",
109
+ "class ChildClass(MyClass): def my_method(self): pass",
110
+ "class MyClass: @classmethod def my_class_method(cls): pass",
111
+ "class MyClass: @staticmethod def my_static_method(): pass",
112
+ "def check_type(obj): return type(obj)",
113
+ "def get_attr(obj, attr): return getattr(obj, attr)",
114
+ "def set_attr(obj, attr, value): setattr(obj, attr, value)",
115
+ "def del_attr(obj, attr): delattr(obj, attr)",
116
+ """try:
117
+ x = 1 / 0
118
+ except ZeroDivisionError:
119
+ pass""",
120
+ """class CustomError(Exception): pass
121
+ def raise_custom_error(): raise CustomError('Error occurred')""",
122
+ """try:
123
+ x = 1 / 0
124
+ except Exception as e: return str(e)""",
125
+ """import logging; logging.basicConfig(filename='error.log', level=logging.ERROR); logging.error('Error occurred')""",
126
+ """import time; def timer(): start = time.time(); return lambda: time.time() - start""",
127
+ """import time; def run_time(): start = time.time(); return lambda: time.time() - start""",
128
+ """import sys; def print_progress(progress): sys.stdout.write(f'\\rProgress: {progress}%'); sys.stdout.flush()""",
129
+ """import time; def delay(seconds): time.sleep(seconds)""",
130
+ "lambda x: x * 2",
131
+ "map(lambda x: x * 2, [1, 2, 3])",
132
+ "filter(lambda x: x > 2, [1, 2, 3])",
133
+ "from functools import reduce; reduce(lambda x, y: x + y, [1, 2, 3])",
134
+ "[x * 2 for x in [1, 2, 3]]",
135
+ "{x: x * 2 for x in [1, 2, 3]}",
136
+ "{x for x in [1, 2, 3]}",
137
+ "set1 & set2",
138
+ "set1 | set2",
139
+ "set1 - set2",
140
+ "[x for x in lst if x is not None]",
141
+ """try:
142
+ with open('file.txt', 'r') as f: pass
143
+ except IOError: pass""",
144
+ "type(var)",
145
+ "bool(s)",
146
+ "if condition: pass",
147
+ "while condition: pass",
148
+ "for item in lst: pass",
149
+ "for key, value in d.items(): pass",
150
+ "for char in s: pass",
151
+ "for item in lst: if condition: break",
152
+ "for item in lst: if condition: continue",
153
+ "def my_func(): pass",
154
+ "def my_func(param=1): pass",
155
+ "def my_func(): return 1, 2",
156
+ "def my_func(*args): pass",
157
+ "def my_func(**kwargs): pass",
158
+ """import time; def timer(func):
159
+ def wrapper(*args, **kwargs):
160
+ start = time.time()
161
+ result = func(*args, **kwargs)
162
+ print(f'Time: {time.time() - start}'); return result
163
+ return wrapper""",
164
+ """def decorator(func):
165
+ def wrapper(*args, **kwargs): return func(*args, **kwargs)
166
+ return wrapper""",
167
+ """from functools import lru_cache; @lru_cache(maxsize=None)
168
+ def my_func(): pass""",
169
+ "def my_generator(): yield 1",
170
+ "gen = my_generator(); next(gen)",
171
+ "class MyIterator: def __iter__(self): return self; def __next__(self): pass",
172
+ "it = iter([1, 2, 3]); next(it)",
173
+ "for i, val in enumerate(lst): pass",
174
+ "list(zip(lst1, lst2))",
175
+ "dict(zip(keys, values))",
176
+ "lst1 == lst2",
177
+ "dict1 == dict2",
178
+ "set1 == set2",
179
+ "set(lst)",
180
+ "set.clear()",
181
+ "len(set) == 0",
182
+ "set.add(item)",
183
+ "set.remove(item)",
184
+ "item in set",
185
+ "len(set)",
186
+ "set1 & set2",
187
+ "set(lst1).issubset(lst2)",
188
+ "sub in s",
189
+ "s[0]",
190
+ "s[-1]",
191
+ "import mimetypes; mimetypes.guess_type(path)[0] == 'text/plain'",
192
+ "import mimetypes; mimetypes.guess_type(path)[0].startswith('image/')",
193
+ "round(num)",
194
+ "import math; math.ceil(num)",
195
+ "import math; math.floor(num)",
196
+ "f'{num:.2f}'",
197
+ "import random; import string; ''.join(random.choices(string.ascii_letters + string.digits, k=8))",
198
+ "import os; os.path.exists(path)",
199
+ "import os; for root, dirs, files in os.walk(path): pass",
200
+ "import os; os.path.splitext(path)[1]",
201
+ "import os; os.path.basename(path)",
202
+ "import os; os.path.abspath(path)",
203
+ "import platform; platform.python_version()",
204
+ "import platform; platform.system()",
205
+ "import multiprocessing; multiprocessing.cpu_count()",
206
+ "import psutil; psutil.virtual_memory().total",
207
+ "import psutil; psutil.disk_usage('/')",
208
+ "import socket; socket.gethostbyname(socket.gethostname())",
209
+ "import requests; try: requests.get('http://www.google.com'); return True; except: return False",
210
+ "import requests; def download_file(url, path): with open(path, 'wb') as f: f.write(requests.get(url).content)",
211
+ "def upload_file(path): with open(path, 'rb') as f: requests.post('http://example.com/upload', files={'file': f})",
212
+ "import requests; requests.post(url, data={'key': 'value'})",
213
+ "import requests; requests.get(url, params={'key': 'value'})",
214
+ "import requests; requests.get(url, headers={'key': 'value'})",
215
+ "from bs4 import BeautifulSoup; BeautifulSoup(html, 'html.parser')",
216
+ "from bs4 import BeautifulSoup; soup.title.text",
217
+ "from bs4 import BeautifulSoup; [a['href'] for a in soup.find_all('a')]",
218
+ "from bs4 import BeautifulSoup; import requests; for img in soup.find_all('img'): requests.get(img['src']).content",
219
+ "from collections import Counter; Counter(text.split())",
220
+ "import requests; session = requests.Session(); session.post(login_url, data={'username': 'user', 'password': 'pass'})",
221
+ "from bs4 import BeautifulSoup; soup.get_text()",
222
+ "import re; re.findall(r'[\\w.-]+@[\\w.-]+', text)",
223
+ "import re; re.findall(r'\\+?\\d[\\d -]{8,12}\\d', text)",
224
+ "import re; re.findall(r'\\d+', text)",
225
+ "import re; re.sub(pattern, repl, text)",
226
+ "import re; re.match(pattern, text)",
227
+ "from bs4 import BeautifulSoup; soup.get_text()",
228
+ "import html; html.escape(text)",
229
+ "import html; html.unescape(text)",
230
+ "import tkinter as tk; root = tk.Tk(); root.mainloop()",
231
+ "import tkinter as tk; def add_button(window, text): return tk.Button(window, text=text)",
232
+ """def bind_click(button, func): button.config(command=func)""",
233
+ """import tkinter.messagebox; def show_alert(message): tkinter.messagebox.showinfo('Info', message)""",
234
+ """def get_entry_text(entry): return entry.get()""",
235
+ "def set_title(window, title): window.title(title)",
236
+ "def set_size(window, width, height): window.geometry(f'{width}x{height}')",
237
+ """def center_window(window):
238
+ window.update_idletasks()
239
+ width = window.winfo_width()
240
+ height = window.winfo_height()
241
+ x = (window.winfo_screenwidth() // 2) - (width // 2)
242
+ y = (window.winfo_screenheight() // 2) - (height // 2)
243
+ window.geometry(f'{width}x{height}+{x}+{y}')""",
244
+ """def create_menu(window): return tk.Menu(window)""",
245
+ "def create_combobox(window): return ttk.Combobox(window)",
246
+ "def create_radiobutton(window, text): return tk.Radiobutton(window, text=text)",
247
+ "def create_checkbutton(window, text): return tk.Checkbutton(window, text=text)",
248
+ """from PIL import ImageTk, Image; def show_image(window, path):
249
+ img = Image.open(path)
250
+ photo = ImageTk.PhotoImage(img)
251
+ label = tk.Label(window, image=photo)
252
+ label.image = photo
253
+ return label""",
254
+ "import pygame; def play_audio(path): pygame.mixer.init(); pygame.mixer.music.load(path); pygame.mixer.music.play()",
255
+ "import cv2; def play_video(path): cap = cv2.VideoCapture(path); while cap.isOpened(): ret, frame = cap.read()",
256
+ "def get_playback_time(): return pygame.mixer.music.get_pos()",
257
+ "import pyautogui; def screenshot(): return pyautogui.screenshot()",
258
+ "import pyautogui; import time; def record_screen(duration): return [pyautogui.screenshot() for _ in range(duration)]",
259
+ "def get_mouse_pos(): return pyautogui.position()",
260
+ "import pyautogui; def type_text(text): pyautogui.write(text)",
261
+ "import pyautogui; def click_mouse(x, y): pyautogui.click(x, y)",
262
+ "import time; def get_timestamp(): return int(time.time())",
263
+ "import datetime; def timestamp_to_date(ts): return datetime.datetime.fromtimestamp(ts)",
264
+ "import time; def date_to_timestamp(dt): return int(time.mktime(dt.timetuple()))",
265
+ "def get_weekday(): return datetime.datetime.now().strftime('%A')",
266
+ "import calendar; def get_month_days(): return calendar.monthrange(datetime.datetime.now().year, datetime.datetime.now().month)[1]",
267
+ "def first_day_of_year(): return datetime.date(datetime.datetime.now().year, 1, 1)",
268
+ "def last_day_of_year(): return datetime.date(datetime.datetime.now().year, 12, 31)",
269
+ "def first_day_of_month(month): return datetime.date(datetime.datetime.now().year, month, 1)",
270
+ "import calendar; def last_day_of_month(month): return datetime.date(datetime.datetime.now().year, month, calendar.monthrange(datetime.datetime.now().year, month)[1])",
271
+ "def is_weekday(): return datetime.datetime.now().weekday() < 5",
272
+ "def is_weekend(): return datetime.datetime.now().weekday() >= 5",
273
+ "def current_hour(): return datetime.datetime.now().hour",
274
+ "def current_minute(): return datetime.datetime.now().minute",
275
+ "def current_second(): return datetime.datetime.now().second",
276
+ "import time; def delay_1s(): time.sleep(1)",
277
+ "import time; def millis_timestamp(): return int(time.time() * 1000)",
278
+ "def format_time(dt, fmt='%Y-%m-%d %H:%M:%S'): return dt.strftime(fmt)",
279
+ "from dateutil.parser import parse; def parse_time(s): return parse(s)",
280
+ "import threading; def create_thread(target): return threading.Thread(target=target)",
281
+ "import time; def thread_pause(seconds): time.sleep(seconds)",
282
+ "def run_threads(*threads): [t.start() for t in threads]",
283
+ "import threading; def current_thread_name(): return threading.current_thread().name",
284
+ "def set_daemon(thread): thread.daemon = True",
285
+ "import threading; lock = threading.Lock()",
286
+ "import multiprocessing; def create_process(target): return multiprocessing.Process(target=target)",
287
+ "import os; def get_pid(): return os.getpid()",
288
+ "import psutil; def is_process_alive(pid): return psutil.pid_exists(pid)",
289
+ "def run_processes(*procs): [p.start() for p in procs]",
290
+ "from queue import Queue; q = Queue()",
291
+ "from multiprocessing import Pipe; parent_conn, child_conn = Pipe()",
292
+ "import os; def limit_cpu_usage(percent): os.system(f'cpulimit -p {os.getpid()} -l {percent}')",
293
+ "import subprocess; def run_command(cmd): subprocess.run(cmd, shell=True)",
294
+ "import subprocess; def get_command_output(cmd): return subprocess.check_output(cmd, shell=True).decode()",
295
+ "def get_exit_code(cmd): return subprocess.call(cmd, shell=True)",
296
+ "def is_success(code): return code == 0",
297
+ "import os; def script_path(): return os.path.realpath(__file__)",
298
+ "import sys; def get_cli_args(): return sys.argv[1:]",
299
+ "import argparse; parser = argparse.ArgumentParser()",
300
+ "parser.print_help()",
301
+ "help('modules')",
302
+ "import pip; def install_pkg(pkg): pip.main(['install', pkg])",
303
+ "import pip; def uninstall_pkg(pkg): pip.main(['uninstall', pkg])",
304
+ "import pkg_resources; def get_pkg_version(pkg): return pkg_resources.get_distribution(pkg).version",
305
+ "import venv; def create_venv(path): venv.create(path)",
306
+ "import pip; def list_pkgs(): return pip.get_installed_distributions()",
307
+ "import pip; def upgrade_pkg(pkg): pip.main(['install', '--upgrade', pkg])",
308
+ "import sqlite3; conn = sqlite3.connect(':memory:')",
309
+ "def execute_query(conn, query): return conn.execute(query)",
310
+ "def insert_record(conn, table, data): conn.execute(f'INSERT INTO {table} VALUES ({",".join("?"*len(data))})', data)",
311
+ "def delete_record(conn, table, condition): conn.execute(f'DELETE FROM {table} WHERE {condition}')",
312
+ "def update_record(conn, table, set_clause, condition): conn.execute(f'UPDATE {table} SET {set_clause} WHERE {condition}')",
313
+ "def fetch_all(conn, query): return conn.execute(query).fetchall()",
314
+ "def safe_query(conn, query, params): return conn.execute(query, params)",
315
+ "def close_db(conn): conn.close()",
316
+ "def create_table(conn, name, columns): conn.execute(f'CREATE TABLE {name} ({columns})')",
317
+ "def drop_table(conn, name): conn.execute(f'DROP TABLE {name}')",
318
+ "def table_exists(conn, name): return conn.execute(f\"SELECT name FROM sqlite_master WHERE type='table' AND name='{name}'\").fetchone()",
319
+ "def list_tables(conn): return conn.execute(\"SELECT name FROM sqlite_master WHERE type='table'\").fetchall()",
320
+ """from sqlalchemy import Column, Integer, String
321
+ class User(Base):
322
+ __tablename__ = 'users'
323
+ id = Column(Integer, primary_key=True)
324
+ name = Column(String)""",
325
+ "session.add(User(name='John'))",
326
+ "session.query(User).filter_by(name='John')",
327
+ "session.query(User).filter_by(name='John').delete()",
328
+ "session.query(User).filter_by(name='John').update({'name': 'Bob'})",
329
+ "Base = declarative_base()",
330
+ "class Admin(User): pass",
331
+ "id = Column(Integer, primary_key=True)",
332
+ "name = Column(String, unique=True)",
333
+ "name = Column(String, default='Unknown')",
334
+ "import csv; def export_csv(data, path): open(path, 'w').write('\\n'.join([','.join(map(str, row)) for row in data]))",
335
+ "import pandas as pd; pd.DataFrame(data).to_excel(path)",
336
+ "import json; json.dump(data, open(path, 'w'))",
337
+ "pd.read_excel(path).values.tolist()",
338
+ "pd.concat([pd.read_excel(f) for f in files])",
339
+ "with pd.ExcelWriter(path, mode='a') as writer: df.to_excel(writer, sheet_name='New')",
340
+ "from openpyxl.styles import copy; copy.copy(style)",
341
+ "from openpyxl.styles import PatternFill; cell.fill = PatternFill(start_color='FFFF00', fill_type='solid')",
342
+ "from openpyxl.styles import Font; cell.font = Font(bold=True)",
343
+ "sheet['A1'].value",
344
+ "sheet['A1'] = value",
345
+ "from PIL import Image; Image.open(path).size",
346
+ "from PIL import Image; Image.open(path).resize((w, h))"
347
+
348
  ]
349
 
350
  # 全局服务状态