-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgithub_search_ai.py
More file actions
121 lines (113 loc) · 4.55 KB
/
Copy pathgithub_search_ai.py
File metadata and controls
121 lines (113 loc) · 4.55 KB
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
#!/usr/bin/env python3
import os
import sys
import json
import urllib.request
import urllib.parse
CONFIG_FILE = os.path.expanduser("~/.github_search_config.json")
def load_config():
if os.path.exists(CONFIG_FILE):
with open(CONFIG_FILE, "r", encoding="utf-8") as f:
return json.load(f)
return {"github_token": "", "ai_key": ""}
def save_config(config):
with open(CONFIG_FILE, "w", encoding="utf-8") as f:
json.dump(config, f, ensure_ascii=False, indent=2)
def translate_to_english(text, ai_key):
prompt = f"Translate this to English search keywords for GitHub: {text}"
url = "https://api.openai.com/v1/chat/completions"
req = urllib.request.Request(url)
req.add_header("Authorization", f"Bearer {ai_key}")
req.add_header("Content-Type", "application/json")
data = {
"model": "gpt-3.5-turbo",
"messages": [{"role": "user", "content": prompt}],
"temperature": 0.3
}
try:
resp = urllib.request.urlopen(req, data=json.dumps(data).encode("utf-8"))
result = json.loads(resp.read())
return result["choices"][0]["message"]["content"].strip()
except:
return text
def search_github(query, github_token):
url = f"https://api.github.com/search/repositories?q={urllib.parse.quote(query)}&per_page=10"
req = urllib.request.Request(url)
if github_token:
req.add_header("Authorization", f"Bearer {github_token}")
resp = urllib.request.urlopen(req)
return json.loads(resp.read())
def simple_translate(text):
word_map = {
"Python": "python", "Web": "web", "框架": "framework",
"高星": "stars:>=1000", "最近": "pushed:>=30d",
"活跃": "pushed:>=90d", "热门": "stars:>=1000",
"最新": "pushed:>=30d", "库": "library", "工具": "tool",
"组件": "component", "HTTP": "http", "客户端": "client",
"数据库": "database", "ORM": "orm", "图表": "chart"
}
result = text
for ch, en in word_map.items():
if ch in result:
result = result.replace(ch, en)
return result
def main():
config = load_config()
print("🚀 GitHub AI Search Assistant")
print("=" * 50)
token_display = config["github_token"][:10] + "..." if config["github_token"] else "Not set"
print("GitHub Token:", token_display)
print("=" * 50)
print("Commands:")
print(" /config - Configure GitHub Token")
print(" /quit - Exit")
print("=" * 50)
while True:
user_input = input("\n👉 Enter query: ").strip()
if user_input.lower() in ["/quit", "/exit", "/q", "quit", "exit"]:
print("👋 Goodbye!")
break
if user_input.lower() == "/config":
print("\n⚙️ Configuration")
prompt = " GitHub Token ["
if config["github_token"]:
prompt += config["github_token"][:10]
prompt += "]: "
token_input = input(prompt).strip()
if token_input:
config["github_token"] = token_input
save_config(config)
print("✅ Configuration saved!")
continue
if not user_input:
print("Please enter a query")
continue
print("\n🔍 Processing...")
search_query = simple_translate(user_input)
print(" → Search query:", search_query)
try:
print(" 🔎 Searching GitHub...")
results = search_github(search_query, config["github_token"])
print("\n🎉 Found", results["total_count"], "projects:")
print("=" * 80)
for i in range(min(10, len(results["items"]))):
item = results["items"][i]
print("\n" + str(i+1) + ". " + item["name"])
print(" 🏷️ " + item["full_name"])
print(" 🔗 " + item["html_url"])
print(" ⭐ " + str(item["stargazers_count"]) + " stars | 🍴 " + str(item["forks_count"]) + " forks")
lang = item.get("language", "Unknown")
updated = item["updated_at"][:10]
print(" 💻 " + lang + " | 📅 " + updated)
desc = item.get("description", "")
if desc:
print(" 📝 " + desc[:150])
except urllib.error.HTTPError as e:
if e.code == 403:
print("❌ Rate limit exceeded. Please set GitHub token with /config")
else:
print("❌ Error:", e)
except Exception as e:
print("❌ Error:", e)
if __name__ == "__main__":
main()