Skip to content

Commit

Permalink
Add files via upload
Browse files Browse the repository at this point in the history
  • Loading branch information
Tokeii0 authored Nov 14, 2024
1 parent 177ef83 commit 79aaa2d
Show file tree
Hide file tree
Showing 10 changed files with 174 additions and 57 deletions.
45 changes: 30 additions & 15 deletions ai_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
from typing import AsyncGenerator, Union
import httpx
import logging
import traceback

class AIClient:
def __init__(self, api_key: str, base_url: str = None, model: str = "yi-lightning",
Expand Down Expand Up @@ -45,22 +46,24 @@ def __init__(self, api_key: str, base_url: str = None, model: str = "yi-lightnin

self.client = AsyncOpenAI(**client_params)

async def get_response_stream(self, prompt: str, stream: bool = True) -> AsyncGenerator[str, None]:
async def get_response_stream(self, prompt: str, stream: bool = True, messages: list = None) -> AsyncGenerator[str, None]:
"""获取AI响应,支持流式和非流式模式"""
try:
messages = [{
"role": "system",
"content": "请直接回答问题,不要使用markdown格式。"
}, {
"role": "user",
"content": prompt
}]
# 如果没有提供messages,使用默认的消息列表
if messages is None:
messages = [{
"role": "system",
"content": "请直接回答问题,不要使用markdown格式。"
}, {
"role": "user",
"content": prompt
}]

# 打印实际调用参数
call_params = {
"model": self.model,
"messages": messages,
"stream": stream # 使用传入的stream参数
"stream": stream
}

if self.api_type == "Azure":
Expand All @@ -82,24 +85,36 @@ async def get_response_stream(self, prompt: str, stream: bool = True) -> AsyncGe
if stream:
# 流式模式
async for chunk in response:
if chunk.choices[0].delta.content:
# if (hasattr(chunk, 'choices') and len(chunk.choices) > 0):
# print(f"响应块的choices: {chunk.choices}") # 添加调试输出
if (hasattr(chunk, 'choices') and
len(chunk.choices) > 0 and
chunk.choices[0].delta and
hasattr(chunk.choices[0].delta, 'content') and
chunk.choices[0].delta.content):
yield chunk.choices[0].delta.content
print("流式模式结束")
else:
# 非流式模式,直接返回完整响应
# 注意:非流式模式下,response不是异步迭代器,而是直接的响应对象
complete_response = response.choices[0].message.content
yield complete_response
if hasattr(response, 'choices') and len(response.choices) > 0:
complete_response = response.choices[0].message.content
yield complete_response
else:
error_msg = "API响应格式错误:未找到有效的响应内容"
print(error_msg)
yield error_msg
print("非流式模式结束")

except Exception as e:
error_msg = f"API调用错误: {str(e)}"
print(error_msg) # 在控制台打印错误
print("详细错误信息:")
traceback.print_exc() # 打印详细的堆栈跟踪
yield error_msg

async def get_response(self, prompt: str) -> str:
async def get_response(self, prompt: str, messages: list = None) -> str:
"""获取非流式响应的辅助方法"""
response = ""
async for chunk in self.get_response_stream(prompt, stream=False):
async for chunk in self.get_response_stream(prompt, stream=False, messages=messages):
response += chunk
return response
45 changes: 35 additions & 10 deletions hotkey_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ class GlobalHotkey(QObject):
screenshot_triggered = Signal()
chat_triggered = Signal()
hotkey_failed = Signal(str)
selection_to_input_triggered = Signal()

def __init__(self, parent=None):
super().__init__(parent)
Expand Down Expand Up @@ -72,7 +73,8 @@ def _window_proc(self, hwnd, msg, wparam, lparam):
try:
# 根据热键ID触发对应信号
if wparam == HOTKEY_SHOW:
self.triggered.emit()
# 当按下 Alt+1 时,触发selection_to_input_triggered信号
self.selection_to_input_triggered.emit()
elif wparam == HOTKEY_SHOW2:
self.triggered.emit()
elif wparam == HOTKEY_SELECTION:
Expand All @@ -98,9 +100,10 @@ def _register_hotkeys(self):
(HOTKEY_SHOW2, self.hotkey2),
(HOTKEY_SELECTION, self.selection_hotkey),
(HOTKEY_SCREENSHOT, self.screenshot_hotkey),
(HOTKEY_CHAT, self.chat_hotkey)
(HOTKEY_CHAT, self.chat_hotkey),
]

print("开始注册热键...") # 调试输出
# 注册每个热键
for hotkey_id, (modifier, key) in hotkeys:
try:
Expand All @@ -109,6 +112,8 @@ def _register_hotkeys(self):
# 转换键码
vk_code = self._get_virtual_key_code(key)

print(f"注册热键: ID={hotkey_id}, 修饰键={modifier}({mod_flag}), 键={key}({vk_code})") # 调试输出

# 使用 user32.dll 直接注册热键
if ctypes.windll.user32.RegisterHotKey(self.hwnd, hotkey_id, mod_flag, vk_code):
self.registered_hotkeys[hotkey_id] = (mod_flag, vk_code)
Expand All @@ -119,6 +124,7 @@ def _register_hotkeys(self):

except Exception as e:
print(f"注册热键 {modifier}+{key} 失败: {str(e)}")
traceback.print_exc()
continue

except Exception as e:
Expand All @@ -141,14 +147,25 @@ def _get_modifier_flag(self, modifier):

def _get_virtual_key_code(self, key):
"""转换键名为虚拟键码"""
# 如果是数字键
if key.isdigit():
return ord(key)
# 如果是字母键
elif len(key) == 1 and key.isalpha():
return ord(key.upper())
# 其他特殊键可以继续添加
return 0
try:
# 如果是数字键
if key.isdigit():
return ord(key) # 直接返回数字的ASCII码
# 如果是字母键
elif len(key) == 1 and key.isalpha():
return ord(key.upper())
# 如果是反引号
elif key == '`':
return 0xC0 # 反引号的虚拟键码
# 如果是其他特殊键,可以继续添加

# 调试输出
print(f"键码转换: {key} -> {ord(key) if len(key) == 1 else 'unknown'}")

return ord(key) if len(key) == 1 else 0
except Exception as e:
print(f"键码转换失败: {str(e)}")
return 0

def _unregister_hotkeys(self):
"""取消注册的热键"""
Expand Down Expand Up @@ -207,3 +224,11 @@ def _parse_shortcut(self, shortcut):
if len(parts) != 2:
return ('Alt', '1')
return (parts[0].capitalize(), parts[1])

def _handle_selection_to_input(self):
"""处理Alt+1热键"""
try:
self.selection_to_input_triggered.emit()
except Exception as e:
print(f"处理Alt+1热键失败: {str(e)}")
self.hotkey_failed.emit(str(e))
12 changes: 7 additions & 5 deletions image_analysis_dialog.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,16 @@ def __init__(self, parent=None):

# 创建主布局
main_layout = QVBoxLayout(self)
main_layout.setContentsMargins(10, 5, 10, 10)
main_layout.setContentsMargins(10, 2, 10, 10)
main_layout.setSpacing(10)

# 创建顶部布局(只包含关闭按钮)
top_layout = QHBoxLayout()
top_layout.setSpacing(0)
top_layout.setContentsMargins(0, 0, 0, 0)
top_layout.addStretch()


# 添加关闭按钮
close_button = QPushButton("×")
close_button.setObjectName("closeButton")
Expand Down Expand Up @@ -195,8 +197,8 @@ def __init__(self, parent=None):
background: transparent;
border: none;
color: #999;
font-size: 18px;
padding: 5px 10px;
font-size: 16px;
padding: 2px 8px;
}
QPushButton#closeButton:hover {
background-color: #ff4444;
Expand All @@ -221,8 +223,8 @@ def __init__(self, parent=None):
border-radius: 4px;
}
QSplitter::handle {
background-color: #e9ecef;
width: 1px;
background-color: transparent;
width: 0px;
}
""")

Expand Down
Loading

0 comments on commit 79aaa2d

Please sign in to comment.