Spaces:
Running
Running
File size: 38,603 Bytes
2a39044 90f5392 892f484 7c08c7b 90f5392 2a39044 90f5392 2a39044 892f484 90f5392 79ce9cc 892f484 adb528f e49fd82 4d96001 e54550e 1d25027 892f484 7c08c7b 892f484 7c08c7b 2a39044 892f484 2a39044 79ce9cc 7c08c7b 79ce9cc 2a39044 7c08c7b 892f484 2a39044 892f484 2a39044 7c08c7b 2a39044 7c08c7b 79ce9cc 2a39044 c79e0ff 892f484 7c08c7b 2a39044 79ce9cc c79e0ff aacc39b 2a39044 c79e0ff 892f484 c79e0ff 892f484 2a39044 c79e0ff 2a39044 79ce9cc c79e0ff 79ce9cc c79e0ff 2a39044 c79e0ff 2a39044 aacc39b c79e0ff 892f484 90f5392 0db0051 2a39044 c79e0ff |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 |
from flask import Flask, request, jsonify, render_template_string
from sentence_transformers import SentenceTransformer, util
import logging
import sys
import signal
# 初始化 Flask 应用
app = Flask(__name__)
# 配置日志,级别设为 INFO
logging.basicConfig(level=logging.INFO)
app.logger = logging.getLogger("CodeSearchAPI")
# 预定义代码片段
CODE_SNIPPETS = [
"fmt.Print(\"Hello, World!\")",
"func sum(a, b int) int { return a + b }",
"func randInt() int { return rand.Intn(100) }",
"func isEven(n int) bool { return n%2 == 0 }",
"func strLen(s string) int { return len(s) }",
"func currentDate() string { return time.Now().Format(\"2006-01-02\") }",
"func fileExists(path string) bool { _, err := os.Stat(path); return !os.IsNotExist(err) }",
"func readFile(path string) (string, error) { data, err := os.ReadFile(path); return string(data), err }",
"func writeFile(path, content string) error { return os.WriteFile(path, []byte(content), 0644) }",
"func currentTime() string { return time.Now().Format(\"15:04:05\") }",
"func toUpper(s string) string { return strings.ToUpper(s) }",
"func toLower(s string) string { return strings.ToLower(s) }",
"func reverseString(s string) string { runes := []rune(s); for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 { runes[i], runes[j] = runes[j], runes[i] }; return string(runes) }",
"func listLen(list []int) int { return len(list) }",
"func maxInList(list []int) int { return max(list...) }",
"func minInList(list []int) int { return min(list...) }",
"func sortList(list []int) []int { sort.Ints(list); return list }",
"func mergeLists(list1, list2 []int) []int { return append(list1, list2...) }",
"func removeFromList(list []int, elem int) []int { return append(list[:elem], list[elem+1:]...) }",
"func isListEmpty(list []int) bool { return len(list) == 0 }",
"func countChar(s string, c rune) int { return strings.Count(s, string(c)) }",
"func containsSubstring(s, substr string) bool { return strings.Contains(s, substr) }",
"func intToString(n int) string { return strconv.Itoa(n) }",
"func stringToInt(s string) int { n, _ := strconv.Atoi(s); return n }",
"func isNumeric(s string) bool { _, err := strconv.Atoi(s); return err == nil }",
"func indexInList(list []int, elem int) int { for i, v := range list { if v == elem { return i } }; return -1 }",
"func clearList(list []int) []int { return list[:0] }",
"func reverseList(list []int) []int { for i, j := 0, len(list)-1; i < j; i, j = i+1, j-1 { list[i], list[j] = list[j], list[i] }; return list }",
"func removeDuplicates(list []int) []int { seen := make(map[int]bool); result := []int{}; for _, v := range list { if !seen[v] { seen[v] = true; result = append(result, v) } }; return result }",
"func isInList(list []int, elem int) bool { for _, v := range list { if v == elem { return true } }; return false }",
"func createDict() map[string]int { return make(map[string]int) }",
"func addToDict(dict map[string]int, key string, value int) { dict[key] = value }",
"func deleteFromDict(dict map[string]int, key string) { delete(dict, key) }",
"func dictKeys(dict map[string]int) []string { keys := []string{}; for k := range dict { keys = append(keys, k) }; return keys }",
"func dictValues(dict map[string]int) []int { values := []int{}; for _, v := range dict { values = append(values, v) }; return values }",
"func mergeDicts(dict1, dict2 map[string]int) map[string]int { for k, v := range dict2 { dict1[k] = v }; return dict1 }",
"func isDictEmpty(dict map[string]int) bool { return len(dict) == 0 }",
"func dictValue(dict map[string]int, key string) int { return dict[key] }",
"func keyInDict(dict map[string]int, key string) bool { _, ok := dict[key]; return ok }",
"func clearDict(dict map[string]int) { for k := range dict { delete(dict, k) } }",
"func countFileLines(path string) (int, error) { data, err := os.ReadFile(path); if err != nil { return 0, err }; return len(strings.Split(string(data), \"\n\")), nil }",
"func writeListToFile(path string, list []int) error { data := strings.Trim(strings.Join(strings.Fields(fmt.Sprint(list)), \" \"), \"[]\"); return os.WriteFile(path, []byte(data), 0644) }",
"func readListFromFile(path string) ([]int, error) { data, err := os.ReadFile(path); if err != nil { return nil, err }; var list []int; for _, v := range strings.Fields(string(data)) { n, _ := strconv.Atoi(v); list = append(list, n) }; return list, nil }",
"func countFileWords(path string) (int, error) { data, err := os.ReadFile(path); if err != nil { return 0, err }; return len(strings.Fields(string(data))), nil }",
"func isLeapYear(year int) bool { return year%4 == 0 && (year%100 != 0 || year%400 == 0) }",
"func formatTime(t time.Time, layout string) string { return t.Format(layout) }",
"func daysBetweenDates(date1, date2 time.Time) int { return int(date2.Sub(date1).Hours() / 24) }",
"func currentDir() string { dir, _ := os.Getwd(); return dir }",
"func listFiles(path string) ([]string, error) { files, err := os.ReadDir(path); if err != nil { return nil, err }; var names []string; for _, file := range files { names = append(names, file.Name()) }; return names, nil }",
"func createDir(path string) error { return os.Mkdir(path, 0755) }",
"func deleteDir(path string) error { return os.RemoveAll(path) }",
"func isFile(path string) bool { info, err := os.Stat(path); return err == nil && !info.IsDir() }",
"func isDir(path string) bool { info, err := os.Stat(path); return err == nil && info.IsDir() }",
"func fileSize(path string) (int64, error) { info, err := os.Stat(path); if err != nil { return 0, err }; return info.Size(), nil }",
"func renameFile(oldPath, newPath string) error { return os.Rename(oldPath, newPath) }",
"func copyFile(src, dst string) error { data, err := os.ReadFile(src); if err != nil { return err }; return os.WriteFile(dst, data, 0644) }",
"func moveFile(src, dst string) error { return os.Rename(src, dst) }",
"func deleteFile(path string) error { return os.Remove(path) }",
"func getEnvVar(key string) string { return os.Getenv(key) }",
"func setEnvVar(key, value string) error { return os.Setenv(key, value) }",
"func openURL(url string) error { return exec.Command(\"xdg-open\", url).Start() }",
"func sendGetRequest(url string) (string, error) { resp, err := http.Get(url); if err != nil { return \"\", err }; defer resp.Body.Close(); body, err := io.ReadAll(resp.Body); if err != nil { return \"\", err }; return string(body), nil }",
"func parseJSON(data string) (map[string]interface{}, error) { var result map[string]interface{}; err := json.Unmarshal([]byte(data), &result); return result, err }",
"func writeJSONToFile(path string, data map[string]interface{}) error { jsonData, err := json.Marshal(data); if err != nil { return err }; return os.WriteFile(path, jsonData, 0644) }",
"func readJSONFromFile(path string) (map[string]interface{}, error) { data, err := os.ReadFile(path); if err != nil { return nil, err }; var result map[string]interface{}; err = json.Unmarshal(data, &result); return result, err }",
"func listToString(list []int) string { return strings.Trim(strings.Join(strings.Fields(fmt.Sprint(list)), \" \"), \"[]\") }",
"func stringToList(s string) []int { var list []int; for _, v := range strings.Fields(s) { n, _ := strconv.Atoi(v); list = append(list, n) }; return list }",
"func joinListWithComma(list []int) string { return strings.Join(strings.Fields(fmt.Sprint(list)), \",\") }",
"func joinListWithNewline(list []int) string { return strings.Join(strings.Fields(fmt.Sprint(list)), \"\n\") }",
"func splitStringBySpace(s string) []string { return strings.Fields(s) }",
"func splitStringByDelimiter(s, delimiter string) []string { return strings.Split(s, delimiter) }",
"func splitStringToChars(s string) []string { return strings.Split(s, \"\") }",
"func replaceString(s, old, new string) string { return strings.ReplaceAll(s, old, new) }",
"func removeSpaces(s string) string { return strings.ReplaceAll(s, \" \", \"\") }",
"func removePunctuation(s string) string { return strings.Map(func(r rune) rune { if unicode.IsPunct(r) { return -1 }; return r }, s) }",
"func isStringEmpty(s string) bool { return len(s) == 0 }",
"func isPalindrome(s string) bool { return s == reverseString(s) }",
"func writeCSV(path string, data [][]string) error { file, err := os.Create(path); if err != nil { return err }; defer file.Close(); writer := csv.NewWriter(file); return writer.WriteAll(data) }",
"func readCSV(path string) ([][]string, error) { file, err := os.Open(path); if err != nil { return nil, err }; defer file.Close(); reader := csv.NewReader(file); return reader.ReadAll() }",
"func countCSVLines(path string) (int, error) { data, err := readCSV(path); if err != nil { return 0, err }; return len(data), nil }",
"func shuffleList(list []int) []int { rand.Shuffle(len(list), func(i, j int) { list[i], list[j] = list[j], list[i] }); return list }",
"func randomElement(list []int) int { return list[rand.Intn(len(list))] }",
"func randomElements(list []int, n int) []int { rand.Shuffle(len(list), func(i, j int) { list[i], list[j] = list[j], list[i] }); return list[:n] }",
"func rollDice() int { return rand.Intn(6) + 1 }",
"func flipCoin() string { if rand.Intn(2) == 0 { return \"Heads\" }; return \"Tails\" }",
"func generatePassword(length int) string { chars := \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()\"; password := make([]byte, length); for i := range password { password[i] = chars[rand.Intn(len(chars))] }; return string(password) }",
"func randomColor() string { return fmt.Sprintf(\"#%06x\", rand.Intn(0xffffff)) }",
"func generateUUID() string { return uuid.New().String() }",
"type MyClass struct{}",
"func NewMyClass() *MyClass { return &MyClass{} }",
"func (m *MyClass) MyMethod() {}",
"type MyClass struct { MyAttribute int }",
"type ChildClass struct { MyClass }",
"func (c *ChildClass) MyMethod() {}",
"func (m *MyClass) MyClassMethod() {}",
"func MyStaticMethod() {}",
"func isInstanceOf(obj interface{}, t reflect.Type) bool { return reflect.TypeOf(obj) == t }",
"func getAttribute(obj interface{}, attr string) interface{} { return reflect.ValueOf(obj).FieldByName(attr).Interface() }",
"func setAttribute(obj interface{}, attr string, value interface{}) { reflect.ValueOf(obj).FieldByName(attr).Set(reflect.ValueOf(value)) }",
"func deleteAttribute(obj interface{}, attr string) { reflect.ValueOf(obj).FieldByName(attr).Set(reflect.Zero(reflect.TypeOf(obj).FieldByName(attr).Type)) }",
"func handleException() { defer func() { if r := recover(); r != nil { fmt.Println(\"Recovered:\", r) } }(); panic(\"An error occurred\") }",
"""func customError() error {
return errors.New("custom error")
}""",
"""func getErrorInfo() {
if err := customError(); err != nil {
fmt.Println("Error:", err)
}
}""",
"""func logError() {
if err := customError(); err != nil {
log.Println("Error:", err)
}
}""",
"""func timer() func() {
start := time.Now()
return func() {
fmt.Println(time.Since(start))
}
}""",
"""func runtime() {
start := time.Now()
time.Sleep(1 * time.Second)
fmt.Println(time.Since(start))
}""",
"""func progressBar() {
for i := 0; i <= 100; i += 10 {
fmt.Printf("\r[%-10s] %d%%", strings.Repeat("=", i/10), i)
time.Sleep(100 * time.Millisecond)
}
fmt.Println()
}""",
"""func delay() {
time.Sleep(1 * time.Second)
}""",
"lambda := func(x int) int { return x * x }",
"result := map(lambda, []int{1, 2, 3, 4})",
"result := filter(func(x int) bool { return x > 2 }, []int{1, 2, 3, 4})",
"result := reduce(func(a, b int) int { return a + b }, []int{1, 2, 3, 4})",
"result := [x * x for x in [1, 2, 3, 4]]",
"result := {x: x * x for x in [1, 2, 3, 4]}",
"result := {x * x for x in [1, 2, 3, 4]}",
"result := intersection(set1, set2)",
"result := union(set1, set2)",
"result := difference(set1, set2)",
"result := [x for x in [1, None, 2, None, 3] if x is not None]",
"""func checkFile(filename string) {
file, err := os.Open(filename)
if err != nil {
fmt.Println("Error:", err)
} else {
file.Close()
}
}""",
"""func checkType(v interface{}) {
fmt.Printf("Type: %T\n", v)
}""",
"""func strToBool(s string) bool {
return s == "true"
}""",
"""func ifCondition(x int) {
if x > 0 {
fmt.Println("Positive")
} else {
fmt.Println("Non-positive")
}
}""",
"""func whileLoop() {
i := 0
while i < 10 {
fmt.Println(i)
i++
}
}""",
"""func forList() {
for _, v := range []int{1, 2, 3} {
fmt.Println(v)
}
}""",
"""func forDict() {
for k, v := range map[string]int{"a": 1, "b": 2} {
fmt.Println(k, v)
}
}""",
"""func forString() {
for _, c := range "hello" {
fmt.Println(c)
}
}""",
"""func breakLoop() {
for i := 0; i < 10; i++ {
if i == 5 {
break
}
fmt.Println(i)
}
}""",
"""func continueLoop() {
for i := 0; i < 10; i++ {
if i == 5 {
continue
}
fmt.Println(i)
}
}""",
"""func defineFunc() {
fmt.Println("Function defined")
}""",
"""func defaultParam(x int = 10) {
fmt.Println(x)
}""",
"""func returnMultiple() (int, string) {
return 1, "hello"
}""",
"""func variadicParams(nums ...int) {
fmt.Println(nums)
}""",
"""func keywordParams(a int, b string) {
fmt.Println(a, b)
}""",
"""func measureTime() {
start := time.Now()
time.Sleep(1 * time.Second)
fmt.Println(time.Since(start))
}""",
"""func decorator(f func()) func() {
return func() {
fmt.Println("Before")
f()
fmt.Println("After")
}
}""",
"""func cacheResult(f func() int) func() int {
var result int
return func() int {
if result == 0 {
result = f()
}
return result
}
}""",
"""func createGenerator() func() int {
i := 0
return func() int {
i++
return i
}
}""",
"""func yieldValue() chan int {
ch := make(chan int)
go func() {
ch <- 1
ch <- 2
close(ch)
}()
return ch
}""",
"""func nextValue() {
ch := yieldValue()
fmt.Println(<-ch)
fmt.Println(<-ch)
}""",
"""func createIterator() func() (int, bool) {
i := 0
return func() (int, bool) {
if i < 3 {
i++
return i, true
}
return 0, false
}
}""",
"""func manualIterate() {
it := createIterator()
for {
v, ok := it()
if !ok {
break
}
fmt.Println(v)
}
}""",
"""func useEnumerate() {
for i, v := range []string{"a", "b", "c"} {
fmt.Println(i, v)
}
}""",
"""func useZip() {
for a, b := range zip([]int{1, 2}, []string{"a", "b"}) {
fmt.Println(a, b)
}
}""",
"""func listToDict() {
dict := make(map[int]string)
for i, v := range []string{"a", "b"} {
dict[i] = v
}
fmt.Println(dict)
}""",
"""func compareLists() {
fmt.Println(reflect.DeepEqual([]int{1, 2}, []int{1, 2}))
}""",
"""func compareDicts() {
fmt.Println(reflect.DeepEqual(map[string]int{"a": 1}, map[string]int{"a": 1}))
}""",
"""func compareSets() {
fmt.Println(reflect.DeepEqual(map[int]bool{1: true}, map[int]bool{1: true}))
}""",
"""func removeDuplicates() {
set := make(map[int]bool)
for _, v := range []int{1, 2, 2, 3} {
set[v] = true
}
fmt.Println(set)
}""",
"""func clearSet() {
set := map[int]bool{1: true, 2: true}
for k := range set {
delete(set, k)
}
fmt.Println(set)
}""",
"func isEmptySet(s map[interface{}]struct{}) bool { return len(s) == 0 }", "func addToSet(s map[interface{}]struct{}, element interface{}) { s[element] = struct{}{} }", "func removeFromSet(s map[interface{}]struct{}, element interface{}) { delete(s, element) }", "func containsInSet(s map[interface{}]struct{}, element interface{}) bool { _, exists := s[element]; return exists }", "func getSetLength(s map[interface{}]struct{}) int { return len(s) }", "func hasIntersection(s1, s2 map[interface{}]struct{}) bool { for k := range s1 { if _, exists := s2[k]; exists { return true } } return false }", "func isSubset(s1, s2 map[interface{}]struct{}) bool { for k := range s1 { if _, exists := s2[k]; !exists { return false } } return true }", "func isSubstring(s, substr string) bool { return strings.Contains(s, substr) }", "func getFirstChar(s string) string { return string(s[0]) }", "func getLastChar(s string) string { return string(s[len(s)-1]) }", "func isTextFile(filename string) bool { return strings.HasSuffix(filename, \".txt\") }", "func isImageFile(filename string) bool { ext := strings.ToLower(filepath.Ext(filename)); return ext == \".jpg\" || ext == \".png\" || ext == \".gif\" }", "func roundNumber(num float64) float64 { return math.Round(num) }", "func ceilNumber(num float64) float64 { return math.Ceil(num) }", "func floorNumber(num float64) float64 { return math.Floor(num) }", "func formatDecimal(num float64, precision int) string { return fmt.Sprintf(\"%.*f\", precision, num) }", "func generateRandomString(length int) string { rand.Seed(time.Now().UnixNano()); b := make([]byte, length); rand.Read(b); return fmt.Sprintf(\"%x\", b)[:length] }", "func pathExists(path string) bool { _, err := os.Stat(path); return !os.IsNotExist(err) }", """func listFilesInDir(dir string) []string {
var files []string
filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
if !info.IsDir() {
files = append(files, path)
}
return nil
})
return files
}""", "func getFileExtension(filename string) string { return filepath.Ext(filename) }", "func getFileName(filename string) string { return filepath.Base(filename) }", "func getFullPath(filename string) string { absPath, _ := filepath.Abs(filename); return absPath }", "func getPythonVersion() string { return runtime.Version() }", "func getPlatformInfo() string { return runtime.GOOS }", "func getCPUCores() int { return runtime.NumCPU() }", "func getMemorySize() uint64 { var mem runtime.MemStats; runtime.ReadMemStats(&mem); return mem.Sys }", """func getDiskUsage() string {
var stat syscall.Statfs_t
syscall.Statfs("/", &stat)
return fmt.Sprintf("Total: %d, Free: %d", stat.Blocks*uint64(stat.Bsize), stat.Bavail*uint64(stat.Bsize))
}""", "func getIPAddress() string { conn, _ := net.Dial(\"udp\", \"8.8.8.8:80\"); defer conn.Close(); return conn.LocalAddr().(*net.UDPAddr).IP.String() }", "func isConnected() bool { _, err := net.LookupIP(\"google.com\"); return err == nil }", """func downloadFile(url, filename string) error {
resp, err := http.Get(url)
if err != nil {
return err
}
defer resp.Body.Close()
out, err := os.Create(filename)
if err != nil {
return err
}
defer out.Close()
_, err = io.Copy(out, resp.Body)
return err
}""", """func uploadFile(filename string) string {
return fmt.Sprintf("File %s uploaded", filename)
}""", """func sendPostRequest(url string, data map[string]string) (string, error) {
jsonData, _ := json.Marshal(data)
resp, err := http.Post(url, "application/json", bytes.NewBuffer(jsonData))
if err != nil {
return "", err
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
return string(body), nil
}""", """func sendRequestWithParams(url string, params map[string]string) (string, error) {
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return "", err
}
q := req.URL.Query()
for key, value := range params {
q.Add(key, value)
}
req.URL.RawQuery = q.Encode()
resp, err := http.DefaultClient.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
return string(body), nil
}""", """func setRequestHeader(req *http.Request, headers map[string]string) {
for key, value := range headers {
req.Header.Set(key, value)
}
}""", """func parseHTML(htmlContent string) (*goquery.Document, error) {
return goquery.NewDocumentFromReader(strings.NewReader(htmlContent))
}""", """func extractTitle(doc *goquery.Document) string {
return doc.Find("title").Text()
}""", """func extractLinks(doc *goquery.Document) []string {
var links []string
doc.Find("a").Each(func(i int, s *goquery.Selection) {
href, exists := s.Attr("href")
if exists {
links = append(links, href)
}
})
return links
}""", """func downloadImagesFromPage(url string) error {
doc, err := goquery.NewDocument(url)
if err != nil {
return err
}
doc.Find("img").Each(func(i int, s *goquery.Selection) {
src, exists := s.Attr("src")
if exists {
downloadFile(src, fmt.Sprintf("image%d.jpg", i))
}
})
return nil
}""", """func countWordFrequency(text string) map[string]int {
words := strings.Fields(text)
freq := make(map[string]int)
for _, word := range words {
freq[word]++
}
return freq
}""", """func simulateLogin(url, username, password string) (string, error) {
form := url.Values{}
form.Add("username", username)
form.Add("password", password)
resp, err := http.PostForm(url, form)
if err != nil {
return "", err
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
return string(body), nil
}""", """func htmlToText(htmlContent string) string {
doc, _ := goquery.NewDocumentFromReader(strings.NewReader(htmlContent))
return doc.Text()
}""", """func extractEmails(text string) []string {
re := regexp.MustCompile(`[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}`)
return re.FindAllString(text, -1)
}""", """func extractPhoneNumbers(text string) []string {
re := regexp.MustCompile(`\d{3}-\d{3}-\d{4}`)
return re.FindAllString(text, -1)
}""", """func findAllNumbers(text string) []string {
re := regexp.MustCompile(`\d+`)
return re.FindAllString(text, -1)
}""", """func replaceWithRegex(text, pattern, replacement string) string {
re := regexp.MustCompile(pattern)
return re.ReplaceAllString(text, replacement)
}""", """func matchRegex(text, pattern string) bool {
re := regexp.MustCompile(pattern)
return re.MatchString(text)
}""", """func removeHTMLTags(htmlContent string) string {
re := regexp.MustCompile(`<[^>]*>`)
return re.ReplaceAllString(htmlContent, "")
}""", """func encodeHTMLEntities(htmlContent string) string {
return html.EscapeString(htmlContent)
}""", """func decodeHTMLEntities(htmlContent string) string {
return html.UnescapeString(htmlContent)
}""", """func createGUIWindow() {
window := gtk.NewWindow(gtk.WINDOW_TOPLEVEL)
window.SetTitle("Simple GUI Window")
window.Connect("destroy", func() {
gtk.MainQuit()
})
window.ShowAll()
gtk.Main()
}""",
"func addButton(w fyne.Window) { w.SetContent(widget.NewButton(\"Button\", nil)) }",
"""func handleClick(b *widget.Button) {
b.OnTapped = func() { fmt.Println("Clicked") }
}""",
"""func showDialog(w fyne.Window) {
dialog.ShowInformation("Title", "Message", w)
}""",
"func getText(e *widget.Entry) string { return e.Text }",
"func setTitle(w fyne.Window) { w.SetTitle(\"Title\") }",
"func resizeWindow(w fyne.Window) { w.Resize(fyne.NewSize(800, 600)) }",
"func centerWindow(w fyne.Window) { w.CenterOnScreen() }",
"""func addMenu(w fyne.Window) {
menu := fyne.NewMainMenu(fyne.NewMenu("File"))
w.SetMainMenu(menu)
}""",
"func createSelect() *widget.Select { return widget.NewSelect([]string{\"a\", \"b\"}, func(s string) {}) }",
"func createRadio() *widget.RadioGroup { return widget.NewRadioGroup([]string{\"a\", \"b\"}, func(s string) {}) }",
"func createCheck() *widget.Check { return widget.NewCheck(\"Check\", func(b bool) {}) }",
"func showImage() *canvas.Image { return canvas.NewImageFromFile(\"image.png\") }",
"""func playAudio() {
exec.Command("afplay", "audio.mp3").Start()
}""",
"""func playVideo() {
exec.Command("vlc", "video.mp4").Start()
}""",
"func getTimestamp() int64 { return time.Now().Unix() }",
"""func timestampToDate(ts int64) string {
return time.Unix(ts, 0).Format("2006-01-02")
}""",
"""func dateToTimestamp(date string) int64 {
t, _ := time.Parse("2006-01-02", date)
return t.Unix()
}""",
"func getWeekday() string { return time.Now().Weekday().String() }",
"""func getMonthDays() int {
return time.Date(time.Now().Year(), time.Now().Month()+1, 0, 0, 0, 0, 0, time.UTC).Day()
}""",
"func firstDayOfYear() time.Time { return time.Date(time.Now().Year(), 1, 1, 0, 0, 0, 0, time.UTC) }",
"func lastDayOfYear() time.Time { return time.Date(time.Now().Year(), 12, 31, 0, 0, 0, 0, time.UTC) }",
"""func firstDayOfMonth(year int, month time.Month) time.Time {
return time.Date(year, month, 1, 0, 0, 0, 0, time.UTC)
}""",
"""func lastDayOfMonth(year int, month time.Month) int {
return time.Date(year, month+1, 0, 0, 0, 0, 0, time.UTC).Day()
}""",
"func isWorkday() bool { wd := time.Now().Weekday(); return wd != time.Saturday && wd != time.Sunday }",
"func isWeekend() bool { wd := time.Now().Weekday(); return wd == time.Saturday || wd == time.Sunday }",
"func currentHour() int { return time.Now().Hour() }",
"func currentMinute() int { return time.Now().Minute() }",
"func currentSecond() int { return time.Now().Second() }",
"func sleep() { time.Sleep(time.Second) }",
"func millis() int64 { return time.Now().UnixNano() / int64(time.Millisecond) }",
"""func formatTime(t time.Time) string {
return t.Format("2006-01-02 15:04:05")
}""",
"""func parseTime(s string) time.Time {
t, _ := time.Parse("2006-01-02", s)
return t
}""",
"""func startThread() {
go func() { fmt.Println("Thread") }()
}""",
"func threadSleep() { time.Sleep(time.Second) }",
"""func multiThread() {
for i := 0; i < 3; i++ { go func(i int) {}(i) }
}""",
"func threadName() string { return runtime.Version() }",
"func setDaemon() { /* Not applicable in Go */ }",
"""func useMutex() {
var mu sync.Mutex
mu.Lock()
defer mu.Unlock()
}""",
"""func createProcess() {
cmd := exec.Command("ls")
cmd.Start()
}""",
"func getPID() int { return os.Getpid() }",
"""func isProcessAlive(pid int) bool {
err := syscall.Kill(pid, syscall.Signal(0))
return err == nil
}""",
"""func multiProcess() {
exec.Command("ls").Start()
}""",
"""func useQueue() {
ch := make(chan int)
go func() { ch <- 1 }()
<-ch
}""",
"""func usePipe() {
r, w, _ := os.Pipe()
w.Write([]byte("data"))
var b [4]byte
r.Read(b[:])
}""",
"func limitCPUUsage() { runtime.GOMAXPROCS(1) }",
"""func runShellCommand(cmd string) error {
return exec.Command("sh", "-c", cmd).Run()
}""",
"""func getCommandOutput(cmd string) (string, error) {
out, err := exec.Command("sh", "-c", cmd).Output()
return string(out), err
}""",
"""func getCommandStatus(cmd string) (int, error) {
err := exec.Command("sh", "-c", cmd).Run()
if err != nil {
if exitError, ok := err.(*exec.ExitError); ok {
return exitError.ExitCode(), nil
}
return -1, err
}
return 0, nil
}""",
"""func isCommandSuccess(cmd string) (bool, error) {
err := exec.Command("sh", "-c", cmd).Run()
return err == nil, err
}""",
"""func getCurrentScriptPath() string {
_, filename, _, _ := runtime.Caller(1)
return filepath.Dir(filename)
}""",
"""func getCommandLineArgs() []string {
return os.Args
}""",
"""func parseArgs() (string, int) {
var name string
var age int
flag.StringVar(&name, "name", "", "Name of the person")
flag.IntVar(&age, "age", 0, "Age of the person")
flag.Parse()
return name, age
}""",
"""func generateHelp() string {
flag.Usage()
return ""
}""",
"""func listPythonModules() {
exec.Command("python", "-c", "help('modules')").Run()
}""",
"""func installPythonPackage(pkg string) error {
return exec.Command("pip", "install", pkg).Run()
}""",
"""func uninstallPythonPackage(pkg string) error {
return exec.Command("pip", "uninstall", "-y", pkg).Run()
}""",
"""func getPackageVersion(pkg string) (string, error) {
out, err := exec.Command("pip", "show", pkg).Output()
if err != nil {
return "", err
}
return string(out), nil
}""",
"""func useVirtualEnv(envPath string) error {
return exec.Command("source", filepath.Join(envPath, "bin", "activate")).Run()
}""",
"""func listInstalledPackages() (string, error) {
out, err := exec.Command("pip", "list").Output()
return string(out), err
}""",
"""func upgradePythonPackage(pkg string) error {
return exec.Command("pip", "install", "--upgrade", pkg).Run()
}""",
"""func connectLocalDB(dbName string) (*sql.DB, error) {
return sql.Open("sqlite3", dbName)
}""",
"""func executeSQLQuery(db *sql.DB, query string) (*sql.Rows, error) {
return db.Query(query)
}""",
"""func insertRecord(db *sql.DB, query string, args ...interface{}) (sql.Result, error) {
return db.Exec(query, args...)
}""",
"""func deleteRecord(db *sql.DB, query string, args ...interface{}) (sql.Result, error) {
return db.Exec(query, args...)
}""",
"""func updateRecord(db *sql.DB, query string, args ...interface{}) (sql.Result, error) {
return db.Exec(query, args...)
}""",
"""func queryMultipleRecords(db *sql.DB, query string, args ...interface{}) (*sql.Rows, error) {
return db.Query(query, args...)
}""",
"""func useParameterizedQuery(db *sql.DB, query string, args ...interface{}) (*sql.Rows, error) {
return db.Query(query, args...)
}""",
"""func closeDBConnection(db *sql.DB) error {
return db.Close()
}""",
"""func createTable(db *sql.DB, query string) (sql.Result, error) {
return db.Exec(query)
}""",
"""func dropTable(db *sql.DB, query string) (sql.Result, error) {
return db.Exec(query)
}""",
"""func tableExists(db *sql.DB, tableName string) (bool, error) {
var exists bool
err := db.QueryRow("SELECT EXISTS (SELECT 1 FROM sqlite_master WHERE type='table' AND name=?)", tableName).Scan(&exists)
return exists, err
}""",
"""func listAllTables(db *sql.DB) ([]string, error) {
rows, err := db.Query("SELECT name FROM sqlite_master WHERE type='table'")
if err != nil {
return nil, err
}
defer rows.Close()
var tables []string
for rows.Next() {
var table string
if err := rows.Scan(&table); err != nil {
return nil, err
}
tables = append(tables, table)
}
return tables, nil
}""",
"""func exportToCSV(data [][]string, filename string) error {
file, err := os.Create(filename)
if err != nil {
return err
}
defer file.Close()
writer := csv.NewWriter(file)
return writer.WriteAll(data)
}""",
"""func exportToExcel(data [][]string, filename string) error {
file := excelize.NewFile()
for i, row := range data {
for j, cell := range row {
file.SetCellValue("Sheet1", fmt.Sprintf("%c%d", 'A'+j, i+1), cell)
}
}
return file.SaveAs(filename)
}""",
"""func exportToJSON(data interface{}, filename string) error {
file, err := os.Create(filename)
if err != nil {
return err
}
defer file.Close()
encoder := json.NewEncoder(file)
return encoder.Encode(data)
}""",
"""func readExcel(filename string) ([][]string, error) {
file, err := excelize.OpenFile(filename)
if err != nil {
return nil, err
}
rows, err := file.GetRows("Sheet1")
return rows, err
}""",
"""func mergeExcelFiles(files []string, output string) error {
merged := excelize.NewFile()
for _, file := range files {
f, err := excelize.OpenFile(file)
if err != nil {
return err
}
rows, err := f.GetRows("Sheet1")
if err != nil {
return err
}
for i, row := range rows {
for j, cell := range row {
merged.SetCellValue("Sheet1", fmt.Sprintf("%c%d", 'A'+j, i+1), cell)
}
}
}
return merged.SaveAs(output)
}""",
"""func addSheetToExcel(filename, sheetName string) error {
file, err := excelize.OpenFile(filename)
if err != nil {
return err
}
file.NewSheet(sheetName)
return file.Save()
}""",
"""func copyExcelStyle(src, dst string) error {
srcFile, err := excelize.OpenFile(src)
if err != nil {
return err
}
dstFile, err := excelize.OpenFile(dst)
if err != nil {
return err
}
styleID, err := srcFile.GetCellStyle("Sheet1", "A1")
if err != nil {
return err
}
dstFile.SetCellStyle("Sheet1", "A1", "A1", styleID)
return dstFile.Save()
}""",
"""func setExcelCellColor(filename, cell, color string) error {
file, err := excelize.OpenFile(filename)
if err != nil {
return err
}
styleID, err := file.NewStyle(&excelize.Style{Fill: excelize.Fill{Type: "pattern", Color: []string{color}, Pattern: 1}})
if err != nil {
return err
}
file.SetCellStyle("Sheet1", cell, cell, styleID)
return file.Save()
}""",
"""func setExcelFontStyle(filename, cell, fontName string, fontSize int) error {
file, err := excelize.OpenFile(filename)
if err != nil {
return err
}
styleID, err := file.NewStyle(&excelize.Style{Font: &excelize.Font{Family: fontName, Size: fontSize}})
if err != nil {
return err
}
file.SetCellStyle("Sheet1", cell, cell, styleID)
return file.Save()
}""",
"""func readExcelCell(filename, cell string) (string, error) {
file, err := excelize.OpenFile(filename)
if err != nil {
return "", err
}
return file.GetCellValue("Sheet1", cell)
}""",
"""func writeExcelCell(filename, cell, value string) error {
file, err := excelize.OpenFile(filename)
if err != nil {
return err
}
file.SetCellValue("Sheet1", cell, value)
return file.Save()
}""",
"""func getImageDimensions(filename string) (int, int, error) {
file, err := os.Open(filename)
if err != nil {
return 0, 0, err
}
defer file.Close()
img, _, err := image.DecodeConfig(file)
return img.Width, img.Height, err
}""",
"""func resizeImage(filename string, width, height int) error {
file, err := os.Open(filename)
if err != nil {
return err
}
defer file.Close()
img, _, err := image.Decode(file)
if err != nil {
return err
}
resized := imaging.Resize(img, width, height, imaging.Lanczos)
return imaging.Save(resized, filename)
}"""
]
# 全局服务状态
service_ready = False
# 优雅关闭处理
def handle_shutdown(signum, frame):
app.logger.info("收到终止信号,开始关闭...")
sys.exit(0)
signal.signal(signal.SIGTERM, handle_shutdown)
signal.signal(signal.SIGINT, handle_shutdown)
# 初始化模型和预计算编码
try:
app.logger.info("开始加载模型...")
model = SentenceTransformer(
"flax-sentence-embeddings/st-codesearch-distilroberta-base",
cache_folder="/model-cache"
)
# 预计算代码片段的编码(强制使用 CPU)
code_emb = model.encode(CODE_SNIPPETS, convert_to_tensor=True, device="cpu")
service_ready = True
app.logger.info("服务初始化完成")
except Exception as e:
app.logger.error("初始化失败: %s", str(e))
raise
# Hugging Face 健康检查端点,必须响应根路径
@app.route('/')
def hf_health_check():
# 如果请求接受 HTML,则返回一个简单的 HTML 页面(包含测试链接)
if request.accept_mimetypes.accept_html:
html = """
<h2>CodeSearch API</h2>
<p>服务状态:{{ status }}</p>
<p>你可以在地址栏输入 /search?query=你的查询 来测试接口</p>
"""
status = "ready" if service_ready else "initializing"
return render_template_string(html, status=status)
# 否则返回 JSON 格式的健康检查
if service_ready:
return jsonify({"status": "ready"}), 200
else:
return jsonify({"status": "initializing"}), 503
# 搜索 API 端点,同时支持 GET 和 POST 请求
@app.route('/search', methods=['GET', 'POST'])
def handle_search():
if not service_ready:
app.logger.info("服务未就绪")
return jsonify({"error": "服务正在初始化"}), 503
try:
# 根据请求方法提取查询内容
if request.method == 'GET':
query = request.args.get('query', '').strip()
else:
data = request.get_json() or {}
query = data.get('query', '').strip()
if not query:
app.logger.info("收到空的查询请求")
return jsonify({"error": "查询不能为空"}), 400
# 记录接收到的查询
app.logger.info("收到查询请求: %s", query)
# 对查询进行编码,并进行语义搜索
query_emb = model.encode(query, convert_to_tensor=True, device="cpu")
hits = util.semantic_search(query_emb, code_emb, top_k=1)[0]
best = hits[0]
result = {
"code": CODE_SNIPPETS[best['corpus_id']],
"score": round(float(best['score']), 4)
}
# 记录返回结果
app.logger.info("返回结果: %s", result)
return jsonify(result)
except Exception as e:
app.logger.error("请求处理失败: %s", str(e))
return jsonify({"error": "服务器内部错误"}), 500
if __name__ == "__main__":
# 本地测试用,Hugging Face Spaces 通常通过 gunicorn 启动
app.run(host='0.0.0.0', port=7860)
|